Skip to content

Commit

Permalink
Merge remote-tracking branch 'github/macfreek/world-examples'
Browse files Browse the repository at this point in the history
  • Loading branch information
Thomas Woolford committed Mar 19, 2012
2 parents 7ce9f43 + 919e9eb commit 5530efb
Show file tree
Hide file tree
Showing 7 changed files with 224 additions and 112 deletions.
91 changes: 91 additions & 0 deletions examples/biome_analysis.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
#!/usr/bin/env python
"""
Counter the number of biomes in the world. Works only for Anvil-based world folders.
"""
import locale, os, sys
from struct import pack, unpack

# local module
try:
import nbt
except ImportError:
# nbt not in search path. Let's see if it can be found in the parent folder
extrasearchpath = os.path.realpath(os.path.join(sys.path[0],os.pardir))
if not os.path.exists(os.path.join(extrasearchpath,'nbt')):
raise
sys.path.append(extrasearchpath)
from nbt.region import RegionFile
from nbt.chunk import Chunk
from nbt.world import AnvilWorldFolder,UnknownWorldFormat

BIOMES = {
0 : "Ocean",
1 : "Plains",
2 : "Desert",
3 : "Mountains",
4 : "Forest",
5 : "Taiga",
6 : "Swamp",
7 : "River",
8 : "Nether",
9 : "Sky",
10: "Frozen Ocean",
11: "Frozen River",
12: "Ice Plains",
13: "Ice Mountains",
14: "Mushroom Island",
15: "Mushroom Shore",
16: "Beach",
17: "Desert Hills",
18: "Forest Hills",
19: "Taiga Hills",
20: "Mountains Edge",
21: "Jungle",
22: "Jungle Hills",
# 255: "Not yet calculated",
}


def print_results(biome_totals):
locale.setlocale(locale.LC_ALL, 'en_US')
for id,count in enumerate(biome_totals):
# Biome ID 255 is ignored. It means it is not calculated by Minecraft yet
if id == 255 or (count == 0 and id not in BIOMES):
continue
if id in BIOMES:
biome = BIOMES[id]+" (%d)" % id
else:
biome = "Unknown (%d)" % id
print(locale.format_string("%-25s %10d", (biome,count)))


def main(world_folder):
world = AnvilWorldFolder(world_folder) # Not supported for McRegion
if not world.valid(): # likely still a McRegion file
sys.stderr.write("World folder %r is empty or not an Anvil formatted world\n" % world_folder)
sys.exit(65) # EX_DATAERR
biome_totals = [0]*256 # 256 counters for 256 biome IDs

try:
for chunk in world.iter_nbt():
for biomeid in chunk["Level"]["Biomes"]:
biome_totals[biomeid] += 1

except KeyboardInterrupt:
print_results(biome_totals)
return 75 # EX_TEMPFAIL

print_results(biome_totals)
return 0 # NOERR


if __name__ == '__main__':
if (len(sys.argv) == 1):
print("No world folder specified!")
sys.exit(64) # EX_USAGE
world_folder = sys.argv[1]
if (not os.path.exists(world_folder)):
print("No such folder as "+world_folder)
sys.exit(72) # EX_IOERR

sys.exit(main(world_folder))
13 changes: 8 additions & 5 deletions examples/block_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ def print_results(block_data_totals):
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_string("%d total blocks in region, %d are solid (%0.4f", (total_blocks, solid_blocks, 100.0*solid_ratio), grouping=True)+"%)")
print(locale.format_string("%d total blocks in region, %d are non-air (%0.4f", (total_blocks, solid_blocks, 100.0*solid_ratio), grouping=True)+"%)")

# Find valuable blocks
print(locale.format_string("Diamond Ore: %8d", block_totals[56], grouping=True))
Expand All @@ -131,7 +131,7 @@ def print_results(block_data_totals):

def main(world_folder, start=None, stop=None):
if (not os.path.exists(world_folder)):
print("No such folder as "+filename)
print("No such folder as "+world_folder)
return 2 # ENOENT

regions = glob.glob(os.path.join(world_folder,'region','*.mcr'))
Expand All @@ -146,17 +146,20 @@ def main(world_folder, start=None, stop=None):

except KeyboardInterrupt:
print_results(block_data_totals)
return 4 # EINTR
return 75 # EX_TEMPFAIL

print_results(block_data_totals)
return 0 # EX_OK


if __name__ == '__main__':
if (len(sys.argv) == 1):
print("No world folder specified!")
sys.exit(22) # EINVAL
print("No world folder specified! Usage: %s <world folder> [minx,miny,minz maxx,maxy,maxz]" % sys.argv[0])
sys.exit(64) # EX_USAGE
world_folder = sys.argv[1]
if (not os.path.exists(world_folder)):
print("No such folder as "+world_folder)
sys.exit(72) # EX_IOERR
start,stop = None,None
if (len(sys.argv) == 4):
# A min/max corner was specified
Expand Down
35 changes: 10 additions & 25 deletions examples/chest_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
Finds and prints the contents of chests (including minecart chests)
"""
import locale, os, sys
import glob

# local module
try:
import nbt
Expand All @@ -13,8 +13,7 @@
if not os.path.exists(os.path.join(extrasearchpath,'nbt')):
raise
sys.path.append(extrasearchpath)
from nbt.region import RegionFile
from nbt.chunk import Chunk
from nbt.world import WorldFolder

class Position(object):
def __init__(self, x,y,z):
Expand Down Expand Up @@ -56,19 +55,6 @@ def chests_per_chunk(chunk):
entities.append(Chest("Chest",(x,y,z),items))
return entities

def process_region_file(filename):
"""Given a region filename, return the number of blocks of each ID in that file"""
chests = []
file = RegionFile(filename)

# Get all chunks
chunks = file.get_chunks()
for cc in chunks:
chunk = file.get_chunk(cc['x'], cc['z'])
leveldata = chunk['Level']
chests.extend(chests_per_chunk(leveldata))

return chests


def print_results(chests):
Expand All @@ -86,26 +72,25 @@ def print_results(chests):


def main(world_folder):
regions = glob.glob(os.path.join(world_folder,'region','*.mcr'))
world = WorldFolder(world_folder)

try:
for filename in regions:
chests = process_region_file(os.path.join(world_folder,'region',filename))
print_results(chests)

for chunk in world.iter_nbt():
print_results(chests_per_chunk(chunk["Level"]))

except KeyboardInterrupt:
return 4 # EINTR
return 75 # EX_TEMPFAIL

return 0 # NOERR


if __name__ == '__main__':
if (len(sys.argv) == 1):
print("No world folder specified!")
sys.exit(22) # EINVAL
sys.exit(64) # EX_USAGE
world_folder = sys.argv[1]
if (not os.path.exists(world_folder)):
print("No such folder as "+filename)
sys.exit(2) # ENOENT
print("No such folder as "+world_folder)
sys.exit(72) # EX_IOERR

sys.exit(main(world_folder))
12 changes: 8 additions & 4 deletions examples/map.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"""

import locale, os, sys
import glob, re, math
import re, math
from struct import pack, unpack
# local module
try:
Expand All @@ -17,7 +17,7 @@
sys.path.append(extrasearchpath)
from nbt.region import RegionFile
from nbt.chunk import Chunk
from nbt.world import WorldFolder,Format
from nbt.world import WorldFolder,McRegionWorldFolder
# PIL module (not build-in)
try:
from PIL import Image
Expand Down Expand Up @@ -175,7 +175,7 @@ def hue2rgb(v1, v2, vH):


def main(world_folder):
world = WorldFolder(world_folder, Format.MCREGION)
world = McRegionWorldFolder(world_folder) # map still only supports McRegion maps
bb = world.get_boundingbox()
map = Image.new('RGB', (16*bb.lenx(),16*bb.lenz()))
t = world.chunk_count()
Expand All @@ -199,6 +199,10 @@ def main(world_folder):
print("Saved map as %s" % filename)
except KeyboardInterrupt:
print(" aborted\n")
filename = os.path.basename(world_folder)+".partial.png"
map.save(filename,"PNG")
print("Saved map as %s" % filename)
return 75 # EX_TEMPFAIL
map.show()
return 0 # NOERR

Expand All @@ -209,7 +213,7 @@ def main(world_folder):
sys.exit(64) # EX_USAGE
world_folder = sys.argv[1]
if (not os.path.exists(world_folder)):
print("No such folder as "+filename)
print("No such folder as "+world_folder)
sys.exit(72) # EX_IOERR

sys.exit(main(world_folder))
38 changes: 9 additions & 29 deletions examples/mob_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
"""

import locale, os, sys
import glob
# local module
try:
import nbt
Expand All @@ -14,8 +13,7 @@
if not os.path.exists(os.path.join(extrasearchpath,'nbt')):
raise
sys.path.append(extrasearchpath)
from nbt.region import RegionFile
from nbt.chunk import Chunk
from nbt.world import WorldFolder

class Position(object):
def __init__(self, x,y,z):
Expand All @@ -37,23 +35,6 @@ def entities_per_chunk(chunk):
entities.append(Entity(entity["id"].value, (x.value,y.value,z.value)))
return entities

def process_region_file(filename):
"""Given a region filename, return the number of blocks of each ID in that file"""
entities = []
file = RegionFile(filename)

# Get all chunks
chunks = file.get_chunks()
print("Parsing %s... %d chunks" % (os.path.basename(filename),len(chunks)))
entities = []
for cc in chunks:
chunk = file.get_chunk(cc['x'], cc['z'])
leveldata = chunk['Level']
# chunk = Chunk(c)
entities.extend(entities_per_chunk(leveldata))

return entities


def print_results(entities):
locale.setlocale(locale.LC_ALL, 'en_US')
Expand All @@ -66,25 +47,24 @@ def print_results(entities):


def main(world_folder):
regions = glob.glob(os.path.join(world_folder,'region','*.mcr'))
world = WorldFolder(world_folder)

try:
for filename in regions:
entities = process_region_file(os.path.join(world_folder,'region',filename))
print_results(entities)

for chunk in world.iter_nbt():
print_results(entities_per_chunk(chunk["Level"]))

except KeyboardInterrupt:
return 4 # EINTR
return 75 # EX_TEMPFAIL
return 0 # NOERR


if __name__ == '__main__':
if (len(sys.argv) == 1):
print("No world folder specified!")
sys.exit(22) # EINVAL
sys.exit(64) # EX_USAGE
world_folder = sys.argv[1]
if (not os.path.exists(world_folder)):
print("No such folder as "+filename)
sys.exit(2) # ENOENT
print("No such folder as "+world_folder)
sys.exit(72) # EX_IOERR

sys.exit(main(world_folder))
6 changes: 3 additions & 3 deletions examples/seed.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,10 @@ def main(world_folder):
if __name__ == '__main__':
if (len(sys.argv) == 1):
print("No world folder specified!")
sys.exit(22) # EINVAL
sys.exit(64) # EX_USAGE
world_folder = sys.argv[1]
if (not os.path.exists(world_folder)):
print("No such folder as "+filename)
sys.exit(2) # ENOENT
print("No such folder as "+world_folder)
sys.exit(72) # EX_IOERR

sys.exit(main(world_folder))
Loading

0 comments on commit 5530efb

Please sign in to comment.