def toolSelected(self): self.editor.mouseLookOff() if self.editor.testBoardKey == 1: self.editor.testBoardKey = 0 self.loadLevel(self.createTestBoard()) return self.editor.mouseLookOff() clipFilename = mcplatform.askOpenFile(title="Import a schematic or level...", schematics=True) # xxx mouthful if clipFilename: if unicode(clipFilename).split(".")[-1] in ("schematic", "schematic.gz", "zip", "inv"): self.loadSchematic(clipFilename) elif unicode(clipFilename).split(".")[-1].lower() == "bo2": self.loadLevel(BOParser.BO2(clipFilename).getSchematic()) elif unicode(clipFilename).split(".")[-1].lower() == "bo3": self.loadLevel(BOParser.BO3(clipFilename).getSchematic()) # alert("BO3 support is currently not available") else: self.loadSchematic(clipFilename) print "Canceled" if self.level is None: print "No level selected." self.editor.toolbar.selectTool(-1)
def promptOpenAndLoad(self): try: filename = mcplatform.askOpenFile() if filename: self.mcedit.loadFile(filename) except Exception, e: logging.error('Error during proptOpenAndLoad: {0!r}'.format(e))
def toolSelected(self): self.editor.mouseLookOff() if self.editor.testBoardKey == 1: self.editor.testBoardKey = 0 self.loadLevel(self.createTestBoard()) return self.editor.mouseLookOff() clipFilename = mcplatform.askOpenFile( title='Import a schematic or level...', schematics=True) # xxx mouthful if clipFilename: if unicode(clipFilename).split(".")[-1] in ("schematic", "schematic.gz", "zip", "inv"): self.loadSchematic(clipFilename) elif unicode(clipFilename).split(".")[-1].lower() == "nbt": structure = pymclevel.schematic.StructureNBT( filename=clipFilename) self.loadLevel(structure.toSchematic()) elif unicode(clipFilename).split(".")[-1].lower() == "bo2": self.loadLevel(BOParser.BO2(clipFilename).getSchematic()) elif unicode(clipFilename).split(".")[-1].lower() == "bo3": self.loadLevel(BOParser.BO3(clipFilename).getSchematic()) # alert("BO3 support is currently not available") else: self.loadSchematic(clipFilename) print "Canceled" if self.level is None: print "No level selected." self.editor.toolbar.selectTool(-1)
def loadFile(self, fName=None): if not fName: fName = mcplatform.askOpenFile(title="Select a NBT (.dat) file...", suffixes=[ 'dat', ]) if fName: if not os.path.isfile(fName): alert("The selected object is not a file.\nCan't load it.") return dontSaveRootTag = False nbtObject = load(fName) dataKeyName = None if nbtObject.get('Data', None): dataKeyName = 'Data' elif nbtObject.get('data', None): dataKeyName = 'data' else: nbtObject.name = 'Data' dataKeyName = 'Data' dontSaveRootTag = True nbtObject = TAG_Compound([ nbtObject, ]) self.editor.currentTool = self self.showPanel(fName, nbtObject, dontSaveRootTag, dataKeyName) self.optionsPanel.dismiss()
def loadFile(fName): if not fName: fName = mcplatform.askOpenFile(title=_("Select a NBT (.dat) file..."), suffixes=['dat',]) if fName: if not os.path.isfile(fName): alert("The selected object is not a file.\nCan't load it.") return dontSaveRootTag = False nbtObject = load(fName) if fName.endswith('.schematic'): nbtObject = TAG_Compound(name='Data', value=nbtObject) dontSaveRootTag = True dataKeyName = 'Data' elif nbtObject.get('Data', None): dataKeyName = 'Data' elif nbtObject.get('data', None): dataKeyName = 'data' else: nbtObject.name = 'Data' dataKeyName = 'Data' dontSaveRootTag = True nbtObject = TAG_Compound([nbtObject,]) # dontSaveRootTag = not fName.endswith('.schematic') return nbtObject, dataKeyName, dontSaveRootTag, fName return [None,] * 4
def open_bullet_file(self): fName = mcplatform.askOpenFile(title="Choose an image file...", suffixes=['png', 'jpg', 'bmp']) if fName: config.nbtTreeSettings.bulletFileName.set(fName) self.bulletFilePath.subwidgets[1].set_text(fName) self.bulletFilePath.subwidgets[1].commit(notify=True) global bullet_image bullet_image = None
def performOLD(level, box, options): file = mcplatform.askOpenFile(title="Select the 3D Model", schematics=False) # After @GentleGiantJGC if file == None: raise Exception('No Model File Specified') print 'Start '+file (version,numModels,VOXchunks,matdefs,matlist) = parseVOXFile(file) colours= getRGBA(VOXchunks) renderModels(level,box,VOXchunks,matdefs,matlist,colours) print 'End'
def importPaste(self): """ Hack for paste to import a level. """ clipFilename = mcplatform.askOpenFile(title='Choose a schematic or level...', schematics=True) if clipFilename: try: self.loadLevel(pymclevel.fromFile(clipFilename, readonly=True)) except Exception: alert("Failed to load file %s" % clipFilename) self.brushMode = "Fill" return
def _open_file(self): file_types = [] for f_type in self.file_types: file_types.append(f_type.replace("*.", "")) file_path = mcplatform.askOpenFile(title='Select a file...', suffixes=file_types) if file_path: self._button.set_text("{filen}".format(filen=os.path.basename(file_path)), True) self.file_path = file_path else: self._button.set_text("Choose a file") self.file_path = None self._button.shrink_wrap() self.shrink_wrap()
def perform(level, box, options): global GlobalLevel GlobalLevel = level filePath = options["Convert"] if filePath == "n/a": try: filePath = askOpenFile("Select *.txt or *.docx file to convert to Book...", defaults=False, suffixes=["txt", "docx"]) except: try: openFile = win32ui.CreateFileDialog(1, None, None, 0, "All Files (*.*)|*.*|Text Files (*.txt)|*.txt|Word Files (*.docx)|*.docx|") openFile.DoModal() filePath = openFile.GetPathName() except: raise Exception("win32ui could not be imported! Please enter the file path manually.") fileName = filePath while "/" in fileName: fileName = fileName[fileName.find("/")+1:] fileExtension = fileName[fileName.find(".")+1:] if options["as the book title"]: bookTitle = options["Use"] else: bookTitle = fileName if options["Use the file name"] == "with extension": bookTitle += "." + fileExtension if filePath is None or fileName == "": raise Exception("Please select a file!") mceutils.showProgress("Generating Book", progressIter()) totalText = decodeFile(filePath, fileExtension, options) makeBook(level, box, options, totalText, bookTitle)
def toolSelected(self): self.editor.mouseLookOff() mods = pygame.key.get_mods() if mods & pygame.KMOD_ALT and mods & pygame.KMOD_SHIFT: self.loadLevel(self.createTestBoard()) return self.editor.mouseLookOff() clipFilename = mcplatform.askOpenFile(title='Import a schematic or level...', schematics=True) # xxx mouthful if clipFilename: self.loadSchematic(clipFilename) print "Canceled" if self.level is None: print "No level selected." self.editor.toolbar.selectTool(-1)
def toolSelected(self): self.editor.mouseLookOff() if self.editor.testBoardKey == 1: self.editor.testBoardKey = 0 self.loadLevel(self.createTestBoard()) return self.editor.mouseLookOff() clipFilename = mcplatform.askOpenFile(title='Import a schematic or level...', schematics=True) # xxx mouthful if clipFilename: self.loadSchematic(clipFilename) print "Canceled" if self.level is None: print "No level selected." self.editor.toolbar.selectTool(-1)
def loadFile(fName): if not fName: fName = mcplatform.askOpenFile(title=_("Select a NBT (.dat) file..."), suffixes=[ 'dat', ]) if fName: if not os.path.isfile(fName): alert("The selected object is not a file.\nCan't load it.") return savePolicy = 0 data = open(fName).read() if struct.Struct('<i').unpack(data[:4])[0] in (3, 4): if struct.Struct('<i').unpack(data[4:8])[0] != len(data[8:]): raise NBTFormatError() with littleEndianNBT(): nbtObject = load(buf=data[8:]) savePolicy = 1 elif struct.Struct('<i').unpack(data[:4])[0] in (1, 2): alert(_("Old PE level.dat, unsupported at the moment.")) else: nbtObject = load(buf=data) if fName.endswith('.schematic'): nbtObject = TAG_Compound(name='Data', value=nbtObject) savePolicy = -1 dataKeyName = 'Data' elif nbtObject.get('Data', None): dataKeyName = 'Data' elif nbtObject.get('data', None): dataKeyName = 'data' else: nbtObject.name = 'Data' dataKeyName = 'Data' if savePolicy == 0: savePolicy = -1 nbtObject = TAG_Compound([ nbtObject, ]) return nbtObject, dataKeyName, savePolicy, fName return [None] * 4
def loadFile(fName): if not fName: fName = mcplatform.askOpenFile(title=_("Select a NBT (.dat) file..."), suffixes=['dat', ]) if fName: if not os.path.isfile(fName): alert("The selected object is not a file.\nCan't load it.") return savePolicy = 0 data = open(fName).read() if struct.Struct('<i').unpack(data[:4])[0] in (3, 4): if struct.Struct('<i').unpack(data[4:8])[0] != len(data[8:]): raise NBTFormatError() with littleEndianNBT(): nbtObject = load(buf=data[8:]) savePolicy = 1 elif struct.Struct('<i').unpack(data[:4])[0] in (1, 2): alert(_("Old PE level.dat, unsupported at the moment.")) else: nbtObject = load(buf=data) if fName.endswith('.schematic'): nbtObject = TAG_Compound(name='Data', value=nbtObject) savePolicy = -1 dataKeyName = 'Data' elif nbtObject.get('Data', None): dataKeyName = 'Data' elif nbtObject.get('data', None): dataKeyName = 'data' else: nbtObject.name = 'Data' dataKeyName = 'Data' if savePolicy == 0: savePolicy = -1 nbtObject = TAG_Compound([nbtObject, ]) return nbtObject, dataKeyName, savePolicy, fName return [None] * 4
def perform(level, box, options): global colourpalletscan try: colourpalletscan except: colourpalletscan = [] if options["Mode"] == "3d Model to Schematic": filterDir = directories.getFiltersDir() kv6Path = '{}/poly2vox.exe'.format(filterDir) #checking all the required files exist and errors if they don't if not os.path.isdir(filterDir): print 'Filter Folder' print filterDir raise Exception( 'Hmm I expected a filter directory here: {}.\nIt seems you do not have a directory in that location' .format(filterDir)) if not os.path.isfile(kv6Path): print 'ploy2vox.exe Path' print kv6Path print 'The filters folder has been found but poly2vox cannot be found' raise Exception( 'poly2vox.exe should be found here: {}.'.format(kv6Path)) fileName = mcplatform.askOpenFile(title="Select the 3D Model", schematics=False) if fileName == None: raise Exception('No Model File Specified') model = fileName.split(os.sep)[-1] meshDir = os.sep.join(fileName.split(os.sep)[0:-1]) if model[-4:].lower() in [ '.obj', '.asc', '.3ds', '.md2', '.md3', '.stl' ]: shutil.copyfile(kv6Path, '{}/poly2vox.exe'.format(meshDir)) else: raise Exception('file format selected not supported') if options["3d import limits"] == "Default": argument = '{} kv6.kv6'.format(model) elif options["3d import limits"] == "Max dimension": argument = '{} kv6.kv6 /v{}'.format(model, int(options["Limit Value"])) elif options["3d import limits"] == "Scale Factor": argument = '{} kv6.kv6 /s{}'.format(model, options["Limit Value"]) defaultDir = os.getcwd() os.chdir(meshDir) #being super cautious here because I have changed the working directory which is probably a dirty thing #to do but textures won't get noticed if poly2vox is run from a different folder. It was either change the #working directory to keep everything together or put everything in the main mcedit directory which would #make a mess and be very difficult to clean up. If any step in the conversion process fails the working #directory needs to be changed back to default otherwise it will mess up MCedit and a restart of the program #would be required. print 'poly2vox {}'.format(argument) try: os.system('poly2vox {}'.format(argument)) except: os.chdir(defaultDir) raise Exception("Failure at Voxelization.") os.chdir(defaultDir) try: kv6 = binascii.hexlify( open('{}/kv6.kv6'.format(meshDir), "rb").read()) except: raise Exception("Failure to read kv6 file.") try: kv62sch(level, kv6, colourpalletscan) except: raise Exception("Failure to convert to schematic.") try: os.remove('{}/poly2vox.exe'.format(meshDir)) except: print 'Unable to remove poly2vox.exe in {}. You will have to have a look why it could not be removed'.format( meshDir) if not options["Leave kv6 (for debugging)"]: try: os.remove('{}/kv6.kv6'.format(meshDir)) except: print 'Unable to remove kv6.kv6 in {}. You will have to have a look why it could not be removed'.format( meshDir) raise Exception('Conversion Finished') if options["Mode"] == "kv6 To Schematic": fileName = mcplatform.askOpenFile(title="Select the kv6 file", schematics=False, suffixes=['kv6']) if fileName == None: raise Exception('No File Selected') kv6 = binascii.hexlify(open(fileName, "rb").read()) kv62sch(level, kv6, colourpalletscan) raise Exception('Conversion Finished') elif options["Mode"] == "Get Colour Pallet": from PIL import Image colourpalletscan = [] fileName = mcplatform.askOpenFile( title="Select an image within the folder", schematics=False) if fileName == None: raise Exception('No File Specified') filepath = os.sep.join(fileName.split(os.sep)[0:-1]) imgno = 0 imgcomp = Image.new('RGBA', (32, 16 * len(Name2ID))) for blockname in Name2ID: if os.path.isfile(filepath + os.sep + blockname + '.png'): img = Image.open(filepath + os.sep + blockname + '.png') (width, height) = img.size rtot = 0 gtot = 0 btot = 0 pixelcount = 0 for y in range(height): for x in range(width): if len(img.getpixel((x, y))) == 3: (r, g, b) = img.getpixel((x, y)) a = 255 elif len(img.getpixel((x, y))) == 4: (r, g, b, a) = img.getpixel((x, y)) else: raise exception( "soooo ... erm ... I don't quite know what this texture is" ) if a > 128: rtot += r gtot += g btot += b pixelcount += 1 ravg = rtot / pixelcount gavg = gtot / pixelcount bavg = btot / pixelcount idmg = Name2ID[blockname] imgcomp.paste(img, (0, 16 * imgno)) imgcomp.paste((ravg, gavg, bavg, 255), (16, 16 * imgno, 32, 16 * imgno + 16)) imgno += 1 print[ravg, gavg, bavg, idmg[0], idmg[1]] colourpalletscan.append([ravg, gavg, bavg, idmg[0], idmg[1]]) imgcomp.save(filepath + os.sep + 'imgcomp.png', 'PNG')
def perform(level, box, options): import WorldConverter reload(WorldConverter) answer = None try: update_data = urllib2.urlopen( 'https://raw.githubusercontent.com/gentlegiantJGC/Minecraft-World-Converter/master/version.txt' ).read().split(';') if filter_version != update_data[0]: #this part I found in the MCedit source code so credit to the MCedit team answer = albow.ask( ('Version {} is available').format(update_data[0]), ['Download', 'Ignore'], default=0, cancel=1) except: print 'Tried checking if there was an update however there was an issue' if answer == "Download": from mcplatform import platform_open platform_open(update_data[1]) raise Exception(update_data[2].replace('\\n', '\n\n')) skippedBlocks = [] convertFrom = options['Convert From'] convertTo = options['Convert To'] if convertFrom == convertTo: raise Exception( "due to some bug that I can't work out this doesn't currently work" ) # needs cleaning up (ideally idenfifying map by actual map type rather than user input?) filePath = None filePath = mcplatform.askOpenFile(title="Select a PC world to read from", schematics=False) if filePath is not None: levelOld = mclevel.fromFile(filePath) else: raise Exception('no file given') if len(list(levelOld.allChunks)) > options["Break Every"]: chunksDonePath = None chunksDonePath = mcplatform.askOpenFile( title="Select somewhere to save chunk list", schematics=False) if chunksDonePath is not None: chunksDoneFO = open(chunksDonePath).read() if chunksDoneFO == '': chunksDoneList = [] else: chunksDoneList = json.loads(chunksDoneFO) else: raise Exception('no file given') else: chunksDoneList = [] chunksDonePath = None # level.showProgress("Processed 0 chunks of {}".format(len(list(levelOld.allChunks))),) # def convertWorld chunksDone = 0 import time t = time.time() for chunkOldCoords in levelOld.allChunks: cx, cz = chunkOldCoords if [cx, cz] in chunksDoneList: chunksDone += 1 continue else: chunksDoneList.append(chunkOldCoords) chunkOld = levelOld.getChunk(cx, cz) generateChunk(level, True, cx, cz, 15) chunk = level.getChunk(cx, cz) chunk.Blocks[:] = copy.deepcopy(chunkOld.Blocks) chunk.Data[:] = copy.deepcopy(chunkOld.Data) if options["NBT"] == "Delete": for e in chunk.TileEntities[:]: del e for e in chunk.Entities[:]: del e for e in chunkOld.TileEntities: # try: # except: # pass chunk.TileEntities.append(copy.deepcopy(e)) ''' copying entities to bedrock seems to cause issues so removed this code until a fix is found for e in chunkOld.Entities: chunk.Entities.append(copy.deepcopy(e)) ''' # chunk.TileEntities = copy.deepcopy(chunkOld.TileEntities) # chunk.Entities = copy.deepcopy(chunkOld.Entities) #else: #need to work out how to copy entities across to the PC version. The above code errors # get a list of all the unique blocks chunkBlockList = np.unique(np.add(chunkOld.Blocks * 16, chunkOld.Data)) # go through every block in that list and find the converted id, data and tile entity for block in chunkBlockList: blockID = block >> 4 blockData = block % 16 blockIDNew, blockDataNew, nbtNew = WorldConverter.convertBlock( convertFrom, convertTo, blockID, blockData) # if blockIDNew is equal to -1 then there is a tile enitity requirement if blockIDNew == -1: # for every location with that block id+data combo for coord in np.argwhere( np.logical_and(chunkOld.Blocks == blockID, chunkOld.Data == blockData)): x, z, y = coord x += cx * 16 z += cz * 16 # get the tile entity te = level.tileEntityAt(x, y, z) if te is None: # if the tile entity does not exist, use fallback id blockIDNew, blockDataNew, nbtNew = WorldConverter.convertBlock( convertFrom, convertTo, blockID, blockData, fallBack=True) if nbtNew is not None: te = WorldConverter.createBlockEntity( chunk, convertTo, blockIDNew, x, y, z) else: # if it does exist blockIDNew, blockDataNew, nbtNew = WorldConverter.convertBlock( convertFrom, convertTo, blockID, blockData, te) level.setBlockAt(x, y, z, blockIDNew) level.setBlockDataAt(x, y, z, blockDataNew) if te is not None and nbtNew is not None: # merge nbtNew with tile entity for nbtToSet in nbtNew: te[nbtToSet['key']] = strToNBT['nbtType']( nbtToSet['value']) # if -2 then there was an exception elif blockIDNew == -2: # print chunkOldCoords # print block # raise Exception skippedBlocks.append((blockID, blockData)) elif blockIDNew != blockID or blockDataNew != blockData: convertTheseBlocks = np.logical_and(chunkOld.Blocks == blockID, chunkOld.Data == blockData) if blockIDNew != blockID: chunk.Blocks[convertTheseBlocks] = blockIDNew if blockDataNew != blockData: chunk.Data[convertTheseBlocks] = blockDataNew if nbtNew is not None and blockIDNew not in [-1, -2]: # for all blocks where there was not a tile entity requirement for coord in np.argwhere( np.logical_and(chunkOld.Blocks == blockID, chunkOld.Data == blockData)): x, z, y = coord x += cx * 16 z += cz * 16 # get the tile entity te = level.tileEntityAt(x, y, z) if te is None: te = WorldConverter.createBlockEntity( chunk, convertTo, blockIDNew, x, y, z) # merge nbtNew with tile entity for nbtToSet in nbtNew: te[nbtToSet['key']] = strToNBT['nbtType']( nbtToSet['value']) if blockIDNew in requiresBlockEntity[convertTo]: for coord in np.argwhere( np.logical_and(chunkOld.Blocks == blockID, chunkOld.Data == blockData)): x, z, y = coord x += cx * 16 z += cz * 16 if level.tileEntityAt(x, y, z) is None: WorldConverter.createBlockEntity( chunk, convertTo, blockIDNew, x, y, z) for te in chunk.TileEntities[:]: WorldConverter.convertBlockEntity(convertFrom, convertTo, te) for e in chunk.Entities[:]: WorldConverter.convertEntity(convertFrom, convertTo, e) # biomes if options['Biomes']: if convertFrom == 'PC': if chunkOld.root_tag and 'Level' in chunkOld.root_tag.keys( ) and 'Biomes' in chunkOld.root_tag["Level"].keys(): array = copy.deepcopy( chunkOld.root_tag["Level"]["Biomes"].value) else: array = np.ones(256) elif convertFrom == 'PE': array = np.fromstring(chunkOld.Biomes.tostring(), 'uint8') if convertTo == 'PC': if chunk.root_tag and 'Level' in chunk.root_tag.keys( ) and 'Biomes' in chunk.root_tag["Level"].keys(): chunk.root_tag["Level"]["Biomes"].value = array elif convertTo == 'PE': array.shape = (16, 16) for biomeID in np.unique(array): chunk.Biomes[array == biomeID] = biomeID # chunk.Biomes[:] = array chunk.chunkChanged() chunksDone += 1 print '{}/{}'.format(chunksDone, len(list(levelOld.allChunks))) if chunksDone % options["Break Every"] == options["Break Every"] - 1: break if skippedBlocks != []: WorldConverter.bugReport( submitThis='skippedBlocks:{}'.format(skippedBlocks)) # print skippedBlocks # for _ in levelNew.saveInPlaceGen(): # pass levelOld.close() print time.time() - t if chunksDonePath is not None: chunksDoneFO = open(chunksDonePath, 'w') json.dump(chunksDoneList, chunksDoneFO) chunksDoneFO.close()
def perform(level, box, options): forward_offset = options['Forward offset'] right_offset = options['Right offset'] up_offset = options['Up offset'] relative_position = options['Relative position'] generate_surrounding_box = options['Generate surrounding box'] if generate_surrounding_box: forward_offset += 1 up_offset += 1 if relative_position == 'North': execution_center = ((box.minx + box.maxx) // 2 - right_offset, box.miny - up_offset + 2, box.maxz + forward_offset - 1) elif relative_position == 'East': execution_center = (box.minx - forward_offset, box.miny - up_offset + 2, (box.minz + box.maxz) // 2 - right_offset) elif relative_position == 'South': execution_center = ((box.minx + box.maxx) // 2 + right_offset, box.miny - up_offset + 2, box.minz - forward_offset) elif relative_position == 'West': execution_center = (box.maxx + forward_offset - 1, box.miny - up_offset + 2, (box.minz + box.maxz) // 2 + right_offset) include_air = options['Include air'] include_blocks = options['Include blocks'] include_null_block_data = options['Include null block data'] include_entities = options['Include entities'] include_commandblockoutput_command = options['Include "gamerule commandBlockOutput false" command'] include_logadmincommands_command = options['Include "gamerule logAdminCommands false" command'] add_initialization_commands = options['Add initialization commands'] add_finalization_commands = options['Add finalization commands'] block_to_enqueue_input = re.split(r'\s*,\s*', options['Blocks to enqueue'].strip()) blocks_to_enqueue = [] for block_id in xrange(0, len(materials.block_map) - 1): if materials.block_map[block_id] in block_to_enqueue_input: blocks_to_enqueue.append(block_id) nbt_tags_to_ignore = re.split(r'\s*,\s*', options['NBT tags to ignore']) + ['x', 'y', 'z'] save_command_to_file = options['Save the command to a file instead of to a Command Block'] ignore_maximum_command_block_command_length = options['Ignore maximum Command Block command length'] box_wall_material_block = options['Box wall material block'] box_wall_material_data = options['Box wall material data value'] box_floor_material_block = options['Box floor material block'] box_floor_material_data = options['Box floor material data value'] box_ceiling_material_block = options['Box ceiling material block'] box_ceiling_material_data = options['Box ceiling material data value'] add_box_signs = options['Add box signs'] add_credits = True command = 'summon minecraft:falling_block ~ ~1 ~ {id:"minecraft:falling_block",Block:"minecraft:redstone_block",Time:1,Passengers:[{id:"minecraft:falling_block",Block:"minecraft:activator_rail",Time:1,Passengers:[' unformatted_command = command first_element = True if include_commandblockoutput_command: command_part = '{id:"minecraft:commandblock_minecart",Command:"gamerule commandBlockOutput false"}' command += '\n\t' + command_part unformatted_command += command_part first_element = False if include_logadmincommands_command: if not first_element: command += ',' unformatted_command += ',' first_element = False command_part = '{id:"minecraft:commandblock_minecart",Command:"gamerule logAdminCommands false"}' command += '\n\t' + command_part unformatted_command += command_part if add_initialization_commands: file = mcplatform.askOpenFile('Select the text file containing the initialization commands...', False, ['txt']) if file is not None: input = open(file) if input is not None: for line in input.read().splitlines(): if not first_element: command += ',' unformatted_command += ',' first_element = False command_part = '{id:"minecraft:commandblock_minecart",Command:"' + escape_string(line) + '"}' command += '\n\t' + command_part unformatted_command += command_part input.close() if include_blocks: if include_air: air_blocks = [] for x in xrange(box.minx, box.maxx): air_blocks.append([]) for y in xrange(box.miny, box.maxy): air_blocks[x - box.minx].append([]) for z in xrange(box.minz, box.maxz): air_blocks[x - box.minx][y - box.miny].append(True) for cuboid in subdivide_in_cuboids(air_blocks, 32768, False, True, False): if not first_element: command += ',' unformatted_command += ',' first_element = False if volume(cuboid[0][0], cuboid[0][1], cuboid[0][2], cuboid[1][0], cuboid[1][1], cuboid[1][2]) == 1: command_part = '{id:"minecraft:commandblock_minecart",Command:"setblock ~' + str(cuboid[0][0] + box.minx - execution_center[0]) + ' ~' + str(cuboid[0][1] + box.miny - execution_center[1]) + ' ~' + str(cuboid[0][2] + box.minz - execution_center[2]) + ' minecraft:air' else: command_part = '{id:"minecraft:commandblock_minecart",Command:"fill ~' + str(cuboid[0][0] + box.minx - execution_center[0]) + ' ~' + str(cuboid[0][1] + box.miny - execution_center[1]) + ' ~' + str(cuboid[0][2] + box.minz - execution_center[2]) + ' ~' + str(cuboid[1][0] + box.minx - execution_center[0]) + ' ~' + str(cuboid[1][1] + box.miny - execution_center[1]) + ' ~' + str(cuboid[1][2] + box.minz - execution_center[2]) + ' minecraft:air' if include_null_block_data: command_part += ' 0' command_part += '"}' command += '\n\t' + command_part unformatted_command += command_part blocks = [] for x in xrange(box.minx, box.maxx): blocks.append([]) for y in xrange(box.miny, box.maxy): blocks[x - box.minx].append([]) for z in xrange(box.minz, box.maxz): blocks[x - box.minx][y - box.miny].append((level.blockAt(x, y, z), level.blockDataAt(x, y, z), level.tileEntityAt(x, y, z))) enqueued = [] for x in xrange(0, len(blocks)): for y in xrange(0, len(blocks[x])): for z in xrange(0, len(blocks[x][y])): block = blocks[x][y][z] if block[0] >= 1: for cuboid in subdivide_in_cuboids(blocks, 32768, False, block, (-1, 0, None)): if volume(cuboid[0][0], cuboid[0][1], cuboid[0][2], cuboid[1][0], cuboid[1][1], cuboid[1][2]) == 1: command_part = '{id:"minecraft:commandblock_minecart",Command:"setblock ~' + str(cuboid[0][0] + box.minx - execution_center[0]) + ' ~' + str(cuboid[0][1] + box.miny - execution_center[1]) + ' ~' + str(cuboid[0][2] + box.minz - execution_center[2]) + ' ' + materials.block_map[block[0]] else: command_part = '{id:"minecraft:commandblock_minecart",Command:"fill ~' + str(cuboid[0][0] + box.minx - execution_center[0]) + ' ~' + str(cuboid[0][1] + box.miny - execution_center[1]) + ' ~' + str(cuboid[0][2] + box.minz - execution_center[2]) + ' ~' + str(cuboid[1][0] + box.minx - execution_center[0]) + ' ~' + str(cuboid[1][1] + box.miny - execution_center[1]) + ' ~' + str(cuboid[1][2] + box.minz - execution_center[2]) + ' ' + materials.block_map[block[0]] if include_null_block_data or block[1] != 0 or (block[1] == 0 and block[2] is not None): command_part += ' ' + str(block[1]) if block[2] is not None: command_part += ' replace ' + escape_string(nbt_to_string(block[2], nbt_tags_to_ignore)) command_part += '"}' if block[0] not in blocks_to_enqueue: if not first_element: command += ',' unformatted_command += ',' first_element = False command += '\n\t' + command_part unformatted_command += command_part else: enqueued.append(command_part) for enqueued_command in enqueued: if not first_element: command += ',' unformatted_command += ',' first_element = False command += '\n\t' + enqueued_command unformatted_command += enqueued_command if include_entities: for (chunk, slices, point) in level.getChunkSlices(box): for entity in chunk.Entities: entity_x = entity['Pos'][0].value entity_y = entity['Pos'][1].value entity_z = entity['Pos'][2].value if (entity_x, entity_y, entity_z) in box: if not first_element: command += ',' unformatted_command += ',' first_element = False command_part = '{id:"minecraft:commandblock_minecart",Command:"summon ' + str(entity['id'].value) + ' ~' + str((Decimal(entity_x - execution_center[0]) - Decimal('0.5')).normalize()) + ' ~' + str((Decimal(entity_y - execution_center[1]) - Decimal('0.0625')).normalize()) + ' ~' + str((Decimal(entity_z - execution_center[2]) - Decimal('0.5')).normalize()) + ' ' + escape_string(nbt_to_string(entity, nbt_tags_to_ignore)) + '"}' command += '\n\t' + command_part unformatted_command += command_part if generate_surrounding_box: if volume(box.minx - 1, box.miny - 1, box.minz - 1, box.maxx, box.maxy, box.maxz) <= 32768: if not first_element: command += ',' unformatted_command += ',' first_element = False command_part = '{id:"minecraft:commandblock_minecart",Command:"fill ~' + str(box.minx - 1 - execution_center[0]) + ' ~' + str(box.miny - 1 - execution_center[1]) + ' ~' + str(box.minz - 1 - execution_center[2]) + ' ~' + str(box.maxx - execution_center[0]) + ' ~' + str(box.maxy - execution_center[1]) + ' ~' + str(box.maxz - execution_center[2]) + ' ' + escape_string(box_wall_material_block) + ' ' + str(box_wall_material_data) + ' outline"}' command += '\n\t' + command_part unformatted_command += command_part else: wall_blocks = [] for x in xrange(0, box.maxx - box.minx + 2): wall_blocks.append([]) for y in xrange(0, box.maxy - box.miny): wall_blocks[x].append([]) for z in xrange(0, box.maxz - box.minz + 2): if x == 0 or x == box.maxx - box.minx + 1 or z == 0 or z == box.maxz - box.minz + 1: wall_blocks[x][y].append(True) else: wall_blocks[x][y].append(False) for cuboid in subdivide_in_cuboids(wall_blocks, 32768, False, True, False): if not first_element: command += ',' unformatted_command += ',' first_element = False command_part = '{id:"minecraft:commandblock_minecart",Command:"fill ~' + str(cuboid[0][0] - 1 + box.minx - execution_center[0]) + ' ~' + str(cuboid[0][1] + box.miny - execution_center[1]) + ' ~' + str(cuboid[0][2] - 1 + box.minz - execution_center[2]) + ' ~' + str(cuboid[1][0] - 1 + box.minx - execution_center[0]) + ' ~' + str(cuboid[1][1] + box.miny - execution_center[1]) + ' ~' + str(cuboid[1][2] - 1 + box.minz - execution_center[2]) + ' ' + escape_string(box_wall_material_block) if include_null_block_data or box_wall_material_data != 0: command_part += ' ' + str(box_wall_material_data) command_part += '"}' command += '\n\t' + command_part unformatted_command += command_part if add_box_signs: file = mcplatform.askOpenFile('Select the text file containing the signs to put on front of the box...', False, ['txt']) if file is not None: input = open(file) if input is not None: signs = OrderedDict() signs_line = 0 coordinate = (0, 0) for line in input.read().splitlines(): if signs_line == 0: if line != '': coordinates = re.split(r'\s*,\s*', line.strip()) coordinate = (int(coordinates[0]), int(coordinates[1])) signs[coordinate] = [] signs_line += 1 else: signs[coordinate].append(line) signs_line += 1 if signs_line == 9: signs_line = 0 for coordinate, sign in signs.items(): if relative_position == 'North': world_coordinate = (box.minx - 1 + coordinate[0] - execution_center[0], box.miny - 1 + coordinate[1] - execution_center[1], box.maxz + 1 - execution_center[2]) sign_data = 3 elif relative_position == 'East': world_coordinate = (box.minx - 2 - execution_center[0], box.miny - 1 + coordinate[1] - execution_center[1], box.minz - 1 + coordinate[0] - execution_center[2]) sign_data = 4 elif relative_position == 'South': world_coordinate = (box.maxx - coordinate[0] - execution_center[0], box.miny - 1 + coordinate[1] - execution_center[1], box.minz - 2 - execution_center[2]) sign_data = 2 else: world_coordinate = (box.maxx + 1 - execution_center[0], box.miny - 1 + coordinate[1] - execution_center[1], box.maxz - coordinate[0] - execution_center[2]) sign_data = 5 if not first_element: command += ',' unformatted_command += ',' first_element = False command_part = '{id:"minecraft:commandblock_minecart",Command:"setblock ~' + str(world_coordinate[0]) + ' ~' + str(world_coordinate[1]) + ' ~' + str(world_coordinate[2]) + ' minecraft:wall_sign ' + str(sign_data) + ' replace {' for i in xrange(0, min(4, len(sign))): sign_text = sign[i] sign_command = sign[i + 4] if len(sign) > i + 4 and len(sign[i + 4]) > 0 else '' if i > 0: command_part += ',' command_part += 'Text' + str(i + 1) + r':\"' if sign_text.startswith('{'): if sign_command != '': command_part += escape_string(escape_string('{"text":"","extra":[' + sign_text + ']')) else: command_part += escape_string(escape_string(sign_text)) elif sign_text.startswith('['): if sign_command != '': command_part += escape_string(escape_string('{"text":"","extra":' + sign_text)) else: command_part += escape_string(escape_string(sign_text)) elif sign_text.startswith('"'): if sign_command != '': command_part += escape_string(escape_string('{"text":' + sign_text)) else: command_part += escape_string(escape_string(sign_text)) else: if sign_command != '': command_part += escape_string(escape_string('{"text":"' + escape_string(sign_text) + '"')) else: command_part += escape_string(escape_string('"' + sign_text + '"')) if sign_command != '': command_part += escape_string(escape_string(',"clickEvent":{"action":"run_command","value":"' + escape_string(sign_command) + '"}}')) command_part += r'\"' command_part += '}"}' command += '\n\t' + command_part unformatted_command += command_part floor_ceiling_blocks = [] for x in xrange(0, box.maxx - box.minx + 2): floor_ceiling_blocks.append([]) floor_ceiling_blocks[x].append([]) for z in xrange(0, box.maxz - box.minz + 2): floor_ceiling_blocks[x][0].append(True) for cuboid in subdivide_in_cuboids(floor_ceiling_blocks, 32768, False, True, False): if not first_element: command += ',' unformatted_command += ',' first_element = False command_part = '{id:"minecraft:commandblock_minecart",Command:"fill ~' + str(cuboid[0][0] - 1 + box.minx - execution_center[0]) + ' ~' + str(cuboid[0][1] - 1 + box.miny - execution_center[1]) + ' ~' + str(cuboid[0][2] - 1 + box.minz - execution_center[2]) + ' ~' + str(cuboid[1][0] - 1 + box.minx - execution_center[0]) + ' ~' + str(cuboid[1][1] - 1 + box.miny - execution_center[1]) + ' ~' + str(cuboid[1][2] - 1 + box.minz - execution_center[2]) + ' ' + escape_string(box_floor_material_block) if include_null_block_data or box_floor_material_data != 0: command_part += ' ' + str(box_floor_material_data) command_part += '"}' command += '\n\t' + command_part unformatted_command += command_part command_part = '{id:"minecraft:commandblock_minecart",Command:"fill ~' + str(cuboid[0][0] - 1 + box.minx - execution_center[0]) + ' ~' + str(cuboid[0][1] + box.maxy - execution_center[1]) + ' ~' + str(cuboid[0][2] - 1 + box.minz - execution_center[2]) + ' ~' + str(cuboid[1][0] - 1 + box.minx - execution_center[0]) + ' ~' + str(cuboid[1][1] + box.maxy - execution_center[1]) + ' ~' + str(cuboid[1][2] - 1 + box.minz - execution_center[2]) + ' ' + escape_string(box_ceiling_material_block) if include_null_block_data or box_ceiling_material_data != 0: command_part += ' ' + str(box_ceiling_material_data) command_part += '"}' command += ',\n\t' + command_part unformatted_command += ',' + command_part if add_finalization_commands: file = mcplatform.askOpenFile('Select the text file containing the finalization commands...', False, ['txt']) if file is not None: input = open(file) if input is not None: for line in input.read().splitlines(): if not first_element: command += ',' unformatted_command += ',' first_element = False command_part = '{id:"minecraft:commandblock_minecart",Command:"' + escape_string(line) + '"}' command += '\n\t' + command_part unformatted_command += command_part input.close() if add_credits: if not first_element: command += ',' unformatted_command += ',' first_element = False command_part = '{id:"minecraft:commandblock_minecart",Command:"' + escape_string('tellraw @p {"color":"yellow","text":"Generated with Mamo\'s ","extra":[{"color":"blue","underlined":true,"text":"Structure spawner generator","clickEvent":{"action":"open_url","value":"https://github.com/xMamo/Structure-spawner-generator"},"hoverEvent":{"action":"show_text","value":"Click here if you want this filter too!"}},"."]}') + '"}' command += '\n\t' + command_part unformatted_command += command_part if not first_element: command += ',' unformatted_command += ',' command_part = r'{id:"minecraft:commandblock_minecart",Command:"setblock ~ ~1 ~ minecraft:command_block 0 replace {auto:1b,Command:\"fill ~ ~-3 ~ ~ ~ ~ minecraft:air' if include_null_block_data: command_part += ' 0' command_part += r'\"}"}' command += '\n\t' + command_part unformatted_command += command_part command_part = '{id:"minecraft:commandblock_minecart",Command:"kill @e[type=minecraft:commandblock_minecart,r=0]"}' command += ",\n\t" + command_part + '\n]}]}' unformatted_command += "," + command_part + ']}]}' if not ignore_maximum_command_block_command_length and len(unformatted_command) > 32500: editor.Notify('Unfortunately no command could be generated, as it would be longer than the Command Block command length limit of 32500 characters.') return command_output = None if save_command_to_file: output_file = mcplatform.askSaveFile(None, 'Select the text file to which you want to save the command...', 'command.txt', 'Text file (*.txt)\0*.txt\0\0', None) if output_file is not None: command_output = open(output_file, mode = 'w') if save_command_to_file and command_output is not None: command_output.write((command + '\n').encode('UTF-8')) command_output.flush() command_output.close() else: schematic = MCSchematic((1, 1, 1), None, None, level.materials) schematic.setBlockAt(0, 0, 0, 137) command_block = TAG_Compound() command_block['id'] = TAG_String('minecraft:command_block') command_block['x'] = TAG_Int(0) command_block['y'] = TAG_Int(0) command_block['z'] = TAG_Int(0) command_block['Command'] = TAG_String(unformatted_command) schematic.addTileEntity(command_block) editor.addCopiedSchematic(schematic)
def open_bullet_file(self): fName = mcplatform.askOpenFile(title="Choose an image file...", suffixes=['png', 'jpg', 'bmp']) if fName: config.nbtTreeSettings.bulletFileName.set(fName)
def promptOpenAndLoad(self): #!# Bad! But used to test the file chooser. # try: filename = mcplatform.askOpenFile() if filename: self.mcedit.loadFile(filename)
def perform(level, box, options): try: level.gamePlatform except: raise Exception( 'This filter requires level.gamePlatform. You will need a version of MCedit that has this' ) global idcount nearest = options[ "Use Nearest-Color Transparency (recommended for lossy image formats):"] tmode = options["Transparency Mode:"] tcolor = options["Transparency Color:"] if tmode == "Use Default Color (#FF00FF)": transparent = (255, 0, 255) elif tmode == "User-Specified Color Below": if tcolor[0] == "#": alphacolor = int(tcolor[1:7], 16) transparent = (alphacolor >> 16, (alphacolor >> 8) & 0xff, alphacolor & 0xff) else: raise Exception( "ERROR! The provided transparency color was formatted incorrectly! Colors must in hexadecimal format, in the form #RRGGBB" ) return else: transparent = None invulnerable = options["Item Frames are invulnerable:"] imgpath = options["Image path:"] facing = options["Item Frames are facing:"] backing = options["Item Frame backing block (replaces air blocks only):"] if backing.ID == 0: raise Exception("ERROR! The backing block CANNOT be air!") return toosmall = options["If selection is too small for image size:"] if level.gamePlatform == 'Java': if level.dimNo: datafolder = level.parentWorld.worldFolder.getFolderPath("data") else: datafolder = level.worldFolder.getFolderPath("data") if not os.path.exists(datafolder): try: os.makedirs(datafolder) except: raise OSError( "ERROR! Data folder does not exist and could not be created. Please create a \"data\" folder at: " + datafolder) return idcountpath = os.path.join(datafolder, "idcounts.dat") if os.path.exists(idcountpath): idcountfile = nbt.load(idcountpath) if "map" in idcountfile: idcount = idcountfile["map"].value else: idcount = 0 idcountfile["map"] = TAG_Short(0) else: idcount = 0 idcountfile = TAG_Compound() idcountfile["map"] = TAG_Short(0) elif level.gamePlatform == 'PE': try: with level.worldFile.world_db() as db: rop = level.worldFile.readOptions idcountfile = loadNBTCompoundList(db.Get(rop, 'MCeditMapIt'))[0] if "map" in idcountfile: idcount = idcountfile["map"].value else: idcount = 0 idcountfile["map"] = TAG_Long(0) except: idcount = 0 idcountfile = TAG_Compound() idcountfile["map"] = TAG_Long(0) if imgpath != "None": if os.path.exists(imgpath): image_path = imgpath else: image_path = mcplatform.askOpenFile(title="Select an Image", schematics=False) else: image_path = mcplatform.askOpenFile(title="Select an Image", schematics=False) if image_path == None: raise Exception("ERROR: No file provided!") return surface = pygame.image.load(image_path) # Adrian Brightmoore # Modification to allow auto-resize to selection dimensions sx, sy, sz = box.size xsize, ysize, zsize = box.size * 128 if toosmall == "Scale to selection": if (facing == "Eastwards (-X to +X)" or facing == "Westwards (+X to -X)"): surface = pygame.transform.smoothscale(surface, (zsize, ysize)) elif (facing == "Northwards (+Z to -Z)" or facing == "Southwards (-Z to +Z)"): surface = pygame.transform.smoothscale(surface, (xsize, ysize)) (height, width) = surface.get_size() # End modification to allow auto-resize to selection dimensions loopx = int(math.ceil(float(width) / 128.0)) loopy = int(math.ceil(float(height) / 128.0)) if level.gamePlatform == 'Java': if (loopx * loopy) + idcount > 32767: raise Exception( "\nERROR! The image size is too large or there are not enough maps left for this world.\n" "Only 32,767 map files are allowed per world, and there are", idcount, "maps in this world.\n" "The image specified requires", (loopx * loopy), "maps.\n") return # elif level.gamePlatform == 'PE': # could do similar code to above but the limit is 2^63 rather than 2^15 so it will never be reached ever chestorframe = "item frames" if ysize < width: if toosmall == "Cancel Image Processing": raise Exception( "\nERROR! The selection height is too small! Your selection should be at least " + str(loopx) + "H in size.\n" "\n" "Cancelled image processing.") else: print "Creating chests instead of Item Frames" chestorframe = "chests" if chestorframe == "item frames" and (facing == "Eastwards (-X to +X)" or facing == "Westwards (+X to -X)"): if zsize < height or sx < 2: if toosmall == "Cancel Image Processing": raise Exception( "\nERROR! The selection size is too small; it selection should be at least\n" "2W x " + str(loopy) + "L x " + str(loopx) + "H in size.\n" "\n" "Cancelled image processing.") else: print "Creating chests instead of Item Frames" chestorframe = "chests" elif chestorframe == "item frames" and (facing == "Northwards (+Z to -Z)" or facing == "Southwards (-Z to +Z)"): if xsize < height or sz < 2: if toosmall == "Cancel Image Processing": raise Exception( "\nERROR! The selection size is too small; it should be at least\n" "" + str(loopy) + "W x 2L x " + str(loopx) + "H in size.\n" "\n" "Cancelled image processing.") else: print "Creating chests instead of Item Frames" chestorframe = "chests" image = numpy.fromstring(pygame.image.tostring(surface, "RGB"), dtype=numpy.uint8).reshape(width, height, 3) progresscount = 1 progressmax = loopx * loopy startid = idcount + 1 def processImageJava(image, loopx, loopy, width, height, cache, transparent, nearest, image_path, progresscount, progressmax): global idcount for lx in xrange(loopx): for ly in xrange(loopy): yield idcount - 1, progressmax, "of image " + image_path progresscount += 1 idcount += 1 converted = numpy.zeros((128, 128), dtype=numpy.uint8) offsetx = lx * 128 offsety = ly * 128 for x in xrange(128): for y in xrange(128): if (offsetx + x) >= width: break elif (offsety + y) >= height: break r, g, b = (image[offsetx + x, offsety + y, 0], image[offsetx + x, offsety + y, 1], image[offsetx + x, offsety + y, 2]) if (r, g, b) in cache: converted[x, y] = cache[(r, g, b)] else: converted[x, y] = FindClosestPaletteIndex( r, g, b, transparent, nearest) if (offsetx + x) >= width: break CreateNewMapFileJava(datafolder, idcount, converted) def processImagePE(image, loopx, loopy, width, height, image_path, progresscount, progressmax): global idcount for lx in xrange(loopx): for ly in xrange(loopy): yield idcount - 1, progressmax, "of image " + image_path progresscount += 1 idcount += 1 print idcount converted = numpy.zeros((65536), dtype=numpy.uint8) offsetx = lx * 128 offsety = ly * 128 for x in xrange(128): for y in xrange(128): if (offsetx + x) >= width: break elif (offsety + y) >= height: break r, g, b = (image[offsetx + x, offsety + y, 0], image[offsetx + x, offsety + y, 1], image[offsetx + x, offsety + y, 2]) converted[4 * (x * 128 + y)] = r converted[4 * (x * 128 + y) + 1] = g converted[4 * (x * 128 + y) + 2] = b converted[4 * (x * 128 + y) + 3] = 255 if (offsetx + x) >= width: break CreateNewMapFilePE(level, idcount, converted) if level.gamePlatform == 'Java': level.showProgress( "Processing image pieces:", processImageJava(image, loopx, loopy, width, height, cache, transparent, nearest, image_path, progresscount, progressmax)) elif level.gamePlatform == 'PE': level.showProgress( "Processing image pieces:", processImagePE(image, loopx, loopy, width, height, image_path, progresscount, progressmax)) print idcount endid = idcount print endid if level.gamePlatform == 'Java': idcountfile["map"] = TAG_Short(idcount) idcountfile.save(idcountpath, compressed=False) elif level.gamePlatform == 'PE': idcountfile["map"] = TAG_Long(idcount) with level.worldFile.world_db() as db: wop = level.worldFile.writeOptions with nbt.littleEndianNBT(): db.Put(wop, 'MCeditMapIt', idcountfile.save(compressed=False)) print "Finished processing image " + image_path + ". Creating " + chestorframe + "..." if chestorframe == "item frames": if level.gamePlatform == 'Java': if facing == "Northwards (+Z to -Z)" or facing == "Southwards (-Z to +Z)": if facing == "Northwards (+Z to -Z)": dir = 0 posIncrement = False else: dir = 2 posIncrement = True else: if facing == "Eastwards (-X to +X)": dir = 3 posIncrement = True else: dir = 1 posIncrement = False if facing == "Northwards (+Z to -Z)" or facing == "Southwards (-Z to +Z)": z = box.minz if posIncrement: z += 1 for y in xrange(box.miny - 1 + loopx, box.miny - 1, -1): for x in xrange(box.minx, box.minx + loopy) if posIncrement else xrange( box.minx - 1 + loopy, box.minx - 1, -1): level.setBlockAt(x, y, z, 0) level.setBlockDataAt(x, y, z, 0) if level.blockAt(x, y, z + (-1 if posIncrement else 1)) == 0: level.setBlockAt(x, y, z + (-1 if posIncrement else 1), backing.ID) level.setBlockDataAt( x, y, z + (-1 if posIncrement else 1), backing.blockData) chunk = level.getChunk(x >> 4, z >> 4) chunk.Entities.append( CreateItemFrameJava(x, y, z, dir, startid, invulnerable)) chunk.dirty = True startid += 1 elif facing == "Eastwards (-X to +X)" or facing == "Westwards (+X to -X)": x = box.minx if posIncrement: x += 1 for y in xrange(box.miny - 1 + loopx, box.miny - 1, -1): for z in xrange(box.minz, box.minz + loopy) if not posIncrement else xrange( box.minz - 1 + loopy, box.minz - 1, -1): level.setBlockAt(x, y, z, 0) level.setBlockDataAt(x, y, z, 0) if level.blockAt(x + (-1 if posIncrement else 1), y, z) == 0: level.setBlockAt(x + (-1 if posIncrement else 1), y, z, backing.ID) level.setBlockDataAt( x + (-1 if posIncrement else 1), y, z, backing.blockData) chunk = level.getChunk(x >> 4, z >> 4) chunk.Entities.append( CreateItemFrameJava(x, y, z, dir, startid, invulnerable)) chunk.dirty = True startid += 1 elif level.gamePlatform == 'PE': if facing == "Northwards (+Z to -Z)" or facing == "Southwards (-Z to +Z)": if facing == "Northwards (+Z to -Z)": dir = 3 posIncrement = False else: dir = 2 posIncrement = True else: if facing == "Eastwards (-X to +X)": dir = 0 posIncrement = True else: dir = 1 posIncrement = False if facing == "Northwards (+Z to -Z)" or facing == "Southwards (-Z to +Z)": z = box.minz if posIncrement: z += 1 for y in xrange(box.miny - 1 + loopx, box.miny - 1, -1): for x in xrange(box.minx, box.minx + loopy) if posIncrement else xrange( box.minx - 1 + loopy, box.minx - 1, -1): level.setBlockAt(x, y, z, 199) level.setBlockDataAt(x, y, z, dir) if level.blockAt(x, y, z + (-1 if posIncrement else 1)) == 0: level.setBlockAt(x, y, z + (-1 if posIncrement else 1), backing.ID) level.setBlockDataAt( x, y, z + (-1 if posIncrement else 1), backing.blockData) chunk = level.getChunk(x >> 4, z >> 4) chunk.TileEntities.append( CreateItemFramePE(x, y, z, startid)) chunk.dirty = True startid += 1 elif facing == "Eastwards (-X to +X)" or facing == "Westwards (+X to -X)": x = box.minx if posIncrement: x += 1 for y in xrange(box.miny - 1 + loopx, box.miny - 1, -1): for z in xrange(box.minz, box.minz + loopy) if not posIncrement else xrange( box.minz - 1 + loopy, box.minz - 1, -1): level.setBlockAt(x, y, z, 199) level.setBlockDataAt(x, y, z, dir) if level.blockAt(x + (-1 if posIncrement else 1), y, z) == 0: level.setBlockAt(x + (-1 if posIncrement else 1), y, z, backing.ID) level.setBlockDataAt( x + (-1 if posIncrement else 1), y, z, backing.blockData) chunk = level.getChunk(x >> 4, z >> 4) chunk.TileEntities.append( CreateItemFramePE(x, y, z, startid)) chunk.dirty = True startid += 1 else: if level.gamePlatform == 'Java': breakout = False entsToAdd = [] for y in xrange(box.miny, box.maxy): for z in xrange(box.minz, box.maxz): for x in xrange(box.minx, box.maxx): newchest = TAG_Compound() newchest["id"] = TAG_String("Chest") newchest["x"] = TAG_Int(x) newchest["y"] = TAG_Int(y) newchest["z"] = TAG_Int(z) newchest["Lock"] = TAG_String() newchest["Items"] = TAG_List() mapitem = TAG_Compound() mapitem["id"] = TAG_String("minecraft:filled_map") mapitem["Count"] = TAG_Byte(1) mapitem["Damage"] = TAG_Short(0) mapitem["Slot"] = TAG_Byte(0) for c in xrange(27): newitem = deepcopy(mapitem) newitem["Slot"] = TAG_Byte(c) newitem["Damage"] = TAG_Short(startid) newchest["Items"].append(newitem) startid += 1 if startid > endid: breakout = True break level.setBlockAt(x, y, z, 54) level.setBlockDataAt(x, y, z, 4) entsToAdd.append( (level.getChunk(x >> 4, z >> 4), deepcopy(newchest))) if breakout: break if breakout: break if breakout: break elif level.gamePlatform == 'PE': breakout = False entsToAdd = [] for y in xrange(box.miny, box.maxy): for z in xrange(box.minz, box.maxz): for x in xrange(box.minx, box.maxx): newchest = TAG_Compound() newchest["id"] = TAG_String("Chest") newchest["x"] = TAG_Int(x) newchest["y"] = TAG_Int(y) newchest["z"] = TAG_Int(z) newchest["Items"] = TAG_List() mapitem = TAG_Compound() mapitem["id"] = TAG_Short(358) mapitem["Count"] = TAG_Byte(16) mapitem["Damage"] = TAG_Short(0) mapitem["tag"] = TAG_Compound() for c in xrange(27): newitem = deepcopy(mapitem) newitem["Slot"] = TAG_Byte(c) newitem["tag"]["map_uuid"] = TAG_Long(startid) newchest["Items"].append(newitem) startid += 1 if startid > endid: breakout = True break level.setBlockAt(x, y, z, 54) level.setBlockDataAt(x, y, z, 4) entsToAdd.append( (level.getChunk(x >> 4, z >> 4), deepcopy(newchest))) if breakout: break if breakout: break if breakout: break for (chunk, entity) in entsToAdd: chunk.TileEntities.append(entity) chunk.dirty = True print "-------------------" print "Filtering complete."
def perform(level, box, options): op = options["Operation:"] cleartrack = options["Clear and prevent output tracking on import:"] reset = options["Reset Success Count on import:"] filterstr = options[ "Dump only commands containing: (\"None\" to dump all)"] filepath = options["File path:"] order = sorts[options["Sort command blocks by:"]] if op == "Dump Command Blocks": if filterstr == "None": filtercoms = False else: filtercoms = True commands = [] for (chunk, _, _) in level.getChunkSlices(box): for e in chunk.TileEntities: x = e["x"].value y = e["y"].value z = e["z"].value if (x, y, z) in box: if "CommandBlock" in e["id"].value: if "CustomName" in e: name = e["CustomName"].value.encode( "unicode-escape") else: name = "@" type = level.blockAt(x, y, z) direction = level.blockDataAt(x, y, z) if "powered" in e: powered = e["powered"].value else: powered = 0 if "auto" in e: auto = e["auto"].value else: auto = 0 if "conditionMet" in e: conditionMet = e["conditionMet"].value else: conditionMet = 0 if filtercoms: if e["Command"].value.find(filterstr) != -1: commands.append( ((x, y, z), type, direction, powered, auto, conditionMet, name, e["Command"].value.encode( "unicode-escape"))) else: commands.append( ((x, y, z), type, direction, powered, auto, conditionMet, name, e["Command"].value.encode("unicode-escape"))) if not commands: raise Exception( "ERROR: No command blocks exist within the selection!") commands.sort( key=lambda s: (s[0][order[0]], s[0][order[1]], s[0][order[2]])) outputlines = [] for (coords, type, direction, powered, auto, conditionMet, comname, command) in commands: outputlines.append( u"#%d,%d,%d|%d|%d|%d|%d|%d:%s\n" % (coords[0], coords[1], coords[2], type, direction, powered, auto, conditionMet, comname)) if "{" in command: mdatapos = command.find("{") outputlines.append(command[:mdatapos] + "\n") outputlines += strexplode(command[mdatapos:]) else: outputlines.append(str(command) + "\n") outputlines.append("\n") if filepath == "None": text_file = mcplatform.askSaveFile( mcplatform.lastSchematicsDir or mcplatform.schematicsDir, "Save Dumped Text File...", "", "Text File\0*.txt\0\0", ".txt") if text_file == None: print "ERROR: No filename provided!" return else: text_file = filepath file = open(text_file, "w") file.writelines(outputlines) file.close() else: if filepath == "None": text_file = mcplatform.askOpenFile( title="Select a Dumped Text File...", schematics=False) if text_file == None: print "ERROR: No filename provided!" return else: text_file = filepath file = open(text_file, 'rb') filearray = file.readlines() file.close() blocks = strcollapse(filearray) for idstr, command in blocks: precoordstr, name = idstr.split(":", 1) if "|" in precoordstr: coordstr, bdata = precoordstr.split("|", 1) else: coordstr = precoordstr bdata = None cx, cy, cz = coordstr.split(",") if bdata: parts = bdata.split("|") if len(parts) != 5: type = 137 direction = 0 powered = 0 auto = 0 conditionMet = 0 else: type = int(parts[0]) direction = int(parts[1]) powered = int(parts[2]) auto = int(parts[3]) conditionMet = int(parts[4]) else: type = 137 direction = 0 powered = 0 auto = 0 conditionMet = 0 cx = int(cx) cy = int(cy) cz = int(cz) level.setBlockAt(cx, cy, cz, type) level.setBlockDataAt(cx, cy, cz, direction) chunk = level.getChunk(cx >> 4, cz >> 4) ent = level.tileEntityAt(cx, cy, cz) if ent != None: if cleartrack: ent["TrackOutput"] = TAG_Byte(0) if "LastOutput" in ent: del ent["LastOutput"] if reset: ent["SuccessCount"] = TAG_Int(0) ent["powered"] = TAG_Byte(powered) ent["auto"] = TAG_Byte(auto) ent["conditionMet"] = TAG_Byte(conditionMet) ent["CustomName"] = TAG_String(name) ent["Command"] = TAG_String(command) chunk.dirty = True else: cmd = TAG_Compound() cmd["id"] = TAG_String("CommandBlock") cmd["x"] = TAG_Int(cx) cmd["y"] = TAG_Int(cy) cmd["z"] = TAG_Int(cz) if cleartrack: cmd["TrackOutput"] = TAG_Byte(0) cmd["powered"] = TAG_Byte(powered) cmd["auto"] = TAG_Byte(auto) cmd["conditionMet"] = TAG_Byte(conditionMet) cmd["CustomName"] = TAG_String(name) cmd["Command"] = TAG_String(command) chunk.TileEntities.remove(cmd) chunk.TileEntities.append(cmd) chunk.dirty = True