put everything through pydev's code auto-formatter

This commit is contained in:
David Vierra 2011-07-23 21:59:18 -10:00
parent 6b9e82c2e4
commit 225f813d28
12 changed files with 1228 additions and 1227 deletions

View File

@ -316,7 +316,7 @@ rotationClasses.append(PistonHead)
def masterRotationTable(rotationFunc):
# compute a 256x16 table mapping each possible blocktype/data combination to
# the resulting data when the block is rotated
table = zeros( (256, 16), dtype='uint8')
table = zeros((256, 16), dtype='uint8')
table[:] = arange(16, dtype='uint8')
for cls in rotationClasses:
for blocktype in cls.blocktypes:

View File

@ -32,7 +32,7 @@ class Entity(object):
def copyWithOffset(cls, entity, copyOffset):
eTag = deepcopy(entity)
positionTags = map(lambda p, co: nbt.TAG_Double(p.value+co), eTag["Pos"], copyOffset)
positionTags = map(lambda p, co: nbt.TAG_Double(p.value + co), eTag["Pos"], copyOffset)
eTag["Pos"] = TAG_List(positionTags)
if eTag["id"].value == "Painting":

View File

@ -91,48 +91,48 @@ class MCIndevLevel(MCLevel):
swapping to be consistent with infinite levels."""
hasEntities = True
def setPlayerSpawnPosition(self, pos, player = None):
def setPlayerSpawnPosition(self, pos, player=None):
assert len(pos) == 3
self.Spawn = array(pos);
def playerSpawnPosition(self, player = None):
def playerSpawnPosition(self, player=None):
return self.Spawn;
def setPlayerPosition(self, pos, player = "Ignored"):
def setPlayerPosition(self, pos, player="Ignored"):
for x in self.root_tag["Entities"]:
if x["id"].value == "LocalPlayer":
x["Pos"] = TAG_List([TAG_Float(p) for p in pos])
def getPlayerPosition(self, player = "Ignored"):
def getPlayerPosition(self, player="Ignored"):
for x in self.root_tag["Entities"]:
if x["id"].value == "LocalPlayer":
return array(map(lambda x:x.value, x["Pos"]));
def setPlayerOrientation(self, yp, player = "Ignored"):
def setPlayerOrientation(self, yp, player="Ignored"):
for x in self.root_tag["Entities"]:
if x["id"].value == "LocalPlayer":
x["Rotation"] = TAG_List([TAG_Float(p) for p in yp])
def playerOrientation(self, player = "Ignored"):
def playerOrientation(self, player="Ignored"):
""" returns (yaw, pitch) """
for x in self.root_tag["Entities"]:
if x["id"].value == "LocalPlayer":
return array(map(lambda x:x.value, x["Rotation"]));
def setBlockDataAt(self, x,y,z, newdata):
if x<0 or y<0 or z<0: return 0
if x>=self.Width or y>=self.Height or z>=self.Length: return 0;
self.Data[x,z,y] = (newdata & 0xf);
def setBlockDataAt(self, x, y, z, newdata):
if x < 0 or y < 0 or z < 0: return 0
if x >= self.Width or y >= self.Height or z >= self.Length: return 0;
self.Data[x, z, y] = (newdata & 0xf);
def blockDataAt(self, x, y, z):
if x<0 or y<0 or z<0: return 0
if x>=self.Width or y>=self.Height or z>=self.Length: return 0;
return self.Data[x,z,y];
if x < 0 or y < 0 or z < 0: return 0
if x >= self.Width or y >= self.Height or z >= self.Length: return 0;
return self.Data[x, z, y];
def blockLightAt(self, x, y, z):
if x<0 or y<0 or z<0: return 0
if x>=self.Width or y>=self.Height or z>=self.Length: return 0;
return self.BlockLight[x,z,y];
if x < 0 or y < 0 or z < 0: return 0
if x >= self.Width or y >= self.Height or z >= self.Length: return 0;
return self.BlockLight[x, z, y];
def __repr__(self):
return u"MCIndevLevel({0}): {1}W {2}L {3}H".format(self.filename, self.Width, self.Length, self.Height)
@ -141,13 +141,13 @@ class MCIndevLevel(MCLevel):
def _isTagLevel(cls, root_tag):
return "MinecraftLevel" == root_tag.name
def __init__(self, root_tag = None, filename = ""):
def __init__(self, root_tag=None, filename=""):
self.Width = 0
self.Height = 0
self.Length = 0
self.Blocks = array([], uint8)
self.Data = array([], uint8)
self.Spawn = (0,0,0)
self.Spawn = (0, 0, 0)
self.filename = filename;
@ -184,8 +184,8 @@ class MCIndevLevel(MCLevel):
self.TileEntities = root_tag[TileEntities]
if len(filter(lambda x:x['id'].value=='LocalPlayer', root_tag[Entities])) == 0: #omen doesn't make a player entity
p=TAG_Compound()
if len(filter(lambda x:x['id'].value == 'LocalPlayer', root_tag[Entities])) == 0: #omen doesn't make a player entity
p = TAG_Compound()
p['id'] = TAG_String('LocalPlayer')
p['Pos'] = TAG_List([TAG_Float(0.), TAG_Float(64.), TAG_Float(0.)])
p['Rotation'] = TAG_List([TAG_Float(0.), TAG_Float(45.)])
@ -194,7 +194,7 @@ class MCIndevLevel(MCLevel):
#self.saveInPlace();
else:
info( u"Creating new Indev levels is not yet implemented.!" )
info(u"Creating new Indev levels is not yet implemented.!")
raise ValueError, "Can't do that yet"
# self.SurroundingGroundHeight = root_tag[Environment][SurroundingGroundHeight].value
# self.SurroundingGroundType = root_tag[Environment][SurroundingGroundType].value
@ -217,7 +217,7 @@ class MCIndevLevel(MCLevel):
def rotateLeft(self):
MCLevel.rotateLeft(self);
self.Data = swapaxes(self.Data, 1, 0)[:,::-1,:]; #x=y; y=-x
self.Data = swapaxes(self.Data, 1, 0)[:, ::-1, :]; #x=y; y=-x
torchRotation = array([0, 4, 3, 1, 2, 5,
6, 7,
@ -225,14 +225,14 @@ class MCIndevLevel(MCLevel):
8, 9, 10, 11, 12, 13, 14, 15]);
torchIndexes = (self.Blocks == self.materials.Torch.ID)
info( u"Rotating torches: {0}".format( len(torchIndexes.nonzero()[0]) ) )
info(u"Rotating torches: {0}".format(len(torchIndexes.nonzero()[0])))
self.Data[torchIndexes] = torchRotation[self.Data[torchIndexes]]
def saveToFile(self, filename = None):
def saveToFile(self, filename=None):
if filename == None: filename = self.filename;
if filename == None:
warn( u"Attempted to save an unnamed file in place" )
warn(u"Attempted to save an unnamed file in place")
return; #you fool!
self.Data <<= 4;
@ -241,24 +241,24 @@ class MCIndevLevel(MCLevel):
self.Blocks = swapaxes(self.Blocks, 0, 2)
self.Data = swapaxes(self.Data, 0, 2)
mapTag = TAG_Compound( name=Map );
mapTag = TAG_Compound(name=Map);
mapTag[Width] = TAG_Short(self.Width);
mapTag[Height] = TAG_Short(self.Height);
mapTag[Length] = TAG_Short(self.Length);
mapTag[Blocks] = TAG_Byte_Array(self.Blocks);
mapTag[Data] = TAG_Byte_Array(self.Data);
mapTag[Data] = TAG_Byte_Array(self.Data);
self.Blocks = swapaxes(self.Blocks, 0, 2)
self.Data = swapaxes(self.Data, 0, 2)
mapTag[Spawn] = TAG_List([TAG_Short(i) for i in self.Spawn])
mapTag[Spawn] = TAG_List([TAG_Short(i) for i in self.Spawn])
self.root_tag[Map] = mapTag;
self.root_tag[Map]
#output_file = gzip.open(self.filename, "wb", compresslevel=1)
try:
os.rename(filename, filename + ".old");
except Exception,e:
except Exception, e:
pass
try:
@ -267,7 +267,7 @@ class MCIndevLevel(MCLevel):
os.rename(filename + ".old", filename);
try: os.remove(filename + ".old");
except Exception,e:
except Exception, e:
pass
self.BlockLight = self.Data & 0xf

View File

@ -257,12 +257,12 @@ items_txt = """
"""
class ItemType (object):
def __init__(self, id, name, imagefile = None, imagecoords = None, maxdamage = 0, damagevalue = 0, stacksize = 64):
self.id=id
self.name=name
self.imagefile=imagefile
self.imagecoords=imagecoords
self.maxdamage=maxdamage
def __init__(self, id, name, imagefile=None, imagecoords=None, maxdamage=0, damagevalue=0, stacksize=64):
self.id = id
self.name = name
self.imagefile = imagefile
self.imagecoords = imagecoords
self.maxdamage = maxdamage
def __repr__(self):
return "ItemType({0}, '{1}')".format(self.id, self.name)
def __str__(self):
@ -270,7 +270,7 @@ class ItemType (object):
class Items (object):
items_txt = items_txt
def __init__(self, filename = None):
def __init__(self, filename=None):
if filename is None:
items_txt = self.items_txt
else:

250
level.py
View File

@ -69,7 +69,7 @@ class MCLevel(object):
return False
def getWorldBounds(self):
return BoundingBox( (0,0,0), self.size )
return BoundingBox((0, 0, 0), self.size)
@property
def displayName(self):
@ -82,7 +82,7 @@ class MCLevel(object):
@property
def bounds(self):
return BoundingBox( (0,0,0), self.size )
return BoundingBox((0, 0, 0), self.size)
def packChunkData(self):
"""called before compression"""
@ -115,7 +115,7 @@ class MCLevel(object):
@property
def loadedChunks(self):
return itertools.product(xrange(0, self.Width+15>>4), xrange(0, self.Length+15>>4))
return itertools.product(xrange(0, self.Width + 15 >> 4), xrange(0, self.Length + 15 >> 4))
@property
def presentChunks(self):
@ -124,7 +124,7 @@ class MCLevel(object):
@property
def chunkCount(self):
return (self.Width+15>>4) * (self.Length+15>>4)
return (self.Width + 15 >> 4) * (self.Length + 15 >> 4)
@property
def allChunks(self):
@ -147,7 +147,7 @@ class MCLevel(object):
f = FakeChunk()
f.world = self;
f.chunkPosition = (cx,cz)
f.chunkPosition = (cx, cz)
f.Blocks = self.fakeBlocksForChunk(cx, cz)
@ -168,7 +168,7 @@ class MCLevel(object):
return f
def getAllChunkSlices(self):
slices = ( slice(None),slice(None),slice(None), )
slices = (slice(None), slice(None), slice(None),)
box = self.bounds
x, y, z = box.origin
@ -180,7 +180,7 @@ class MCLevel(object):
continue
yield ( chunk, slices, (xPos * 16 - x, 0, zPos * 16 - z) )
yield (chunk, slices, (xPos * 16 - x, 0, zPos * 16 - z))
def getChunkSlices(self, box):
@ -201,29 +201,29 @@ class MCLevel(object):
#when yielding slices of chunks on the edge of the box, adjust the
#slices by an offset
minxoff, minzoff = box.minx-(box.mincx<<4), box.minz-(box.mincz<<4);
maxxoff, maxzoff = box.maxx-(box.maxcx<<4)+16, box.maxz-(box.maxcz<<4)+16;
minxoff, minzoff = box.minx - (box.mincx << 4), box.minz - (box.mincz << 4);
maxxoff, maxzoff = box.maxx - (box.maxcx << 4) + 16, box.maxz - (box.maxcz << 4) + 16;
for cx in range(box.mincx, box.maxcx):
localMinX=0
localMaxX=16
if cx==box.mincx:
localMinX=minxoff
localMinX = 0
localMaxX = 16
if cx == box.mincx:
localMinX = minxoff
if cx==box.maxcx-1:
localMaxX=maxxoff
if cx == box.maxcx - 1:
localMaxX = maxxoff
newMinX = localMinX + (cx << 4) - box.minx
newMaxX = localMaxX + (cx << 4) - box.minx
for cz in range(box.mincz, box.maxcz):
localMinZ=0
localMaxZ=16
if cz==box.mincz:
localMinZ=minzoff
if cz==box.maxcz-1:
localMaxZ=maxzoff
localMinZ = 0
localMaxZ = 16
if cz == box.mincz:
localMinZ = minzoff
if cz == box.maxcz - 1:
localMaxZ = maxzoff
newMinZ = localMinZ + (cz << 4) - box.minz
newMaxZ = localMaxZ + (cz << 4) - box.minz
try:
@ -232,24 +232,24 @@ class MCLevel(object):
continue;
yield (ch,
(slice(localMinX,localMaxX),slice(localMinZ,localMaxZ),slice(box.miny,box.maxy)),
(slice(localMinX, localMaxX), slice(localMinZ, localMaxZ), slice(box.miny, box.maxy)),
(newMinX, 0, newMinZ))
ch.compress()
def containsPoint(self, x, y, z):
return (x >=0 and x < self.Width and
y >=0 and y < self.Height and
z >=0 and z < self.Length )
return (x >= 0 and x < self.Width and
y >= 0 and y < self.Height and
z >= 0 and z < self.Length)
def containsChunk(self, cx, cz):
#w+15 to allow non 16 aligned schematics
return (cx >=0 and cx < (self.Width+15 >> 4) and
cz >=0 and cz < (self.Length+15 >> 4))
return (cx >= 0 and cx < (self.Width + 15 >> 4) and
cz >= 0 and cz < (self.Length + 15 >> 4))
def chunkIsLoaded(self, cx, cz):
return self.containsChunk(cx,cz)
return self.containsChunk(cx, cz)
def chunkIsCompressed(self, cx, cz):
return False
@ -265,7 +265,7 @@ class MCLevel(object):
cxOff = cx << 4
czOff = cz << 4
b = self.Blocks[cxOff:cxOff+16, czOff:czOff+16, 0:self.Height, ];
b = self.Blocks[cxOff:cxOff + 16, czOff:czOff + 16, 0:self.Height, ];
#(w, l, h) = b.shape
#if w<16 or l<16:
# b = resize(b, (16,16,h) )
@ -277,7 +277,7 @@ class MCLevel(object):
czOff = cz << 4
if hasattr(self, "Data"):
return self.Data[cxOff:cxOff+16, czOff:czOff+16, 0:self.Height, ];
return self.Data[cxOff:cxOff + 16, czOff:czOff + 16, 0:self.Height, ];
else:
return zeros(shape=(16, 16, self.Height), dtype='uint8')
@ -287,76 +287,76 @@ class MCLevel(object):
def setSkylightAt(self, *args): pass
def setBlockDataAt(self, x,y,z, newdata): pass
def setBlockDataAt(self, x, y, z, newdata): pass
def blockDataAt(self, x, y, z): return 0;
def blockLightAt(self, x, y, z): return 15;
def blockAt(self, x, y, z):
if x<0 or y<0 or z<0: return 0
if x>=self.Width or y>=self.Height or z>=self.Length: return 0;
return self.Blocks[x,z,y]
if x < 0 or y < 0 or z < 0: return 0
if x >= self.Width or y >= self.Height or z >= self.Length: return 0;
return self.Blocks[x, z, y]
def setBlockAt(self, x, y, z, blockID):
if x<0 or y<0 or z<0: return 0
if x>=self.Width or y>=self.Height or z>=self.Length: return 0;
self.Blocks[x,z,y] = blockID
if x < 0 or y < 0 or z < 0: return 0
if x >= self.Width or y >= self.Height or z >= self.Length: return 0;
self.Blocks[x, z, y] = blockID
def blocksInRanges(self, origin, size):
# origin is (x,y,z), size is (w,h,l)
(x,y,z) = origin
(w,h,l) = size
(x, y, z) = origin
(w, h, l) = size
# end = tuple([o+s for o,s in zip(origin,size)])
return self.Blocks[x:x+w,z:z+l,y:y+h]
return self.Blocks[x:x + w, z:z + l, y:y + h]
def blockReplaceTable(self, blocksToReplace):
blocktable = zeros( (256, 16), dtype='bool')
blocktable = zeros((256, 16), dtype='bool')
for b in blocksToReplace:
if b.hasAlternate:
blocktable[b.ID,b.blockData] = True
blocktable[b.ID, b.blockData] = True
else:
blocktable[b.ID] = True
return blocktable
def fillBlocks(self, box, blockInfo, blocksToReplace = []):
def fillBlocks(self, box, blockInfo, blocksToReplace=[]):
if box is None:
box = self.bounds
else:
box = box.intersect(self.bounds)
info( u"Filling blocks in {0} with {1}, replacing{2}".format(box, blockInfo, blocksToReplace) )
info(u"Filling blocks in {0} with {1}, replacing{2}".format(box, blockInfo, blocksToReplace))
slices = map(slice, box.origin, box.maximum)
blocks = self.Blocks[slices[0],slices[2],slices[1]]
blocks = self.Blocks[slices[0], slices[2], slices[1]]
if len(blocksToReplace):
blocktable = self.blockReplaceTable(blocksToReplace)
if hasattr(self, "Data"):
data = self.Data[slices[0],slices[2],slices[1]]
mask = blocktable[blocks,data]
data = self.Data[slices[0], slices[2], slices[1]]
mask = blocktable[blocks, data]
data[mask] = blockInfo.blockData;
else:
mask = blocktable[blocks,0]
mask = blocktable[blocks, 0]
blocks[mask] = blockInfo.ID;
else:
blocks[:] = blockInfo.ID;
if hasattr(self, "Data"):
self.Data[slices[0],slices[2],slices[1]] = blockInfo.blockData;
self.Data[slices[0], slices[2], slices[1]] = blockInfo.blockData;
#self.saveInPlace();
classicWoolMask = zeros((256,), dtype='bool')
classicWoolMask[range(21, 37)] = True;
classicToAlphaWoolTypes = range(21)+[
classicToAlphaWoolTypes = range(21) + [
0xE, #"Red", (21)
0x1, #"Orange",
0x4, #"Yellow",
@ -391,23 +391,23 @@ class MCLevel(object):
return convertedBlocks, convertedBlockData
def rotateLeft(self):
self.Blocks = swapaxes(self.Blocks, 1, 0)[:,::-1,:]; #x=z; z=-x
self.Blocks = swapaxes(self.Blocks, 1, 0)[:, ::-1, :]; #x=z; z=-x
pass;
def roll(self):
self.Blocks = swapaxes(self.Blocks, 2, 0)[:,:,::-1]; #x=y; y=-x
self.Blocks = swapaxes(self.Blocks, 2, 0)[:, :, ::-1]; #x=y; y=-x
pass
def flipVertical(self):
self.Blocks = self.Blocks[:,:,::-1]; #y=-y
self.Blocks = self.Blocks[:, :, ::-1]; #y=-y
pass
def flipNorthSouth(self):
self.Blocks = self.Blocks[::-1,:,:]; #x=-x
self.Blocks = self.Blocks[::-1, :, :]; #x=-x
pass
def flipEastWest(self):
self.Blocks = self.Blocks[:,::-1,:]; #z=-z
self.Blocks = self.Blocks[:, ::-1, :]; #z=-z
pass
@ -415,7 +415,7 @@ class MCLevel(object):
def copyBlocksFromFiniteToFinite(self, sourceLevel, sourceBox, destinationPoint, blocksToCopy):
# assume destinationPoint is entirely within this level, and the size of sourceBox fits entirely within it.
sourcex, sourcey, sourcez = map(slice, sourceBox.origin, sourceBox.maximum)
destCorner2 = map(lambda a,b:a+b, sourceBox.size, destinationPoint)
destCorner2 = map(lambda a, b:a + b, sourceBox.size, destinationPoint)
destx, desty, destz = map(slice, destinationPoint, destCorner2)
sourceData = None
@ -429,7 +429,7 @@ class MCLevel(object):
mask = slice(None, None)
if not (blocksToCopy is None):
typemask = zeros( (256) , dtype='bool')
typemask = zeros((256) , dtype='bool')
typemask[blocksToCopy] = True;
mask = typemask[convertedSourceBlocks]
@ -445,18 +445,18 @@ class MCLevel(object):
if blocksToCopy is not None:
typemask = zeros( (256) , dtype='bool')
typemask = zeros((256) , dtype='bool')
typemask[blocksToCopy] = True;
for (chunk, slices, point) in chunkIterator:
point = map(lambda a,b:a+b, point, destinationPoint)
point = map(lambda a, b:a + b, point, destinationPoint)
point = point[0], point[2], point[1]
mask = slice(None, None)
convertedSourceBlocks, convertedSourceData = self.convertBlocksFromLevel(sourceLevel, chunk.Blocks[slices], chunk.Data[slices])
destSlices = [slice(p, p+s.stop-s.start) for p,s in zip(point,slices) ]
destSlices = [slice(p, p + s.stop - s.start) for p, s in zip(point, slices) ]
blocks = self.Blocks[ destSlices ];
@ -479,52 +479,52 @@ class MCLevel(object):
# if the destination box is outside the level, it and the source corners are moved inward to fit.
# ValueError is raised if the source corners are outside sourceLevel
(x,y,z) = map(int, destinationPoint)
(x, y, z) = map(int, destinationPoint)
sourceBox = BoundingBox(sourceBox.origin, sourceBox.size)
(lx,ly,lz) = sourceBox.size;
debug(u"Asked to copy {0} blocks \n\tfrom {1} in {3}\n\tto {2} in {4}" .format (ly*lz*lx,sourceBox, destinationPoint, sourceLevel, self))
(lx, ly, lz) = sourceBox.size;
debug(u"Asked to copy {0} blocks \n\tfrom {1} in {3}\n\tto {2} in {4}" .format (ly * lz * lx, sourceBox, destinationPoint, sourceLevel, self))
#clip the source ranges to this level's edges. move the destination point as needed.
#xxx abstract this
if y<0:
sourceBox.origin[1] -=y
if y < 0:
sourceBox.origin[1] -= y
sourceBox.size[1] += y
y = 0;
if y+sourceBox.size[1]>self.Height:
sourceBox.size[1] -=y+sourceBox.size[1]-self.Height
y=self.Height-sourceBox.size[1]
if y + sourceBox.size[1] > self.Height:
sourceBox.size[1] -= y + sourceBox.size[1] - self.Height
y = self.Height - sourceBox.size[1]
#for infinite levels, don't clip along those dimensions because the
#infinite copy func will just skip missing chunks
if self.Width != 0:
if x<0:
sourceBox.origin[0] -=x
if x < 0:
sourceBox.origin[0] -= x
sourceBox.size[0] += x
x = 0;
if x+sourceBox.size[0]>self.Width:
sourceBox.size[0] -=x+sourceBox.size[0]-self.Width
if x + sourceBox.size[0] > self.Width:
sourceBox.size[0] -= x + sourceBox.size[0] - self.Width
#x=self.Width-sourceBox.size[0]
if self.Length != 0:
if z<0:
sourceBox.origin[2] -=z
if z < 0:
sourceBox.origin[2] -= z
sourceBox.size[2] += z
z = 0;
if z+sourceBox.size[2]>self.Length:
sourceBox.size[2] -=z+sourceBox.size[2]-self.Length
if z + sourceBox.size[2] > self.Length:
sourceBox.size[2] -= z + sourceBox.size[2] - self.Length
#z=self.Length-sourceBox.size[2]
destinationPoint = (x,y,z)
destinationPoint = (x, y, z)
return sourceBox, destinationPoint
def copyBlocksFrom(self, sourceLevel, sourceBox, destinationPoint, blocksToCopy = None):
def copyBlocksFrom(self, sourceLevel, sourceBox, destinationPoint, blocksToCopy=None):
if (not sourceLevel.isInfinite) and not(
sourceLevel.containsPoint(*sourceBox.origin) and
sourceLevel.containsPoint(*map(lambda x:x-1, sourceBox.maximum))):
sourceLevel.containsPoint(*map(lambda x:x - 1, sourceBox.maximum))):
raise ValueError, "{0} cannot provide blocks between {1}".format(sourceLevel, sourceBox)
@ -534,7 +534,7 @@ class MCLevel(object):
print "Empty source box, aborting"
return;
info( u"Copying {0} blocks from {1} to {2}" .format (sourceBox.volume,sourceBox, destinationPoint) )
info(u"Copying {0} blocks from {1} to {2}" .format (sourceBox.volume, sourceBox, destinationPoint))
if not (sourceLevel.isInfinite):
self.copyBlocksFromFiniteToFinite(sourceLevel, sourceBox, destinationPoint, blocksToCopy)
@ -548,26 +548,26 @@ class MCLevel(object):
self.saveToFile(self.filename);
@classmethod
def setPlayerPosition(self, pos, player = "Player"):
def setPlayerPosition(self, pos, player="Player"):
pass;
def getPlayerPosition(self, player = "Player"):
return (8,self.Height*0.75,8);
def getPlayerPosition(self, player="Player"):
return (8, self.Height * 0.75, 8);
def getPlayerDimension(self, player = "Player"): return 0;
def setPlayerDimension(self, d, player = "Player"): return;
def getPlayerDimension(self, player="Player"): return 0;
def setPlayerDimension(self, d, player="Player"): return;
def setPlayerSpawnPosition(self, pos, player = None):
def setPlayerSpawnPosition(self, pos, player=None):
pass;
def playerSpawnPosition(self, player = None):
def playerSpawnPosition(self, player=None):
return self.getPlayerPosition();
def setPlayerOrientation(self, yp, player = "Player"):
def setPlayerOrientation(self, yp, player="Player"):
pass
def playerOrientation(self, player = "Player"):
return (-45.,0.)
def playerOrientation(self, player="Player"):
return (-45., 0.)
def copyEntityWithOffset(self, entity, copyOffset):
return Entity.copyWithOffset(entity, copyOffset)
@ -575,9 +575,9 @@ class MCLevel(object):
def copyTileEntityWithOffset(self, tileEntity, copyOffset):
eTag = deepcopy(tileEntity)
eTag['x'] = TAG_Int(tileEntity['x'].value+copyOffset[0])
eTag['y'] = TAG_Int(tileEntity['y'].value+copyOffset[1])
eTag['z'] = TAG_Int(tileEntity['z'].value+copyOffset[2])
eTag['x'] = TAG_Int(tileEntity['x'].value + copyOffset[0])
eTag['y'] = TAG_Int(tileEntity['y'].value + copyOffset[1])
eTag['z'] = TAG_Int(tileEntity['z'].value + copyOffset[2])
return eTag
def copyEntitiesFromInfinite(self, sourceLevel, sourceBox, destinationPoint):
@ -585,16 +585,16 @@ class MCLevel(object):
for (chunk, slices, point) in chunkIterator:
#remember, slices are ordered x,z,y so you can subscript them like so: chunk.Blocks[slices]
cx,cz = chunk.chunkPosition
wx,wz = cx<<4, cz<<4
cx, cz = chunk.chunkPosition
wx, wz = cx << 4, cz << 4
copyOffset = map(lambda x,y:x-y, destinationPoint, sourceBox.origin)
copyOffset = map(lambda x, y:x - y, destinationPoint, sourceBox.origin)
for entity in chunk.Entities:
x,y,z = map(lambda x:x.value, entity[Pos])
x, y, z = map(lambda x:x.value, entity[Pos])
if x-wx<slices[0].start or x-wx>=slices[0].stop: continue
if y<slices[2].start or y>=slices[2].stop: continue
if z-wz<slices[1].start or z-wz>=slices[1].stop: continue
if x - wx < slices[0].start or x - wx >= slices[0].stop: continue
if y < slices[2].start or y >= slices[2].stop: continue
if z - wz < slices[1].start or z - wz >= slices[1].stop: continue
eTag = self.copyEntityWithOffset(entity, copyOffset)
@ -603,10 +603,10 @@ class MCLevel(object):
for tileEntity in chunk.TileEntities:
if not 'x' in tileEntity: continue
x,y,z = tileEntity['x'].value, tileEntity['y'].value, tileEntity['z'].value
if x-wx<slices[0].start or x-wx>=slices[0].stop: continue
if y<slices[2].start or y>=slices[2].stop: continue
if z-wz<slices[1].start or z-wz>=slices[1].stop: continue
x, y, z = tileEntity['x'].value, tileEntity['y'].value, tileEntity['z'].value
if x - wx < slices[0].start or x - wx >= slices[0].stop: continue
if y < slices[2].start or y >= slices[2].stop: continue
if z - wz < slices[1].start or z - wz >= slices[1].stop: continue
eTag = self.copyTileEntityWithOffset(tileEntity, copyOffset)
@ -626,7 +626,7 @@ class MCLevel(object):
else:
entsCopied = 0;
tileEntsCopied = 0;
copyOffset = map(lambda x,y:x-y, destinationPoint, sourcePoint0)
copyOffset = map(lambda x, y:x - y, destinationPoint, sourcePoint0)
for entity in getEntitiesInRange(sourceBox, sourceLevel.Entities):
eTag = self.copyEntityWithOffset(entity, copyOffset)
@ -637,18 +637,18 @@ class MCLevel(object):
for entity in getTileEntitiesInRange(sourceBox, sourceLevel.TileEntities):
if not 'x' in entity: continue
x,y,z = entity['x'].value, entity['y'].value, entity['z'].value
x, y, z = entity['x'].value, entity['y'].value, entity['z'].value
eTag = deepcopy(entity)
eTag['x'] = TAG_Int(x+copyOffset[0])
eTag['y'] = TAG_Int(y+copyOffset[1])
eTag['z'] = TAG_Int(z+copyOffset[2])
eTag['x'] = TAG_Int(x + copyOffset[0])
eTag['y'] = TAG_Int(y + copyOffset[1])
eTag['z'] = TAG_Int(z + copyOffset[2])
try:
self.addTileEntity(eTag)
tileEntsCopied += 1;
except ChunkNotPresent:
pass
debug( u"Copied {0} entities, {1} tile entities".format(entsCopied, tileEntsCopied) )
debug(u"Copied {0} entities, {1} tile entities".format(entsCopied, tileEntsCopied))
def removeEntitiesInBox(self, box):
@ -661,7 +661,7 @@ class MCLevel(object):
newEnts.append(ent);
entsRemoved = len(self.Entities) - len(newEnts);
debug( "Removed {0} entities".format(entsRemoved))
debug("Removed {0} entities".format(entsRemoved))
self.Entities.value[:] = newEnts
@ -678,32 +678,32 @@ class MCLevel(object):
newEnts.append(ent);
entsRemoved = len(self.TileEntities) - len(newEnts);
debug( "Removed {0} tile entities".format(entsRemoved))
debug("Removed {0} tile entities".format(entsRemoved))
self.TileEntities.value[:] = newEnts
return entsRemoved
def generateLights(self, dirtyChunks = None):
def generateLights(self, dirtyChunks=None):
pass;
def adjustExtractionParameters(self, box):
x,y,z = box.origin
w,h,l = box.size
x, y, z = box.origin
w, h, l = box.size
destX = destY = destZ = 0;
if y<0:
if y < 0:
destY -= y
h += y
y = 0;
if y >= self.Height: return;
if y+h>=self.Height:
h -=y+h-self.Height
y=self.Height-h
if y + h >= self.Height:
h -= y + h - self.Height
y = self.Height - h
if h<=0: return
if h <= 0: return
if self.Width:
if x < 0:
@ -729,7 +729,7 @@ class MCLevel(object):
if l <= 0: return
box = BoundingBox ( (x,y,z), (w,h,l) )
box = BoundingBox ((x, y, z), (w, h, l))
return box, (destX, destY, destZ)
@ -738,8 +738,8 @@ def getEntitiesInRange(sourceBox, entities):
entsInRange = [];
for entity in entities:
dir()
x,y,z = Entity.pos(entity)
if not (x,y,z) in sourceBox: continue
x, y, z = Entity.pos(entity)
if not (x, y, z) in sourceBox: continue
entsInRange.append(entity)
return entsInRange
@ -749,8 +749,8 @@ def getTileEntitiesInRange(sourceBox, tileEntities):
for tileEntity in tileEntities:
if not 'x' in tileEntity: continue
x,y,z = TileEntity.pos(tileEntity)
if not (x,y,z) in sourceBox: continue
x, y, z = TileEntity.pos(tileEntity)
if not (x, y, z) in sourceBox: continue
entsInRange.append(tileEntity)
return entsInRange

View File

@ -6,7 +6,7 @@ NOTEX = (0xB0, 0x80)
class Block(object):
def __init__(self, materials, blockID, blockData = 0, **kw):
def __init__(self, materials, blockID, blockData=0, **kw):
"""
Defines a blocktype.
Keyword parameters:
@ -25,11 +25,11 @@ class Block(object):
self.name = kw.pop('name', materials.names[blockID][blockData])
self.brightness = kw.pop('brightness', materials.defaultBrightness)
self.brightness = kw.pop('brightness', materials.defaultBrightness)
self.opacity = kw.pop('opacity', materials.defaultOpacity)
self.aka = kw.pop('aka', "")
self.color = kw.pop('color', materials.flatColors[blockID,blockData])
self.color = kw.pop('color', materials.flatColors[blockID, blockData])
self.ID = blockID
self.blockData = blockData
@ -37,7 +37,7 @@ class Block(object):
def __str__(self):
return "<Block {name} ({id}:{data}) hasAlternate:{ha}>".format(
name=self.name,id=self.ID,data=self.blockData,ha=self.hasAlternate)
name=self.name, id=self.ID, data=self.blockData, ha=self.hasAlternate)
def __repr__(self):
return str(self)
@ -45,14 +45,14 @@ class Block(object):
wildcard = False
def anySubtype(self):
bl = Block( self.materials, self.ID, self.blockData )
bl = Block(self.materials, self.ID, self.blockData)
bl.wildcard = True
return bl
class MCMaterials(object):
defaultBrightness = 0
defaultOpacity = 15
defaultTexture = NOTEX
def __init__(self, defaultName = "Unused Block"):
def __init__(self, defaultName="Unused Block"):
object.__init__(self)
self.defaultName = defaultName
@ -167,7 +167,7 @@ class MCMaterials(object):
(201, 119, 240, 85), #Redstone Repeater (Off)
(201, 119, 240, 85), #Redstone Repeater (On)
])
self.flatColors[:len(defaultColors),:,:] = array(defaultColors)[:,newaxis,:]
self.flatColors[:len(defaultColors), :, :] = array(defaultColors)[:, newaxis, :]
def __repr__(self):
return "<MCMaterials ({0})>".format(self.name)
@ -176,15 +176,15 @@ class MCMaterials(object):
name = name.lower()
return [v for v in self.allBlocks if name in v.name.lower() or name in v.aka.lower()]
def blockWithID(self, id, data = 0):
if (id,data) in self.blocksByID:
return self.blocksByID[id,data]
def blockWithID(self, id, data=0):
if (id, data) in self.blocksByID:
return self.blocksByID[id, data]
else:
bl = Block(self, id, blockData=data)
bl.hasAlternate = True
return bl
def Block(self, blockID, blockData = 0, **kw):
def Block(self, blockID, blockData=0, **kw):
block = Block(self, blockID, blockData, **kw)
self.lightEmission[blockID] = block.brightness
@ -196,7 +196,7 @@ class MCMaterials(object):
texture = kw.pop('texture', None)
if texture:
self.blockTextures[blockID,(blockData or slice(None))] = texture
self.blockTextures[blockID, (blockData or slice(None))] = texture
if blockData is 0:
self.names[blockID] = [block.name] * 16
@ -216,62 +216,62 @@ class MCMaterials(object):
return block
def __cmp__(self, rhs):
return (self.ID, self.blockData).__cmp__( (rhs.ID, rhs.blockData) )
return (self.ID, self.blockData).__cmp__((rhs.ID, rhs.blockData))
###
### MATERIALS for the latest version of the game ###
###
materials = MCMaterials(defaultName = "Future Block!");
materials = MCMaterials(defaultName="Future Block!");
materials.name = "Alpha"
am = materials
am.Air = am.Block(0,
name="Air",
texture=(0x80,0xB0),
texture=(0x80, 0xB0),
opacity=0,
)
am.Stone = am.Block(1,
name="Stone",
texture=(0x10,0x00),
texture=(0x10, 0x00),
)
am.Grass = am.Block(2,
name="Grass",
texture=((0x30,0x00), (0x30,0x00), (0x00,0x00), (0x20,0x00), (0x30,0x00), (0x30,0x00)),
texture=((0x30, 0x00), (0x30, 0x00), (0x00, 0x00), (0x20, 0x00), (0x30, 0x00), (0x30, 0x00)),
)
am.Dirt = am.Block(3,
name="Dirt",
texture=(0x20,0x00),
texture=(0x20, 0x00),
)
am.Cobblestone = am.Block(4,
name="Cobblestone",
texture=(0x00,0x10),
texture=(0x00, 0x10),
)
am.WoodPlanks = am.Block(5,
name="Wood Planks",
texture=(0x40,0x00),
texture=(0x40, 0x00),
)
am.Sapling = am.Block(6,
name="Sapling",
texture=(0xF0,0x00),
texture=(0xF0, 0x00),
opacity=0,
)
am.SpruceSapling = am.Block(6, blockData=1,
name="Spruce Sapling",
texture=(0xF0,0x30),
texture=(0xF0, 0x30),
opacity=0,
)
am.BirchSapling = am.Block(6, blockData=2,
name="Birch Sapling",
texture=(0xF0,0x40),
texture=(0xF0, 0x40),
opacity=0,
)
@ -279,151 +279,151 @@ am.BirchSapling = am.Block(6, blockData=2,
am.Bedrock = am.Block(7,
name="Bedrock",
aka="Adminium",
texture=(0x10,0x10),
texture=(0x10, 0x10),
)
am.WaterActive = am.Block(8,
name="Water (active)",
texture=(0xF0,0xD0),
texture=(0xF0, 0xD0),
opacity=3,
)
am.WaterStill = am.Block(9,
name="Water (still)",
texture=(0xF0,0xD0),
texture=(0xF0, 0xD0),
opacity=3,
)
am.LavaActive = am.Block(10,
name="Lava (active)",
texture=(0xF0,0xF0),
texture=(0xF0, 0xF0),
brightness=15,
)
am.LavaStill = am.Block(11,
name="Lava (still)",
texture=(0xF0,0xF0),
texture=(0xF0, 0xF0),
brightness=15,
)
am.Sand = am.Block(12,
name="Sand",
texture=(0x20,0x10),
texture=(0x20, 0x10),
)
am.Gravel = am.Block(13,
name="Gravel",
texture=(0x30,0x10),
texture=(0x30, 0x10),
)
am.GoldOre = am.Block(14,
name="Gold Ore",
texture=(0x00,0x20),
texture=(0x00, 0x20),
)
am.IronOre = am.Block(15,
name="Iron Ore",
texture=(0x10,0x20),
texture=(0x10, 0x20),
)
am.CoalOre = am.Block(16,
name="Coal Ore",
texture=(0x20,0x20),
texture=(0x20, 0x20),
)
am.Wood = am.Block(17,
name="Wood",
texture=((0x40,0x10), (0x40,0x10), (0x50,0x10), (0x50,0x10), (0x40,0x10), (0x40,0x10)),
texture=((0x40, 0x10), (0x40, 0x10), (0x50, 0x10), (0x50, 0x10), (0x40, 0x10), (0x40, 0x10)),
)
am.Ironwood = am.Block(17, blockData=1,
name="Ironwood",
aka="Redwood",
texture=((0x40,0x70), (0x40,0x70), (0x50,0x10), (0x50,0x10), (0x40,0x70), (0x40,0x70)),
texture=((0x40, 0x70), (0x40, 0x70), (0x50, 0x10), (0x50, 0x10), (0x40, 0x70), (0x40, 0x70)),
)
am.BirchWood = am.Block(17, blockData=2,
name="Birch Wood",
texture=((0x50,0x70), (0x50,0x70), (0x50,0x10), (0x50,0x10), (0x50,0x70), (0x50,0x70)),
texture=((0x50, 0x70), (0x50, 0x70), (0x50, 0x10), (0x50, 0x10), (0x50, 0x70), (0x50, 0x70)),
)
am.Leaves = am.Block(18,
name="Leaves",
texture=(0x50,0x30),
texture=(0x50, 0x30),
opacity=1,
color=(99, 188, 76, 128),
)
am.PineLeaves = am.Block(18, blockData=1,
name="Pine Leaves",
texture=(0x50,0x80),
texture=(0x50, 0x80),
opacity=1,
color=(74, 131, 66, 128),
)
am.BirchLeaves = am.Block(18, blockData=2,
name="Birch Leaves",
texture=(0x50,0x30),
texture=(0x50, 0x30),
opacity=1,
color=(89, 151, 76, 128),
)
am.LeavesDecaying = am.Block(18, blockData=0 | 4,
name="Leaves (Decaying)",
texture=(0x50,0x30),
texture=(0x50, 0x30),
opacity=1,
)
am.PineLeavesDecaying = am.Block(18, blockData=1 | 4,
name="Pine Leaves (Decaying)",
texture=(0x50,0x80),
texture=(0x50, 0x80),
opacity=1,
color=am.PineLeaves.color
)
am.BirchLeavesDecaying = am.Block(18, blockData=2 | 4,
name="Birch Leaves (Decaying)",
texture=(0x50,0x30),
texture=(0x50, 0x30),
opacity=1,
color=am.BirchLeaves.color
)
am.Sponge = am.Block(19,
name="Sponge",
texture=(0x00,0x30),
texture=(0x00, 0x30),
)
am.Glass = am.Block(20,
name="Glass",
texture=(0x10,0x30),
texture=(0x10, 0x30),
opacity=0,
)
am.LapisLazuliOre = am.Block(21,
name="Lapis Lazuli Ore",
texture=(0x00,0xA0),
texture=(0x00, 0xA0),
)
am.LapisLazuliBlock = am.Block(22,
name="Lapis Lazuli Block",
texture=(0x00,0x90),
texture=(0x00, 0x90),
)
am.Dispenser = am.Block(23,
name="Dispenser",
texture=((0xE0,0x20), (0xE0,0x20), (0xE0,0x30), (0x10,0x00), (0xD0,0x20), (0xD0,0x20)),
texture=((0xE0, 0x20), (0xE0, 0x20), (0xE0, 0x30), (0x10, 0x00), (0xD0, 0x20), (0xD0, 0x20)),
)
am.Sandstone = am.Block(24,
name="Sandstone",
texture=((0x00,0xC0), (0x00,0xC0), (0x00,0xB0), (0x00,0xD0), (0x00,0xC0), (0x00,0xC0)),
texture=((0x00, 0xC0), (0x00, 0xC0), (0x00, 0xB0), (0x00, 0xD0), (0x00, 0xC0), (0x00, 0xC0)),
)
am.NoteBlock = am.Block(25,
name="Note Block",
texture=(0xA0,0x40),
texture=(0xA0, 0x40),
)
am.Bed = am.Block(26,
@ -457,19 +457,19 @@ am.Web = am.Block(30,
opacity=0,
)
am.UnusedShrub = am.Block(31, blockData = 0,
am.UnusedShrub = am.Block(31, blockData=0,
name="[Unused Shrub]",
texture=(0x80, 0x30),
opacity=0,
)
am.TallGrass = am.Block(31, blockData = 1,
am.TallGrass = am.Block(31, blockData=1,
name="Tall Grass",
texture=(0x70, 0x20),
opacity=0,
)
am.Shrub = am.Block(31, blockData = 2,
am.Shrub = am.Block(31, blockData=2,
name="Shrub",
texture=(0x80, 0x30),
opacity=0,
@ -499,459 +499,459 @@ am.WhiteWool = am.Block(35,
color=(0xff, 0xff, 0xff, 0xff)
)
am.OrangeWool = am.Block(35, blockData = 1,
am.OrangeWool = am.Block(35, blockData=1,
name="Orange Wool",
texture=(0x20, 0xD0),
color=(0xea, 0x7f, 0x37, 0xff)
)
am.MagentaWool = am.Block(35, blockData = 2,
am.MagentaWool = am.Block(35, blockData=2,
name="Magenta Wool",
texture=(0x20, 0xC0),
color=(0xbf, 0x4b, 0xc9, 0xff)
)
am.LightBlueWool = am.Block(35, blockData = 3,
am.LightBlueWool = am.Block(35, blockData=3,
name="Light Blue Wool",
texture=(0x20, 0xB0),
color=(0x68, 0x8b, 0xd4, 0xff)
)
am.YellowWool = am.Block(35, blockData = 4,
am.YellowWool = am.Block(35, blockData=4,
name="Yellow Wool",
texture=(0x20, 0xA0),
color=(0xc2, 0xb5, 0x1c, 0xff)
)
am.LightGreenWool = am.Block(35, blockData = 5,
am.LightGreenWool = am.Block(35, blockData=5,
name="Light Green Wool",
texture=(0x20, 0x90),
color=(0x3b, 0xbd, 0x30, 0xff)
)
am.PinkWool = am.Block(35, blockData = 6,
am.PinkWool = am.Block(35, blockData=6,
name="Pink Wool",
texture=(0x20, 0x80),
color=(0xd9, 0x83, 0x9b, 0xff)
)
am.GrayWool = am.Block(35, blockData = 7,
am.GrayWool = am.Block(35, blockData=7,
name="Gray Wool",
texture=(0x20, 0x70),
color=(0x42, 0x42, 0x42, 0xff)
)
am.LightGrayWool = am.Block(35, blockData = 8,
am.LightGrayWool = am.Block(35, blockData=8,
name="Light Gray Wool",
texture=(0x10, 0xE0),
color=(0x9e, 0xa6, 0xa6, 0xff)
)
am.CyanWool = am.Block(35, blockData = 9,
am.CyanWool = am.Block(35, blockData=9,
name="Cyan Wool",
texture=(0x10, 0xD0),
color=(0x27, 0x75, 0x95, 0xff)
)
am.PurpleWool = am.Block(35, blockData = 10,
am.PurpleWool = am.Block(35, blockData=10,
name="Purple Wool",
texture=(0x10, 0xC0),
color=(0x81, 0x36, 0xc4, 0xff)
)
am.BlueWool = am.Block(35, blockData = 11,
am.BlueWool = am.Block(35, blockData=11,
name="Blue Wool",
texture=(0x10, 0xB0),
color=(0x27, 0x33, 0xa1, 0xff)
)
am.BrownWool = am.Block(35, blockData = 12,
am.BrownWool = am.Block(35, blockData=12,
name="Brown Wool",
texture=(0x10, 0xA0),
color=(0x56, 0x33, 0x1c, 0xff)
)
am.DarkGreenWool = am.Block(35, blockData = 13,
am.DarkGreenWool = am.Block(35, blockData=13,
name="Dark Green Wool",
texture=(0x10, 0x90),
color=(0x38, 0x4d, 0x18, 0xff)
)
am.RedWool = am.Block(35, blockData = 14,
am.RedWool = am.Block(35, blockData=14,
name="Red Wool",
texture=(0x10, 0x80),
color=(0xa4, 0x2d, 0x29, 0xff)
)
am.BlackWool = am.Block(35, blockData = 15,
am.BlackWool = am.Block(35, blockData=15,
name="Black Wool",
texture=(0x10, 0x70),
color = (0, 0, 0, 0xff)
color=(0, 0, 0, 0xff)
)
am.Flower = am.Block(37,
name="Flower",
texture=(0xD0,0x00),
texture=(0xD0, 0x00),
opacity=0,
)
am.Rose = am.Block(38,
name="Rose",
texture=(0xC0,0x00),
texture=(0xC0, 0x00),
opacity=0,
)
am.BrownMushroom = am.Block(39,
name="Brown Mushroom",
texture=(0xD0,0x10),
texture=(0xD0, 0x10),
opacity=0,
brightness=1,
)
am.RedMushroom = am.Block(40,
name="Red Mushroom",
texture=(0xC0,0x10),
texture=(0xC0, 0x10),
opacity=0,
)
am.BlockofGold = am.Block(41,
name="Block of Gold",
texture=(0x70,0x10),
texture=(0x70, 0x10),
)
am.BlockofIron = am.Block(42,
name="Block of Iron",
texture=(0x60,0x10),
texture=(0x60, 0x10),
)
am.DoubleStoneSlab = am.Block(43,
name="Double Stone Slab",
texture=((0x50,0x00), (0x50,0x00), (0x60,0x00), (0x60,0x00), (0x50,0x00), (0x50,0x00)),
texture=((0x50, 0x00), (0x50, 0x00), (0x60, 0x00), (0x60, 0x00), (0x50, 0x00), (0x50, 0x00)),
)
am.DoubleSandstoneSlab = am.Block(43, blockData=1,
name="Double Sandstone Slab",
texture=((0x00,0xC0), (0x00,0xC0), (0x00,0xB0), (0x00,0xD0), (0x00,0xC0), (0x00,0xC0)),
texture=((0x00, 0xC0), (0x00, 0xC0), (0x00, 0xB0), (0x00, 0xD0), (0x00, 0xC0), (0x00, 0xC0)),
color=am.Sandstone.color,
)
am.DoubleWoodenSlab = am.Block(43, blockData=2,
name="Double Wooden Slab",
texture=(0x40,0x00),
texture=(0x40, 0x00),
color=am.WoodPlanks.color
)
am.DoubleCobblestoneSlab = am.Block(43, blockData=3,
name="Double Cobblestone Slab",
texture=(0x00,0x10),
texture=(0x00, 0x10),
)
am.StoneSlab = am.Block(44,
name="Stone Slab",
texture=((0x50,0x00), (0x50,0x00), (0x60,0x00), (0x60,0x00), (0x50,0x00), (0x50,0x00)),
texture=((0x50, 0x00), (0x50, 0x00), (0x60, 0x00), (0x60, 0x00), (0x50, 0x00), (0x50, 0x00)),
)
am.SandstoneSlab = am.Block(44, blockData=1,
name="Sandstone Slab",
texture=((0x00,0xC0), (0x00,0xC0), (0x00,0xB0), (0x00,0xD0), (0x00,0xC0), (0x00,0xC0)),
texture=((0x00, 0xC0), (0x00, 0xC0), (0x00, 0xB0), (0x00, 0xD0), (0x00, 0xC0), (0x00, 0xC0)),
color=am.Sandstone.color,
)
am.WoodenSlab = am.Block(44, blockData=2,
name="Wooden Slab",
texture=(0x40,0x00),
texture=(0x40, 0x00),
color=am.WoodPlanks.color
)
am.CobblestoneSlab = am.Block(44, blockData=3,
name="Cobblestone Slab",
texture=(0x00,0x10),
texture=(0x00, 0x10),
)
am.Brick = am.Block(45,
name="Brick",
texture=(0x70,0x00),
texture=(0x70, 0x00),
)
am.TNT = am.Block(46,
name="TNT",
texture=((0x80,0x00), (0x80,0x00), (0x90,0x00), (0xA0,0x00), (0x80,0x00), (0x80,0x00)),
texture=((0x80, 0x00), (0x80, 0x00), (0x90, 0x00), (0xA0, 0x00), (0x80, 0x00), (0x80, 0x00)),
)
am.Bookshelf = am.Block(47,
name="Bookshelf",
texture=((0x30,0x20), (0x30,0x20), (0x40,0x00), (0x40,0x00), (0x30,0x20), (0x30,0x20)),
texture=((0x30, 0x20), (0x30, 0x20), (0x40, 0x00), (0x40, 0x00), (0x30, 0x20), (0x30, 0x20)),
)
am.MossStone = am.Block(48,
name="Moss Stone",
aka="Mossy Cobblestone",
texture=(0x40,0x20),
texture=(0x40, 0x20),
)
am.Obsidian = am.Block(49,
name="Obsidian",
texture=(0x50,0x20),
texture=(0x50, 0x20),
)
am.Torch = am.Block(50,
name="Torch",
texture=(0x00,0x50),
texture=(0x00, 0x50),
brightness=14,
opacity=0,
)
am.Fire = am.Block(51,
name="Fire",
texture=(0xF0,0x10),
texture=(0xF0, 0x10),
brightness=15,
)
am.MonsterSpawner = am.Block(52,
name="Monster Spawner",
aka="Mob Cage",
texture=(0x10,0x40),
texture=(0x10, 0x40),
opacity=0,
)
am.WoodenStairs = am.Block(53,
name="Wooden Stairs",
texture=(0x40,0x00),
texture=(0x40, 0x00),
opacity=0,
)
am.Chest = am.Block(54,
name="Chest",
texture=((0xA0,0x10), (0xA0,0x10), (0xA0,0x10), (0xB0,0x10), (0x90,0x10), (0x90,0x10)),
texture=((0xA0, 0x10), (0xA0, 0x10), (0xA0, 0x10), (0xB0, 0x10), (0x90, 0x10), (0x90, 0x10)),
)
am.RedstoneWire = am.Block(55,
name="Redstone Wire",
texture=(0x40,0xA0), #note: as of 1.5 the texture is unsaturated like leaves
texture=(0x40, 0xA0), #note: as of 1.5 the texture is unsaturated like leaves
opacity=0,
)
am.DiamondOre = am.Block(56,
name="Diamond Ore",
texture=(0x20,0x30),
texture=(0x20, 0x30),
)
am.BlockofDiamond = am.Block(57,
name="Block of Diamond",
texture=(0x80,0x10),
texture=(0x80, 0x10),
)
am.CraftingTable = am.Block(58,
name="Crafting Table",
aka="Workbench",
texture=((0xB0,0x30), (0xB0,0x30), (0xB0,0x20), (0x40,0x10), (0xC0,0x30), (0xC0,0x30)),
texture=((0xB0, 0x30), (0xB0, 0x30), (0xB0, 0x20), (0x40, 0x10), (0xC0, 0x30), (0xC0, 0x30)),
)
am.Crops = am.Block(59,
name="Crops",
aka="Wheat",
texture=(0xF0,0x50),
texture=(0xF0, 0x50),
opacity=0,
)
am.Farmland = am.Block(60,
name="Farmland",
aka="Soil",
texture=(0x60,0x50),
texture=(0x60, 0x50),
)
am.Furnace = am.Block(61,
name="Furnace",
texture=((0xD0,0x20), (0xD0,0x20), (0x10,0x00), (0x10,0x00), (0xC0,0x20), (0xC0,0x20)),
texture=((0xD0, 0x20), (0xD0, 0x20), (0x10, 0x00), (0x10, 0x00), (0xC0, 0x20), (0xC0, 0x20)),
)
am.LitFurnace = am.Block(62,
name="Lit Furnace",
texture=((0xD0,0x20), (0xD0,0x20), (0x10,0x00), (0x10,0x00), (0xD0,0x30), (0xD0,0x30)),
texture=((0xD0, 0x20), (0xD0, 0x20), (0x10, 0x00), (0x10, 0x00), (0xD0, 0x30), (0xD0, 0x30)),
brightness=14,
)
am.Sign = am.Block(63,
name="Sign",
texture=(0x80,0xB0),
texture=(0x80, 0xB0),
opacity=0,
)
am.WoodenDoor = am.Block(64,
name="Wooden Door",
texture=(0x10,0x50),
texture=(0x10, 0x50),
opacity=0,
)
am.Ladder = am.Block(65,
name="Ladder",
texture=(0x30,0x50),
texture=(0x30, 0x50),
opacity=0,
)
am.Rail = am.Block(66,
name="Rail",
aka="Minecart Track",
texture=(0x00,0x80),
texture=(0x00, 0x80),
opacity=0,
)
am.StoneStairs = am.Block(67,
name="Stone Stairs",
texture=(0x00,0x10),
texture=(0x00, 0x10),
opacity=0,
)
am.WallSign = am.Block(68,
name="Wall Sign",
texture=(0x80,0xB0),
texture=(0x80, 0xB0),
opacity=0,
)
am.Lever = am.Block(69,
name="Lever",
aka="Switch",
texture=(0x80,0xB0),
texture=(0x80, 0xB0),
opacity=0,
)
am.StoneFloorPlate = am.Block(70,
name="Stone Floor Plate",
texture=(0x80,0xB0),
texture=(0x80, 0xB0),
opacity=0,
)
am.IronDoor = am.Block(71,
name="Iron Door",
texture=(0x20,0x50),
texture=(0x20, 0x50),
opacity=0,
)
am.WoodFloorPlate = am.Block(72,
name="Wood Floor Plate",
texture=(0x80,0xB0),
texture=(0x80, 0xB0),
opacity=0,
)
am.RedstoneOre = am.Block(73,
name="Redstone Ore",
texture=(0x30,0x30),
texture=(0x30, 0x30),
)
am.RedstoneOreGlowing = am.Block(74,
name="Redstone Ore (glowing)",
texture=(0x30,0x30),
texture=(0x30, 0x30),
brightness=9,
)
am.RedstoneTorchOff = am.Block(75,
name="Redstone Torch (off)",
texture=(0x30,0x70),
texture=(0x30, 0x70),
opacity=0,
)
am.RedstoneTorchOn = am.Block(76,
name="Redstone Torch (on)",
texture=(0x30,0x60),
texture=(0x30, 0x60),
opacity=0,
brightness=7,
)
am.Button = am.Block(77,
name="Button",
texture=(0x80,0xB0),
texture=(0x80, 0xB0),
opacity=0,
)
am.SnowLayer = am.Block(78,
name="Snow Layer",
texture=(0x20,0x40),
texture=(0x20, 0x40),
opacity=0,
)
am.Ice = am.Block(79,
name="Ice",
texture=(0x30,0x40),
texture=(0x30, 0x40),
opacity=3,
)
am.Snow = am.Block(80,
name="Snow",
texture=(0x20,0x40),
texture=(0x20, 0x40),
)
am.Cactus = am.Block(81,
name="Cactus",
texture=((0x60,0x40), (0x60,0x40), (0x70,0x40), (0x50,0x40), (0x60,0x40), (0x60,0x40)),
texture=((0x60, 0x40), (0x60, 0x40), (0x70, 0x40), (0x50, 0x40), (0x60, 0x40), (0x60, 0x40)),
)
am.Clay = am.Block(82,
name="Clay",
texture=(0x80,0x40),
texture=(0x80, 0x40),
)
am.SugarCane = am.Block(83,
name="Sugar Cane",
aka="Reeds, Papyrus",
texture=(0x90,0x40),
texture=(0x90, 0x40),
opacity=0,
)
am.Jukebox = am.Block(84,
name="Jukebox",
texture=((0xA0,0x40), (0xA0,0x40), (0xA0,0x40), (0xB0,0x40), (0xA0,0x40), (0xA0,0x40)),
texture=((0xA0, 0x40), (0xA0, 0x40), (0xA0, 0x40), (0xB0, 0x40), (0xA0, 0x40), (0xA0, 0x40)),
)
am.Fence = am.Block(85,
name="Fence",
texture=(0x80,0xB0),
texture=(0x80, 0xB0),
opacity=0,
)
am.Pumpkin = am.Block(86,
name="Pumpkin",
texture=((0x70,0x70), (0x60,0x70), (0x60,0x60), (0x60,0x70), (0x60,0x70), (0x60,0x70)),
texture=((0x70, 0x70), (0x60, 0x70), (0x60, 0x60), (0x60, 0x70), (0x60, 0x70), (0x60, 0x70)),
color=(0xcc, 0x77, 0x18, 0xFF)
)
am.Netherrack = am.Block(87,
name="Netherrack",
aka="Bloodstone",
texture=(0x70,0x60),
texture=(0x70, 0x60),
)
am.SoulSand = am.Block(88,
name="Soul Sand",
aka="Slow Sand",
texture=(0x80,0x60),
texture=(0x80, 0x60),
)
am.Glowstone = am.Block(89,
name="Glowstone",
texture=(0x90,0x60),
texture=(0x90, 0x60),
brightness=15,
color=(0xFF, 0xEE, 0x00, 0xFF)
)
am.NetherPortal = am.Block(90,
name="Nether Portal",
texture=(0x80,0xB0),
texture=(0x80, 0xB0),
opacity=0,
brightness=11,
)
am.JackOLantern = am.Block(91,
name="Jack-o'-Lantern",
texture=((0x80,0x70), (0x60,0x70), (0x60,0x60), (0x60,0x70), (0x60,0x70), (0x60,0x70)),
texture=((0x80, 0x70), (0x60, 0x70), (0x60, 0x60), (0x60, 0x70), (0x60, 0x70), (0x60, 0x70)),
brightness=15,
color=(0xcc, 0x77, 0x18, 0xFF)
)
am.Cake = am.Block(92,
name="Cake",
texture=((0xA0,0x70), (0xA0,0x70), (0x90,0x70), (0xC0,0x70), (0xA0,0x70), (0xA0,0x70)),
texture=((0xA0, 0x70), (0xA0, 0x70), (0x90, 0x70), (0xC0, 0x70), (0xA0, 0x70), (0xA0, 0x70)),
opacity=0,
)
@ -969,12 +969,12 @@ am.RedstoneRepeaterOn = am.Block(94,
am.AprilFoolsChest = am.Block(95,
name="April Fools Chest",
texture=((0xA0,0x10), (0xA0,0x10), (0xA0,0x10), (0xB0,0x10), (0x90,0x10), (0x90,0x10)),
texture=((0xA0, 0x10), (0xA0, 0x10), (0xA0, 0x10), (0xB0, 0x10), (0x90, 0x10), (0x90, 0x10)),
)
am.Trapdoor = am.Block(96,
name="Trapdoor",
texture=(0x10,0x50),
texture=(0x10, 0x50),
opacity=0,
)
@ -987,18 +987,18 @@ classicMaterials.lightAbsorption = materials.lightAbsorption
classicMaterials.lightEmission = materials.lightEmission
namedMaterials = dict( (i.name, i) for i in (materials, classicMaterials) )
namedMaterials = dict((i.name, i) for i in (materials, classicMaterials))
#filters certain block types in old maps to types available in /game/
blockFilterClassicToAlpha = arange(256, dtype=uint8)
b = blockFilterClassicToAlpha
b[8]=9; #water to still water
b[10]=11; #lava to still lava
b[36]=35; # the new white cloth
b[52]=9; # infinite water source - now mob spawner
b[53]=11; # infinite lava source - now wooden stair
b[55]=35; # cog - 55 is now red wire
b[8] = 9; #water to still water
b[10] = 11; #lava to still lava
b[36] = 35; # the new white cloth
b[52] = 9; # infinite water source - now mob spawner
b[53] = 11; # infinite lava source - now wooden stair
b[55] = 35; # cog - 55 is now red wire
del b;
for i in range(21, 35): blockFilterClassicToAlpha[i] = 35; # recolor all cloth to white

102
mce.py
View File

@ -80,7 +80,7 @@ class mce(object):
last_played = os.getenv("MCE_LAST_PLAYED", None)
def commandUsage(self, command):
" returns usage info for the named command - just give the docstring for the handler func "
func = getattr(self, "_"+command)
func = getattr(self, "_" + command)
return func.__doc__
commands = [
@ -158,23 +158,23 @@ class mce(object):
sourcePoint2 = self.readIntPoint(command)
sourceSize = map(operator.sub, sourcePoint2, sourcePoint)
else:
sourceSize = self.readIntPoint(command, isPoint = False)
sourceSize = self.readIntPoint(command, isPoint=False)
if len([p for p in sourceSize if p <= 0]):
raise UsageError, "Box size cannot be zero or negative"
box = BoundingBox(sourcePoint, sourceSize)
return box
def readIntPoint(self, command, isPoint = True):
def readIntPoint(self, command, isPoint=True):
point = self.readPoint(command, isPoint)
point = map(int, map(floor, point))
return point
def readPoint(self, command, isPoint = True):
def readPoint(self, command, isPoint=True):
self.prettySplit(command)
try:
word = command.pop(0)
if isPoint and (word in self.level.players):
x,y,z = self.level.getPlayerPosition(word)
x, y, z = self.level.getPlayerPosition(word)
if len(command) and command[0].lower() == "delta":
command.pop(0)
try:
@ -184,7 +184,7 @@ class mce(object):
except ValueError:
raise UsageError, "Error decoding point input (expected a number)."
return (x,y,z)
return (x, y, z)
except IndexError:
raise UsageError, "Error decoding point input (expected more values)."
@ -204,7 +204,7 @@ class mce(object):
except IndexError:
raise UsageError, "Error decoding point input (expected more values)."
return (x,y,z)
return (x, y, z)
def readBlockInfo(self, command):
keyword = command.pop(0)
@ -343,7 +343,7 @@ class mce(object):
blocksToCopy = self.readBlocksToCopy(command);
tempSchematic = self.level.extractSchematic(box);
self.level.copyBlocksFrom(tempSchematic, BoundingBox((0,0,0), box.origin), destPoint, blocksToCopy);
self.level.copyBlocksFrom(tempSchematic, BoundingBox((0, 0, 0), box.origin), destPoint, blocksToCopy);
self.needsSave = True;
print "Cloned 0 blocks."
@ -404,7 +404,7 @@ class mce(object):
print "Replacing {0} with {1}".format(blockInfo.name, newBlockInfo.name)
self.level.fillBlocks(box, newBlockInfo, blocksToReplace = [blockInfo])
self.level.fillBlocks(box, newBlockInfo, blocksToReplace=[blockInfo])
self.needsSave = True;
print "Done."
@ -434,7 +434,7 @@ class mce(object):
Also updates the level's 'SizeOnDisk' field, correcting its size in the
world select menu.
"""
blockCounts = zeros( (4096,), 'uint64')
blockCounts = zeros((4096,), 'uint64')
sizeOnDisk = 0;
print "Analyzing {0} chunks...".format(self.level.chunkCount)
@ -453,7 +453,7 @@ class mce(object):
sizeOnDisk += ch.compressedSize();
ch.unload();
if i % 100 == 0:
logging.info( "Chunk {0}...".format( i ) )
logging.info("Chunk {0}...".format(i))
for blockID in range(256):
block = self.level.materials.blockWithID(blockID, 0)
@ -467,7 +467,7 @@ class mce(object):
idstring=idstring, name=self.level.materials.blockWithID(blockID, data).name, count=blockCounts[i]);
else:
count = int(sum( blockCounts[(d<<8)+blockID] for d in range(16) ))
count = int(sum(blockCounts[(d << 8) + blockID] for d in range(16)))
if count:
idstring = "({id})".format(id=blockID)
print "{idstring:9} {name:30}: {count:<10}".format(
@ -600,7 +600,7 @@ class mce(object):
else:
filename = self.level.displayName + ".signs"
outFile = codecs.open(filename, "w", encoding = 'utf-8');
outFile = codecs.open(filename, "w", encoding='utf-8');
print "Dumping signs..."
signCount = 0;
@ -617,7 +617,7 @@ class mce(object):
outFile.write(str(map(lambda x:tileEntity[x].value, "xyz")) + "\n");
for i in range(4):
outFile.write(tileEntity["Text{0}".format(i+1)].value + u"\n");
outFile.write(tileEntity["Text{0}".format(i + 1)].value + u"\n");
if i % 100 == 0:
print "Chunk {0}...".format(i)
@ -697,12 +697,12 @@ class mce(object):
id = itemTag["id"].value
damage = itemTag["Damage"].value
item = items.findItem(id, damage)
itemname=item.name
itemname = item.name
except KeyError:
itemname="Unknown Item {0}".format(itemTag)
itemname = "Unknown Item {0}".format(itemTag)
except Exception, e:
itemname = repr(e)
outFile.write("{0} {1}\n".format(itemTag["Count"].value,itemname));
outFile.write("{0} {1}\n".format(itemTag["Count"].value, itemname));
else:
outFile.write("Empty Chest\n")
@ -756,8 +756,8 @@ class mce(object):
print "Removing all entities except Painting..."
def match(entityID): return entityID != "Painting";
for cx,cz in self.level.allChunks:
chunk = self.level.getChunk(cx,cz)
for cx, cz in self.level.allChunks:
chunk = self.level.getChunk(cx, cz)
entitiesRemoved = 0;
for entity in list(chunk.Entities):
@ -835,11 +835,11 @@ class mce(object):
box = self.readBox(command)
i=0;
for cx,cz in list(self.level.allChunks):
i = 0;
for cx, cz in list(self.level.allChunks):
if cx < box.mincx or cx >= box.maxcx or cz < box.mincz or cz >= box.maxcz:
self.level.deleteChunk(cx,cz)
i+=1;
self.level.deleteChunk(cx, cz)
i += 1;
print "Pruned {0} chunks." .format(i)
@ -852,7 +852,7 @@ class mce(object):
"""
if len(command):
box = self.readBox(command)
chunks = itertools.product(range(box.mincx, box.maxcx),range(box.mincz, box.maxcz))
chunks = itertools.product(range(box.mincx, box.maxcx), range(box.mincz, box.maxcz))
else:
chunks = self.level.allChunks
@ -887,7 +887,7 @@ class mce(object):
if mclevel.MCInfdevOldLevel.isLevel(filename):
raise IOError, "{0} is already a Minecraft Alpha world".format(filename)
level = mclevel.MCInfdevOldLevel(filename, create = True);
level = mclevel.MCInfdevOldLevel(filename, create=True);
self.level = level;
@ -946,7 +946,7 @@ class mce(object):
minutes = (timeOfDay % 1000) / 60;
print "It is {0}:{1:02} {2} on Day {3}".format(clockHours%12 or 12, minutes, ampm, days)
print "It is {0}:{1:02} {2} on Day {3}".format(clockHours % 12 or 12, minutes, ampm, days)
else:
times = { "morning":6, "noon":12, "evening":18, "midnight":24 }
word = command[0];
@ -973,7 +973,7 @@ class mce(object):
if ticks < 0: ticks += 18000
ampm = ("AM", "PM")[hours > 11 and hours < 24]
print "Changed time to {0}:{1:02} {2}".format(hours%12 or 12, minutes, ampm)
print "Changed time to {0}:{1:02} {2}".format(hours % 12 or 12, minutes, ampm)
self.level.Time = ticks
self.needsSave = True;
@ -1010,7 +1010,7 @@ class mce(object):
else:
print "\nWorld size: \n {0[0]:7} wide\n {0[1]:7} tall\n {0[2]:7} long\n".format(bounds.size);
def _heightmap(self,command):
def _heightmap(self, command):
"""
heightmap <filename>
@ -1049,57 +1049,57 @@ class mce(object):
water_level = 64
xchunks = (height+15)/16
zchunks = (width+15)/16
xchunks = (height + 15) / 16
zchunks = (width + 15) / 16
start = datetime.datetime.now()
for cx in range(xchunks):
for cz in range(zchunks):
try:
self.level.createChunk(cx,cz)
self.level.createChunk(cx, cz)
except:
pass
c = self.level.getChunk(cx,cz)
c = self.level.getChunk(cx, cz)
imgarray = numpy.asarray(greyimg.crop( (cz*16, cx*16, cz*16+16, cx*16+16) ))
imgarray = numpy.asarray(greyimg.crop((cz * 16, cx * 16, cz * 16 + 16, cx * 16 + 16)))
imgarray = imgarray / 2; #scale to 0-127
for x in range(16):
for z in range(16):
if z+(cz*16) < width-1 and x+(cx*16) < height-1:
if z + (cz * 16) < width - 1 and x + (cx * 16) < height - 1:
#world dimension X goes north-south
#first array axis goes up-down
h = imgarray[x,z]
h = imgarray[x, z]
c.Blocks[x,z,h+1:] = 0 #air
c.Blocks[x,z,h:h+1] = 2 #grass
c.Blocks[x,z,h-4:h] = 3 #dirt
c.Blocks[x,z,:h-4] = 1 #rock
c.Blocks[x, z, h + 1:] = 0 #air
c.Blocks[x, z, h:h + 1] = 2 #grass
c.Blocks[x, z, h - 4:h] = 3 #dirt
c.Blocks[x, z, :h - 4] = 1 #rock
if h < water_level:
c.Blocks[x,z,h+1:water_level] = 9 #water
if h < water_level+2:
c.Blocks[x,z,h-2:h+1] = 12 #sand if it's near water level
c.Blocks[x, z, h + 1:water_level] = 9 #water
if h < water_level + 2:
c.Blocks[x, z, h - 2:h + 1] = 12 #sand if it's near water level
c.Blocks[x,z,0] = 7 #bedrock
c.Blocks[x, z, 0] = 7 #bedrock
c.chunkChanged()
c.TerrainPopulated = False
#the quick lighting from chunkChanged has already lit this simple terrain completely
c.needsLighting = False
logging.info( "%s Just did chunk %d,%d" % (datetime.datetime.now().strftime("[%H:%M:%S]"),cx,cz) )
logging.info("%s Just did chunk %d,%d" % (datetime.datetime.now().strftime("[%H:%M:%S]"), cx, cz))
logging.info( "Done with mapping!" )
logging.info("Done with mapping!")
self.needsSave = True;
stop = datetime.datetime.now()
logging.info( "Took %s." % str(stop-start) )
logging.info("Took %s." % str(stop - start))
spawnz = width / 2
spawnx = height / 2;
spawny = greyimg.getpixel((spawnx, spawnz))
logging.info( "You probably want to change your spawn point. I suggest {0}".format( (spawnx, spawny, spawnz) ) )
logging.info("You probably want to change your spawn point. I suggest {0}".format((spawnx, spawny, spawnz)))
def _execute(self, command):
"""
@ -1109,7 +1109,7 @@ class mce(object):
if len(command) == 0:
print "You must give the file with commands to execute"
else:
commandFile = open(command[0],"r")
commandFile = open(command[0], "r")
commandsFromFile = commandFile.readlines()
for commandFromFile in commandsFromFile:
print commandFromFile
@ -1229,11 +1229,11 @@ class mce(object):
print "{idstring:9} : {name} {aka}".format(idstring=idstring, name=b.name, aka=aka)
def printUsage(self, command = ""):
def printUsage(self, command=""):
if command.lower() in self.commands:
print "Usage: ", self.commandUsage(command.lower());
else:
print self.__doc__.format(commandPrefix=("","mce.py <world> ")[not self.batchMode]);
print self.__doc__.format(commandPrefix=("", "mce.py <world> ")[not self.batchMode]);
def printUsageAndQuit(self):
@ -1344,7 +1344,7 @@ class mce(object):
elif len(matches):
print "Ambiguous command. Matches: "
for k in matches:
print " ",k;
print " ", k;
return;
else:
raise UsageError, "Command {0} not recognized.".format(keyword)

View File

@ -226,24 +226,24 @@ def fromFile(filename, loadInfinite=True):
''' The preferred method for loading Minecraft levels of any type.
pass False to loadInfinite if you'd rather not load infdev levels.
'''
info( u"Identifying " + filename )
info(u"Identifying " + filename)
class LoadingError(RuntimeError): pass
if not filename:
raise IOError, "File not found: "+filename
raise IOError, "File not found: " + filename
if not os.path.exists(filename):
raise IOError, "File not found: "+filename
raise IOError, "File not found: " + filename
if (ZipSchematic._isLevel(filename)):
info( "Zipfile found, attempting zipped infinite level" )
info("Zipfile found, attempting zipped infinite level")
lev = ZipSchematic(filename);
info( "Detected zipped Infdev level" )
info("Detected zipped Infdev level")
return lev
if (MCInfdevOldLevel._isLevel(filename)):
info( u"Detected Infdev level.dat" )
info(u"Detected Infdev level.dat")
if (loadInfinite):
return MCInfdevOldLevel(filename=filename);
else:
@ -267,7 +267,7 @@ def fromFile(filename, loadInfinite=True):
if MCJavaLevel._isDataLevel(data):
info( u"Detected Java-style level" )
info(u"Detected Java-style level")
lev = MCJavaLevel(filename, data);
lev.compressed = False;
return lev;
@ -277,8 +277,8 @@ def fromFile(filename, loadInfinite=True):
unzippedData = None;
try:
unzippedData = gunzip(rawdata)
except Exception,e:
info( u"Exception during Gzip operation, assuming {0} uncompressed: {1!r}".format(filename, e) )
except Exception, e:
info(u"Exception during Gzip operation, assuming {0} uncompressed: {1!r}".format(filename, e))
if unzippedData is None:
compressed = False;
unzippedData = rawdata
@ -286,7 +286,7 @@ def fromFile(filename, loadInfinite=True):
data = fromstring(unzippedData, dtype='uint8')
if MCJavaLevel._isDataLevel(data):
info( u"Detected compressed Java-style level" )
info(u"Detected compressed Java-style level")
lev = MCJavaLevel(filename, data);
lev.compressed = compressed;
return lev;
@ -294,8 +294,8 @@ def fromFile(filename, loadInfinite=True):
try:
root_tag = nbt.load(buf=data);
except Exception, e:
info( u"Error during NBT load: {0!r}".format(e) )
info( u"Fallback: Detected compressed flat block array, yzx ordered " )
info(u"Error during NBT load: {0!r}".format(e))
info(u"Fallback: Detected compressed flat block array, yzx ordered ")
try:
lev = MCJavaLevel(filename, data);
lev.compressed = compressed;
@ -305,14 +305,14 @@ def fromFile(filename, loadInfinite=True):
else:
if(MCIndevLevel._isTagLevel(root_tag)):
info( u"Detected Indev .mclevel" )
info(u"Detected Indev .mclevel")
return MCIndevLevel(root_tag, filename)
if(MCSchematic._isTagLevel(root_tag)):
info( u"Detected Schematic." )
info(u"Detected Schematic.")
return MCSchematic(root_tag=root_tag, filename=filename)
if (INVEditChest._isTagLevel(root_tag)):
info( u"Detected INVEdit inventory file" )
info(u"Detected INVEdit inventory file")
return INVEditChest(root_tag=root_tag, filename=filename);

20
nbt.py
View File

@ -68,9 +68,9 @@ class TAG_Value(object):
def pretty_string(self, indent=0):
if self.name:
return " "*indent + "%s( \"%s\" ): %s" % (str(self.__class__.__name__), self.name, self.value)
return " " * indent + "%s( \"%s\" ): %s" % (str(self.__class__.__name__), self.name, self.value)
else:
return " "*indent + "%s: %s" % (str(self.__class__.__name__), self.value)
return " " * indent + "%s: %s" % (str(self.__class__.__name__), self.value)
def nbt_length(self):
return struct.calcsize(self.fmt);
@ -169,14 +169,14 @@ class TAG_Byte_Array(TAG_Value):
def pretty_string(self, indent=0):
if self.name:
return " "*indent + "%s( \"%s\" ): shape=%s dtype=%s %s" % (
return " " * indent + "%s( \"%s\" ): shape=%s dtype=%s %s" % (
str(self.__class__.__name__),
self.name,
str(self.value.shape),
str(self.value.dtype),
self.value)
else:
return " "*indent + "%s: %s %s" % (str(self.__class__.__name__), str(self.value.shape), self.value)
return " " * indent + "%s: %s %s" % (str(self.__class__.__name__), str(self.value.shape), self.value)
def __init__(self, value=zeros(0, uint8), name=None, data=""):
self.name = name
@ -215,7 +215,7 @@ class TAG_Int_Array(TAG_Byte_Array):
def write_value(self, buf):
#print self.value
valuestr = self.value.tostring()
buf.write(struct.pack(self.fmt % (len(valuestr),), len(valuestr)/4, valuestr))
buf.write(struct.pack(self.fmt % (len(valuestr),), len(valuestr) / 4, valuestr))
class TAG_Short_Array(TAG_Int_Array):
"""An array of ints"""
@ -238,7 +238,7 @@ class TAG_Short_Array(TAG_Int_Array):
def write_value(self, buf):
#print self.value
valuestr = self.value.tostring()
buf.write(struct.pack(self.fmt % (len(valuestr),), len(valuestr)/2, valuestr))
buf.write(struct.pack(self.fmt % (len(valuestr),), len(valuestr) / 2, valuestr))
class TAG_String(TAG_Value):
"""String in UTF-8
@ -285,9 +285,9 @@ class TAG_Compound(TAG_Value, collections.MutableMapping):
def pretty_string(self, indent=0):
if self.name:
pretty = " "*indent + "%s( \"%s\" ):\n" % (str(self.__class__.__name__), self.name)
pretty = " " * indent + "%s( \"%s\" ):\n" % (str(self.__class__.__name__), self.name)
else:
pretty = " "*indent + "%s():\n" % (str(self.__class__.__name__))
pretty = " " * indent + "%s():\n" % (str(self.__class__.__name__))
indent += 4
for tag in self.value:
pretty += tag.pretty_string(indent) + "\n"
@ -379,9 +379,9 @@ class TAG_List(TAG_Value, collections.MutableSequence):
def pretty_string(self, indent=0):
if self.name:
pretty = " "*indent + "%s( \"%s\" ):\n" % (str(self.__class__.__name__), self.name)
pretty = " " * indent + "%s( \"%s\" ):\n" % (str(self.__class__.__name__), self.name)
else:
pretty = " "*indent + "%s():\n" % (str(self.__class__.__name__), )
pretty = " " * indent + "%s():\n" % (str(self.__class__.__name__),)
indent += 4
for tag in self.value:

View File

@ -19,7 +19,7 @@ def generate_file_list(directory):
yield os.path.join(dirpath, filename)
def sha1_file(name, checksum=None):
CHUNKSIZE=1024
CHUNKSIZE = 1024
if checksum is None:
checksum = hashlib.sha1()
if fnmatch.fnmatch(name, "*.dat"):
@ -71,7 +71,7 @@ def untared_content(src):
f.extractall(dest)
yield dest
def launch_subprocess(directory, arguments, env = {}):
def launch_subprocess(directory, arguments, env={}):
#my python breaks with an empty environ, i think it wants PATH
#if sys.platform == "win32":
newenv = {}
@ -146,13 +146,13 @@ def do_test_match_output(test_data, result_check, arguments=[]):
alpha_tests = [
(do_test, 'baseline', '9e7460d39c8e0456789cf89fee45276db2719aaa', []),
(do_test, 'degrief', '403e6c6147cf1f8d73377b18bbf5e4973606a311', ['degrief']),
(do_test_match_output, 'analyze', '89ae362dec7f6c0fd743d6ed4e3957459cb3c34d', ['analyze']),
(do_test, 'relight', 'e0cf60c62adfdb313f198af5314c31f89d158c12', ['relight']),
(do_test, 'replace', 'd73767293e903b6d1c49c1838eb1849b69d83ad8', ['replace', 'Water (active)', 'with', 'Lava (active)']),
(do_test, 'fill', 'f4f57c3d902b6894031d416cb9279232e7e24bd7', ['fill', 'Water (active)']),
(do_test, 'heightmap', '9e7460d39c8e0456789cf89fee45276db2719aaa', ['heightmap', 'regression_test/mars.png']),
(do_test, 'baseline', '9e7460d39c8e0456789cf89fee45276db2719aaa', []),
(do_test, 'degrief', '403e6c6147cf1f8d73377b18bbf5e4973606a311', ['degrief']),
(do_test_match_output, 'analyze', '89ae362dec7f6c0fd743d6ed4e3957459cb3c34d', ['analyze']),
(do_test, 'relight', 'e0cf60c62adfdb313f198af5314c31f89d158c12', ['relight']),
(do_test, 'replace', 'd73767293e903b6d1c49c1838eb1849b69d83ad8', ['replace', 'Water (active)', 'with', 'Lava (active)']),
(do_test, 'fill', 'f4f57c3d902b6894031d416cb9279232e7e24bd7', ['fill', 'Water (active)']),
(do_test, 'heightmap', '9e7460d39c8e0456789cf89fee45276db2719aaa', ['heightmap', 'regression_test/mars.png']),
]
import optparse
@ -174,19 +174,19 @@ def main(argv):
fails = []
for func, name, sha, args in alpha_tests:
print "Starting regression {0} ({1})".format( name, args )
print "Starting regression {0} ({1})".format(name, args)
if any(fnmatch.fnmatch(name, x) for x in do_these_regressions):
if options.profile:
print >>sys.stderr, "Starting to profile to %s.profile" % name
print >> sys.stderr, "Starting to profile to %s.profile" % name
os.environ['MCE_PROFILE'] = '%s.profile' % name
try:
func(test_data, sha, args)
except RegressionError, e:
fails.append( "Regression {0} failed: {1}".format(name, e) )
fails.append("Regression {0} failed: {1}".format(name, e))
print fails[-1]
else:
passes.append( "Regression {0!r} complete.".format(name) )
passes.append("Regression {0!r} complete.".format(name))
print passes[-1]
print "{0} tests passed.".format(len(passes))

View File

@ -468,6 +468,7 @@ def extractSchematicFrom(sourceLevel, box):
return tempSchematic
import tempfile
def extractZipSchematicFrom(sourceLevel, box, zipfilename):
#converts classic blocks to alpha
#probably should only apply to alpha levels