Skip to content

Commit

Permalink
Merge remote branch 'MidnightLightning/master'
Browse files Browse the repository at this point in the history
* Lots of cleanup. 
* Regionfiles now work correctly.
* Chunk convenience class added.
* Started work on Docs. 
* Filename handling in write_file better.
* All tests now pass.
  • Loading branch information
twoolie committed Sep 23, 2011
2 parents b748659 + 2e23e9b commit d86217e
Show file tree
Hide file tree
Showing 17 changed files with 1,003 additions and 98 deletions.
2 changes: 2 additions & 0 deletions CONTRIBUTORS.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
MidnightLightning
Fenixin
5 changes: 4 additions & 1 deletion MANIFEST.in
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
include *.txt
include nbt\bigtest.nbt
include bigtest.nbt
include tests.py
include examples
include doc
2 changes: 0 additions & 2 deletions README.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ From The spec:

read the full spec at http://www.minecraft.net/docs/NBT.txt

** Warning: Although the API is nearing freeze, it may change slightly before the 1.0 release **

Usage:
1) Reading files.

Expand Down
File renamed without changes.
Empty file added doc/chunk.rst
Empty file.
216 changes: 216 additions & 0 deletions doc/conf.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
# -*- coding: utf-8 -*-
#
# NBT documentation build configuration file, created by
# sphinx-quickstart on Fri Sep 23 10:31:02 2011.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

import sys, os

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))

# -- General configuration -----------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.coverage', 'sphinx.ext.viewcode']

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The suffix of source filenames.
source_suffix = '.rst'

# The encoding of source files.
#source_encoding = 'utf-8-sig'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'NBT'
copyright = u'2011, Thomas Woolford'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = nbt._get_version()
# The full version, including alpha/beta/rc tags.
release = nbt._get_version()

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']

# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []


# -- Options for HTML output ---------------------------------------------------

# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'

# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}

# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []

# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None

# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None

# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}

# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}

# If false, no module index is generated.
#html_domain_indices = True

# If false, no index is generated.
#html_use_index = True

# If true, the index is split into individual pages for each letter.
#html_split_index = False

# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True

# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True

# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True

# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''

# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None

# Output file base name for HTML help builder.
htmlhelp_basename = 'NBTdoc'


# -- Options for LaTeX output --------------------------------------------------

# The paper size ('letter' or 'a4').
#latex_paper_size = 'a4'

# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '12pt'

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'NBT.tex', u'NBT Documentation',
u'Thomas Woolford', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False

# If true, show page references after internal links.
#latex_show_pagerefs = False

# If true, show URL addresses after external links.
#latex_show_urls = False

# Additional stuff for the LaTeX preamble.
#latex_preamble = ''

# Documents to append as an appendix to all manuals.
#latex_appendices = []

# If false, no module index is generated.
#latex_domain_indices = True


# -- Options for manual page output --------------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'nbt', u'NBT Documentation',
[u'Thomas Woolford'], 1)
]
31 changes: 31 additions & 0 deletions doc/index.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
Welcome to NBT's documentation!
===============================

This is a Named Binary Tag parser based upon the specification by Markus Persson.

From The spec:
"NBT (Named Binary Tag) is a tag based binary format designed to carry large
amounts of binary data with smaller amounts of additional data.
An NBT file consists of a single GZIPped Named Tag of type TAG_Compound."

read the full spec at http://www.minecraft.net/docs/NBT.txt

This project also contains helper classes for dealing with Regions and Chunks in
minecraft, the main use case for the NBT format.

Contents:

.. toctree::
:maxdepth: 2

nbt
region
chunk

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

Empty file added doc/nbt.rst
Empty file.
Empty file added doc/region.rst
Empty file.
114 changes: 114 additions & 0 deletions examples/block_analysis.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
from nbt.region import RegionFile
from nbt.chunk import Chunk
import locale, os, sys

if (len(sys.argv) == 1):
print "No world folder specified!"
sys.exit()

world_folder = sys.argv[1]
if (not os.path.exists(world_folder)):
print "No such folder as "+filename
sys.exit()

if (world_folder[-1] == '/'):
world_folder = world_folder[:-1] # Trim trailing slash

regions = os.listdir(world_folder+'/region/')

start = None
stop = None
if (len(sys.argv) == 4):
# A min/max corner was specified
start_str = sys.argv[2][1:-1] # Strip parenthesis...
start = tuple(start_str.split(',')) # and convert to tuple
stop_str = sys.argv[3][1:-1] # Strip parenthesis...
stop = tuple(stop_str.split(',')) # and convert to tuple

block_totals = [0]*255 # up to 255 block types
try:
for filename in regions:
print "Parsing",filename,"..."
pieces = filename.split('.')
rx = int(pieces[1])
rz = int(pieces[2])

# Does the region overlap the bounding box at all?
if (start != None):
if ( (rx+1)*512-1 < int(start[0]) or (rz+1)*512-1 < int(start[2]) ):
continue
elif (stop != None):
if ( rx*512-1 > int(stop[0]) or rz*512-1 > int(stop[2]) ):
continue

file = RegionFile(filename=world_folder+'/region/'+filename)

# Get all chunks
chunks = file.get_chunks()
for c in chunks:
# Does the chunk overlap the bounding box at all?
if (start != None):
if ( (c['x']+1)*16 + rx*512 - 1 < int(start[0]) or (c['z']+1)*16 + rz*512 - 1 < int(start[2]) ):
continue
elif (stop != None):
if ( c['x']*16 + rx*512 - 1 > int(stop[0]) or c['z']*16 + rz*512 - 1 > int(stop[2]) ):
continue

chunk = Chunk(file.get_chunk(c['x'], c['z']))
#print "Parsing chunk ("+str(c['x'])+", "+str(c['z'])+")"

# Parse the blocks
for z in range(16):
world_z = z + c['z']*16 + rz*512
if ( (start != None and world_z < int(start[2])) or (stop != None and world_z > int(stop[2])) ):
# Outside the bounding box; skip to next iteration
#print "Z break:",world_z,start[2],stop[2]
break
for x in range(16):
world_x = x + c['x']*16 + rx*512
if ( (start != None and world_x < int(start[0])) or (stop != None and world_x > int(stop[0])) ):
# Outside the bounding box; skip to next iteration
#print "X break:",world_x,start[0],stop[0]
break
for y in range(128):
if ( (start != None and y < int(start[1])) or (stop != None and y > int(stop[1])) ):
# Outside the bounding box; skip to next iteration
#print "Y break:",y,start[1],stop[1]
break

#print "Chunk:",c['x'], c['z'],"Coord:",x,y,z
block_id = chunk.blocks.get_block(x,y,z)
block_totals[block_id] += 1
except KeyboardInterrupt:
print block_totals
raise

print block_totals

# Analyze blocks
locale.setlocale(locale.LC_ALL, 'en_US')

total_blocks = sum(block_totals)
solid_blocks = total_blocks - block_totals[0]
solid_ratio = (solid_blocks+0.0)/total_blocks if (total_blocks > 0) else 0
print locale.format("%d", total_blocks, grouping=True),'total blocks in region,',locale.format("%d", solid_blocks, grouping=True),"are solid ({0:0.4%})".format(solid_ratio)

# Find valuable blocks
print 'Diamond Ore:', locale.format("%d", block_totals[56], grouping=True)
print 'Gold Ore:', locale.format("%d", block_totals[14], grouping=True)
print 'Redstone Ore:', locale.format("%d", block_totals[73], grouping=True)
print 'Iron Ore:', locale.format("%d", block_totals[15], grouping=True)
print 'Coal Ore:', locale.format("%d", block_totals[16], grouping=True)
print 'Lapis Lazuli Ore:', locale.format("%d", block_totals[21], grouping=True)
print 'Dungeons:', locale.format("%d", block_totals[52], grouping=True)

print 'Clay:', locale.format("%d", block_totals[82], grouping=True)
print 'Sugar Cane:', locale.format("%d", block_totals[83], grouping=True)
print 'Cacti:', locale.format("%d", block_totals[81], grouping=True)
print 'Pumpkin:', locale.format("%d", block_totals[86], grouping=True)
print 'Dandelion:', locale.format("%d", block_totals[37], grouping=True)
print 'Rose:', locale.format("%d", block_totals[38], grouping=True)
print 'Brown Mushroom:', locale.format("%d", block_totals[39], grouping=True)
print 'Red Mushroom:', locale.format("%d", block_totals[40], grouping=True)
print 'Lava Springs:', locale.format("%d", block_totals[11], grouping=True)

Loading

0 comments on commit d86217e

Please sign in to comment.