repo
stringlengths
2
99
file
stringlengths
13
225
code
stringlengths
0
18.3M
file_length
int64
0
18.3M
avg_line_length
float64
0
1.36M
max_line_length
int64
0
4.26M
extension_type
stringclasses
1 value
MCEdit-Unified
MCEdit-Unified-master/leveleditor.py
"""Copyright (c) 2010-2012 David Rio Vierra Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.""" # Moving this here to get log entries ASAP -- D.C.-G. import logging from pymclevel.schematic import StructureNBT from utilities import mcworld_support log = logging.getLogger(__name__) #-# Modified by D.C.-G. for translation purpose #.# Marks the layout modifications. -- D.C.-G. from editortools.thumbview import ThumbView import keys import pygame from albow.fields import FloatField from albow import ChoiceButton, TextInputRow, CheckBoxLabel, showProgress, IntInputRow, ScrollPanel from editortools.blockview import BlockButton try: import ftp_client ftp_supported = True log.info('FPTUtil module found, FTP server support enabled') except ImportError: ftp_supported = False log.info('FTPUtil module not found, FTP server support is disabled') #import sys #from pymclevel import nbt #from editortools.select import SelectionTool #from pymclevel.box import BoundingBox from waypoints import WaypointManager from editortools.timeditor import TimeEditor """ leveleditor.py Viewport objects for Camera and Chunk views, which respond to some keyboard and mouse input. LevelEditor object responds to some other keyboard and mouse input, plus handles the undo stack and implements tile entity editors for chests, signs, and more. Toolbar object which holds instances of EditorTool imported from editortools/ """ import gc import os #import math import csv #import copy import time import numpy from config import config #from config import DEF_ENC #import frustum import glutils import release import mceutils import platform #import functools import editortools import itertools import mcplatform import pymclevel import renderer import directories import panels import viewports import shutil from os.path import dirname, isdir from datetime import datetime, timedelta from collections import defaultdict, deque from OpenGL import GL from albow import alert, ask, AttrRef, Button, Column, input_text, IntField, Row, \ TableColumn, TableView, TextFieldWrapped, TimeField, Widget, CheckBox, \ unparented import albow.resource albow.resource.font_proportion = config.settings.fontProportion.get() get_font = albow.resource.get_font from albow.controls import Label, ValueDisplay, Image, RotatableImage from albow.dialogs import Dialog, QuickDialog, wrapped_label from albow.openglwidgets import GLOrtho, GLViewport from albow.translate import _, getLang from pygame import display, event, mouse, MOUSEMOTION, image from depths import DepthOffset from editortools.operation import Operation from editortools.chunk import GeneratorPanel, ChunkTool from glbackground import GLBackground, Panel from glutils import Texture from mcplatform import askSaveFile from pymclevel.minecraft_server import alphanum_key # ????? from renderer import MCRenderer #from pymclevel.entity import Entity from pymclevel.infiniteworld import AnvilWorldFolder, SessionLockLost, MCAlphaDimension,\ MCInfdevOldLevel # Block and item translation from mclangres import translate as trn from mclangres import buildResources try: import resource # @UnresolvedImport resource.setrlimit(resource.RLIMIT_NOFILE, (500, -1)) except: pass # Label = GLLabel arch = platform.architecture()[0] def DebugDisplay(obj, *attrs): col = [] for attr in attrs: def _get(attr): return lambda: str(getattr(obj, attr)) col.append(Row((Label(attr + " = "), ValueDisplay(width=600, get_value=_get(attr))))) col = Column(col, align="l") b = GLBackground() b.add(col) b.shrink_wrap() return b # if self.defaultScale >= 0.5: # return super(ChunkViewport, self).drawCeiling() class LevelEditor(GLViewport): anchor = "tlbr" __maxCopies = 32 def __init__(self, mcedit): self.mcedit = mcedit rect = mcedit.rect GLViewport.__init__(self, rect) self.currentCopyPage = 0 self.frames = 0 self.frameStartTime = datetime.now() self.oldFrameStartTime = self.frameStartTime self.dragInProgress = False self.debug = 0 self.debugString = "" self.testBoardKey = 0 self.world_from_ftp = False self.perfSamples = 5 self.frameSamples = [timedelta(0, 0, 0)] * 5 self.unsavedEdits = 0 self.undoStack = [] self.redoStack = [] self.copyStack = [] self.nbtCopyBuffer = mcedit.nbtCopyBuffer self.level = None # Tracking the dimension changes. self.prev_dimension = None self.new_dimension = None self.cameraInputs = [0., 0., 0.] self.cameraPanKeys = [0., 0.] self.movements = [ config.keys.left.get(), config.keys.right.get(), config.keys.forward.get(), config.keys.back.get(), config.keys.up.get(), config.keys.down.get() ] self.toolbarKeys = [ config.keys.select.get(), config.keys.brush.get(), config.keys.clone.get(), config.keys.fillAndReplace.get(), config.keys.filter.get(), config.keys.importKey.get(), config.keys.players.get(), config.keys.worldSpawnpoint.get(), config.keys.chunkControl.get(), config.keys.nbtExplorer.get() ] self.cameraPan = [ config.keys.panLeft.get(), config.keys.panRight.get(), config.keys.panUp.get(), config.keys.panDown.get() ] self.sprintKey = config.keys.sprint.get() self.different_keys = { "mouse1": "Mouse1", "mouse2": "Mouse2", "mouse3": "Button 3", "mouse4": "Scroll Up", "mouse5": "Scroll Down", "mouse6": "Button 4", "mouse7": "Button 5", "Delete": "Del" } self.rightClickNudge = False self.root = self.get_root() self.cameraToolDistance = self.defaultCameraToolDistance self.createRenderers() self.sixteenBlockTex = self.genSixteenBlockTexture() self.generateStars() self.optionsBar = Widget() self.mcEditButton = Button("Menu", action=self.showControls) def chooseDistance(): self.changeViewDistance(int(self.viewDistanceReadout.get_value())) if self.renderer.viewDistance not in xrange(2,config.settings.maxViewDistance.get()+1,2): self.renderer.viewDistance = 2 self.viewDistanceReadout = ChoiceButton(["%s"%a for a in xrange(2,config.settings.maxViewDistance.get()+1,2)], width=20, ref=AttrRef(self.renderer, "viewDistance"), choose=chooseDistance) self.viewDistanceReadout.selectedChoice = "%s"%self.renderer.viewDistance self.viewDistanceReadout.shrink_wrap() def showViewOptions(): col = [CheckBoxLabel("Entities", expand=0, fg_color=(0xff, 0x22, 0x22), ref=config.settings.drawEntities), CheckBoxLabel("Items", expand=0, fg_color=(0x22, 0xff, 0x22), ref=config.settings.drawItems), CheckBoxLabel("TileEntities", expand=0, fg_color=(0xff, 0xff, 0x22), ref=config.settings.drawTileEntities), CheckBoxLabel("TileTicks", expand=0, ref=config.settings.drawTileTicks), CheckBoxLabel("Player Heads", expand=0, ref=config.settings.drawPlayerHeads), CheckBoxLabel("Unpopulated Chunks", expand=0, fg_color=renderer.TerrainPopulatedRenderer.color, ref=config.settings.drawUnpopulatedChunks), CheckBoxLabel("Chunks Borders", expand=0, fg_color=renderer.ChunkBorderRenderer.color, ref=config.settings.drawChunkBorders), CheckBoxLabel("Sky", expand=0, ref=config.settings.drawSky), CheckBoxLabel("Fog", expand=0, ref=config.settings.drawFog), CheckBoxLabel("Ceiling", expand=0, ref=config.settings.showCeiling), CheckBoxLabel("Chunk Redraw", expand=0, fg_color=(0xff, 0x99, 0x99), ref=config.settings.showChunkRedraw), CheckBoxLabel("Hidden Ores", expand=0, ref=config.settings.showHiddenOres, tooltipText="Check to show/hide specific ores using the settings below.")] for ore in config.settings.hiddableOres.get(): col.append(CheckBoxLabel("* " + _(self.level.materials[ore].name.replace(" Ore", "")), expand=0, ref=config.settings["showOre{}".format(ore)])) col = Column(col, align="r", spacing=4, expand='h') d = QuickDialog() d.add(col) d.shrink_wrap() d.topleft = self.viewButton.bottomleft d.present(centered=False) self.viewButton = Button("Show...", action=showViewOptions) self.waypointManager = WaypointManager(editor=self) self.waypointManager.load() #self.loadWaypoints() self.waypointsButton = Button("Waypoints/Goto", action=self.showWaypointsDialog) self.viewportButton = Button("Camera View", action=self.swapViewports, tooltipText=_("Shortcut: {0}").format(_(config.keys.toggleView.get()))) self.recordUndoButton = CheckBoxLabel("Undo", ref=AttrRef(self, 'recordUndo')) # TODO: Mark print directories.getDataDir(os.path.join(u"toolicons", u"session_good.png")) #self.sessionLockLock = Image(image.load(open(directories.getDataDir(os.path.join(u"toolicons", # u"session_good.png")), 'rb'), 'rb')) self.sessionLockLock = Image(image.load(directories.getDataFile('toolicons', 'session_good.png'))) self.sessionLockLock.tooltipText = "Session Lock is being used by MCEdit" self.sessionLockLock.mouse_down = self.mouse_down_session self.sessionLockLabel = Label("Session:", margin=0) self.sessionLockLabel.tooltipText = "Session Lock is being used by MCEdit" self.sessionLockLabel.mouse_down = self.mouse_down_session # TODO: Marker row = (self.mcEditButton, Label("View Distance:"), self.viewDistanceReadout, self.viewButton, self.viewportButton, self.recordUndoButton, Row((self.sessionLockLabel, self.sessionLockLock), spacing=2), self.waypointsButton) self.topRow = row = Row(row) self.add(row) self.statusLabel = ValueDisplay(width=self.width, ref=AttrRef(self, "statusText")) self.mainViewport = viewports.CameraViewport(self) self.chunkViewport = viewports.ChunkViewport(self) self.mainViewport.height -= row.height self.mainViewport.height -= self.statusLabel.height self.statusLabel.bottom = self.bottom self.statusLabel.anchor = "blrh" self.add(self.statusLabel) self.viewportContainer = Widget(is_gl_container=True, anchor="tlbr") self.viewportContainer.top = row.bottom self.viewportContainer.size = self.mainViewport.size self.add(self.viewportContainer) config.settings.viewMode.addObserver(self) config.settings.undoLimit.addObserver(self) self.reloadToolbar() self.currentTool = None self.toolbar.selectTool(0) self.controlPanel = panels.ControlPanel(self) # logger = logging.getLogger() # adapter = logging.StreamHandler(sys.stdout) # adapter.addFilter(LogFilter(self)) # logger.addHandler(adapter) self.revertPlayerSkins = False #-# Translation live update preparation def set_update_ui(self, v): GLViewport.set_update_ui(self, v) if v: self.statusLabel.width = self.width self.topRow.calc_size() self.controlPanel.set_update_ui(v) # Update the unparented widgets. for a in unparented.values(): a.set_update_ui(v) #-# def __del__(self): self.deleteAllCopiedSchematics() def showCreateDialog(self): widg = Widget() nameField = TextFieldWrapped(width=200) waypoints = self.waypointManager.waypoint_names defaultName = 'Waypoint{}' n = 1 while n <= 50: if defaultName.format(n) in waypoints: n += 1 else: break nameField.value = defaultName.format(n) xField = FloatField() yField = FloatField() zField = FloatField() saveCameraRotation = CheckBoxLabel("Save Rotation") xField.value = round(self.mainViewport.cameraPosition[0], 2) yField.value = round(self.mainViewport.cameraPosition[1], 2) zField.value = round(self.mainViewport.cameraPosition[2], 2) coordRow = Row((Label("X:"), xField, Label("Y:"), yField, Label("Z:"), zField)) col = Column((Row((Label("Waypoint Name:"), nameField)), coordRow, saveCameraRotation), align="c") widg.add(col) widg.shrink_wrap() d = Dialog(widg, ["Create", "Cancel"]) def click_outside(event): if event not in d: x, y, z = self.blockFaceUnderCursor[0] if y == 0: y = 64 y += 3 xField.value, yField.value, zField.value = x, y, z def key_down(event): """Defines keyboard actions for the waypoint creation dialog. :param event: object: The event to be processed.""" key = self.root.getKey(event) if key == "Return": d.dismiss("Create") elif key == "Escape": d.dismiss("Cancel") else: Dialog.key_down(d, event) d.key_down = key_down # Trigger escape key press when one field has focus to the dialog dismiss action. nameField.escape_action = xField.escape_action = yField.escape_action = zField.escape_action = d.dismiss d.mouse_down = click_outside result = d.present() if result == "Create": if nameField.value in self.waypointManager.waypoint_names: self.Notify("You cannot have duplicate waypoint names") return if saveCameraRotation.checkbox.value: self.waypointManager.add_waypoint(nameField.value, (xField.value, yField.value, zField.value), (self.mainViewport.yaw, self.mainViewport.pitch), self.level.dimNo) else: self.waypointManager.add_waypoint(nameField.value, (xField.value, yField.value, zField.value), (0.0, 0.0), self.level.dimNo) if "Empty" in self.waypointManager.waypoints: del self.waypointManager.waypoints["Empty"] self.waypointDialog.dismiss() self.waypointManager.save() def gotoWaypoint(self): if self.waypointsChoiceButton.value == "Empty": return self.gotoDimension(self.waypointManager.waypoints[self.waypointsChoiceButton.value][5]) self.mainViewport.skyList = None self.mainViewport.drawSkyBackground() self.mainViewport.cameraPosition = self.waypointManager.waypoints[self.waypointsChoiceButton.value][:3] self.mainViewport.yaw = self.waypointManager.waypoints[self.waypointsChoiceButton.value][3] self.mainViewport.pitch = self.waypointManager.waypoints[self.waypointsChoiceButton.value][4] self.mainViewport.skyList = None self.mainViewport.drawSkyBackground() self.waypointDialog.dismiss() def deleteWaypoint(self): self.waypointDialog.dismiss() if self.waypointsChoiceButton.value == "Empty": return self.waypointManager.delete(self.waypointsChoiceButton.value) def gotoLastWaypoint(self, lastPos): #!# Added checks to verify the waypoint NBT data consistency. (Avoid crashed in case of corrupted file.) if lastPos.get("Dimension") and lastPos.get("Coordinates") and lastPos.get("Rotation"): self.gotoDimension(lastPos["Dimension"].value) self.mainViewport.skyList = None self.mainViewport.drawSkyBackground() self.mainViewport.cameraPosition = [lastPos["Coordinates"][0].value, lastPos["Coordinates"][1].value, lastPos["Coordinates"][2].value ] self.mainViewport.yaw = lastPos["Rotation"][0].value self.mainViewport.pitch = lastPos["Rotation"][1].value def showWaypointsDialog(self): """Displays the waypoints dialog. Also used to jump to coordinates.""" self.waypointDialog = Dialog() self.waypointsChoiceButton = ChoiceButton(self.waypointManager.waypoints.keys()) createWaypointButton = Button("Create Waypoint", action=self.showCreateDialog) gotoWaypointButton = Button("Goto Waypoint", action=self.gotoWaypoint) deleteWaypointButton = Button("Delete Waypoint", action=self.deleteWaypoint) saveCameraOnClose = CheckBoxLabel("Save Camera position on world close", ref=config.settings.savePositionOnClose) gotoPanel = Widget() gotoPanel.goto_coords = False gotoPanel.X, gotoPanel.Y, gotoPanel.Z = map(int, self.mainViewport.cameraPosition) def set_goto_coords(): """Triggers camera move to the selected coordinates.""" self.waypointDialog.dismiss() gotoPanel.goto_coords = True def click_outside(event): """Selects coordinates outside the dialog and updates the corresponding X, Y and Z fields in the dialog. Immediately moves the camera to the coordinates on double-click. :param event: object: The event to be processed.""" if event not in self.waypointDialog: x, y, z = self.blockFaceUnderCursor[0] if y == 0: y = 64 y += 3 gotoPanel.X, gotoPanel.Y, gotoPanel.Z = x, y, z if event.num_clicks == 2: gotoPanel.goto_coords = True self.waypointDialog.dismiss() def on_choose(): """Handles choice for the waypoints dropdown choice button.""" choice = self.waypointsChoiceButton.value waypoint = self.waypointManager.waypoints[choice] gotoPanel.X, gotoPanel.Y, gotoPanel.Z = map(int, waypoint[0:3]) def key_down(event): """Defines keyboard actions for the waypoints dialog. :param event: object: The event to be processed.""" if self.root.getKey(event) == "Escape": gotoPanel.goto_coords = False self.waypointDialog.dismiss() else: Dialog.key_down(self.waypointDialog, event) self.waypointsChoiceButton.choose = on_choose on_choose() x_field = IntField(ref=AttrRef(gotoPanel, "X")) y_field = IntField(ref=AttrRef(gotoPanel, "Y")) z_field = IntField(ref=AttrRef(gotoPanel, "Z")) # Trigger escape key press when one field has focus to the dialog dismiss action. x_field.escape_action = y_field.escape_action = z_field.escape_action = self.waypointDialog.dismiss coordinateRow = ( Label("X: "), x_field, Label("Y: "), y_field, Label("Z: "), z_field, ) gotoRow = Row(coordinateRow) gotoCoordinateButton = Button("Goto Coordinates", action=set_goto_coords) col = Column( ( self.waypointsChoiceButton, Row( ( createWaypointButton, gotoWaypointButton, deleteWaypointButton, ) ), saveCameraOnClose, gotoRow, gotoCoordinateButton, Button("Close", action=self.waypointDialog.dismiss), ) ) self.waypointDialog.add(col) self.waypointDialog.shrink_wrap() self.waypointDialog.mouse_down = click_outside self.waypointDialog.key_down = key_down self.waypointDialog.present(True) if gotoPanel.goto_coords: destPoint = [gotoPanel.X, gotoPanel.Y, gotoPanel.Z] if self.currentViewport is self.chunkViewport: self.swapViewports() self.mainViewport.cameraPosition = destPoint def mouse_down_session(self, evt): class SessionLockOptions(Panel): def __init__(self): Panel.__init__(self) self.autoChooseCheckBox = CheckBoxLabel("Override Minecraft Changes (Not Recommended)", ref=config.session.override, tooltipText="Always override Minecraft changes when map is open in MCEdit. (Not recommended)") col = Column((Label("Session Lock Options"), self.autoChooseCheckBox, Button("OK", action=self.dismiss))) self.add(col) self.shrink_wrap() if evt.button == 3: sessionLockPanel = SessionLockOptions() sessionLockPanel.present() _viewMode = None _level = None @property def level(self): return self._level @level.setter def level(self, level): self._level = level if hasattr(level, "setSessionLockCallback"): level.setSessionLockCallback(self.lockAcquired, self.lockLost) @property def viewMode(self): return self._viewMode @viewMode.setter def viewMode(self, val): if val == self._viewMode: return ports = {"Chunk": self.chunkViewport, "Camera": self.mainViewport} for p in ports.values(): p.set_parent(None) port = ports.get(val, self.mainViewport) self.mainViewport.mouseLookOff() self._viewMode = val if val == "Camera": x, y, z = self.chunkViewport.cameraPosition try: h = self.level.heightMapAt(int(x), int(z)) except: h = 0 y = max(self.mainViewport.cameraPosition[1], h + 2) self.mainViewport.cameraPosition = x, y, z # self.mainViewport.yaw = 180.0 # self.mainViewport.pitch = 90.0 self.mainViewport.cameraVector = self.mainViewport._cameraVector() self.renderer.overheadMode = False self.viewportButton.text = "Chunk View" else: x, y, z = self.mainViewport.cameraPosition self.chunkViewport.cameraPosition = x, y, z self.renderer.overheadMode = True self.viewportButton.text = "Camera View" self.viewportContainer.add(port) self.currentViewport = port self.chunkViewport.size = self.mainViewport.size = self.viewportContainer.size self.renderer.loadNearbyChunks() @staticmethod def swapViewports(): if config.settings.viewMode.get() == "Chunk": config.settings.viewMode.set("Camera") else: config.settings.viewMode.set("Chunk") def addCopiedSchematic(self, sch): self.copyStack.insert(0, sch) if len(self.copyStack) > self.maxCopies: self.deleteCopiedSchematic(self.copyStack[-1]) self.updateCopyPanel() @staticmethod def _deleteSchematic(sch): if hasattr(sch, 'close'): sch.close() if sch.filename and os.path.exists(sch.filename): os.remove(sch.filename) def deleteCopiedSchematic(self, sch): self._deleteSchematic(sch) self.copyStack = [s for s in self.copyStack if s is not sch] self.updateCopyPanel() def deleteAllCopiedSchematics(self): for s in self.copyStack: self._deleteSchematic(s) copyPanel = None def updateCopyPanel(self): if self.copyPanel: self.copyPanel.set_parent(None) self.copyPanel = None if 0 == len(self.copyStack): return self.copyPanel = self.createCopyPanel() self.copyPanel.right = self.mainViewport.right self.copyPanel.top = self.subwidgets[0].bottom + 2 self.add(self.copyPanel) thumbCache = None fboCache = None def __getMaxCopies(self): return config.settings.maxCopies.get() or self.__maxCopies def __setMaxCopies(self, *args, **kwargs): return def __delMaxCopies(self): return maxCopies = property(__getMaxCopies, __setMaxCopies, __delMaxCopies, "Copy stack size.") def createCopyPanel(self): panel = GLBackground() panel.bg_color = (0.0, 0.0, 0.0, 0.5) panel.pages = [] if len(self.copyStack) > self.maxCopies: for sch in self.copyStack[self.maxCopies:]: self.deleteCopiedSchematic(sch) prevButton = Button("Previous Page") self.thumbCache = thumbCache = self.thumbCache or {} self.fboCache = self.fboCache or {} for k in self.thumbCache.keys(): if k not in self.copyStack: del self.thumbCache[k] inner_height = 0 itemNo = Label("#%s" % ("W" * len("%s" % self.maxCopies)), doNotTranslate=True) fixedwidth = 0 + itemNo.width del itemNo def createOneCopyPanel(sch, i): p = GLBackground() p.bg_color = (0.0, 0.0, 0.0, 0.4) itemNo = Label("#%s%s" % (" " * (len("%s" % self.maxCopies) - len("%s" % (i + 1))), (i + 1)), doNotTranslate=True) thumb = thumbCache.get(sch) if thumb is None: thumb = ThumbView(sch) thumb.mouse_down = lambda e: self.pasteSchematic(sch) thumb.tooltipText = "Click to import this item." thumbCache[sch] = thumb self.addWorker(thumb.renderer) deleteButton = Button("Delete", action=lambda: (self.deleteCopiedSchematic(sch))) saveButton = Button("Save", action=lambda: (self.exportSchematic(sch))) sizeLabel = Label("{0} x {1} x {2}".format(sch.Length, sch.Width, sch.Height)) r = Row((itemNo, thumb, Column((sizeLabel, Row((deleteButton, saveButton))), spacing=5))) p.add(r) itemNo.width = 0 + fixedwidth p.shrink_wrap() return p page = [] for i in xrange(len(self.copyStack)): sch = self.copyStack[i] p = createOneCopyPanel(sch, i) if self.netherPanel is None: bottom = pygame.display.get_surface().get_height() - 60 else: bottom = self.netherPanel.top - 2 if inner_height + p.height + 2 <= bottom - (self.subwidgets[0].bottom + 2) - prevButton.height - (panel.margin * 2): inner_height += p.height + 2 page.append(p) else: inner_height = p.height panel.pages.append(Column(page, spacing=2, align="l", margin=0)) panel.pages[-1].shrink_wrap() page = [p] if page: panel.pages.append(Column(page, spacing=2, align="l", margin=0)) panel.pages[-1].shrink_wrap() prevButton.shrink_wrap() self.currentCopyPage = min(self.currentCopyPage, len(panel.pages) - 1) col = Column([panel.pages[self.currentCopyPage]], spacing=2, align="l", margin=0) col.shrink_wrap() def changeCopyPage(this, delta): if delta > 0: m = min a = self.currentCopyPage + delta, len(this.pages) - 1 elif delta < 0: m = max a = self.currentCopyPage - 1, 0 else: return self.currentCopyPage = m(*a) for i in xrange(len(this.pages)): page = this.pages[i] if i == self.currentCopyPage: page.visible = True this.subwidgets[0].subwidgets[1].subwidgets[0] = page page.parent = this.subwidgets[0].subwidgets[1] else: page.visible = False pb = this.subwidgets[0].subwidgets[0].subwidgets[0] nb = this.subwidgets[0].subwidgets[0].subwidgets[1] if self.currentCopyPage == 0: pb.enabled = False nb.enabled = True elif 0 < self.currentCopyPage < len(this.pages) - 1: pb.enabled = True nb.enabled = True elif self.currentCopyPage == len(this.pages) - 1: pb.enabled = True nb.enabled = False this.subwidgets[0].subwidgets[1].shrink_wrap() this.subwidgets[0].shrink_wrap() this.shrink_wrap() this.width = 0 + this.orgwidth nextButton = Button("Next Page", action=lambda: changeCopyPage(panel, 1), width=prevButton.width, height=prevButton.height) prevButton.action = lambda: changeCopyPage(panel, -1) if len(panel.pages) < 2: prevButton.enabled = False nextButton.enabled = False elif self.currentCopyPage == 0: prevButton.enabled = False nextButton.enabled = True elif 0 < self.currentCopyPage < len(panel.pages) - 1: prevButton.enabled = True nextButton.enabled = True elif self.currentCopyPage == len(panel.pages) - 1: prevButton.enabled = True nextButton.enabled = False btns = Row((prevButton, nextButton), spacing=2, align='c') btns.shrink_wrap() mainCol = Column((btns, col), spacing=2, align='c') mainCol.shrink_wrap() panel.add(mainCol) panel.shrink_wrap() panel.anchor = "whrt" panel.orgwidth = 0 + panel.width return panel @mceutils.alertException def showAnalysis(self, schematic): self.analyzeBox(schematic, schematic.bounds) def analyzeBox(self, level, box): entityCounts = defaultdict(int) tileEntityCounts = defaultdict(int) types = numpy.zeros(65536, dtype='uint32') def _analyzeBox(): i = 0 for (chunk, slices, point) in level.getChunkSlices(box): i += 1 yield i, box.chunkCount blocks = numpy.array(chunk.Blocks[slices], dtype='uint16') blocks |= (numpy.array(chunk.Data[slices], dtype='uint16') << 12) b = numpy.bincount(blocks.ravel()) types[:b.shape[0]] = types[:b.shape[0]].astype(int) + b for ent in chunk.getEntitiesInBox(box): entID = level.__class__.entityClass.getId(ent["id"].value) if ent["id"].value == "Item": try: v = pymclevel.items.items.findItem(ent["Item"]["id"].value, ent["Item"]["Damage"].value).name v += " (Item)" except pymclevel.items.ItemNotFound: v = "Unknown Item" else: v = ent["id"].value entityCounts[(entID, v)] += 1 for ent in chunk.getTileEntitiesInBox(box): tileEntityCounts[ent["id"].value] += 1 with mceutils.setWindowCaption("ANALYZING - "): showProgress(_("Analyzing {0} blocks...").format(box.volume), _analyzeBox(), cancel=True) entitySum = numpy.sum(entityCounts.values()) tileEntitySum = numpy.sum(tileEntityCounts.values()) presentTypes = types.nonzero() blockCounts = sorted([(level.materials[t & 0xfff, t >> 12], types[t]) for t in presentTypes[0]]) rows = blockRows = [("", "", ""), (box.volume, "<%s>" % _("Blocks"), "")] #rows = list(blockRows) rows.extend([[count, trn(block.name), ("({0}:{1})".format(block.ID, block.blockData))] for block, count in blockCounts]) #rows.sort(key=lambda x: alphanum_key(x[2]), reverse=True) def extendEntities(): if entitySum: rows.extend([("", "", ""), (entitySum, "<%s>" % _("Entities"), "")]) rows.extend([(count, trn(id[1]), id[0]) for (id, count) in sorted(entityCounts.iteritems())]) if tileEntitySum: rows.extend([("", "", ""), (tileEntitySum, "<%s>" % _("TileEntities"), "")]) rows.extend([(count, trn(id), "") for (id, count) in sorted(tileEntityCounts.iteritems())]) extendEntities() columns = [ TableColumn("Count", 100), TableColumn("Name", 400), TableColumn("ID", 120), ] table = TableView(columns=columns) table.sortColumn = columns[2] table.reverseSort = True def sortColumn(col): if table.sortColumn == col: table.reverseSort = not table.reverseSort else: table.reverseSort = (col.title == "Count") colnum = columns.index(col) def sortKey(x): val = x[colnum] if isinstance(val, basestring): alphanum_key(val) return val blockRows.sort(key=sortKey, reverse=table.reverseSort) table.sortColumn = col rows[:] = blockRows extendEntities() table.num_rows = lambda: len(rows) table.row_data = lambda i: rows[i] table.row_is_selected = lambda x: False table.click_column_header = sortColumn tableBacking = Widget() tableBacking.add(table) tableBacking.shrink_wrap() def saveToFile(): dt = datetime.now().strftime("%Y-%m-%d--%H-%M-%S") filename = askSaveFile(directories.docsFolder, title='Save analysis...', defaultName=self.level.displayName + "_analysis_" + dt + ".txt", filetype='Comma Separated Values\0*.txt\0\0', suffix="txt", ) if filename: try: csvfile = csv.writer(open(filename, "wb")) except Exception as e: alert(str(e)) else: for row in rows: _row=[] if row == ("", "", ""): _row = ["Number", "Type", "ID"] else: for a in row: if isinstance(a, unicode): _row.append(a.encode('utf-8')) else: _row.append(a) csvfile.writerow(_row) saveButton = Button("Save to file...", action=saveToFile) col = Column((Label("Analysis"), tableBacking, saveButton)) dlg = Dialog(client=col, responses=["OK"]) def dispatch_key(name, evt): super(Dialog, dlg).dispatch_key(name, evt) if not hasattr(evt, 'key'): return if name == 'key_down': keyname = self.root.getKey(evt) if keyname == 'Up': table.rows.scroll_up() elif keyname == 'Down': table.rows.scroll_down() elif keyname == 'Page up': table.rows.scroll_to_item(max(0, table.rows.cell_to_item_no(0, 0) - table.rows.num_rows())) elif keyname == 'Page down' and table.rows.cell_to_item_no(table.rows.num_rows(), 0) != None: table.rows.scroll_to_item(min(len(rows), table.rows.cell_to_item_no(table.rows.num_rows(), 0))) dlg.dispatch_key = dispatch_key dlg.present() def exportSchematic(self, schematic): filename = mcplatform.askSaveSchematic( directories.schematicsDir, self.level.displayName, ({"Minecraft Schematics": ["schematic"], "Minecraft Structure NBT": ["nbt"]},[])) def save_as_nbt(schem, filename): structure = StructureNBT.fromSchematic(schem) if 'Version' in self.level.root_tag['Data']: structure._version = self.level.root_tag['Data']['Version'].get('Id', pymclevel.TAG_Int(1)).value structure.save(filename) if filename: if filename.endswith(".schematic"): schematic.saveToFile(filename) elif filename.endswith(".nbt"): if (schematic.Height, schematic.Length, schematic.Width) >= (50, 50, 50): result = ask("You're trying to export a large selection as a Structure NBT file, this is not recommended " + "and may cause MCEdit to hang and/or crash. We recommend you export this selection as a Schematic instead.", responses=['Export as Structure anyway', 'Export as Schematic', 'Cancel Export'], wrap_width=80) if result == 'Export as Structure anyway': save_as_nbt(schematic, filename) elif result == 'Export as Schematic': schematic.saveToFile(filename.replace('.nbt', '.schematic')) elif result == 'Cancel Export': return save_as_nbt(schematic, filename) def getLastCopiedSchematic(self): if len(self.copyStack) == 0: return None return self.copyStack[0] toolbar = None def YesNoWidget(self, msg): self.user_yon_response = None self.yon = Widget() self.yon.bg_color = (0.0, 0.0, 0.6) label = Label(msg) ybutton = Button("Yes", action=self.yes) nbutton = Button("No", action=self.no) col = Column((label, ybutton, nbutton)) self.yon.add(col) self.yon.shrink_wrap() self.yon.present() waiter = None while waiter is None: if self.user_yon_response is not None: return self.user_yon_response def yes(self): self.yon.dismiss() self.user_yon_response = True def no(self): self.yon.dismiss() self.user_yon_response = False def _resize_selection_box(self, new_box): import inspect # Let's get our hands dirty stack = inspect.stack() filename = os.path.basename(stack[1][1]) old_box = self.selectionTool.selectionBox() msg = """ Filter "{0}" wants to resize the selection box Origin: {1} -> {2} Size: {3} -> {4} Do you want to resize the Selection Box?""".format( filename, (old_box.origin[0], old_box.origin[1], old_box.origin[2]), (new_box.origin[0], new_box.origin[1], new_box.origin[2]), (old_box.size[0], old_box.size[1], old_box.size[2]), (new_box.size[0], new_box.size[1], new_box.size[2]) ) result = ask(msg, ["Yes", "No"]) if result == "Yes": self.selectionTool.setSelection(new_box) return new_box else: return False def addExternalWidget(self, obj): if isinstance(obj, Widget): return self.addExternalWidget_Widget(obj) elif isinstance(obj, (dict, tuple, list)): return self.addExternalWidget_Dict(obj) def addExternalWidget_Widget(self, obj): obj.shrink_wrap() result = Dialog(obj, ["Ok", "Cancel"]).present() if result == "Ok": print obj else: return 'user canceled' def addExternalWidget_Dict(self, provided_fields): def addNumField(wid, name, val, minimum=None, maximum=None, increment=0.1): if isinstance(val, float): ftype = FloatField if isinstance(increment, int): increment = float(increment) else: ftype = IntField if increment == 0.1: increment = 1 if isinstance(increment, float): increment = int(round(increment)) if minimum == maximum: minimum = None maximum = None field = ftype(value=val, width=100, min=minimum, max=maximum) field._increment = increment wid.inputDict[name] = AttrRef(field, 'value') return Row([Label(name), field]) widget = Widget() rows = [] cols = [] max_height = self.mainViewport.height widget.inputDict = {} if isinstance(provided_fields, dict): provided_fields = [(key, value) for key, value in provided_fields.iteritems()] for inputName, inputType in provided_fields: if isinstance(inputType, tuple) and inputType != (): if isinstance(inputType[0], (int, long, float)): if len(inputType) == 2: min, max = inputType val = min increment = 0.1 elif len(inputType) == 3: val, min, max = inputType increment = 0.1 elif len(inputType) == 4: val, min, max, increment = inputType rows.append(addNumField(widget, inputName, val, min, max, increment)) if isinstance(inputType[0], (str, unicode)): isChoiceButton = False if inputType[0] == "string": keywords = [] width = None value = None for keyword in inputType: if isinstance(keyword, (str, unicode)) and keyword != "string": keywords.append(keyword) for word in keywords: splitWord = word.split('=') if len(splitWord) > 1: v = None try: v = int(splitWord[1]) except: pass key = splitWord[0] if v is not None: if key == "width": width = v else: if key == "value": value = splitWord[1] if val is None: value = "" if width is None: width = 200 field = TextFieldWrapped(value=value, width=width) widget.inputDict[inputName] = AttrRef(field, 'value') row = Row((Label(inputName), field)) rows.append(row) else: isChoiceButton = True if isChoiceButton: choiceButton = ChoiceButton(map(str, inputType)) widget.inputDict[inputName] = AttrRef(choiceButton, 'selectedChoice') rows.append(Row((Label(inputName), choiceButton))) elif isinstance(inputType, bool): chkbox = CheckBox(value=inputType) widget.inputDict[inputName] = AttrRef(chkbox, 'value') row = Row((Label(inputName), chkbox)) rows.append(row) elif isinstance(inputType, (int, float)): rows.append(addNumField(widget, inputName, inputType)) elif inputType == "blocktype" or isinstance(inputType, pymclevel.materials.Block): blockButton = BlockButton(self.level.materials) if isinstance(inputType, pymclevel.materials.Block): blockButton.blockInfo = inputType row = Column((Label(inputName), blockButton)) widget.inputDict[inputName] = AttrRef(blockButton, 'blockInfo') rows.append(row) elif inputType == "label": rows.append(wrapped_label(inputName, 50)) elif inputType == "string": input = None if input is not None: size = input else: size = 200 field = TextFieldWrapped(value="") row = TextInputRow(inputName, ref=AttrRef(field, 'value'), width=size) widget.inputDict[inputName] = AttrRef(field, 'value') rows.append(row) else: raise ValueError(("Unknown option type", inputType)) height = sum(r.height for r in rows) if height > max_height: h = 0 for i, r in enumerate(rows): h += r.height if h > height / 2: break cols.append(Column(rows[:i])) rows = rows[i:] if len(rows): cols.append(Column(rows)) if len(cols): widget.add(Row(cols)) widget.shrink_wrap() result = Dialog(widget, ["Ok", "Cancel"]).present() if result == "Ok": return dict((k, v.get()) for k, v in widget.inputDict.iteritems()) else: return "user canceled" @staticmethod def Notify(msg): ask(msg, ["Close"], cancel=0) def reloadToolbar(self): self.toolbar = EditorToolbar(self, tools=[editortools.SelectionTool(self), editortools.BrushTool(self), editortools.CloneTool(self), editortools.FillTool(self), editortools.FilterTool(self), editortools.ConstructionTool(self), editortools.PlayerPositionTool(self), editortools.PlayerSpawnPositionTool(self), editortools.ChunkTool(self), editortools.NBTExplorerTool(self), ]) self.toolbar.anchor = 'bwh' self.add(self.toolbar) self.toolbar.bottom = self.viewportContainer.bottom # bottoms are touching self.toolbar.centerx = self.centerx is_gl_container = True maxDebug = 1 allBlend = False onscreen = True mouseEntered = True defaultCameraToolDistance = 10 mouseSensitivity = 5.0 longDistanceMode = config.settings.longDistanceMode.property() @staticmethod def genSixteenBlockTexture(): has12 = GL.glGetString(GL.GL_VERSION) >= "1.2" if has12: maxLevel = 2 mode = GL.GL_LINEAR_MIPMAP_NEAREST else: maxLevel = 1 mode = GL.GL_LINEAR def makeSixteenBlockTex(): darkColor = (0x30, 0x30, 0x30, 0xff) lightColor = (0x80, 0x80, 0x80, 0xff) w, h, = 256, 256 teximage = numpy.zeros((w, h, 4), dtype='uint8') teximage[:] = 0xff teximage[:, ::16] = lightColor teximage[::16, :] = lightColor teximage[:2] = darkColor teximage[-1:] = darkColor teximage[:, -1:] = darkColor teximage[:, :2] = darkColor GL.glTexParameter(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAX_LEVEL, maxLevel - 1) for lev in xrange(maxLevel): step = 1 << lev if lev: teximage[::16] = 0xff teximage[:, ::16] = 0xff teximage[:2] = darkColor teximage[-1:] = darkColor teximage[:, -1:] = darkColor teximage[:, :2] = darkColor GL.glTexImage2D(GL.GL_TEXTURE_2D, lev, GL.GL_RGBA8, w / step, h / step, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, teximage[::step, ::step].ravel()) return Texture(makeSixteenBlockTex, mode) @staticmethod def showProgress(*a, **kw): return showProgress(*a, **kw) def drawConstructionCube(self, box, color, texture=None): if texture is None: texture = self.sixteenBlockTex # textured cube faces GL.glEnable(GL.GL_BLEND) GL.glEnable(GL.GL_DEPTH_TEST) GL.glDepthMask(False) # edges within terrain GL.glDepthFunc(GL.GL_GREATER) try: GL.glColor(color[0], color[1], color[2], max(color[3], 0.35)) except IndexError: raise GL.glLineWidth(1.0) mceutils.drawCube(box, cubeType=GL.GL_LINE_STRIP) # edges on or outside terrain GL.glDepthFunc(GL.GL_LEQUAL) GL.glColor(color[0], color[1], color[2], max(color[3] * 2, 0.75)) GL.glLineWidth(2.0) mceutils.drawCube(box, cubeType=GL.GL_LINE_STRIP) GL.glDepthFunc(GL.GL_LESS) GL.glColor(color[0], color[1], color[2], color[3]) GL.glDepthFunc(GL.GL_LEQUAL) mceutils.drawCube(box, texture=texture, selectionBox=True) GL.glDepthMask(True) GL.glDisable(GL.GL_BLEND) GL.glDisable(GL.GL_DEPTH_TEST) def loadFile(self, filename, addToRecent=True): """ Called when the user picks a level using Load World or Open File. """ if self.level and self.unsavedEdits > 0: resp = ask("Save unsaved edits before loading?", ["Cancel", "Don't Save", "Save"], default=2, cancel=0) if resp == "Cancel": return if resp == "Save": self.saveFile() self.root.RemoveEditFiles() self.freezeStatus(_("Loading ") + filename) if self.level: self.selectionTool.endSelection() self.level.close() try: level = pymclevel.fromFile(filename) except Exception as e: logging.exception( 'Wasn\'t able to open a file {file => %s}' % filename ) alert(_(u"I don't know how to open {0}:\n\n{1!r}").format(filename, e)) self.closeEditor() return assert level log.debug("Loaded world is %s" % repr(level)) if hasattr(level, 'materials'): level.materials.addJSONBlocksFromVersion(level.gamePlatform, level.gameVersionNumber) if addToRecent: self.mcedit.addRecentWorld(filename) if len(level.players) >= 50 and config.settings.downloadPlayerSkins.get(): result = ask("MCEdit has detected that there are a large amount of players in this world, would you like to still download skins (This can take a decent amount of time)", responses=["Download Skins", "Don't Download"]) if result == "Don't Download": config.settings.downloadPlayerSkins.set(False) self.revertPlayerSkins = True try: self.currentViewport.cameraPosition = level.getPlayerPosition() y, p = level.getPlayerOrientation() if p == -90.0: p += 0.000000001 if p == 90.0: p -= 0.000000001 self.mainViewport.yaw, self.mainViewport.pitch = y, p pdim = level.getPlayerDimension() if pdim and pdim in level.dimensions: level = level.dimensions[pdim] except (KeyError, pymclevel.PlayerNotFound): # TagNotFound # player tag not found, maybe try: self.currentViewport.cameraPosition = level.playerSpawnPosition() except KeyError: # TagNotFound self.currentViewport.cameraPosition = numpy.array((0, level.Height * 0.75, 0)) self.mainViewport.yaw = -45. self.mainViewport.pitch = 0.0 self.removeNetherPanel() gamePlatform = level.gamePlatform gameVersionNumber = level.gameVersionNumber if gamePlatform == 'Schematic': log.info('Loading \'Schematic\' file.') elif gamePlatform == 'PE': log.info('Loading \'Bedrock\' world.') buildResources(gamePlatform, getLang()) else: log.info('Loading world for version {}.'.format({True: "prior to 1.9 (detection says 'Unknown')", False: gameVersionNumber}[gameVersionNumber == 'Unknown'])) buildResources(gameVersionNumber, getLang()) self.loadLevel(level) self.renderer.position = self.currentViewport.cameraPosition self.renderer.loadNearbyChunks() def loadLevel(self, level, saveChanges=False): """ Called to load a level, world, or dimension into the editor and display it in the viewport. """ self.level = level if hasattr(level, 'acquireSessionLock'): level.acquireSessionLock() self.toolbar.removeToolPanels() self.selectedChunks = set() self.mainViewport.stopMoving() self.renderer.level = level self.addWorker(self.renderer) self.recordUndo = True if not saveChanges: self.undoStack = [] self.afterSaveUndoStack = [] self.redoStack = [] self.clearUnsavedEdits() self.initWindowCaption() self.selectionTool.selectNone() for t in self.toolbar.tools: t.levelChanged() if "select" not in str(self.currentTool): self.toolbar.selectTool(0) if isinstance(self.level, pymclevel.MCInfdevOldLevel): if self.level.parentWorld: dimensions = self.level.parentWorld.dimensions else: dimensions = self.level.dimensions dimensionsMenu = [("Overworld", "0")] dimensionsMenu += [ (pymclevel.MCAlphaDimension.dimensionNames.get(dimNo, "Dimension {0}".format(dimNo)), str(dimNo)) for dimNo in dimensions] for dim, name in pymclevel.MCAlphaDimension.dimensionNames.iteritems(): if dim not in dimensions: dimensionsMenu.append((name, str(dim))) def presentMenu(): try: dimNo = int([d[1] for d in dimensionsMenu if d[0] == self.netherButton.selectedChoice][0]) except: return self.gotoDimension(dimNo) self.mainViewport.skyList = None self.mainViewport.drawSkyBackground() dimensionsList = [d[0] for d in dimensionsMenu] self.netherButton = ChoiceButton(dimensionsList, choose=presentMenu) self.netherButton.selectedChoice = [d[0] for d in dimensionsMenu if d[1] == str(self.level.dimNo)][0] self.remove(self.topRow) # TODO: Marker self.topRow = Row((self.mcEditButton, Label("View Distance:"), self.viewDistanceReadout, self.viewButton, self.viewportButton, self.recordUndoButton, self.netherButton, Row((self.sessionLockLabel, self.sessionLockLock), spacing=2), self.waypointsButton)) self.add(self.topRow, 0) else: self.remove(self.topRow) self.topRow = Row(( self.mcEditButton, Label("View Distance:"), self.viewDistanceReadout, self.viewButton, self.viewportButton, self.recordUndoButton, self.waypointsButton)) self.add(self.topRow, 0) self.level.sessionLockLock = self.sessionLockLock #!# Adding waypoints handling for all world types # Need to take care of the dimension. # If the camera last position was saved, changing dimension is broken; the view is sticked to the overworld. #!# if self.prev_dimension == self.new_dimension: self.waypointManager = WaypointManager(os.path.dirname(self.level.filename), self) self.waypointManager.load() if len(list(self.level.allChunks)) == 0: resp = ask( "It looks like this level is completely empty!\nYou'll have to create some chunks before you can get started.", responses=["Create Chunks", "Cancel"]) if resp == "Create Chunks": x, y, z = self.mainViewport.cameraPosition box = pymclevel.BoundingBox((x - 128, 0, z - 128), (256, self.level.Height, 256)) self.selectionTool.setSelection(box) self.toolbar.selectTool(8) self.toolbar.tools[8].createChunks() self.mainViewport.cameraPosition = (x, self.level.Height, z) def removeNetherPanel(self): if self.netherPanel: self.remove(self.netherPanel) self.netherPanel = None @mceutils.alertException def gotoEarth(self): assert self.level.parentWorld self.removeNetherPanel() self.loadLevel(self.level.parentWorld, True) x, y, z = self.mainViewport.cameraPosition self.mainViewport.cameraPosition = [x * 8, y, z * 8] @mceutils.alertException def gotoNether(self): self.removeNetherPanel() x, y, z = self.mainViewport.cameraPosition self.mainViewport.cameraPosition = [x / 8, y, z / 8] self.loadLevel(self.level.getDimension(-1), True) def gotoDimension(self, dimNo): if dimNo == self.level.dimNo: return else: # Record the new dimension self.new_dimension = dimNo if dimNo == -1 and self.level.dimNo == 0: self.gotoNether() elif dimNo == 0 and self.level.dimNo == -1: self.gotoEarth() else: self.removeNetherPanel() if dimNo: if dimNo == 1: self.mainViewport.cameraPosition = (0, 96, 0) self.loadLevel(self.level.getDimension(dimNo), True) else: self.loadLevel(self.level.parentWorld, True) netherPanel = None def initWindowCaption(self): filename = self.level.filename last_dir, f_name = os.path.split(filename) last_dir = os.path.basename(last_dir) title = u"{f_name} - Unified ~ {ver}".format(f_name=os.path.join(last_dir, f_name), ver=release.get_version() % _("for")) title = title.encode('utf-8') display.set_caption(title) @mceutils.alertException def reload(self): filename = self.level.filename for p in self.toolbar.tools[6].nonSavedPlayers: if os.path.exists(p): os.remove(p) self.loadFile(filename) self.mainViewport.skyList = None self.mainViewport.drawSkyBackground() @mceutils.alertException def saveFile(self): with mceutils.setWindowCaption("SAVING - "): if isinstance(self.level, pymclevel.ChunkedLevelMixin): # xxx relight indev levels? level = self.level if level.parentWorld: level = level.parentWorld if hasattr(level, 'checkSessionLock'): try: level.checkSessionLock() except SessionLockLost as e: alert(_(e.message) + _("\n\nYour changes cannot be saved.")) return if hasattr(level, 'dimensions'): for level in itertools.chain(level.dimensions.itervalues(), [level]): if "Canceled" == showProgress("Lighting chunks", level.generateLightsIter(), cancel=True): return if self.level == level: if isinstance(level, pymclevel.MCInfdevOldLevel): needsRefresh = [c.chunkPosition for c in level._loadedChunkData.itervalues() if c.dirty] needsRefresh.extend(level.unsavedWorkFolder.listChunks()) elif isinstance(level, pymclevel.PocketLeveldbWorld): needsRefresh = [c.chunkPosition for c in level._loadedChunks.itervalues() if c.dirty] else: needsRefresh = [c for c in level.allChunks if level.getChunk(*c).dirty] #xxx change MCInfdevOldLevel to monitor changes since last call self.invalidateChunks(needsRefresh) else: if "Canceled" == showProgress("Lighting chunks", level.generateLightsIter(), cancel=True): return if self.level == level: if isinstance(level, pymclevel.MCInfdevOldLevel): needsRefresh = [c.chunkPosition for c in level._loadedChunkData.itervalues() if c.dirty] needsRefresh.extend(level.unsavedWorkFolder.listChunks()) elif isinstance(level, pymclevel.PocketLeveldbWorld): needsRefresh = [c.chunkPosition for c in level._loadedChunks.itervalues() if c.dirty] else: needsRefresh = [c for c in level.allChunks if level.getChunk(*c).dirty] #xxx change MCInfdevOldLevel to monitor changes since last call self.invalidateChunks(needsRefresh) self.freezeStatus("Saving...") chunks = self.level.chunkCount count = [0] def copyChunks(): for _ in self.level.saveInPlaceGen(): count[0] += 1 yield count[0], chunks if "Canceled" == showProgress("Copying chunks", copyChunks(), cancel=True): return self.recordUndo = True self.clearUnsavedEdits(True) self.toolbar.tools[6].nonSavedPlayers = [] @mceutils.alertException def saveAs(self): shortName = os.path.split(os.path.split(self.level.filename)[0])[1] if isinstance(self.level, pymclevel.leveldbpocket.PocketLeveldbWorld): filename = mcplatform.askSaveFile(directories.minecraftSaveFileDir, _("Name the new copy."), self.level.LevelName + " - Copy", _('Minecraft World\0*.*\0MCWorld File\0*.mcworld\0\0'), "") else: filename = mcplatform.askSaveFile(directories.minecraftSaveFileDir, _("Name the new copy."), shortName + " - Copy", _('Minecraft World\0*.*\0\0'), "") if filename is None: return if filename.endswith(".mcworld"): result = mcworld_support.save_world(self.level.worldFile.path, filename) self.Notify("Successfully saved: \"{}\"".format(result)) return #if filename.endswith() if isinstance(self.level, pymclevel.leveldbpocket.PocketLeveldbWorld): shutil.copytree(self.level.worldFile.path, filename) self.level.worldFile.path = filename self.level.filename = os.path.join(filename, 'level.dat') else: shutil.copytree(self.level.worldFolder.filename, filename) self.level.worldFolder = AnvilWorldFolder(filename) self.level.filename = os.path.join(self.level.worldFolder.filename, "level.dat") if hasattr(self.level, "acquireSessionLock"): self.level.acquireSessionLock() self.saveFile() self.initWindowCaption() def addUnsavedEdit(self): if self.unsavedEdits: self.remove(self.saveInfoBackground) self.unsavedEdits += 1 self.saveInfoBackground = GLBackground() self.saveInfoBackground.bg_color = (0.0, 0.0, 0.0, 0.6) self.saveInfoLabel = Label(self.saveInfoLabelText) self.saveInfoLabel.anchor = "blwh" self.saveInfoBackground.add(self.saveInfoLabel) self.saveInfoBackground.shrink_wrap() self.saveInfoBackground.left = 50 self.saveInfoBackground.bottom = self.toolbar.toolbarRectInWindowCoords()[1] self.add(self.saveInfoBackground) self.saveInfoBackground = self.saveInfoBackground def removeUnsavedEdit(self): self.unsavedEdits -= 1 self.remove(self.saveInfoBackground) if self.unsavedEdits: self.saveInfoBackground = GLBackground() self.saveInfoBackground.bg_color = (0.0, 0.0, 0.0, 0.6) self.saveInfoLabel = Label(self.saveInfoLabelText) self.saveInfoLabel.anchor = "blwh" self.saveInfoBackground.add(self.saveInfoLabel) self.saveInfoBackground.shrink_wrap() self.saveInfoBackground.left = 50 self.saveInfoBackground.bottom = self.toolbar.toolbarRectInWindowCoords()[1] self.add(self.saveInfoBackground) self.saveInfoBackground = self.saveInfoBackground def clearUnsavedEdits(self, saving=False): if self.unsavedEdits: self.unsavedEdits = 0 self.remove(self.saveInfoBackground) if saving: for operation in self.undoStack: self.afterSaveUndoStack.append(operation) self.undoStack = [] @property def saveInfoLabelText(self): if self.unsavedEdits == 0: return "" return _("{0} unsaved edits. {1} to save. {2}").format(self.unsavedEdits, config.keys.save.get(), "" if self.recordUndo else "(UNDO DISABLED)") @property def viewDistanceLabelText(self): return _("View Distance ({0})").format(self.renderer.viewDistance) def createRenderers(self): self.renderer = MCRenderer() self.workers = deque() if self.level: self.renderer.level = self.level self.addWorker(self.renderer) self.renderer.viewDistance = int(config.settings.viewDistance.get()) def addWorker(self, chunkWorker): if chunkWorker not in self.workers: self.workers.appendleft(chunkWorker) def removeWorker(self, chunkWorker): if chunkWorker in self.workers: self.workers.remove(chunkWorker) def getFrameDuration(self): frameDuration = timedelta(0, 1, 0) / self.renderer.targetFPS return frameDuration lastRendererDraw = datetime.now() def idleevent(self): if any(self.cameraInputs) or any(self.cameraPanKeys): self.postMouseMoved() if (self.renderer.needsImmediateRedraw or (self.renderer.needsRedraw and datetime.now() - self.lastRendererDraw > timedelta(0, 1, 0) / 3)): self.invalidate() self.lastRendererDraw = datetime.now() if self.renderer.needsImmediateRedraw: self.invalidate() if not self.root.bonus_draw_time: frameDuration = self.getFrameDuration() while frameDuration > (datetime.now() - self.frameStartTime): self.doWorkUnit() return self.doWorkUnit() def activeevent(self, evt): self.mainViewport.activeevent(evt) if evt.state & 0x4: # minimized if evt.gain == 0: logging.debug("Offscreen") self.onscreen = False self.mouseLookOff() else: logging.debug("Onscreen") self.onscreen = True self.invalidate() if evt.state & 0x1: # mouse enter/leave if evt.gain == 0: logging.debug("Mouse left") self.mouseEntered = False self.mouseLookOff() else: logging.debug("Mouse entered") self.mouseEntered = True def swapDebugLevels(self): self.debug += 1 if self.debug > self.maxDebug: self.debug = 0 if self.debug: self.showDebugPanel() else: self.hideDebugPanel() def showDebugPanel(self): dp = GLBackground() debugLabel = ValueDisplay(width=1100, ref=AttrRef(self, "debugString")) inspectLabel = ValueDisplay(width=1100, ref=AttrRef(self, "inspectionString")) dp.add(Column((debugLabel, inspectLabel))) dp.shrink_wrap() dp.bg_color = (0, 0, 0, 0.6) self.add(dp) dp.top = 40 self.debugPanel = dp def hideDebugPanel(self): self.remove(self.debugPanel) @property def statusText(self): try: return self.currentTool.statusText except Exception as e: return repr(e) def toolMouseDown(self, evt, f): # xxx f is a tuple if self.level and f is not None: focusPoint, direction = f if focusPoint is not None and direction is not None: self.currentTool.mouseDown(evt, focusPoint, direction) def toolMouseUp(self, evt, f): # xxx f is a tuple if self.level and f is not None: focusPoint, direction = f if focusPoint is not None and direction is not None: self.currentTool.mouseUp(evt, focusPoint, direction) def mouse_up(self, evt): button = keys.remapMouseButton(evt.button) evt.dict['keyname'] = "mouse{}".format(button) self.key_up(evt) def mouse_drag(self, evt): if self.level: f = self.blockFaceUnderCursor if f is not None: focusPoint, direction = f self.currentTool.mouseDrag(evt, focusPoint, direction) def mouse_down(self, evt): button = keys.remapMouseButton(evt.button) evt.dict['keyname'] = "mouse{}".format(button) self.mcedit.focus_switch = self self.turn_off_focus() self.key_down(evt) def mouseLookOff(self): self.mouseWasCaptured = False self.mainViewport.mouseLookOff() def mouseLookOn(self): self.mainViewport.mouseLookOn() def turn_off_focus(self): self.focus_switch = None @property def blockFaceUnderCursor(self): return self.currentViewport.blockFaceUnderCursor def generateStars(self): starDistance = 999.0 starCount = 2000 r = starDistance randPoints = (numpy.random.random(size=starCount * 3)) * 2.0 * r randPoints.shape = (starCount, 3) nearbyPoints = (randPoints[:, 0] < r) & (randPoints[:, 1] < r) & (randPoints[:, 2] < r) randPoints[nearbyPoints] += r randPoints[:starCount / 2, 0] = -randPoints[:starCount / 2, 0] randPoints[::2, 1] = -randPoints[::2, 1] randPoints[::4, 2] = -randPoints[::4, 2] randPoints[1::4, 2] = -randPoints[1::4, 2] randsizes = numpy.random.random(size=starCount) * 6 + 0.8 vertsPerStar = 4 vertexBuffer = numpy.zeros((starCount, vertsPerStar, 3), dtype='float32') def normvector(x): return x / numpy.sqrt(numpy.sum(x * x, 1))[:, numpy.newaxis] viewVector = normvector(randPoints) rmod = numpy.random.random(size=starCount * 3) * 2.0 - 1.0 rmod.shape = (starCount, 3) referenceVector = viewVector + rmod rightVector = normvector(numpy.cross(referenceVector, viewVector)) * randsizes[:, numpy.newaxis] # vector perpendicular to viewing line upVector = normvector(numpy.cross(rightVector, viewVector)) * randsizes[:, numpy.newaxis] # vector perpendicular previous vector and viewing line p = randPoints p1 = p + (- upVector - rightVector) p2 = p + (upVector - rightVector) p3 = p + (upVector + rightVector) p4 = p + (- upVector + rightVector) vertexBuffer[:, 0, :] = p1 vertexBuffer[:, 1, :] = p2 vertexBuffer[:, 2, :] = p3 vertexBuffer[:, 3, :] = p4 self.starVertices = vertexBuffer.ravel() starColor = None def drawStars(self): pos = self.mainViewport.cameraPosition self.mainViewport.cameraPosition = [x / 128.0 for x in pos] self.mainViewport.setModelview() GL.glColor(.5, .5, .5, 1.) GL.glVertexPointer(3, GL.GL_FLOAT, 0, self.starVertices) GL.glDrawArrays(GL.GL_QUADS, 0, len(self.starVertices) / 3) self.mainViewport.cameraPosition = pos self.mainViewport.setModelview() fractionalReachAdjustment = True @staticmethod def postMouseMoved(): evt = event.Event(MOUSEMOTION, rel=(0, 0), pos=mouse.get_pos(), buttons=mouse.get_pressed()) event.post(evt) def resetReach(self): self.postMouseMoved() if self.currentTool.resetToolReach(): return self.cameraToolDistance = self.defaultCameraToolDistance def increaseReach(self): self.postMouseMoved() if self.currentTool.increaseToolReach(): return self.cameraToolDistance = self._incrementReach(self.cameraToolDistance) def decreaseReach(self): self.postMouseMoved() if self.currentTool.decreaseToolReach(): return self.cameraToolDistance = self._decrementReach(self.cameraToolDistance) def _incrementReach(self, reach): reach += 1 if reach > 30 and self.fractionalReachAdjustment: reach *= 1.05 return reach def _decrementReach(self, reach): reach -= 1 if reach > 30 and self.fractionalReachAdjustment: reach *= 0.95 return reach def key_up(self, evt): self.currentTool.keyUp(evt) keyname = evt.dict.get('keyname', None) or self.root.getKey(evt) try: keyname = self.different_keys[keyname] except: pass if keyname == config.keys.brake.get(): self.mainViewport.brakeOff() if keyname == config.keys.fastNudge.get(): self.rightClickNudge = False if keyname == 'F7': self.testBoardKey = 0 if keyname == config.keys.fastNudge.get(): self.rightClickNudge = False def key_down(self, evt): if not pygame.key.get_focused(): return keyname = evt.dict.get('keyname', None) or self.root.getKey(evt) try: keyname = self.different_keys[keyname] except: pass #!# D.C.-G. #!# Here we have the part which is responsible for the fallback to the #!# select tool when pressing 'Escape' key. #!# It may be interesting to work on this to be able to return to a tool #!# which have called another. if keyname == 'Escape': if self.selectionTool.selectionInProgress: self.selectionTool.cancel() elif "fill" in str(self.currentTool) and self.toolbar.tools[3].replacing: self.toolbar.tools[3].replacing = False self.toolbar.tools[3].showPanel() elif "select" not in str(self.currentTool): self.toolbar.selectTool(0) else: self.mouseLookOff() self.showControls() self.currentTool.keyDown(evt) if keyname == "Alt-F4": self.quit() return if keyname == config.keys.longDistanceMode.get(): self.longDistanceMode = not self.longDistanceMode if keyname == "Alt-1" or keyname == "Alt-2" or keyname == "Alt-3" or keyname == "Alt-4" or keyname == "Alt-5": name = "option" + keyname[len(keyname) - 1:] if hasattr(self.currentTool, name): getattr(self.currentTool, name)() if keyname == config.keys.fastNudge.get(): self.rightClickNudge = True if "clone" in str(self.currentTool): blocksOnlyModifier = config.keys.blocksOnlyModifier.get() if keyname.startswith(blocksOnlyModifier): tempKeyname = keyname[len(blocksOnlyModifier) + 1:] blocksOnly = True else: tempKeyname = keyname blocksOnly = False if tempKeyname == config.keys.flip.get(): self.currentTool.flip(blocksOnly=blocksOnly) if tempKeyname == config.keys.rollClone.get(): self.currentTool.roll(blocksOnly=blocksOnly) if tempKeyname == config.keys.rotateClone.get(): self.currentTool.rotate(blocksOnly=blocksOnly) if tempKeyname == config.keys.mirror.get(): self.currentTool.mirror(blocksOnly=blocksOnly) if "Brush" in str(self.currentTool): if keyname == config.keys.decreaseBrush.get(): self.currentTool.decreaseBrushSize() if keyname == config.keys.increaseBrush.get(): self.currentTool.increaseBrushSize() blocksOnlyModifier = config.keys.blocksOnlyModifier.get() if keyname.startswith(blocksOnlyModifier): tempKeyname = keyname[len(blocksOnlyModifier) + 1:] blocksOnly = True else: tempKeyname = keyname blocksOnly = False if tempKeyname == config.keys.rotateBrush.get(): self.currentTool.rotate(blocksOnly=blocksOnly) if tempKeyname == config.keys.rollBrush.get(): self.currentTool.roll(blocksOnly=blocksOnly) if "fill" in str(self.currentTool) and keyname == config.keys.replaceShortcut.get(): self.currentTool.openReplace() if keyname == config.keys.quit.get(): self.quit() return if keyname == config.keys.viewDistance.get(): self.swapViewDistance() if keyname == config.keys.selectAll.get(): self.selectAll() if keyname == config.keys.deselect.get(): self.deselect() if keyname == config.keys.cut.get(): self.cutSelection() if keyname == config.keys.copy.get(): self.copySelection() if keyname == config.keys.paste.get(): self.pasteSelection() if keyname == config.keys.reloadWorld.get(): self.reload() if keyname == config.keys.open.get(): self.askOpenFile() if keyname == config.keys.quickLoad.get(): self.askLoadWorld() if keyname == config.keys.undo.get(): self.undo() if keyname == config.keys.redo.get(): self.redo() if keyname == config.keys.save.get(): self.saveFile() if keyname == config.keys.newWorld.get(): self.createNewLevel() if keyname == config.keys.closeWorld.get(): self.closeEditor() if keyname == config.keys.worldInfo.get(): self.showWorldInfo() if keyname == config.keys.gotoPanel.get(): self.showWaypointsDialog() if keyname == config.keys.saveAs.get(): self.saveAs() if keyname == config.keys.exportSelection.get(): self.selectionTool.exportSelection() if keyname == 'Ctrl-Alt-F9': try: expr = input_text(">>> ", 600) expr = compile(expr, 'eval', 'single') alert("Result: {0!r}".format(eval(expr, globals(), locals()))) except Exception as e: alert("Exception: {0!r}".format(e)) if keyname == 'Ctrl-Alt-F10': alert("MCEdit, a Minecraft World Editor\n\nCopyright 2010 David Rio Vierra") if keyname == config.keys.toggleView.get(): self.swapViewports() if keyname == config.keys.brake.get(): self.mainViewport.brakeOn() if keyname == config.keys.resetReach.get(): self.resetReach() if keyname == config.keys.increaseReach.get(): self.increaseReach() if keyname == config.keys.decreaseReach.get(): self.decreaseReach() if keyname == config.keys.swap.get(): self.currentTool.swap() if keyname == config.keys.confirmConstruction.get(): self.confirmConstruction() if keyname == config.keys.debugOverlay.get(): self.swapDebugLevels() if keyname == config.keys.toggleRenderer.get(): self.renderer.render = not self.renderer.render if keyname == config.keys.deleteBlocks.get(): self.deleteSelectedBlocks() if keyname == config.keys.flyMode.get(): config.settings.flyMode.set(not config.settings.flyMode.get()) config.save() for i, keyName in enumerate(self.toolbarKeys): if keyname == keyName: self.toolbar.selectTool(i) if keyname in ('F1', 'F2', 'F3', 'F4', 'F5'): self.mcedit.loadRecentWorldNumber(int(keyname[1])) if keyname == 'F7': self.testBoardKey = 1 if self.selectionSize(): filter_keys = [i for (i, j) in config.config.items("Filter Keys") if j == keyname] if filter_keys: if not self.toolbar.tools[4].filterModules: self.toolbar.tools[4].reloadFilters() filters = [i for i in self.toolbar.tools[4].filterModules if i.lower() == filter_keys[0]] if filters: if self.currentTool != 4: self.toolbar.selectTool(4) if self.toolbar.tools[4].panel.selectedName != filters[0]: self.toolbar.tools[4].panel.selectedName = filters[0] self.toolbar.tools[4].panel.reload() self.root.fix_sticky_ctrl() # TODO: Close marker def closeEditor(self): if self.unsavedEdits: answer = ask("Save unsaved edits before closing?", ["Cancel", "Don't Save", "Save"], default=-1, cancel=0) self.root.fix_sticky_ctrl() if answer == "Save": self.saveFile() if answer == "Cancel": return for p in self.toolbar.tools[6].nonSavedPlayers: if os.path.exists(p): os.remove(p) if config.settings.savePositionOnClose.get(): self.waypointManager.saveLastPosition(self.mainViewport, self.level.dimNo) self.waypointManager.save() self.clearUnsavedEdits() self.unsavedEdits = 0 self.root.RemoveEditFiles() self.root.fix_sticky_ctrl() self.selectionTool.endSelection() self.mainViewport.mouseLookOff() if self.level: self.level.close() self.level = None self.renderer.stopWork() self.removeWorker(self.renderer) self.renderer.level = None self.mcedit.removeEditor() self.controlPanel.dismiss() display.set_caption(("MCEdit ~ " + release.get_version()%_("for")).encode('utf-8')) if self.revertPlayerSkins: config.settings.downloadPlayerSkins.set(True) self.revertPlayerSkins = False # TODO: Load marker def loadWorldFromFTP(self): widget = Widget() ftp_ip_lbl = Label("FTP Server IP:") ftp_ip_field = TextFieldWrapped(width=400) ip_row = Row((ftp_ip_lbl, ftp_ip_field)) ftp_user_lbl = Label("FTP Username:") ftp_user_field = TextFieldWrapped(width=400) user_row = Row((ftp_user_lbl, ftp_user_field)) ftp_pass_lbl = Label("FTP Password:") ftp_pass_field = TextFieldWrapped(width=400) pass_row = Row((ftp_pass_lbl, ftp_pass_field)) note_creds = Label("NOTE: MCEdit-Unified will not use any FTP server info other than to login to the server") note_wait = Label("Please wait while MCEdit-Unified downloads the world. It will be opened once completed") col = Column((ip_row, user_row, pass_row, note_creds, note_wait)) widget.add(col) widget.shrink_wrap() d = Dialog(widget, ["Connect", "Cancel"]) if d.present() == "Connect": if ftp_user_field.get_text() == "" and ftp_pass_field.get_text() == "": self._ftp_client = ftp_client.FTPClient(ftp_ip_field.get_text()) else: try: self._ftp_client = ftp_client.FTPClient(ftp_ip_field.get_text(), username=ftp_user_field.get_text(), password=ftp_pass_field.get_text()) except ftp_client.InvalidCreditdentialsException as e: alert(e.message) return self._ftp_client.safe_download() self.mcedit.loadFile(os.path.join(self._ftp_client.get_level_path(), 'level.dat'), addToRecent=False) self.world_from_ftp = True def uploadChanges(self): if self.world_from_ftp and ftp_supported: if self.unsavedEdits: answer = ask("Save unsaved edits before closing?", ["Cancel", "Don't Save", "Save"], default=-1, cancel=0) self.root.fix_sticky_ctrl() if answer == "Save": self.saveFile() if answer == "Cancel": return self._ftp_client.upload() self.clearUnsavedEdits() self.unsavedEdits = 0 self.root.RemoveEditFiles() self.root.fix_sticky_ctrl() self.selectionTool.endSelection() self.mainViewport.mouseLookOff() if self.level: self.level.close() self.level = None self.renderer.stopWork() self.removeWorker(self.renderer) self.renderer.level = None self.mcedit.removeEditor() self.controlPanel.dismiss() display.set_caption(("MCEdit ~ " + release.get_version()%_("for")).encode('utf-8')) self._ftp_client.cleanup() elif not self.world_from_ftp: alert("This world was not downloaded from a FTP server. Uploading worlds that were not downloaded from a FTP server is currently not possible") elif not ftp_supported: alert('Uploading changes to an FTP server is disabled due to the \'ftputil\' module not being installed') def repairRegions(self): worldFolder = self.level.worldFolder for filename in worldFolder.findRegionFiles(): rf = worldFolder.tryLoadRegionFile(filename) if rf: rf.repair() alert("Repairs complete. See the console window for details.") @mceutils.alertException def showWorldInfo(self): worldInfoPanel = Dialog() items = [] #t = functools.partial(isinstance, self.level) if isinstance(self.level, pymclevel.MCInfdevOldLevel): if self.level.version == pymclevel.MCInfdevOldLevel.VERSION_ANVIL: levelFormat = "Minecraft Infinite World (Anvil Format)" elif self.level.version == pymclevel.MCInfdevOldLevel.VERSION_MCR: levelFormat = "Minecraft Infinite World (Region Format)" else: levelFormat = "Minecraft Infinite World (Old Chunk Format)" elif isinstance(self.level, pymclevel.MCIndevLevel): levelFormat = "Minecraft Indev (.mclevel format)" elif isinstance(self.level, pymclevel.MCSchematic): levelFormat = "MCEdit Schematic" elif isinstance(self.level, pymclevel.ZipSchematic): levelFormat = "MCEdit Schematic (Zipped Format)" elif isinstance(self.level, pymclevel.MCJavaLevel): levelFormat = "Minecraft Classic or raw block array" elif isinstance(self.level, pymclevel.PocketLeveldbWorld): levelFormat = "Minecraft Pocket Edition" else: levelFormat = "Unknown" formatLabel = Label(levelFormat) items.append(Row([Label("Format:"), formatLabel])) nameField = TextFieldWrapped(width=300, value=self.level.LevelName) def alt21(): nameField.insertion_point = len(nameField.text) nameField.insert_char(u'\xa7') alt21button = Button(u"\xa7", action=alt21) label = Label("Name:") items.append(Row((label, nameField, alt21button))) if hasattr(self.level, 'Time'): time = self.level.Time # timezone adjust - # minecraft time shows 0:00 on day 0 at the first sunrise # I want that to be 6:00 on day 1, so I add 30 hours time_editor = TimeEditor(current_tick_time=time) items.append(time_editor) if hasattr(self.level, 'RandomSeed'): seedField = IntField(width=250, value=self.level.RandomSeed) seedLabel = Label("RandomSeed: ") items.append(Row((seedLabel, seedField))) if hasattr(self.level, 'GameType'): t = self.level.GameType types = ["Survival", "Creative"] def gametype(t): if t < len(types): return types[t] return "Unknown" def action(): if b.gametype < 2: b.gametype = 1 - b.gametype b.text = gametype(b.gametype) b = Button(gametype(t), action=action) b.gametype = t gametypeRow = Row((Label("Game Type:"), b)) items.append(gametypeRow) button = Button("Repair regions", action=self.repairRegions) items.append(button) def openFolder(): filename = self.level.filename if not isdir(filename): filename = dirname(filename) mcplatform.platform_open(filename) revealButton = Button("Open Folder", action=openFolder) items.append(revealButton) if isinstance(self.level, pymclevel.MCInfdevOldLevel): chunkCount = self.level.chunkCount chunkCountLabel = Label(_("Number of chunks: {0}").format(chunkCount)) items.append(chunkCountLabel) if hasattr(self.level, 'worldFolder') and hasattr(self.level.worldFolder, 'regionFiles'): worldFolder = self.level.worldFolder regionCount = len(worldFolder.regionFiles) regionCountLabel = Label(_("Number of regions: {0}").format(regionCount)) items.append(regionCountLabel) size = self.level.size sizelabel = Label("{L}L x {W}W x {H}H".format(L=size[2], H=size[1], W=size[0])) items.append(sizelabel) if hasattr(self.level, "Entities"): label = Label(_("{0} Entities").format(len(self.level.Entities))) items.append(label) if hasattr(self.level, "TileEntities"): label = Label(_("{0} TileEntities").format(len(self.level.TileEntities))) items.append(label) col = Column(items) self.change = False def dismiss(*args, **kwargs): self.change = True worldInfoPanel.dismiss(self, *args, **kwargs) def cancel(*args, **kwargs): Changes = False if hasattr(self.level, 'Time'): time = time_editor.get_time_value() if self.level.Time != time: Changes = True if hasattr(self.level, 'DayTime'): day_time = time_editor.get_daytime_value() if self.level.DayTime != day_time: Changes = True if hasattr(self.level, 'RandomSeed') and seedField.value != self.level.RandomSeed: Changes = True if hasattr(self.level, 'LevelName') and nameField.value != self.level.LevelName: Changes = True if hasattr(self.level, 'GameType') and b.gametype != self.level.GameType: Changes = True if not Changes: worldInfoPanel.dismiss(self, *args, **kwargs) return result = ask("Do you want to keep your changes?", ["Yes", "No", "Cancel"]) if result == "Cancel": return if result == "No": worldInfoPanel.dismiss(self, *args, **kwargs) return if result == "Yes": dismiss(*args, **kwargs) col = Column((col, Row((Button("OK", action=dismiss), Button("Cancel", action=cancel))))) worldInfoPanel.add(col) worldInfoPanel.shrink_wrap() def dispatchKey(name, evt): dispatch_key_saved(name, evt) if name == "key_down": keyname = self.get_root().getKey(evt) if keyname == 'Escape': cancel() dispatch_key_saved = worldInfoPanel.dispatch_key worldInfoPanel.dispatch_key = dispatchKey worldInfoPanel.present() if not self.change: return class WorldInfoChangedOperation(Operation): def __init__(self, editor, level): self.editor = editor self.level = level self.canUndo = True self.changeLevelName = changeLevelName self.changeTime = changeTime self.changeDayTime = changeDayTime self.changeSeed = changeSeed self.changeGameType = changeGameType def perform(self, recordUndo=True): if recordUndo: if changeLevelName: self.UndoText = self.level.LevelName self.RedoText = nameField.value if changeTime: self.UndoTime = self.level.Time self.RedoTime = time if changeDayTime: self.UndoDayTime = self.level.DayTime self.RedoDayTime = day_time if changeSeed: self.UndoSeed = self.level.RandomSeed self.RedoSeed = seedField.value if changeGameType: self.UndoGameType = self.level.GameType self.RedoGameType = b.gametype if changeLevelName: self.level.LevelName = nameField.value if changeTime: self.level.Time = time if changeDayTime: self.level.DayTime = day_time if changeSeed: self.level.RandomSeed = seedField.value if changeGameType: self.level.GameType = b.gametype def undo(self): if self.changeLevelName: self.level.LevelName = self.UndoText if self.changeTime: self.level.Time = self.UndoTime if self.changeDayTime: self.level.DayTime = self.UndoDayTime if self.changeSeed: self.level.RandomSeed = self.UndoSeed if self.changeGameType: self.level.GameType = self.UndoGameType def redo(self): if self.changeLevelName: self.level.LevelName = self.RedoText if self.changeTime: self.level.Time = self.RedoTime if self.changeDayTime: self.level.DayTime = self.RedoDayTime if self.changeSeed: self.level.RandomSeed = self.RedoSeed if self.changeGameType: self.level.GameType = self.RedoGameType changeTime = False changeSeed = False changeLevelName = False changeGameType = False changeDayTime = False if hasattr(self.level, 'Time'): time = time_editor.get_time_value() if self.level.Time != time: changeTime = True if hasattr(self.level, 'DayTime'): day_time = time_editor.get_daytime_value() if self.level.DayTime != day_time: changeDayTime = True if hasattr(self.level, 'RandomSeed') and seedField.value != self.level.RandomSeed: changeSeed = True if hasattr(self.level, 'LevelName') and nameField.value != self.level.LevelName: changeLevelName = True if hasattr(self.level, 'GameType') and b.gametype != self.level.GameType: changeGameType = True if changeTime or changeSeed or changeLevelName or changeGameType: op = WorldInfoChangedOperation(self, self.level) self.addOperation(op) self.addUnsavedEdit() def swapViewDistance(self): if self.renderer.viewDistance >= config.settings.maxViewDistance.get(): self.renderer.viewDistance = self.renderer.minViewDistance else: self.renderer.viewDistance += 2 self.addWorker(self.renderer) config.settings.viewDistance.set(self.renderer.viewDistance) def changeViewDistance(self, dist): self.renderer.viewDistance = min(config.settings.maxViewDistance.get(), dist) self.addWorker(self.renderer) config.settings.viewDistance.set(self.renderer.viewDistance) @mceutils.alertException def askLoadWorld(self): if not os.path.isdir(directories.minecraftSaveFileDir): alert(_(u"Could not find the Minecraft saves directory!\n\n({0} was not found or is not a directory)").format( directories.minecraftSaveFileDir)) return worldPanel = Widget() potentialWorlds = os.listdir(directories.minecraftSaveFileDir) potentialWorlds = [os.path.join(directories.minecraftSaveFileDir, p) for p in potentialWorlds] worldFiles = [p for p in potentialWorlds if pymclevel.MCInfdevOldLevel.isLevel(p)] worlds = [] for f in worldFiles: try: lev = pymclevel.MCInfdevOldLevel(f, readonly=True) except Exception: continue else: worlds.append(lev) if len(worlds) == 0: alert("No worlds found! You should probably play Minecraft to create your first world.") return def loadWorld(): self.mcedit.loadFile(self.worldData[worldTable.selectedWorldIndex][3].filename) self.root.fix_sticky_ctrl() def click_row(i, evt): worldTable.selectedWorldIndex = i if evt.num_clicks == 2: loadWorld() dialog.dismiss("Cancel") def dispatch_key(name, evt): if name != "key_down": return keyname = self.root.getKey(evt) if keyname == "Escape": dialog.dismiss("Cancel") elif keyname == "Up": worldTable.selectedWorldIndex = max(0, worldTable.selectedWorldIndex - 1) worldTable.rows.scroll_to_item(worldTable.selectedWorldIndex) elif keyname == "Down": worldTable.selectedWorldIndex = min(len(worlds) - 1, worldTable.selectedWorldIndex + 1) worldTable.rows.scroll_to_item(worldTable.selectedWorldIndex) elif keyname == 'Page up': worldTable.selectedWorldIndex = max(0, worldTable.selectedWorldIndex - worldTable.rows.num_rows()) worldTable.rows.scroll_to_item(worldTable.selectedWorldIndex) elif keyname == 'Page down': worldTable.selectedWorldIndex = min(len(worlds) - 1, worldTable.selectedWorldIndex + worldTable.rows.num_rows()) worldTable.rows.scroll_to_item(worldTable.selectedWorldIndex) elif keyname == "Return": loadWorld() dialog.dismiss("Cancel") else: old_dispatch_key(name, evt) text = fld.text.lower() worldsToUse = [] splitText = text.split(" ") amount = len(splitText) for v in allWorlds: nameParts = [a.lower() for a in nameFormat(v)] i = 0 spiltTextUsed = [] for v2 in nameParts: Start = True j = 0 while j < len(splitText) and Start: if splitText[j] in v2 and j not in spiltTextUsed: i += 1 spiltTextUsed.append(j) Start = False j += 1 if i == amount: worldsToUse.append(v) self.worldData = [[dateFormat(d), nameFormat(w), w, d] for w, d in ((w, dateobj(w.LastPlayed)) for w in worldsToUse)] self.worldData.sort(key=lambda (a, b, w, d): d, reverse=True) worldTable.selectedWorldIndex = 0 worldTable.num_rows = lambda: len(self.worldData) worldTable.row_data = lambda i: self.worldData[i] worldTable.rows.scroll_to_item(0) def key_up(evt): pass allWorlds = worlds lbl = Label("Search") fld = TextFieldWrapped(300) old_dispatch_key = fld.dispatch_key fld.dispatch_key = dispatch_key row = Row((lbl, fld)) worldTable = TableView(columns=[ TableColumn("Last Played", 200, "l"), TableColumn("Level Name", 300, "l"), TableColumn("File Name", 300, "l") ]) def dateobj(lp): try: return datetime.utcfromtimestamp(lp / 1000.0) except: return datetime.utcfromtimestamp(0.0) def dateFormat(lp): try: return lp.strftime("%x %X").decode('utf-8') except: return u"{0} seconds since the epoch.".format(lp) def nameFormat(w): try: if w.LevelName == w.displayName.decode("utf-8"): return w.LevelName, w.LevelName return u"%s" % w.LevelName, u"%s" % w.displayName.decode("utf-8") except: try: return w.LevelName, w.LevelName except: try: return w.displayName, w.displayName except: return "[UNABLE TO READ]", "[? ? ?]" self.worldData = [[dateFormat(d)] + list(nameFormat(w)) + [w, d] for w, d in ((w, dateobj(w.LastPlayed)) for w in worlds)] self.worldData.sort(key=lambda (a, b, c, w, d): d, reverse=True) worldTable.selectedWorldIndex = 0 worldTable.num_rows = lambda: len(self.worldData) worldTable.row_data = lambda i: self.worldData[i] worldTable.row_is_selected = lambda x: x == worldTable.selectedWorldIndex worldTable.click_row = click_row worldTable.top = row.bottom worldPanel.add(row) worldPanel.add(worldTable) worldPanel.shrink_wrap() if ftp_supported: options = ["Load", "From FTP Server", "Cancel"] else: options = ["Load", "Cancel"] dialog = Dialog(worldPanel, options) dialog.key_up = key_up result = dialog.present() if result == "Load": loadWorld() if result == "From FTP Server": self.loadWorldFromFTP() def askOpenFile(self): self.mouseLookOff() try: filename = mcplatform.askOpenFile(schematics=True) if filename: self.parent.loadFile(filename) except Exception: logging.exception('Error while asking user for filename') return def createNewLevel(self): self.mouseLookOff() newWorldPanel = Widget() newWorldPanel.w = newWorldPanel.h = 16 newWorldPanel.x = newWorldPanel.z = newWorldPanel.f = 0 newWorldPanel.y = 64 newWorldPanel.seed = 0 label = Label("Creating a new world.") generatorPanel = GeneratorPanel() xinput = IntInputRow("X: ", ref=AttrRef(newWorldPanel, "x")) yinput = IntInputRow("Y: ", ref=AttrRef(newWorldPanel, "y")) zinput = IntInputRow("Z: ", ref=AttrRef(newWorldPanel, "z")) finput = IntInputRow("f: ", ref=AttrRef(newWorldPanel, "f"), min=0, max=3) xyzrow = Row([xinput, yinput, zinput, finput]) seedinput = IntInputRow("Seed: ", width=250, ref=AttrRef(newWorldPanel, "seed")) winput = IntInputRow("East-West Chunks: ", ref=AttrRef(newWorldPanel, "w"), min=0) hinput = IntInputRow("North-South Chunks: ", ref=AttrRef(newWorldPanel, "h"), min=0) gametypes = ["Survival", "Creative"] worldtypes = {"Default": ("DEFAULT", "default"), "Superflat": ("FLAT", "flat"), "Large Biomes": ("LARGEBIOMES", "largeBiomes"), "Amplified": ("AMPLIFIED", "amplified")} def gametype(t): if t < len(gametypes): return gametypes[t] return "Unknown" def gametypeAction(): if gametypeButton.gametype < 2: gametypeButton.gametype = 1 - gametypeButton.gametype gametypeButton.text = gametype(gametypeButton.gametype) gametypeButton = Button(gametype(0), action=gametypeAction) gametypeButton.gametype = 0 gametypeRow = Row((Label("Game Type:"), gametypeButton)) worldtypeButton = ChoiceButton(worldtypes.keys()) worldtypeRow = Row((Label("World Type:"), worldtypeButton)) newWorldPanel.add( Column((label, Row([winput, hinput]), xyzrow, seedinput, gametypeRow, worldtypeRow, generatorPanel), align="l")) newWorldPanel.shrink_wrap() result = Dialog(client=newWorldPanel, responses=["Create", "Cancel"]).present() if result == "Cancel": return filename = mcplatform.askCreateWorld(directories.minecraftSaveFileDir) if not filename: return w = newWorldPanel.w h = newWorldPanel.h x = newWorldPanel.x y = newWorldPanel.y z = newWorldPanel.z f = newWorldPanel.f seed = newWorldPanel.seed or None generationtype = worldtypes[worldtypeButton.get_value()][0] self.freezeStatus("Creating world...") try: newlevel = pymclevel.MCInfdevOldLevel(filename=filename, create=True, random_seed=seed) # chunks = list(itertools.product(xrange(w / 2 - w + cx, w / 2 + cx), xrange(h / 2 - h + cz, h / 2 + cz))) if generatorPanel.generatorChoice.selectedChoice == "Flatland": y = generatorPanel.chunkHeight newlevel.setPlayerPosition((x + 0.5, y + 2.8, z + 0.5)) newlevel.setPlayerOrientation((f * 90.0, 0.0)) newlevel.setPlayerSpawnPosition((x, y + 1, z)) newlevel.GameType = gametypeButton.gametype newlevel.GeneratorName = worldtypes[worldtypeButton.get_value()][1] newlevel.saveInPlace() worker = generatorPanel.generate(newlevel, pymclevel.BoundingBox((x - w * 8, 0, z - h * 8), (w * 16, newlevel.Height, h * 16)), useWorldType=generationtype) if "Canceled" == showProgress("Generating chunks...", worker, cancel=True): generatorPanel.kill_process() raise RuntimeError("Canceled.") if y < 64: y = 64 newlevel.setBlockAt(x, y, z, pymclevel.alphaMaterials.Sponge.ID) if newlevel.parentWorld: newlevel = newlevel.parentWorld newlevel.acquireSessionLock() newlevel.saveInPlace() self.loadFile(filename) except Exception: logging.exception( 'Error while creating world. {world => %s}' % filename ) return return newlevel def confirmConstruction(self): self.currentTool.confirm() def selectionToChunks(self, remove=False, add=False): box = self.selectionBox() if box: if box == self.level.bounds: self.selectedChunks = set(self.level.allChunks) return selectedChunks = self.selectedChunks boxedChunks = set(box.chunkPositions) if boxedChunks.issubset(selectedChunks): remove = True if remove and not add: selectedChunks.difference_update(boxedChunks) else: selectedChunks.update(boxedChunks) self.selectionTool.selectNone() def chunksToSelection(self): if len(self.selectedChunks) == 0: return starting_chunk = self.selectedChunks.pop() box = self.selectionTool.selectionBoxForCorners((starting_chunk[0] << 4, 0, starting_chunk[1] << 4), ((starting_chunk[0] << 4) + 15, 256, (starting_chunk[1] << 4) + 15)) for c in self.selectedChunks: box = box.union(self.selectionTool.selectionBoxForCorners((c[0] << 4, 0, c[1] << 4), ((c[0] << 4) + 15, 256, (c[1] << 4) + 15))) self.selectedChunks = set([]) self.selectionTool.selectNone() self.selectionTool.setSelection(box) def selectAll(self): if self.currentViewport is self.chunkViewport: self.selectedChunks = set(self.level.allChunks) else: self.selectionTool.selectAll() def deselect(self): self.selectionTool.deselect() self.selectedChunks.clear() def endSelection(self): self.selectionTool.endSelection() def cutSelection(self): self.selectionTool.cutSelection() def copySelection(self): self.selectionTool.copySelection() def pasteSelection(self): schematic = self.getLastCopiedSchematic() self.pasteSchematic(schematic) def pasteSchematic(self, schematic): if schematic is None: return self.currentTool.cancel() self.currentTool = self.toolbar.tools[5] self.currentTool.loadLevel(schematic) def deleteSelectedBlocks(self): self.selectionTool.deleteBlocks() @mceutils.alertException def undo(self): if len(self.undoStack) == 0 and len(self.afterSaveUndoStack) == 0: return with mceutils.setWindowCaption("UNDOING - "): self.freezeStatus("Undoing the previous operation...") wasSelectionBox = False if self.selectionBox(): wasSelectionBox = True if len(self.undoStack) > 0: op = self.undoStack.pop() normalUndo = True else: op = self.afterSaveUndoStack.pop() normalUndo = False if self.recordUndo: self.redoStack.append(op) if len(self.redoStack) > self.undoLimit: self.redoStack.pop(0) op.undo() changedBox = op.dirtyBox() if changedBox is not None: self.invalidateBox(changedBox) if not self.selectionBox() and wasSelectionBox: self.toolbar.selectTool(0) self.toolbar.tools[0].currentCorner = 1 if ".SelectionOperation" not in str(op) and ".NudgeSelectionOperation" not in str(op): if normalUndo: self.removeUnsavedEdit() else: self.addUnsavedEdit() self.root.fix_sticky_ctrl() def redo(self): if len(self.redoStack) == 0: return with mceutils.setWindowCaption("REDOING - "): self.freezeStatus("Redoing the previous operation...") op = self.redoStack.pop() if self.recordUndo: self.undoStack.append(op) if len(self.undoStack) > self.undoLimit: self.undoStack.pop(0) op.redo() changedBox = op.dirtyBox() if changedBox is not None: self.invalidateBox(changedBox) if op.changedLevel: self.addUnsavedEdit() self.root.fix_sticky_ctrl() def invalidateBox(self, box): self.renderer.invalidateChunksInBox(box) def invalidateChunks(self, c): self.renderer.invalidateChunks(c) def invalidateAllChunks(self): self.renderer.invalidateAllChunks() def discardAllChunks(self): self.renderer.discardAllChunks() def addDebugString(self, string): if self.debug: self.debugString += string averageFPS = 0.0 averageCPS = 0.0 shouldLoadAndRender = True def gl_draw(self): self.debugString = "" self.inspectionString = "" if not self.level: return if not self.shouldLoadAndRender: return self.renderer.loadVisibleChunks() self.addWorker(self.renderer) if self.currentTool.previewRenderer: self.currentTool.previewRenderer.loadVisibleChunks() self.addWorker(self.currentTool.previewRenderer) self.frames += 1 frameDuration = self.getFrameDuration() while frameDuration > ( datetime.now() - self.frameStartTime): # if it's less than 0ms until the next frame, go draw. otherwise, go work. self.doWorkUnit() frameStartTime = datetime.now() timeDelta = frameStartTime - self.frameStartTime # self.addDebugString("FrameStart: {0} CameraTick: {1}".format(frameStartTime, self.mainViewport.lastTick)) # self.addDebugString("D: %d, " % () ) self.currentFrameDelta = timeDelta self.frameSamples.pop(0) self.frameSamples.append(timeDelta) frameTotal = numpy.sum(self.frameSamples) self.averageFPS = 1000000. / ( (frameTotal.microseconds + 1000000 * frameTotal.seconds) / float(len(self.frameSamples)) + 0.00001) r = self.renderer chunkTotal = numpy.sum(r.chunkSamples) cps = 1000000. / ( (chunkTotal.microseconds + 1000000 * chunkTotal.seconds) / float(len(r.chunkSamples)) + 0.00001) self.averageCPS = cps self.oldFrameStartTime = self.frameStartTime self.frameStartTime = frameStartTime if self.debug > 0: self.debugString = _("FPS: %0.1f/%0.1f, CPS: %0.1f, VD: %d, W: %d, WF: %d, MBv: %0.1f, ") % ( 1000000. / (float(timeDelta.microseconds) + 0.000001), self.averageFPS, cps, self.renderer.viewDistance, len(self.workers), self.renderer.workFactor, self.renderer.bufferUsage / 1000000.) self.debugString += _("DL: {dl} ({dlcount}), Tx: {t}, gc: {g}, ").format( dl=len(glutils.DisplayList.allLists), dlcount=glutils.gl.listCount, t=len(glutils.Texture.allTextures), g=len(gc.garbage)) if self.renderer: self.renderer.addDebugInfo(self.addDebugString) def doWorkUnit(self, onMenu=False): if len(self.workers): try: w = self.workers.popleft() w.next() self.workers.append(w) except StopIteration: if hasattr(w, "needsRedraw") and w.needsRedraw: self.invalidate() if onMenu: time.sleep(0.001) def updateInspectionString(self, blockPosition): self.inspectionString += str(blockPosition) + ": " x, y, z = blockPosition cx, cz = x // 16, z // 16 try: if self.debug: if isinstance(self.level, pymclevel.MCIndevLevel): bl = self.level.blockLightAt(*blockPosition) blockID = self.level.blockAt(*blockPosition) bdata = self.level.blockDataAt(*blockPosition) self.inspectionString += _("ID: %d:%d (%s), ") % ( blockID, bdata, self.level.materials.names[blockID][bdata]) self.inspectionString += _("Data: %d, Light: %d, ") % (bdata, bl) elif isinstance(self.level, pymclevel.ChunkedLevelMixin): sl = self.level.skylightAt(*blockPosition) bl = self.level.blockLightAt(*blockPosition) bdata = self.level.blockDataAt(*blockPosition) blockID = self.level.blockAt(*blockPosition) self.inspectionString += _("ID: %d:%d (%s), ") % ( blockID, bdata, self.level.materials.names[blockID][bdata]) try: path = self.level.getChunk(cx, cz).filename except: path = "chunks.dat" self.inspectionString += _("Data: %d, L: %d, SL: %d") % ( bdata, bl, sl) try: hm = self.level.heightMapAt(x, z) self.inspectionString += _(", H: %d") % hm except: pass try: tp = self.level.getChunk(cx, cz).TerrainPopulated self.inspectionString += _(", TP: %d") % tp except: pass self.inspectionString += _(", D: %d") % self.level.getChunk(cx, cz).dirty self.inspectionString += _(", NL: %d") % self.level.getChunk(cx, cz).needsLighting try: biome = self.level.getChunk(cx, cz).Biomes[x & 15, z & 15] from pymclevel import biome_types self.inspectionString += _(", Bio: %s") % biome_types.biome_types[biome] except AttributeError: pass if isinstance(self.level, pymclevel.pocket.PocketWorld): ch = self.level.getChunk(cx, cz) self.inspectionString += _(", DC: %s") % ch.DirtyColumns[z & 15, x & 15] self.inspectionString += _(", Ch(%d, %d): %s") % (cx, cz, path) else: # classic blockID = self.level.blockAt(*blockPosition) self.inspectionString += _("ID: %d (%s), ") % ( blockID, self.level.materials.names[blockID][0]) except Exception as e: self.inspectionString += _("Chunk {0} had an error: {1!r}").format( (int(numpy.floor(blockPosition[0])) >> 4, int(numpy.floor(blockPosition[2])) >> 4), e) import traceback traceback.print_exc() def drawWireCubeReticle(self, color=(1.0, 1.0, 1.0, 1.0), position=None): GL.glPolygonOffset(DepthOffset.TerrainWire, DepthOffset.TerrainWire) GL.glEnable(GL.GL_POLYGON_OFFSET_FILL) blockPosition, faceDirection = self.blockFaceUnderCursor blockPosition = position or blockPosition mceutils.drawTerrainCuttingWire(pymclevel.BoundingBox(blockPosition, (1, 1, 1)), c1=color) GL.glDisable(GL.GL_POLYGON_OFFSET_FILL) @staticmethod def drawString(x, y, color, string): return @staticmethod def freezeStatus(string): return def selectionSize(self): return self.selectionTool.selectionSize() def selectionBox(self): return self.selectionTool.selectionBox() def selectionChanged(self): if not self.currentTool.toolEnabled(): self.toolbar.selectTool(0) self.currentTool.selectionChanged() def addOperation(self, op): self.performWithRetry(op) if self.recordUndo and op.canUndo: self.undoStack.append(op) if len(self.undoStack) > self.undoLimit: self.undoStack.pop(0) recordUndo = True def performWithRetry(self, op): try: op.perform(self.recordUndo) except MemoryError: self.invalidateAllChunks() op.perform(self.recordUndo) def quit(self): if config.settings.savePositionOnClose.get(): self.waypointManager.saveLastPosition(self.mainViewport, self.level.getPlayerDimension()) self.waypointManager.save() self.mouseLookOff() self.mcedit.confirm_quit() mouseWasCaptured = False def showControls(self): #.# self.controlPanel.top = self.subwidgets[0].bottom self.controlPanel.left = (self.width - self.controlPanel.width) / 2 #.# self.controlPanel.present(False) infoPanel = None def showChunkRendererInfo(self): if self.infoPanel: self.infoPanel.set_parent(None) return self.infoPanel = infoPanel = Widget(bg_color=(0, 0, 0, 80)) infoPanel.add(Label("")) def idleHandler(evt): x, y, z = self.blockFaceUnderCursor[0] cx, cz = x // 16, z // 16 cr = self.renderer.chunkRenderers.get((cx, cz)) if cr is None: return crNames = [_("%s - %0.1fkb") % (type(br).__name__, br.bufferSize() / 1000.0) for br in cr.blockRenderers] infoLabel = Label("\n".join(crNames)) infoPanel.remove(infoPanel.subwidgets[0]) infoPanel.add(infoLabel) infoPanel.shrink_wrap() self.invalidate() infoPanel.idleevent = idleHandler infoPanel.topleft = self.viewportContainer.topleft self.add(infoPanel) infoPanel.click_outside_response = -1 def handleMemoryError(self): if self.renderer.viewDistance <= 2: raise MemoryError("Out of memory. Please restart MCEdit.") if hasattr(self.level, 'compressAllChunks'): self.level.compressAllChunks() self.toolbar.selectTool(0) self.renderer.viewDistance -= 4 self.renderer.discardAllChunks() logging.warning( 'Out of memory, decreasing view distance. {view => %s}' % ( self.renderer.viewDistance ) ) config.settings.viewDistance.set(self.renderer.viewDistance) config.save() def lockLost(self): #image_path = directories.getDataDir(os.path.join("toolicons", "session_bad.png")) image_path = directories.getDataFile('toolicons', 'session_bad.png') self.sessionLockLock.set_image(get_image(image_path, prefix="")) self.sessionLockLock.tooltipText = "Session Lock is being used by Minecraft" self.sessionLockLabel.tooltipText = "Session Lock is being used by Minecraft" if not self.waypointManager.already_saved and config.settings.savePositionOnClose.get(): self.waypointManager.saveLastPosition(self.mainViewport, self.level.getPlayerDimension()) def lockAcquired(self): #image_path = directories.getDataDir(os.path.join("toolicons", "session_good.png")) image_path = directories.getDataFile('toolicons', 'session_good.png') self.sessionLockLock.set_image(get_image(image_path, prefix="")) self.sessionLockLock.tooltipText = "Session Lock is being used by MCEdit" self.sessionLockLabel.tooltipText = "Session Lock is being used by MCEdit" self.root.sessionStolen = False self.waypointManager.already_saved = False class EditorToolbar(GLOrtho): toolbarSize = (204, 24) tooltipsUp = True toolbarTextureSize = (202., 22.) currentToolTextureRect = (0., 22., 24., 24.) toolbarWidthRatio = 0.5 # toolbar's width as fraction of screen width. def toolbarSizeForScreenWidth(self, width): f = max(1, int(width + 418) / 420) return [x * f for x in self.toolbarSize] def __init__(self, rect, tools, *args, **kw): GLOrtho.__init__(self, xmin=0, ymin=0, xmax=self.toolbarSize[0], ymax=self.toolbarSize[1], near=-4.0, far=4.0) self.size = self.toolbarTextureSize self.tools = tools for i, t in enumerate(tools): t.toolNumber = i t.hotkey = i + 1 self.toolTextures = {} self.toolbarDisplayList = glutils.DisplayList() self.reloadTextures() def set_parent(self, parent, index=None): GLOrtho.set_parent(self, parent, index) self.parent_resized(0, 0) def parent_resized(self, dw, dh): self.size = self.toolbarSizeForScreenWidth(self.parent.width) self.centerx = self.parent.centerx self.bottom = self.parent.viewportContainer.bottom # xxx resize children when get def getTooltipText(self): toolNumber = self.toolNumberUnderMouse(mouse.get_pos()) return self.tools[toolNumber].tooltipText tooltipText = property(getTooltipText) def toolNumberUnderMouse(self, pos): x, y = self.global_to_local(pos) (tx, ty, tw, th) = self.toolbarRectInWindowCoords() toolNumber = float(len(self.tools)) * x / tw return min(int(toolNumber), len(self.tools) - 1) def set_update_ui(self, v): for tool in self.tools: if tool.optionsPanel: tool.optionsPanel.set_update_ui(v) GLOrtho.set_update_ui(self, v) def mouse_down(self, evt): if self.parent.level: toolNo = self.toolNumberUnderMouse(evt.pos) if toolNo < 0 or toolNo > len(self.tools) - 1: return if evt.button == 1: self.selectTool(toolNo) if evt.button == 3: self.showToolOptions(toolNo) def showToolOptions(self, toolNumber): if len(self.tools) > toolNumber >= 0: t = self.tools[toolNumber] # if not t.toolEnabled(): # return if t.optionsPanel: t.optionsPanel.present() def selectTool(self, toolNumber): ''' pass a number outside the bounds to pick the selection tool''' if toolNumber >= len(self.tools) or toolNumber < 0: toolNumber = 0 t = self.tools[toolNumber] if not t.toolEnabled(): return if self.parent.currentTool == t: self.parent.currentTool.toolReselected() return else: self.parent.selectionTool.hidePanel() if self.parent.currentTool is not None: self.parent.currentTool.cancel() self.parent.currentTool.toolDeselected() self.parent.currentTool = t self.parent.currentTool.toolSelected() return def removeToolPanels(self): for tool in self.tools: tool.hidePanel() def toolbarRectInWindowCoords(self): """returns a rectangle (x, y, w, h) representing the toolbar's location in the window. use for hit testing.""" (pw, ph) = self.parent.size pw = float(pw) ph = float(ph) x, y = self.toolbarSizeForScreenWidth(pw) tw = x * 200. / 202. th = y * 20. / 22. tx = (pw - tw) / 2 ty = ph - th * 22. / 20. return tx, ty, tw, th def toolTextureChanged(self): self.toolbarDisplayList.invalidate() def reloadTextures(self): self.toolTextureChanged() self.guiTexture = mceutils.loadPNGTexture('gui.png') self.toolTextures = {} for tool in self.tools: if hasattr(tool, 'reloadTextures'): tool.reloadTextures() if hasattr(tool, 'markerList'): tool.markerList.invalidate() def drawToolbar(self): GL.glEnableClientState(GL.GL_TEXTURE_COORD_ARRAY) GL.glColor(1., 1., 1., 1.) w, h = self.toolbarTextureSize self.guiTexture.bind() GL.glVertexPointer(3, GL.GL_FLOAT, 0, numpy.array(( 1, h + 1, 0.5, w + 1, h + 1, 0.5, w + 1, 1, 0.5, 1, 1, 0.5, ), dtype="f4")) GL.glTexCoordPointer(2, GL.GL_FLOAT, 0, numpy.array(( 0, 0, w, 0, w, h, 0, h, ), dtype="f4")) GL.glDrawArrays(GL.GL_QUADS, 0, 4) for i in xrange(len(self.tools)): tool = self.tools[i] if tool.toolIconName is None: continue try: if tool.toolIconName not in self.toolTextures: filename = "toolicons" + os.sep + "{0}.png".format(tool.toolIconName) self.toolTextures[tool.toolIconName] = mceutils.loadPNGTexture(filename) x = 20 * i + 4 y = 4 w = 16 h = 16 self.toolTextures[tool.toolIconName].bind() GL.glVertexPointer(3, GL.GL_FLOAT, 0, numpy.array(( x, y + h, 1, x + w, y + h, 1, x + w, y, 1, x, y, 1, ), dtype="f4")) GL.glTexCoordPointer(2, GL.GL_FLOAT, 0, numpy.array(( 0, 0, w * 16, 0, w * 16, h * 16, 0, h * 16, ), dtype="f4")) GL.glDrawArrays(GL.GL_QUADS, 0, 4) except Exception: logging.exception('Error while drawing toolbar.') GL.glDisableClientState(GL.GL_TEXTURE_COORD_ARRAY) gfont = None def gl_draw(self): GL.glEnable(GL.GL_TEXTURE_2D) GL.glEnable(GL.GL_BLEND) self.toolbarDisplayList.call(self.drawToolbar) GL.glColor(1.0, 1.0, 0.0) try: currentToolNumber = self.tools.index(self.parent.currentTool) except ValueError: pass else: # draw a bright rectangle around the current tool (texx, texy, texw, texh) = self.currentToolTextureRect tx = 20. * float(currentToolNumber) ty = 0. tw = 24. th = 24. GL.glEnableClientState(GL.GL_TEXTURE_COORD_ARRAY) self.guiTexture.bind() GL.glVertexPointer(3, GL.GL_FLOAT, 0, numpy.array(( tx, ty, 2, tx + tw, ty, 2, tx + tw, ty + th, 2, tx, ty + th, 2, ), dtype="f4")) GL.glTexCoordPointer(2, GL.GL_FLOAT, 0, numpy.array(( texx, texy + texh, texx + texw, texy + texh, texx + texw, texy, texx, texy, ), dtype="f4")) GL.glDrawArrays(GL.GL_QUADS, 0, 4) GL.glDisableClientState(GL.GL_TEXTURE_COORD_ARRAY) GL.glDisable(GL.GL_TEXTURE_2D) redOutBoxes = numpy.zeros(9 * 4 * 2, dtype='float32') cursor = 0 for i in xrange(len(self.tools)): t = self.tools[i] if t.toolEnabled(): continue redOutBoxes[cursor:cursor + 8] = [ 4 + i * 20, 4, 4 + i * 20, 20, 20 + i * 20, 20, 20 + i * 20, 4, ] cursor += 8 if cursor: GL.glColor(1.0, 0.0, 0.0, 0.3) GL.glVertexPointer(2, GL.GL_FLOAT, 0, redOutBoxes) GL.glDrawArrays(GL.GL_QUADS, 0, cursor / 2) GL.glDisable(GL.GL_BLEND) from albow.resource import get_image
134,511
37.355289
195
py
MCEdit-Unified
MCEdit-Unified-master/mceutils.py
"""Copyright (c) 2010-2012 David Rio Vierra Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.""" # import resource_packs # not the right place, moving it a bit furtehr """ mceutils.py Exception catching, some basic box drawing, texture pack loading, oddball UI elements """ # Modified by D.C.-G. for translation purpose #.# Marks the layout modifications. -- D.C.-G. #!# #!# The stuff in there related to albow should be in albow module. #!# This stuff will then be available for components base classes in this GUI module. #!# And make albow/widgets more coherent to use. #!# from resource_packs import ResourcePackHandler from albow.controls import ValueDisplay from albow import alert, ask, Button, Column, Label, root, Row, ValueButton, Widget from albow.translate import _ from datetime import datetime import directories import numpy from OpenGL import GL import os import png from pygame import display import pymclevel import logging #!# Used to track the ALBOW stuff imported from here def warn(obj): name = getattr(obj, '__name__', getattr(getattr(obj, '__class__', obj), '__name__', obj)) logging.getLogger().warn('%s.%s is deprecated and will be removed. Use albow.%s instead.' % (obj.__module__, name, name)) #!# def alertException(func): def _alertException(*args, **kw): try: return func(*args, **kw) except root.Cancel: alert("Canceled.") except pymclevel.infiniteworld.SessionLockLost as e: alert(_(e.message) + _("\n\nYour changes cannot be saved.")) except Exception as e: logging.exception("Exception:") ask(_("Error during {0}: {1!r}").format(func, e)[:1000], ["OK"], cancel=0) return _alertException def drawFace(box, face, type=GL.GL_QUADS): x, y, z, = box.origin x2, y2, z2 = box.maximum if face == pymclevel.faces.FaceXDecreasing: faceVertices = numpy.array( (x, y2, z2, x, y2, z, x, y, z, x, y, z2, ), dtype='f4') elif face == pymclevel.faces.FaceXIncreasing: faceVertices = numpy.array( (x2, y, z2, x2, y, z, x2, y2, z, x2, y2, z2, ), dtype='f4') elif face == pymclevel.faces.FaceYDecreasing: faceVertices = numpy.array( (x2, y, z2, x, y, z2, x, y, z, x2, y, z, ), dtype='f4') elif face == pymclevel.faces.FaceYIncreasing: faceVertices = numpy.array( (x2, y2, z, x, y2, z, x, y2, z2, x2, y2, z2, ), dtype='f4') elif face == pymclevel.faces.FaceZDecreasing: faceVertices = numpy.array( (x, y, z, x, y2, z, x2, y2, z, x2, y, z, ), dtype='f4') elif face == pymclevel.faces.FaceZIncreasing: faceVertices = numpy.array( (x2, y, z2, x2, y2, z2, x, y2, z2, x, y, z2, ), dtype='f4') faceVertices.shape = (4, 3) dim = face >> 1 dims = [0, 1, 2] dims.remove(dim) texVertices = numpy.array( faceVertices[:, dims], dtype='f4' ).flatten() faceVertices.shape = (12,) texVertices *= 16 GL.glEnableClientState(GL.GL_TEXTURE_COORD_ARRAY) GL.glVertexPointer(3, GL.GL_FLOAT, 0, faceVertices) GL.glTexCoordPointer(2, GL.GL_FLOAT, 0, texVertices) GL.glEnable(GL.GL_POLYGON_OFFSET_FILL) GL.glEnable(GL.GL_POLYGON_OFFSET_LINE) if type is GL.GL_LINE_STRIP: indexes = numpy.array((0, 1, 2, 3, 0), dtype='uint32') GL.glDrawElements(type, 5, GL.GL_UNSIGNED_INT, indexes) else: GL.glDrawArrays(type, 0, 4) GL.glDisable(GL.GL_POLYGON_OFFSET_FILL) GL.glDisable(GL.GL_POLYGON_OFFSET_LINE) GL.glDisableClientState(GL.GL_TEXTURE_COORD_ARRAY) def drawCube(box, cubeType=GL.GL_QUADS, blockType=0, texture=None, textureVertices=None, selectionBox=False): """ pass a different cubeType e.g. GL_LINE_STRIP for wireframes """ x, y, z, = box.origin x2, y2, z2 = box.maximum dx, dy, dz = x2 - x, y2 - y, z2 - z cubeVertices = numpy.array( ( x, y, z, x, y2, z, x2, y2, z, x2, y, z, x2, y, z2, x2, y2, z2, x, y2, z2, x, y, z2, x2, y, z2, x, y, z2, x, y, z, x2, y, z, x2, y2, z, x, y2, z, x, y2, z2, x2, y2, z2, x, y2, z2, x, y2, z, x, y, z, x, y, z2, x2, y, z2, x2, y, z, x2, y2, z, x2, y2, z2, ), dtype='f4') if textureVertices is None: textureVertices = numpy.array( ( 0, -dy * 16, 0, 0, dx * 16, 0, dx * 16, -dy * 16, dx * 16, -dy * 16, dx * 16, 0, 0, 0, 0, -dy * 16, dx * 16, -dz * 16, 0, -dz * 16, 0, 0, dx * 16, 0, dx * 16, 0, 0, 0, 0, -dz * 16, dx * 16, -dz * 16, dz * 16, 0, 0, 0, 0, -dy * 16, dz * 16, -dy * 16, dz * 16, -dy * 16, 0, -dy * 16, 0, 0, dz * 16, 0, ), dtype='f4') textureVertices.shape = (6, 4, 2) if selectionBox: textureVertices[0:2] += (16 * (x & 15), 16 * (y2 & 15)) textureVertices[2:4] += (16 * (x & 15), -16 * (z & 15)) textureVertices[4:6] += (16 * (z & 15), 16 * (y2 & 15)) textureVertices[:] += 0.5 GL.glVertexPointer(3, GL.GL_FLOAT, 0, cubeVertices) if texture is not None: GL.glEnable(GL.GL_TEXTURE_2D) GL.glEnableClientState(GL.GL_TEXTURE_COORD_ARRAY) texture.bind() GL.glTexCoordPointer(2, GL.GL_FLOAT, 0, textureVertices), GL.glEnable(GL.GL_POLYGON_OFFSET_FILL) GL.glEnable(GL.GL_POLYGON_OFFSET_LINE) GL.glDrawArrays(cubeType, 0, 24) GL.glDisable(GL.GL_POLYGON_OFFSET_FILL) GL.glDisable(GL.GL_POLYGON_OFFSET_LINE) if texture is not None: GL.glDisableClientState(GL.GL_TEXTURE_COORD_ARRAY) GL.glDisable(GL.GL_TEXTURE_2D) def drawTerrainCuttingWire(box, c0=(0.75, 0.75, 0.75, 0.4), c1=(1.0, 1.0, 1.0, 1.0)): # glDepthMask(False) GL.glEnable(GL.GL_DEPTH_TEST) GL.glDepthFunc(GL.GL_LEQUAL) GL.glColor(*c1) GL.glLineWidth(2.0) drawCube(box, cubeType=GL.GL_LINE_STRIP) GL.glDepthFunc(GL.GL_GREATER) GL.glColor(*c0) GL.glLineWidth(1.0) drawCube(box, cubeType=GL.GL_LINE_STRIP) GL.glDepthFunc(GL.GL_LEQUAL) GL.glDisable(GL.GL_DEPTH_TEST) # glDepthMask(True) def loadAlphaTerrainTexture(): #texW, texH, terraindata = loadPNGFile(os.path.join(directories.getDataDir(), ResourcePackHandler.Instance().get_selected_resource_pack().terrain_path())) texW, texH, terraindata = loadPNGFile(directories.getDataFile(ResourcePackHandler.Instance().get_selected_resource_pack().terrain_path())) def _loadFunc(): loadTextureFunc(texW, texH, terraindata) tex = glutils.Texture(_loadFunc) tex.data = terraindata return tex def loadPNGData(filename_or_data): reader = png.Reader(filename_or_data) (w, h, data, metadata) = reader.read_flat() data = numpy.array(data, dtype='uint8') data.shape = (h, w, metadata['planes']) if data.shape[2] == 1: # indexed color. remarkably straightforward. data.shape = data.shape[:2] data = numpy.array(reader.palette(), dtype='uint8')[data] if data.shape[2] < 4: data = numpy.insert(data, 3, 255, 2) return w, h, data def loadPNGFile(filename): (w, h, data) = loadPNGData(filename) powers = (16, 32, 64, 128, 256, 512, 1024, 2048, 4096) assert (w in powers) and (h in powers) # how crude return w, h, data def loadTextureFunc(w, h, ndata): GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA, w, h, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, ndata) return w, h def loadPNGTexture(filename, *a, **kw): #filename = os.path.join(directories.getDataDir(), filename) filename = directories.getDataFile(filename) try: w, h, ndata = loadPNGFile(filename) tex = glutils.Texture(functools.partial(loadTextureFunc, w, h, ndata), *a, **kw) tex.data = ndata return tex except Exception as e: print "Exception loading ", filename, ": ", repr(e) return glutils.Texture() import glutils def normalize(x): l = x[0] * x[0] + x[1] * x[1] + x[2] * x[2] if l <= 0.0: return [0, 0, 0] size = numpy.sqrt(l) if size <= 0.0: return [0, 0, 0] return map(lambda a: a / size, x) def normalize_size(x): l = x[0] * x[0] + x[1] * x[1] + x[2] * x[2] if l <= 0.0: return [0., 0., 0.], 0. size = numpy.sqrt(l) if size <= 0.0: return [0, 0, 0], 0 return (x / size), size # Label = GLLabel class HotkeyColumn(Widget): is_gl_container = True def __init__(self, items, keysColumn=None, buttonsColumn=None, item_spacing=None): warn(self) if keysColumn is None: keysColumn = [] if buttonsColumn is None: buttonsColumn = [] labels = [] Widget.__init__(self) for t in items: if len(t) == 3: (hotkey, title, action) = t tooltipText = None else: (hotkey, title, action, tooltipText) = t if isinstance(title, (str, unicode)): button = Button(title, action=action) else: button = ValueButton(ref=title, action=action, width=200) button.anchor = self.anchor label = Label(hotkey, width=100, margin=button.margin) label.anchor = "wh" label.height = button.height labels.append(label) if tooltipText: button.tooltipText = tooltipText keysColumn.append(label) buttonsColumn.append(button) self.buttons = list(buttonsColumn) #.# if not item_spacing: buttonsColumn = Column(buttonsColumn) else: buttonsColumn = Column(buttonsColumn, spacing=item_spacing) #.# buttonsColumn.anchor = self.anchor #.# if not item_spacing: keysColumn = Column(keysColumn) else: keysColumn = Column(keysColumn, spacing=item_spacing) commandRow = Row((keysColumn, buttonsColumn)) self.labels = labels self.add(commandRow) self.shrink_wrap() from albow import CheckBox, AttrRef, Menu class MenuButton(Button): def __init__(self, title, choices, **kw): warn(self) Button.__init__(self, title, **kw) self.choices = choices self.menu = Menu(title, ((c, c) for c in choices)) def action(self): index = self.menu.present(self, (0, 0)) if index == -1: return self.menu_picked(index) def menu_picked(self, index): pass class ChoiceButton(ValueButton): align = "c" choose = None def __init__(self, choices, scrolling=True, scroll_items=30, **kw): # passing an empty list of choices is ill-advised warn(self) if 'choose' in kw: self.choose = kw.pop('choose') ValueButton.__init__(self, action=self.showMenu, **kw) self.scrolling = scrolling self.scroll_items = scroll_items self.choices = choices or ["[UNDEFINED]"] widths = [self.font.size(_(c))[0] for c in choices] + [self.width] if len(widths): self.width = max(widths) + self.margin * 2 self.choiceIndex = 0 def showMenu(self): choiceIndex = self.menu.present(self, (0, 0)) if choiceIndex != -1: self.choiceIndex = choiceIndex if self.choose: self.choose() def get_value(self): return self.selectedChoice @property def selectedChoice(self): if self.choiceIndex >= len(self.choices) or self.choiceIndex < 0: return "" return self.choices[self.choiceIndex] @selectedChoice.setter def selectedChoice(self, val): idx = self.choices.index(val) if idx != -1: self.choiceIndex = idx @property def choices(self): return self._choices @choices.setter def choices(self, ch): self._choices = ch self.menu = Menu("", ((name, "pickMenu") for name in self._choices), self.scrolling, self.scroll_items) def CheckBoxLabel(title, *args, **kw): warn(CheckBoxLabel) tooltipText = kw.pop('tooltipText', None) cb = CheckBox(*args, **kw) lab = Label(title, fg_color=cb.fg_color) lab.mouse_down = cb.mouse_down if tooltipText: cb.tooltipText = tooltipText lab.tooltipText = tooltipText class CBRow(Row): margin = 0 @property def value(self): return self.checkbox.value @value.setter def value(self, val): self.checkbox.value = val row = CBRow((lab, cb)) row.checkbox = cb return row from albow import FloatField, IntField, TextFieldWrapped def FloatInputRow(title, *args, **kw): warn(FloatInputRow) return Row((Label(title, tooltipText=kw.get('tooltipText')), FloatField(*args, **kw))) def IntInputRow(title, *args, **kw): warn(IntInputRow) return Row((Label(title, tooltipText=kw.get('tooltipText')), IntField(*args, **kw))) from albow.dialogs import Dialog from datetime import timedelta def TextInputRow(title, *args, **kw): warn(TextInputRow) return Row((Label(title, tooltipText=kw.get('tooltipText')), TextFieldWrapped(*args, **kw))) def setWindowCaption(prefix): caption = display.get_caption()[0] prefix = _(prefix) if isinstance(prefix, unicode): prefix = prefix.encode("utf8") class ctx: def __enter__(self): display.set_caption(prefix + caption) def __exit__(self, *args): display.set_caption(caption) return ctx() def showProgress(progressText, progressIterator, cancel=False): """Show the progress for a long-running synchronous operation. progressIterator should be a generator-like object that can return either None, for an indeterminate indicator, A float value between 0.0 and 1.0 for a determinate indicator, A string, to update the progress info label or a tuple of (float value, string) to set the progress and update the label""" warn(ShowProgress) class ProgressWidget(Dialog): progressFraction = 0.0 firstDraw = False root = None def draw(self, surface): if self.root is None: self.root = self.get_root() Widget.draw(self, surface) frameStart = datetime.now() frameInterval = timedelta(0, 1, 0) / 2 amount = None try: while datetime.now() < frameStart + frameInterval: amount = progressIterator.next() if self.firstDraw is False: self.firstDraw = True break except StopIteration: self.dismiss() infoText = "" if amount is not None: if isinstance(amount, tuple): if len(amount) > 2: infoText = ": " + amount[2] amount, max = amount[:2] else: max = amount maxwidth = (self.width - self.margin * 2) if amount is None: self.progressBar.width = maxwidth self.progressBar.bg_color = (255, 255, 25, 255) elif isinstance(amount, basestring): self.statusText = amount else: self.progressAmount = amount if isinstance(amount, (int, float)): self.progressFraction = float(amount) / (float(max) or 1) self.progressBar.width = maxwidth * self.progressFraction self.statusText = str("{0} / {1}".format(amount, max)) else: self.statusText = str(amount) if infoText: self.statusText += infoText @property def estimateText(self): delta = (datetime.now() - self.startTime) progressPercent = (int(self.progressFraction * 10000)) if progressPercent > 10000: progressPercent = 10000 left = delta * (10000 - progressPercent) / (progressPercent or 1) return _("Time left: {0}").format(left) def cancel(self): if cancel: self.dismiss(False) def idleevent(self): self.invalidate() def key_down(self, event): pass def key_up(self, event): pass def mouse_up(self, event): try: if "SelectionTool" in str(self.root.editor.currentTool): if self.root.get_nudge_block().count > 0: self.root.get_nudge_block().mouse_up(event) except: pass widget = ProgressWidget() widget.progressText = _(progressText) widget.statusText = "" widget.progressAmount = 0.0 progressLabel = ValueDisplay(ref=AttrRef(widget, 'progressText'), width=550) statusLabel = ValueDisplay(ref=AttrRef(widget, 'statusText'), width=550) estimateLabel = ValueDisplay(ref=AttrRef(widget, 'estimateText'), width=550) progressBar = Widget(size=(550, 20), bg_color=(150, 150, 150, 255)) widget.progressBar = progressBar col = (progressLabel, statusLabel, estimateLabel, progressBar) if cancel: cancelButton = Button("Cancel", action=widget.cancel, fg_color=(255, 0, 0, 255)) col += (Column((cancelButton,), align="r"),) widget.add(Column(col)) widget.shrink_wrap() widget.startTime = datetime.now() if widget.present(): return widget.progressAmount else: return "Canceled" from glutils import DisplayList import functools
19,496
28.143498
159
py
MCEdit-Unified
MCEdit-Unified-master/compass.py
""" compass """ import logging from OpenGL import GL from drawable import Drawable from glutils import gl from mceutils import loadPNGTexture from config import config import os log = logging.getLogger(__name__) def makeQuad(minx, miny, width, height): return [minx, miny, minx + width, miny, minx + width, miny + height, minx, miny + height] class CompassOverlay(Drawable): _tex = None _yawPitch = (0., 0.) x, y = 0, 0 def __init__(self): super(CompassOverlay, self).__init__() @property def yawPitch(self): return self._yawPitch @yawPitch.setter def yawPitch(self, value): self._yawPitch = value self.invalidate() def drawSelf(self): if self._tex is None: filename = os.path.join("toolicons", "compass.png") self._tex = loadPNGTexture(filename) self._tex.bind() size = 0.001 * config.settings.compassSize.get() with gl.glPushMatrix(GL.GL_MODELVIEW): GL.glLoadIdentity() yaw, pitch = self.yawPitch if config.settings.viewMode.get() == "Chunk": yaw = -180 GL.glTranslatef(1. - (size + self.x), size + self.y, 0.0) # position on upper right corner GL.glRotatef(180 - yaw, 0., 0., 1.) # adjust to north GL.glColor3f(1., 1., 1.) with gl.glEnableClientState(GL.GL_TEXTURE_COORD_ARRAY): GL.glVertexPointer(2, GL.GL_FLOAT, 0, makeQuad(-size, -size, 2 * size, 2 * size)) GL.glTexCoordPointer(2, GL.GL_FLOAT, 0, makeQuad(0, 0, 256, 256)) with gl.glEnable(GL.GL_BLEND, GL.GL_TEXTURE_2D): GL.glDrawArrays(GL.GL_QUADS, 0, 4)
1,743
27.590164
103
py
MCEdit-Unified
MCEdit-Unified-master/mcplatform.py
"""Copyright (c) 2010-2012 David Rio Vierra Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.""" # -# Modified by D.C.-G. for translation purpose # !# Tests for file chooser """ mcplatform.py Platform-specific functions, folder paths, and the whole fixed/portable nonsense. """ import logging log = logging.getLogger(__name__) import directories import os from os.path import dirname, exists, join import sys import platform enc = sys.getfilesystemencoding() hasXlibDisplay = False if sys.platform == "win32": if platform.architecture()[0] == "32bit": plat = "win32" if platform.architecture()[0] == "64bit": plat = "win-amd64" #sys.path.append(join(directories.getDataDir(), "pymclevel", "build", "lib." + plat + "-2.6").encode(enc)) sys.path.append(directories.getDataFile('pymclevel', 'build', 'lib.{}-2.6'.format(plat)).encode(enc)) elif sys.platform in ['linux2', 'darwin']: try: import Xlib.display import Xlib.X import Xlib.protocol hasXlibDisplay = True except ImportError: hasXlibDisplay = None #os.environ["YAML_ROOT"] = join(directories.getDataDir(), "pymclevel").encode(enc) os.environ['YAML_ROOT'] = directories.getDataFile('pymclevel').encode(enc) from pygame import display from albow import request_new_filename, request_old_filename from albow.translate import _ from pymclevel import minecraftSaveFileDir, getMinecraftProfileDirectory, getSelectedProfile from datetime import datetime import re import subprocess try: import pygtk pygtk.require('2.0') import gtk if gtk.pygtk_version < (2, 3, 90): raise ImportError hasGtk = True except ImportError: hasGtk = False # Using old method as fallback texturePacksDir = os.path.join(getMinecraftProfileDirectory(getSelectedProfile()), "texturepacks") # Compatibility layer for filters: filtersDir = directories.filtersDir schematicsDir = directories.schematicsDir # !# Disabling platform specific file chooser: # !# Please, don't touch these two lines and the 'platChooser' stuff. -- D.C.-G. #platChooser = sys.platform in ('linux2', 'darwin') platChooser = sys.platform == 'darwin' def dynamic_arguments(func_to_replace, askFile_func): def wrapper(initialDir, displayName, fileFormat): if isinstance(fileFormat, tuple): return func_to_replace(initialDir, displayName, fileFormat) else: def old_askSaveSchematic(initialDir, displayName, fileFormat): dt = datetime.now().strftime("%Y-%m-%d--%H-%M-%S") return askFile_func(initialDir, title=_('Save this schematic...'), defaultName=displayName + "_" + dt + "." + fileFormat, filetype=_('Minecraft Schematics (*.{0})\0*.{0}\0\0').format(fileFormat), suffix=fileFormat, ) return old_askSaveSchematic(initialDir, displayName, fileFormat) return wrapper def getTexturePacks(): try: return os.listdir(texturePacksDir) except: return [] if sys.platform == "win32": try: from win32 import win32gui from win32 import win32api from win32.lib import win32con except ImportError: import win32gui import win32api import win32con try: import win32com.client from win32com.shell import shell, shellcon # @UnresolvedImport except: pass try: import pywintypes except: pass if sys.platform == 'darwin': cmd_name = "Cmd" option_name = "Opt" else: cmd_name = "Ctrl" option_name = "Alt" def OSXVersionChecker(name, compare): """Rediculously complicated function to compare current System version to inputted version.""" if compare != 'gt' and compare != 'lt' and compare != 'eq' and compare != 'gteq' and compare != 'lteq': print "Invalid version check {}".format(compare) return False if sys.platform == 'darwin': try: systemVersion = platform.mac_ver()[0].split('.') if len(systemVersion) == 2: systemVersion.append('0') major, minor, patch = 10, 0, 0 if name.lower() == 'cheetah': minor = 0 patch = 4 elif name.lower() == 'puma': minor = 1 patch = 5 elif name.lower() == 'jaguar': minor = 2 patch = 8 elif name.lower() == 'panther': minor = 3 patch = 9 elif name.lower() == 'tiger': minor = 4 patch = 11 elif name.lower() == 'snow_leopard': minor = 5 patch = 8 elif name.lower() == 'snow_leopard': minor = 6 patch = 8 elif name.lower() == 'lion': minor = 7 patch = 5 elif name.lower() == 'mountain_lion': minor = 8 patch = 5 elif name.lower() == 'mavericks': minor = 9 patch = 5 elif name.lower() == 'yosemite': minor = 10 patch = 0 else: major = 0 if int(systemVersion[0]) > int(major): ret_val = 1 elif int(systemVersion[0]) < int(major): ret_val = -1 else: if int(systemVersion[1]) > int(minor): ret_val = 1 elif int(systemVersion[1]) < int(minor): ret_val = -1 else: if int(systemVersion[2]) > int(patch): ret_val = 1 elif int(systemVersion[2]) < int(patch): ret_val = -1 else: ret_val = 0 if ret_val == 0 and (compare == 'eq' or compare == 'gteq' or compare == 'lteq'): return True elif ret_val == -1 and (compare == 'lt' or compare == 'lteq'): return True elif ret_val == 1 and (compare == 'gt' or compare == 'gteq'): return True except: print "An error occured determining the system version" return False else: return False lastSchematicsDir = None lastSaveDir = None def buildFileTypes(filetypes): result = "" for key in reversed(filetypes[0].keys()): ftypes = [] result += key + " (" for ftype in filetypes[0][key]: ftypes.append("*." + ftype) result += ",".join(ftypes) + ")\0" result += ";".join(ftypes) + "\0" return result + "\0" def askOpenFile(title='Select a Minecraft level....', schematics=False, suffixes=None): title = _(title) global lastSchematicsDir, lastSaveDir if not suffixes: suffixes = ["mclevel", "dat", "mine", "mine.gz", "mcworld"] suffixesChanged = False else: suffixesChanged = True initialDir = lastSaveDir or minecraftSaveFileDir if schematics: initialDir = lastSchematicsDir or directories.schematicsDir def _askOpen(_suffixes): if schematics: _suffixes.append("schematic") _suffixes.append("schematic.gz") _suffixes.append("zip") _suffixes.append("inv") _suffixes.append("nbt") # BO support _suffixes.append("bo2") _suffixes.append("bo3") _suffixes.sort() if sys.platform == "win32": # !# if suffixesChanged: sendSuffixes = _suffixes else: sendSuffixes = None return askOpenFileWin32(title, schematics, initialDir, sendSuffixes) elif hasGtk and not platChooser: # !# #Linux (When GTK 2.4 or newer is installed) return askOpenFileGtk(title, _suffixes, initialDir) else: log.debug("Calling internal file chooser.") log.debug("'initialDir' is %s (%s)" % (repr(initialDir), type(initialDir))) try: iDir = initialDir.encode(enc) except Exception as e: iDir = initialDir log.debug("Could not encode 'initialDir' %s" % repr(initialDir)) log.debug("Encode function returned: %s" % e) if "All files (*.*)" not in _suffixes and "*.* (*.*)" not in _suffixes: _suffixes.append("All files (*.*)") return request_old_filename(suffixes=_suffixes, directory=iDir) filename = _askOpen(suffixes) if filename: if schematics: lastSchematicsDir = dirname(filename) else: lastSaveDir = dirname(filename) return filename def askOpenFileWin32(title, schematics, initialDir, suffixes=None): try: if not suffixes: f = (_('Levels and Schematics') + '\0*.mclevel;*.dat;*.mine;*.mine.gz;*.schematic;*.zip;*.schematic.gz;*.inv;*.nbt;*.mcworld\0' + '*.*\0*.*\0\0') else: f = "All\0" for suffix in suffixes: f += "*." + suffix + ";" f += "\0*.*\0\0" filename, customfilter, flags = win32gui.GetOpenFileNameW( hwndOwner=display.get_wm_info()['window'], InitialDir=initialDir, Flags=(win32con.OFN_EXPLORER | win32con.OFN_NOCHANGEDIR | win32con.OFN_FILEMUSTEXIST | win32con.OFN_LONGNAMES ), Title=title, Filter=f, ) except Exception: pass else: return filename def askOpenFileGtk(title, suffixes, initialDir): fls = [] def run_dlg(): chooser = gtk.FileChooserDialog(title, None, gtk.FILE_CHOOSER_ACTION_SAVE, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK)) chooser.set_default_response(gtk.RESPONSE_OK) chooser.set_current_folder(initialDir) chooser.set_current_name("world") # For some reason the Windows isn't closing if this line ins missing or the parameter is "" # Add custom Filter file_filter = gtk.FileFilter() file_filter.set_name(_("Levels and Schematics")) for suffix in suffixes: file_filter.add_pattern("*." + suffix) chooser.add_filter(file_filter) # Add "All files" Filter file_filter = gtk.FileFilter() file_filter.set_name("All files") file_filter.add_pattern("*") chooser.add_filter(file_filter) response = chooser.run() if response == gtk.RESPONSE_OK: fls.append(chooser.get_filename()) else: fls.append(None) chooser.destroy() gtk.main_quit() gtk.idle_add(run_dlg) gtk.main() return fls[0] def askSaveSchematic(initialDir, displayName, fileFormats): fileFormat = buildFileTypes(fileFormats) dt = datetime.now().strftime("%Y-%m-%d--%H-%M-%S") return askSaveFile(initialDir, title=_('Save this schematic...'), defaultName=displayName + "_" + dt + "." + fileFormats[0][fileFormats[0].keys()[1]][0], filetype=fileFormat, suffix=fileFormat, ) def askCreateWorld(initialDir): defaultName = name = _("Untitled World") i = 0 while exists(join(initialDir, name)): i += 1 name = defaultName + " " + str(i) return askSaveFile(initialDir, title=_('Name this new world.'), defaultName=name, filetype=_('Minecraft World\0*.*\0\0'), suffix="", ) def askSaveFile(initialDir, title, defaultName, filetype, suffix): if sys.platform == "win32": # !# try: if isinstance(suffix, (list, tuple)) and suffix: suffix = suffix[0] print repr(filetype) if not filetype.endswith("*.*\0*.*\0\0"): filetype = filetype[:-1] + "*.*\0*.*\0\0" print repr(filetype) (filename, customfilter, flags) = win32gui.GetSaveFileNameW( hwndOwner=display.get_wm_info()['window'], InitialDir=initialDir, Flags=win32con.OFN_EXPLORER | win32con.OFN_NOCHANGEDIR | win32con.OFN_OVERWRITEPROMPT, File=defaultName, DefExt=suffix, Title=title, Filter=filetype, ) except Exception as e: print "Error getting file name: ", e return try: filename = filename[:filename.index('\0')] filename = filename.decode(sys.getfilesystemencoding()) except: pass else: # Reformat the Windows stuff if "\0" in suffix and suffix.count("*.") > 1: _suffix = suffix.split("\0")[:-2] else: _suffix = suffix if "\0" in filetype and filetype.count("*.") > 0: _filetype = filetype.split("\0")[:-2] else: _filetype = filetype if hasGtk and not platChooser: # !# #Linux (When GTK 2.4 or newer is installed) fls = [] def run_dlg(): chooser = gtk.FileChooserDialog(title, None, gtk.FILE_CHOOSER_ACTION_SAVE, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK)) chooser.set_default_response(gtk.RESPONSE_OK) chooser.set_current_folder(initialDir) chooser.set_current_name(defaultName) # Add custom Filter if isinstance(_filetype, list) or isinstance(_filetype, tuple): for i, stuff in enumerate(_filetype): if i % 2 == 0: file_filter = gtk.FileFilter() file_filter.set_name(stuff) else: if ";" in stuff: for _suff in stuff.split(";"): if _suff: file_filter.add_pattern(_suff) else: file_filter.add_pattern(stuff) chooser.add_filter(file_filter) if i % 2 == 0: if ";" in stuff: for _suff in stuff.split(";"): if _suff: file_filter.add_pattern(_suff) else: file_filter.add_pattern(stuff) chooser.add_filter(file_filter) else: file_filter = gtk.FileFilter() file_filter.set_name(filetype[:filetype.index("\0")]) if "\0" in suffix and suffix.count("*.") > 1: __suffix = suffix.split("\0")[:-2] else: __suffix = suffix if isinstance(__suffix, list) or isinstance(__suffix, tuple): for suff in __suffix: file_filter.add_pattern("*." + suff) else: file_filter.add_pattern("*." + __suffix) chooser.add_filter(file_filter) # Add "All files" Filter file_filter = gtk.FileFilter() file_filter.set_name("All files") file_filter.add_pattern("*") chooser.add_filter(file_filter) response = chooser.run() if response == gtk.RESPONSE_OK: fls.append(chooser.get_filename()) else: fls.append(None) chooser.destroy() gtk.main_quit() gtk.idle_add(run_dlg) gtk.main() filename = fls[0] else: # Fallback log.debug("Calling internal file chooser.") log.debug("'initialDir' is %s (%s)" % (repr(initialDir), type(initialDir))) log.debug("'defaultName' is %s (%s)" % (repr(defaultName), type(defaultName))) try: iDir = initialDir.encode(enc) except Exception as e: iDir = initialDir log.debug("Could not encode 'initialDir' %s" % repr(initialDir)) log.debug("Encode function returned: %s" % e) try: dName = defaultName.encode(enc) except Exception as e: dName = defaultName log.debug("Could not encode 'defaultName' %s" % repr(defaultName)) log.debug("Encode function returned: %s" % e) if isinstance(_suffix, list) or isinstance(_suffix, tuple): sffxs = [a[1:] for a in _suffix[1::2]] sffx = sffxs.pop(0) sffxs.append('.*') else: sffx = _suffix sffxs = [] for i, stuff in enumerate(_filetype): if i % 2 == 0: file_filter = stuff else: file_filter += " (%s)"%stuff sffxs.append(file_filter) if i % 2 == 0: file_filter += " (%s)"%stuff sffxs.append(file_filter) if "All files (*.*)" not in sffxs and "*.* (*.*)" not in sffxs: sffxs.append("All files (*.*)") filename = request_new_filename(prompt=title, suffix=sffx, extra_suffixes=sffxs, directory=iDir, filename=dName, pathname=None) return filename askSaveSchematic = dynamic_arguments(askSaveSchematic, askSaveFile) # Start Open Folder Dialogs # TODO: Possibly get an OS X dialog def askOpenFolderWin32(title, initialDir): try: desktop_pidl = shell.SHGetFolderLocation(0, shellcon.CSIDL_DESKTOP, 0, 0) pidl, display_name, image_list = shell.SHBrowseForFolder ( win32gui.GetDesktopWindow(), desktop_pidl, "Choose a folder", 0, None, None ) return shell.SHGetPathFromIDList(pidl) except pywintypes.com_error as e: if e.args[0] == -2147467259: print "Invalid folder selected" def askOpenFolderGtk(title, initialDir): if hasGtk: fls = [] def run_dlg(): chooser = gtk.FileChooserDialog(title, None, gtk.FILE_CHOOSER_ACTION_SAVE, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK)) chooser.set_default_response(gtk.RESPONSE_OK) chooser.set_current_folder(initialDir) chooser.set_current_name("world") chooser.set_action(gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER) response = chooser.run() if response == gtk.RESPONSE_OK: fls.append(chooser.get_filename()) # Returns the folder path if gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER is the action else: fls.append(None) chooser.destroy() gtk.main_quit() gtk.idle_add(run_dlg) gtk.main() return fls[0] else: print "You currently need gtk to use an Open Folder Dialog!" def platform_open(path): try: if sys.platform == "win32": os.startfile(path) elif sys.platform == "darwin": os.system('open "' + path + '"') else: os.system('xdg-open "' + path + '"') except Exception as e: print "platform_open failed on {0}: {1}".format(sys.platform, e) win32_window_size = True #============================================================================= #============================================================================= # DESKTOP ENVIRONMENTS AND OS SIDE WINDOW MANAGEMENT. # # The idea is to have a single object to deal with underling OS specific window management interface. # This will help to save/restore MCEdit window sate, position and size. # # TODO: # * Test on the actually unsupported Linux DEs. # * Review WWindowHandler class for Windows. # * Create a DWindowHandler class for Darwin (OSX). # Window states MINIMIZED = 0 NORMAL = 1 MAXIMIZED = 2 FULLSCREEN = 3 #============================================================================= # Linux desktop environment detection. # # source: http://stackoverflow.com/questions/2035657/what-is-my-current-desktop-environment (http://stackoverflow.com/a/21213358) # # Tweaked, of course ;) # def get_desktop_environment(): # From http://stackoverflow.com/questions/2035657/what-is-my-current-desktop-environment # and http://ubuntuforums.org/showthread.php?t=652320 # and http://ubuntuforums.org/showthread.php?t=652320 # and http://ubuntuforums.org/showthread.php?t=1139057 if sys.platform in ("win32", "cygwin"): return "windows" elif sys.platform == "darwin": return "mac" else: # Most likely either a POSIX system or something not much common ds = os.environ.get("DESKTOP_SESSION", None) if ds in ('default', None): ds = os.environ.get("XDG_CURRENT_DESKTOP", None) if ds is not None: # easier to match if we doesn't have to deal with caracter cases desktop_session = ds.lower() found = re.findall(r"gnome|unity|cinnamon|mate|xfce4|lxde|fluxbox|blackbox|openbox|icewm|jwm|afterstep|trinity|kde", desktop_session, re.I) if len(found) == 1: return found[0] elif len(found) > 1: print "Houston? We have a problem...\n\nThe desktop environment can't be found: '%s' has been detected to be %s alltogeteher." % (ds, " and ".join((", ".join(found[:-1]), found[-1]))) return 'unknown' # # Special cases ## # Canonical sets $DESKTOP_SESSION to Lubuntu rather than LXDE if using LXDE. # There is no guarantee that they will not do the same with the other desktop environments. elif "xfce" in desktop_session or desktop_session.startswith("xubuntu"): return "xfce4" elif desktop_session.startswith("ubuntu"): return "unity" elif desktop_session.startswith("lubuntu"): return "lxde" elif desktop_session.startswith("kubuntu"): return "kde" elif desktop_session.startswith("razor"): # e.g. razorkwin return "razor-qt" elif desktop_session.startswith("wmaker"): # e.g. wmaker-common return "windowmaker" if os.environ.get('KDE_FULL_SESSION', None) == 'true': return "kde" elif os.environ.get('GNOME_DESKTOP_SESSION_ID', None): if not "deprecated" in os.environ.get('GNOME_DESKTOP_SESSION_ID', None): return "gnome2" # From http://ubuntuforums.org/showthread.php?t=652320 elif is_running("xfce-mcs-manage"): return "xfce4" elif is_running("ksmserver"): return "kde" return "unknown" def is_running(process): # From http://www.bloggerpolis.com/2011/05/how-to-check-if-a-process-is-running-using-python/ # and http://richarddingwall.name/2009/06/18/windows-equivalents-of-ps-and-kill-commands/ try: # Linux/Unix s = subprocess.Popen(["ps", "axw"], stdout=subprocess.PIPE) except: # Windows s = subprocess.Popen(["tasklist", "/v"], stdout=subprocess.PIPE) for x in s.stdout: if re.search(process, x): return True return False #============================================================================= # Window handling. desktop_environment = get_desktop_environment() DEBUG_WM = False USE_WM = True # Desktops settings # Each entry in the platform sub-dictionaries represent which object is used to get/set the window metrics. # # For Linux: # Valid entries are: position_gap, position_getter, position_setter, size_getter, size_setter and state. # Entries can be omitted; default values will be used. # For position_gap the default is (0, 0, False, False) # For the other ones, the default is the Pygame window object. # # position_gap is used on some environment to restore the windows at the coords it was formerly. # The two first values of the tuple are the amount of pixels to add to the window x and y coords. # The two last ones tell whether these pixels shall be added only once (at program startup) or always. # desktops = {'linux2': { 'cinnamon': { # Actually, there's a bug when resizing on XCinnamon. 'position_setter': 'parent', 'position_getter': 'parent.parent', 'position_gap': (9, 8, True, True), 'state': 'parent' }, 'gnome': { 'position_setter': 'parent', 'position_getter': 'parent.parent', 'size_setter': 'parent', 'size_getter': 'parent', 'state': 'parent' }, 'kde': { 'position_setter': 'parent', 'position_getter': 'parent.parent.parent', 'state': 'parent' }, 'unity': { 'position_setter': 'parent', 'position_getter': 'parent.parent.parent', 'position_gap': (10, 10, False, False), 'size_setter': 'parent', 'state': 'parent' } }, } # The environments in the next definition need to be tested. linux_unsuported = ('afterstep', 'blackbox', 'fluxbox', 'gnome2', 'icewm', 'jwm', 'lxde', 'mate', 'openbox', 'razor-qt', 'trinity', 'windowmaker', 'xfce4') # Window handlers classes class BaseWindowHandler(object): """Abstract class for the platform specific window handlers. If initialized, this class casts a NotImplementedError.""" desk_env = desktop_environment def __init__(self, *args, **kwargs): """...""" if not len(kwargs): raise NotImplementedError("Abstract class.") self.mode = kwargs['mode'] def set_mode(self, size, mode): """Wrapper for pygame.display.set_mode().""" display.set_mode(size, mode) def get_root_rect(self): """...""" raise NotImplementedError("Abstract method.") def get_size(self): """...""" raise NotImplementedError("Abstract method.") def set_size(self, size, update=True): """...""" raise NotImplementedError("Abstract method.") def get_position(self): """...""" raise NotImplementedError("Abstract method.") def set_position(self, pos, update=True): """...""" raise NotImplementedError("Abstract method.") def get_state(self): """...""" raise NotImplementedError("Abstract method.") def set_state(self, state=NORMAL, size=(-1, -1), pos=(-1, -1), update=True): """...""" raise NotImplementedError("Abstract method.") def flush(self): """Just does nothing...""" return def sync(self): """Just does nothing...""" return class XWindowHandler(BaseWindowHandler): """Object to deal with XWindow managers (Linux).""" desk_env = desktop_environment def __init__(self, pos=(0, 0), size=(0, 0), mode=None): """Set up the internal handlers.""" BaseWindowHandler.__init__(self, pos=pos, size=size, mode=mode) self.mode = mode # setup the internal data, especially the Xlib object we need. # Tests if DEBUG_WM: print "#" * 72 print "XWindowHandler.__init__" print "Desktop environment:", desktop_environment dis = self.display = Xlib.display.Display() pygame_win = dis.create_resource_object('window', display.get_wm_info()['window']) if DEBUG_WM: root = dis.screen().root active_wid_id = root.get_full_property(dis.intern_atom('_NET_ACTIVE_WINDOW'), Xlib.X.AnyPropertyType).value[0] active_win = dis.create_resource_object('window', active_wid_id) # Print pygame_win and active_win styff for (win, name) in ((pygame_win, 'pygame_win'), (active_win, 'active_win')): print "=" * 72 print "%s guts" % name, "(ID %s)" % win.id print "-" * 72 print "* State" prop = win.get_full_property(dis.intern_atom("_NET_WM_STATE"), 4) print " ", prop if prop: print dir(prop) print "* Geometry" print " ", win.get_geometry() parent = win.query_tree().parent p = '%s.parent' % name while parent.id != root.id: print "-" * 72 print p, "ID", parent.id print "* State" prop = parent.get_full_property(dis.intern_atom("_NET_WM_STATE"), 4) print " ", prop if prop: print dir(prop) print "* Geometry" print " ", parent.get_geometry() parent = parent.query_tree().parent p += ".parent" # Size handlers self.base_handler = pygame_win self.base_handler_id = pygame_win.id size = desktops['linux2'][self.desk_env].get('size_getter', None) if size: if DEBUG_WM: print "size_getter.split('.')", size.split('.') handler = pygame_win for item in size.split('.'): handler = getattr(handler.query_tree(), item) self.sizeGetter = handler else: self.sizeGetter = pygame_win size = desktops['linux2'][self.desk_env].get('size_setter', None) if size: if DEBUG_WM: print "size_setter.split('.')", size.split('.') handler = pygame_win for item in size.split('.'): handler = getattr(handler.query_tree(), item) self.sizeSetter = handler else: self.sizeSetter = pygame_win # Position handlers pos = desktops['linux2'][self.desk_env].get('position_getter', None) if pos: if DEBUG_WM: print "pos_getter.split('.')", pos.split('.') handler = pygame_win for item in pos.split('.'): handler = getattr(handler.query_tree(), item) self.positionGetter = handler else: self.positionGetter = pygame_win pos = desktops['linux2'][self.desk_env].get('position_setter', None) if pos: if DEBUG_WM: print "pos_setter.split('.')", pos.split('.') handler = pygame_win for item in pos.split('.'): handler = getattr(handler.query_tree(), item) self.positionSetter = handler else: self.positionSetter = pygame_win # Position gap. Used to correct wrong positions on some environments. self.position_gap = desktops['linux2'][self.desk_env].get('position_gap', (0, 0, False, False)) self.starting = True self.gx, self.gy = 0, 0 # State handler state = desktops['linux2'][self.desk_env].get('state', None) if state: if DEBUG_WM: print "state.split('.')", state.split('.') handler = pygame_win for item in state.split('.'): handler = getattr(handler.query_tree(), item) self.stateHandler = handler else: self.stateHandler = pygame_win if DEBUG_WM: print "self.positionGetter:", self.positionGetter, 'ID:', self.positionGetter.id print "self.positionSetter:", self.positionSetter, 'ID:', self.positionSetter.id print "self.sizeGetter:", self.sizeGetter, 'ID:', self.sizeGetter.id print "self.sizeSetter:", self.sizeSetter, 'ID:', self.sizeSetter.id print "self.stateHandler:", self.stateHandler, 'ID:', self.stateHandler.id print self.stateHandler.get_wm_state() def get_root_rect(self): """Return a four values tuple containing the position and size of the very first OS window object.""" geom = self.display.screen().root.get_geometry() return geom.x, geom.y, geom.width, geom.height def get_size(self): """Return the window actual size as a tuple (width, height).""" geom = self.sizeGetter.get_geometry() if DEBUG_WM: print "Actual size is", geom.width, geom.height return geom.width, geom.height def set_size(self, size, update=True): """Set the window size. :size: list or tuple: the new size. Raises a TypeError if something else than a list or a tuple is sent.""" if isinstance(size, (list, tuple)): # Call the Xlib object handling the size to update it. if DEBUG_WM: print "Setting size to", size print "actual size", self.get_size() self.sizeSetter.configure(width=size[0], height=size[1]) if update: self.sync() else: # Raise a Type error. raise TypeError("%s is not a list or a tuple." % size) def get_position(self): """Return the window actual position as a tuple.""" geom = self.positionGetter.get_geometry() # if DEBUG_WM: # print "Actual position is", geom.x, geom.y return geom.x, geom.y def set_position(self, pos, update=True): """Set the window position. :pos: list or tuple: the new position (x, y). :update: bool: wheteher to call the internal sync method.""" if DEBUG_WM: print "Setting position to", pos if isinstance(pos, (list, tuple)): gx, gy = 0 or self.gx, 0 or self.gy if self.starting: gx, gy = self.position_gap[:2] if self.position_gap[2]: self.gx = gx if self.position_gap[3]: self.gy = gy self.starting = False # Call the Xlib object handling the position to update it. self.positionSetter.configure(x=pos[0] + gx, y=pos[1] + gy) if update: self.sync() else: # Raise a Type error. raise TypeError("%s is not a list or a tuple." % pos) def get_state(self): """Return wheter the window is maximized or not, or minimized or full screen.""" state = self.stateHandler.get_full_property(self.display.intern_atom("_NET_WM_STATE"), 4) # if DEBUG_WM: # print "state_1.value", state.value # print "max vert", self.display.intern_atom("_NET_WM_STATE_MAXIMIZED_VERT") ,self.display.intern_atom("_NET_WM_STATE_MAXIMIZED_VERT") in state.value # print "max horz", self.display.intern_atom("_NET_WM_STATE_MAXIMIZED_HORZ"), self.display.intern_atom("_NET_WM_STATE_MAXIMIZED_HORZ") in state.value if self.display.intern_atom("_NET_WM_STATE_MAXIMIZED_HORZ") in state.value and self.display.intern_atom("_NET_WM_STATE_MAXIMIZED_VERT") in state.value: # if DEBUG_WM: # print MAXIMIZED return MAXIMIZED elif self.display.intern_atom("_NET_WM_STATE_HIDEN") in state.value: # if DEBUG_WM: # print MINIMIZED return MINIMIZED elif self.display.intern_atom("_NET_WM_STATE_FULLSCREEN") in state.value: # if DEBUG_WM: # print FULLSCREEN return FULLSCREEN # if DEBUG_WM: # print NORMAL return NORMAL def set_state(self, state=NORMAL, size=(-1, -1), pos=(-1, -1), update=True): """Set whether the window is maximized or not, or minimized or full screen. If no argument is given, assume the state will be windowed and not maximized. If arguments are given, only the first is relevant. The other ones are ignored. ** Only maximized and normal states are implemented for now. ** :state: valid arguments: 'minimized', MINIMIZED, 0. 'normal', NORMAL, 1: windowed, not maximized. 'maximized', MAXIMIZED, 2. 'fullscreen, FULLSCREEN, 3. :size: list, tuple: the new size; if (-1, -1) self.get_size() is used. If one element is -1 it is replaced by the corresponding valur from self.get_size(). :pos: list, tuple: the new position; if (-1, -1), self.get_position is used. If one element is -1 it is replaced by the corresponding valur from self.get_position(). :update: bool: whether to call the internal flush method.""" if state not in (0, MINIMIZED, 'minimized', 1, NORMAL, 'normal', 2, MAXIMIZED, 'maximized', 3, FULLSCREEN, 'fullscreen'): # Raise a value error. raise ValueError("Invalid state argument: %s is not a correct value" % state) if not isinstance(size, (list, tuple)): raise TypeError("Invalid size argument: %s is not a list or a tuple.") if not isinstance(pos, (list, tuple)): raise TypeError("Invalid pos argument: %s is not a list or a tuple.") if state in (1, NORMAL, 'normal'): size = list(size) sz = self.get_size() if size[0] == -1: size[0] = sz[0] if size[1] == -1: size[1] = sz[1] pos = list(pos) ps = self.get_position() if pos[0] == -1: pos[0] = ps[0] if pos[1] == -1: pos[1] = ps[1] self.set_mode(size, self.mode) self.set_position(pos) elif state in (0, MINIMIZED, 'minimized'): pass elif state in (2, MAXIMIZED, 'maximized'): data = [1, self.display.intern_atom("_NET_WM_STATE_MAXIMIZED_VERT", False), self.display.intern_atom("_NET_WM_STATE_MAXIMIZED_HORZ", False)] data = (data + ([0] * (5 - len(data))))[:5] if DEBUG_WM: print self.stateHandler.get_wm_state() print "creating event", Xlib.protocol.event.ClientMessage print dir(self.stateHandler) x_event = Xlib.protocol.event.ClientMessage(window=self.stateHandler, client_type=self.display.intern_atom("_NET_WM_STATE", False), data=(32, data)) if DEBUG_WM: print "sending event" self.display.screen().root.send_event(x_event, event_mask=Xlib.X.SubstructureRedirectMask) if DEBUG_WM: print self.stateHandler.get_wm_state() elif state in (3, FULLSCREEN, 'fullscreen'): pass if update: self.flush() def flush(self): """Wrapper around Xlib.Display.flush()""" if DEBUG_WM: print "* flushing display" self.display.flush() def sync(self): """Wrapper around Xlib.Display.sync()""" if DEBUG_WM: print "* syncing display" self.display.sync() #======================================================================= # WARNING: This class has been built on Linux using wine. # Please review this code and change it consequently before using it without '--debug-wm' switch! class WWindowHandler(BaseWindowHandler): """Object to deal with Microsoft Window managers.""" desk_env = desktop_environment def __init__(self, pos=(0, 0), size=(0, 0), mode=None): """Set up the internal handlers.""" BaseWindowHandler.__init__(self, pos=pos, size=size, mode=mode) # Tests if DEBUG_WM: print "#" * 72 print "WWindowHandler.__init__" print "Desktop environment:", desktop_environment for item in dir(win32con): if 'maxim' in item.lower() or 'minim' in item.lower() or 'full' in item.lower(): print item, getattr(win32con, item) self.base_handler = display self.base_handler_id = display.get_wm_info()['window'] if platform.dist() == ('', '', ''): # We're running on a native Windows. def set_mode(self, size, mode): """Wrapper for pygame.display.set_mode().""" # Windows pygame implementation seem to work on the display mode and size on it's own... return else: # We're running on wine. def set_mode(self, size, mode): """Wrapper for pygame.display.set_mode().""" self.wine_state_fix = False if getattr(self, 'wine_state_fix', False): self.set_size(size) self.wine_state_fix = True def get_root_rect(self): """Return a four values tuple containing the position and size of the very first OS window object.""" flags, showCmd, ptMin, ptMax, rect = win32gui.GetWindowPlacement(win32gui.GetDesktopWindow()) return rect def get_size(self): """Return the window actual size as a tuple (width, height).""" flags, showCmd, ptMin, ptMax, rect = win32gui.GetWindowPlacement(self.base_handler_id) w = rect[2] - rect[0] h = rect[3] - rect[1] return w, h def set_size(self, size, update=True): """Set the window size. :size: list or tuple: the new size. :mode: bool: (re)set the pygame.display mode; self.mode must be a pygame display mode object. Raises a TypeError if something else than a list or a tuple is sent.""" if isinstance(size, (list, tuple)): w, h = size cx, cy = win32gui.GetCursorPos() if DEBUG_WM: print "Settin size to", size print "actual size", self.get_size() print "actual position", self.get_position() print 'cursor pos', cx, cy flags, showCmd, ptMin, ptMax, rect = win32gui.GetWindowPlacement(self.base_handler_id) if DEBUG_WM: print "set_size rect", rect, "ptMin", ptMin, "ptMax", ptMax, "flags", flags x = rect[0] y = rect[1] rect = x, y, x + w, y + h win32gui.SetWindowPlacement(self.base_handler_id, (0, showCmd, ptMin, ptMax, rect)) else: # Raise a Type error. raise TypeError("%s is not a list or a tuple." % repr(size)) def get_position(self): """Return the window actual position as a tuple.""" flags, showCmd, ptMin, ptMax, rect = win32gui.GetWindowPlacement(self.base_handler_id) x, y, r, b = rect return x, y def set_position(self, pos, update=True): """Set the window position. :pos: list or tuple: the new position (x, y).""" if DEBUG_WM: print "Setting position to", pos if isinstance(pos, (list, tuple)): self.first_pos = False x, y = pos if update: flags, showCmd, ptMin, ptMax, rect = win32gui.GetWindowPlacement(self.base_handler_id) if DEBUG_WM: print "set_position rect", rect, "ptMin", ptMin, "ptMax", ptMax realW = rect[2] - rect[0] realH = rect[3] - rect[1] if DEBUG_WM: print 'rect[0]', rect[0], 'rect[1]', rect[1] print 'realW', realW, 'realH', realH print 'cursor pos', win32gui.GetCursorPos() rect = (x, y, x + realW, y + realH) win32gui.SetWindowPlacement(self.base_handler_id, (0, showCmd, ptMin, ptMax, rect)) else: # Raise a Type error. raise TypeError("%s is not a list or a tuple." % repr(pos)) def get_state(self): """Return wheter the window is maximized or not, or minimized or full screen.""" flags, state, ptMin, ptMax, rect = win32gui.GetWindowPlacement(self.base_handler_id) if DEBUG_WM: print "state", state if state == win32con.SW_MAXIMIZE: return MAXIMIZED elif state == win32con.SW_MINIMIZE: return MINIMIZED return NORMAL def set_state(self, state=NORMAL, size=(-1, -1), pos=(-1, -1), update=True): """Set wheter the window is maximized or not, or minimized or full screen. If no argument is given, assume the state will be windowed and not maximized. If arguments are given, only the first is relevant. The other ones are ignored. ** Only maximized and normal states are implemented for now. ** :state: valid arguments: 'minimized', MINIMIZED, 0. 'normal', NORMAL, 1: windowed, not maximized. 'maximized', MAXIMIZED, 2. 'fullscreen, FULLSCREEN, 3. :size: list, tuple: the new size; if (-1, -1) self.get_size() is used. If one element is -1 it is replaced by the corresponding valur from self.get_size(). :pos: list, tuple: the new position; if (-1, -1), self.get_position is used. If one element is -1 it is replaced by the corresponding valur from self.get_position(). :update: bool: whether to call the internal flush method.""" if state not in (0, MINIMIZED, 'minimized', 1, NORMAL, 'normal', 2, MAXIMIZED, 'maximized', 3, FULLSCREEN, 'fullscreen'): # Raise a value error. raise ValueError("Invalid state argument: %s is not a correct value" % state) if not isinstance(size, (list, tuple)): raise TypeError("Invalid size argument: %s is not a list or a tuple.") if not isinstance(pos, (list, tuple)): raise TypeError("Invalid pos argument: %s is not a list or a tuple.") if state in (1, NORMAL, 'normal'): size = list(size) sz = self.get_size() if size[0] == -1: size[0] = sz[0] if size[1] == -1: size[1] = sz[1] pos = list(pos) ps = self.get_position() if pos[0] == -1: pos[0] = ps[0] if pos[1] == -1: pos[1] = ps[1] self.set_mode(size, self.mode) self.set_position(pos) elif state in (0, MINIMIZED, 'minimized'): pass elif state in (2, MAXIMIZED, 'maximized'): win32gui.ShowWindow(self.base_handler_id, win32con.SW_MAXIMIZE) elif state in (3, FULLSCREEN, 'fullscreen'): pass WindowHandler = None def setupWindowHandler(): """'Link' the corresponding window handler class to WindowHandler.""" # Don't initialize the window handler here. # We need MCEdit display objects to get the right object. global WindowHandler if USE_WM: log.warn("Initializing window management...") if sys.platform == 'linux2': if XWindowHandler.desk_env == 'unknown': log.warning("Your desktop environment could not be determined. The support for window sizing/moving is not availble.") elif XWindowHandler.desk_env in linux_unsuported: log.warning("Your desktop environment is not yet supported for window sizing/moving.") else: WindowHandler = XWindowHandler log.info("XWindowHandler initialized.") elif sys.platform == 'win32': WindowHandler = WWindowHandler log.info("WWindowHandler initialized.") return WindowHandler
50,148
38.394344
203
py
MCEdit-Unified
MCEdit-Unified-master/config.py
"""Copyright (c) 2010-2012 David Rio Vierra Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.""" """ config.py Configuration settings and storage. """ import logging import collections import ConfigParser from locale import getdefaultlocale DEF_ENC = getdefaultlocale()[1] if DEF_ENC is None: DEF_ENC = "UTF-8" import directories import weakref log = logging.getLogger(__name__) class Config(object): def __init__(self, config_definitions): log.info("Loading config...") self.config = ConfigParser.RawConfigParser([], ConfigDict) self.config.observers = {} try: self.config.read(self.getPath()) except Exception as e: log.error(e) log.warn("Error while reading configuration file mcedit.ini: {0}".format(e)) self.transformConfig() self._sections = {} for (sectionKey, sectionName), items in config_definitions.iteritems(): self._sections[sectionKey] = ConfigSection(self.config, sectionName, items) setattr(self, sectionKey, self._sections[sectionKey]) self.save() def __getitem__(self, section): return self._sections[section] @staticmethod def getPath(): return directories.configFilePath @staticmethod def transformKey(value, n=0): if 'left' in value and len(value) > 5: value = value[5:] elif 'right' in value and len(value) > 6: value = value[6:] if 'a' <= value <= 'z': value = value.replace(value[0], value[0].upper(), 1) if n >= 36 and "Ctrl-" not in value: value = "Ctrl-" + value if value == "Mouse3": value = "Button 3" elif value == "Mouse4": value = "Scroll Up" elif value == "Mouse5": value = "Scroll Down" elif value == "Mouse6": value = "Button 4" elif value == "Mouse7": value = "Button 5" return value @staticmethod def convert(key): vals = key.replace('-', ' ').translate(None, '()').lower().split(' ') return vals[0] + "".join(x.title() for x in vals[1:]) def reset(self): for section in self.config.sections(): self.config.remove_section(section) def transformConfig(self): if self.config.has_section("Version") and self.config.has_option("Version", "version"): version = self.config.get("Version", "version") else: self.reset() return if version == "1.1.1.1": n = 1 for (name, value) in self.config.items("Keys"): if name != "Swap View" and name != "Toggle Fps Counter": self.config.set("Keys", name, self.transformKey(value, n)) elif name == "Swap View": self.config.set("Keys", "View Distance", self.transformKey(value, n)) self.config.set("Keys", "Swap View", "None") elif name == "Toggle Fps Counter": self.config.set("Keys", "Debug Overlay", self.transformKey(value, n)) self.config.set("Keys", "Toggle Fps Counter", "None") n += 1 if self.config.get("Keys", "Brake") == "Space": version = "1.1.2.0-update" else: version = "1.1.2.0-new" self.config.set("Version", "version", version) self.save() if "1.1.2.0" in version: self.config.set("Settings", "report crashes new", False) self.config.set("Settings", "report crashes asked", False) self.config.set("Version", "version", "1.6.0.0") self.save() def save(self): try: cf = file(self.getPath(), 'w') self.config.write(cf) cf.close() except Exception as e: log.error(e) log.error("Error saving configuration settings to mcedit.ini: {0}".format(e)) class ConfigSection(object): def __init__(self, config, section, items): self.section = section if not config.has_section(section): config.add_section(section) self._items = {} for item in items: if isinstance(item, ConfigValue): value = item elif type(item[2]) in ListValue.allowedTypes: value = ListValue(item[0], item[1], item[2]) else: value = ConfigValue(item[0], item[1], item[2]) value.config = config value.section = section self._items[value.key] = value value.get() if value.section == "Keys" and value.config.get(value.section, value.name) == "Delete": value.config.set(value.section, value.name, "Del") def __getitem__(self, key): return self._items[key] def __getattr__(self, key): return self.__getitem__(key) def items(self): return [(i.name, i.get()) for k, i in self._items.iteritems()] class ConfigValue(object): allowedTypes = [int, float, bool, basestring, str, unicode] def __init__(self, key, name, default=None): if default is None: default = name name = key self.key = key self.name = name self.default = default self.type = type(default) if self.type not in self.allowedTypes: raise TypeError("Invalid config type %s" % repr(self.type)) def get(self): try: if self.type is bool: return self.config.getboolean(self.section, self.name) if self.type is unicode: return self.type(self.config.get(self.section, self.name).decode(DEF_ENC)) return self.type(self.config.get(self.section, self.name)) except Exception as e: if self.default is None: log.error(e) raise self.set(self.default) return self.default def getRaw(self): return self.config.get(self.section, self.name) def _setter(self, setter): def _s(s, value): if setter is not None: setter(s, value) return self.set(value) return _s def set(self, value): log.debug("Property Change: %15s %30s = %s", self.section, self.name, value) if self.type is unicode and isinstance(value, unicode): value = value.encode(DEF_ENC) self.config.set(self.section, self.name, str(value)) self._notifyObservers(value) def addObserver(self, target, attr=None, callback=None): """ Register 'target' for changes in the config var named by section and name. When the config is changed, calls setattr with target and attr. attr may be None; it will be created from the name by lowercasing the first word, uppercasing the rest, and removing spaces. e.g. "block buffer" becomes "blockBuffer" """ observers = self.config.observers.setdefault((self.section, self.name), {}) if not attr: attr = self.key log.debug("Subscribing %s.%s", target, attr) attr = intern(str(attr)) targetref = weakref.ref(target) observers.setdefault((targetref, attr), callback) val = self.get() setattr(target, attr, val) if callback: callback(val) def _notifyObservers(self, value): observers = self.config.observers.get((self.section, self.name), {}) newObservers = {} for targetref, attr in observers: target = targetref() if target: log.debug("Notifying %s", target) setattr(target, attr, value) callback = observers[targetref, attr] if callback: callback(value) newObservers[targetref, attr] = callback self.config.observers[(self.section, self.name)] = newObservers def property(self, setter=None): assert self.default is not None this = self def _getter(self): return this.get() return property(_getter, self._setter(setter), None) def __repr__(self): return "<%s>" % " ".join(( self.__class__.__name__, "section=%r" % self.section, "key=%r" % self.key, "name=%r" % self.name, "default=%s" % self.default, "type=%s" % self.type )) def __int__(self): return int(self.get()) def __float__(self): return float(self.get()) def __bool__(self): return bool(self.get()) class ListValue(ConfigValue): allowedTypes = [list, tuple] def __init__(self, key, name, default=None): if default is None or len(default) < 1: raise ValueError("Default value %s is empty." % repr(default)) self.subtype = type(default[0]) super(ListValue, self).__init__(key, name, default) def get(self): try: return self.type(self.subtype(x.strip()) for x in self._config.get(self.section, self.name).translate(None, '[]()').split(',')) except Exception as e: if self.default is None: log.error(e) raise self.set(self.default) return self.default def __repr__(self): return "<%s>" % " ".join(( self.__class__.__name__, "section=%r" % self.section, "key=%r" % self.key, "name=%r" % self.name, "default=%s" % self.default, "type=%s" % self.type, "subtype=%s" % self.subtype )) class ColorValue(ListValue): allowedTypes = [tuple] defaultColors = {} def __init__(self, key, name, default=None): super(ColorValue, self).__init__(key, name, default) ColorValue.defaultColors[name] = self def get(self): values = super(ColorValue, self).get() return tuple(min(max(x, 0.0), 1.0) for x in values) class ConfigDict(collections.MutableMapping): def __init__(self, *args, **kwargs): self.dict = dict(*args, **kwargs) self.keyorder = [] def keys(self): return list(self.keyorder) def items(self): return list(self.__iteritems__()) def __iteritems__(self): return ((k, self.dict[k]) for k in self.keys()) def __iter__(self): return self.keys().__iter__() def __getitem__(self, k): return self.dict[k] def __setitem__(self, k, v): self.dict[k] = v if k not in self.keyorder: self.keyorder.append(k) def __delitem__(self, k): del self.dict[k] if k in self.keyorder: self.keyorder.remove(k) def __contains__(self, k): return self.dict.__contains__(k) def __len__(self): return self.dict.__len__() def copy(self): k = ConfigDict() k.dict = self.dict.copy() k.keyorder = list(self.keyorder) return k # Quick Reference: # 7 Bedrock # 9 Still_Water # 11 Still_Lava # 14 Gold_Ore # 15 Iron_Ore # 16 Coal_Ore # 21 Lapis_Lazuli_Ore # 24 Sandstone # 49 Obsidian # 56 Diamond_Ore # 73 Redstone_Ore # 129 Emerald_Ore # 153 Nether_Quartz_Ore hiddableOres = (7, 16, 15, 21, 73, 14, 56, 153) definitions = { ("keys", "Keys"): [ ("forward", "forward", "W"), ("back", "back", "S"), ("left", "left", "A"), ("right", "right", "D"), ("up", "up", "Space"), ("down", "down", "Shift"), ("brake", "brake", "C"), ("sprint", "sprint", "None"), ("rotateClone", "rotate (clone)", "E"), ("rollClone", "roll (clone)", "R"), ("flip", "flip", "F"), ("mirror", "mirror", "G"), ("rotateBrush", "rotate (brush)", "E"), ("rollBrush", "roll (brush)", "G"), ("increaseBrush", "increase brush", "R"), ("decreaseBrush", "decrease brush", "F"), ("replaceShortcut", "replace shortcut", "R"), ("swap", "swap", "X"), ("panLeft", "pan left", "J"), ("panRight", "pan right", "L"), ("panUp", "pan up", "I"), ("panDown", "pan down", "K"), ("toggleView", "toggle view", "Tab"), ("resetReach", "reset reach", "Button 3"), ("increaseReach", "increase reach", "Scroll Up"), ("decreaseReach", "decrease reach", "Scroll Down"), ("confirmConstruction", "confirm construction", "Return"), ("openLevel", "open level", "O"), ("newLevel", "new level", "N"), ("deleteBlocks", "delete blocks", "Del"), ("lineTool", "line tool", "Z"), ("longDistanceMode", "long-distance mode", "Alt-Z"), ("flyMode", "fly mode", "None"), ("debugOverlay", "debug overlay", "0"), ("showBlockInfo", "show block info", "Alt"), ("pickBlock", "pick block", "Alt"), ("selectChunks", "select chunks", "Z"), ("deselectChunks", "deselect chunks", "Alt"), ("brushLineTool", "brush line tool", "Z"), ("snapCloneToAxis", "snap clone to axis", "Ctrl"), ("blocksOnlyModifier", "blocks-only modifier", "Alt"), ("fastIncrementModifierHold", "fast increment modifier", "Ctrl"), ("fastNudge", "fast nudge", "None"), ("takeAScreenshot", "take a screenshot", "F6"), ("quit", "quit", "Ctrl-Q"), ("viewDistance", "view distance", "Ctrl-F"), ("selectAll", "select all", "Ctrl-A"), ("deselect", "deselect", "Ctrl-D"), ("cut", "cut", "Ctrl-X"), ("copy", "copy", "Ctrl-C"), ("paste", "paste", "Ctrl-V"), ("reloadWorld", "reload world", "Ctrl-R"), ("open", "open", "Ctrl-O"), ("quickLoad", "quick load", "Ctrl-L"), ("undo", "undo", "Ctrl-Z"), ("redo", "redo", "Ctrl-Y"), ("save", "save", "Ctrl-S"), ("saveAs", "save as", "Ctrl-Alt-S"), ("newWorld", "new world", "Ctrl-N"), ("closeWorld", "close world", "Ctrl-W"), ("worldInfo", "world info", "Ctrl-I"), ("gotoPanel", "goto panel", "Ctrl-G"), ("exportSelection", "export selection", "Ctrl-E"), ("toggleRenderer", "toggle renderer", "Ctrl-M"), ("uploadWorld", "upload world", "Ctrl-U"), ("select", "select", "1"), ("brush", "brush", "2"), ("clone", "clone", "3"), ("fillAndReplace", "fill and replace", "4"), ("filter", "filter", "5"), ("importKey", "import", "6"), ("players", "players", "7"), ("worldSpawnpoint", "world spawnpoint", "8"), ("chunkControl", "chunk control", "9"), ("nbtExplorer", "nbt explorer", "None"), ], ("version", "Version"): [ ("version", "version", "1.6.0.0") ], ("settings", "Settings"): [ ("flyMode", "Fly Mode", False), ("enableMouseLag", "Enable Mouse Lag", False), ("longDistanceMode", "Long Distance Mode", False), ("shouldResizeAlert", "Window Size Alert", True), ("closeMinecraftWarning", "Close Minecraft Warning", True), ("skin", "MCEdit Skin", "[Current]"), ("fov", "Field of View", 70.0), ("spaceHeight", "Space Height", 64), ("blockBuffer", "Block Buffer", 256 * 1048576), ("reportCrashes", "report crashes new", False), ("reportCrashesAsked", "report crashes asked", False), ("staticCommandsNudge", "Static Coords While Nudging", False), ("moveSpawnerPosNudge", "Change Spawners While Nudging", False), ("rotateBlockBrush", "rotateBlockBrushRow", True), ("langCode", "Language String", "en_US"), ("viewDistance", "View Distance", 8), ("targetFPS", "Target FPS", 30), ("windowWidth", "window width", 1152), ("windowHeight", "window height", 864), ("windowMaximized", "window maximized", False), ("windowMaximizedHeight", "window maximized height", 0), ("windowMaximizedWidth", "window maximized width", 0), ("windowX", "window x", 0), ("windowY", "window y", 0), ("windowShowCmd", "window showcmd", 1), ("setWindowPlacement", "SetWindowPlacement", True), ("showHiddenOres", "show hidden ores", False), ("hiddableOres", "hiddable ores", hiddableOres), ] + [ ("showOre%s" % i, "show ore %s" % i, True) for i in hiddableOres ] + [ ("fastLeaves", "fast leaves", True), ("roughGraphics", "rough graphics", False), ("showChunkRedraw", "show chunk redraw", True), ("drawSky", "draw sky", True), ("drawFog", "draw fog", True), ("showCeiling", "show ceiling", True), ("drawEntities", "draw entities", True), ("drawMonsters", "draw monsters", True), ("drawItems", "draw items", True), ("drawTileEntities", "draw tile entities", True), ("drawTileTicks", "draw tile ticks", False), ("drawUnpopulatedChunks", "draw unpopulated chunks", True), ("drawChunkBorders", "draw chunk borders", False), ("vertexBufferLimit", "vertex buffer limit", 384), ("vsync", "vertical sync", 0), ("viewMode", "View Mode", "Camera"), ("undoLimit", "Undo Limit", 20), ("recentWorlds", "Recent Worlds", ['']), ("resourcePack", "Resource Pack", u"Default"), ("maxCopies", "Copy stack size", 32), ("superSecretSettings", "Super Secret Settings", False), ("compassToggle", "Compass Toggle", True), ("compassSize", "Compass Size", 60), ("fogIntensity", "Fog Intensity", 20), ("fontProportion", "Fonts Proportion", 100), ("downloadPlayerSkins", "Download Player Skins", True), ("maxViewDistance", "Max View Distance", 32), ("drawPlayerHeads", "Draw Player Heads", True), ("showQuickBlockInfo", "Show Block Info when hovering", True), ("savePositionOnClose", "Save camera position on close", False), ("showWindowSizeWarning", "Show window size warning", True) ], ("controls", "Controls"): [ ("mouseSpeed", "mouse speed", 5.0), ("cameraAccel", "camera acceleration", 125.0), ("cameraDrag", "camera drag", 100.0), ("cameraMaxSpeed", "camera maximum speed", 60.0), ("cameraBrakingSpeed", "camera braking speed", 8.0), ("invertMousePitch", "invert mouse pitch", False), ("autobrake", "autobrake", True), ("swapAxes", "swap axes looking down", False) ], ("brush", "Brush"): [ ("brushSizeL", "Brush Shape L", 3), ("brushSizeH", "Brush Shape H", 3), ("brushSizeW", "Brush Shape W", 3), ("updateBrushOffset", "Update Brush Offset", False), ("chooseBlockImmediately", "Choose Block Immediately", False), ("alpha", "Alpha", 0.66) ], ("clone", "Clone"): [ ("copyAir", "Copy Air", True), ("copyWater", "Copy Water", True), ("copyBiomes", "Copy Biomes", False), ("staticCommands", "Change Coordinates", False), ("moveSpawnerPos", "Change Spawners Pos", False), ("regenerateUUID", "Regenerate UUIDs", True), ("placeImmediately", "Place Immediately", True) ], ("fill", "Fill"): [ ("chooseBlockImmediately", "Choose Block Immediately", True), ("chooseBlockImmediatelyReplace", "Choose Block Immediately for Replace", True) ], ("spawn", "Spawn"): [ ("spawnProtection", "Spawn Protection", True) ], ("selection", "Selection"): [ ("showPreviousSelection", "Show Previous Selection", True), ("color", "Color", "white") ], ("selectionColors", "Selection Colors"): [ ColorValue("white", "white", (1.0, 1.0, 1.0)), ColorValue("blue", "blue", (0.75, 0.75, 1.0)), ColorValue("green", "green", (0.75, 1.0, 0.75)), ColorValue("red", "red", (1.0, 0.75, 0.75)), ColorValue("teal", "teal", (0.75, 1.0, 1.0)), ColorValue("pink", "pink", (1.0, 0.75, 1.0)), ColorValue("yellow", "yellow", (1.0, 1.0, 0.75)), ColorValue("grey", "grey", (0.6, 0.6, 0.6)), ColorValue("black", "black", (0.0, 0.0, 0.0)) ], ("fastNudgeSettings", "Fast Nudge Settings"): [ ("blocksWidth", "Blocks Width", False), ("blocksWidthNumber", "Blocks Width Number", 16), ("selectionWidth", "Selection Width", False), ("selectionWidthNumber", "Selection Width Number", 16), ("pointsWidth", "Points Width", False), ("pointsWidthNumber", "Points Width Number", 16), ("cloneWidth", "clone Width", True), ("cloneWidthNumber", "Clone Width Number", 16), ("importWidth", "Import Width", False), ("importWidthNumber", "Import Width Number", 8), ], ("nbtTreeSettings", "NBT Tree Settings"): [ ("useBulletStyles", "Use Bullet Styles", True), ("useBulletText", "Use Bullet Text", False), ("useBulletImages", "Use Bullet Images", True), ("defaultBulletImages", "Default Bullet Images", True), #("bulletFileName", "Bullet Images File", directories.os.path.join(directories.getDataDir(), 'Nbtsheet.png')), ("bulletFileName", 'Bullet Image File', directories.getDataFile('Nbtsheet.png')), ("showAllTags", "Show all the tags in the tree", False), ], ("Filter Keys", "Filter Keys"): [], ("session", "Session",): [ ("override", "Override", False) ], ("commands", "Commands"): [ ("sorting", "Sorting", "chain"), ("space", "Space", True), ("fileFormat", "File Format", "txt") ], ("schematicCopying", "Schematics Copying"): [ ("cancelCommandBlockOffset", "Cancel Command Block Offset", False) ] } config = None if config is None: config = Config(definitions)
22,623
35.025478
139
py
MCEdit-Unified
MCEdit-Unified-master/release.py
import os.path import directories import json import urllib2 import sys from sys import platform as _platform VERSION = None TAG = None DEV = None def build_version_tag_dev(): ''' Get and return the name of the current version, the stage of development MCEdit-Unified is in, and if the program is in development mode. ''' try: #with open(os.path.join(directories.getDataDir(), "RELEASE-VERSION.json"), 'rb') as jsonString: with open(directories.getDataFile('RELEASE-VERSION.json'), 'rb') as jsonString: current = json.load(jsonString) return (current["name"].replace("{tag_name}", current["tag_name"]).replace("{mc_versions}", current["mc_versions"]).replace("{pe_versions}", current["pe_versions"]), current["tag_name"], current["development"]) except: raise VERSION, TAG, DEV = build_version_tag_dev() def get_version(): ''' Returns the name of the current version ''' return VERSION def get_release_tag(): ''' Returns the stage of development MCEdit-Unified is in ''' return TAG def is_dev(): ''' Returns if MCEdit-Unified is in development mode ''' return DEV def fetch_new_version_info(): return json.loads(urllib2.urlopen("https://api.github.com/repos/Podshot/MCEdit-Unified/releases").read()) def check_for_new_version(release_api_response): ''' Checks for a new MCEdit-Unified version, if the current one is not in development mode ''' try: if not is_dev(): # release_api_response = json.loads(urllib2.urlopen("https://api.github.com/repos/Khroki/MCEdit-Unified/releases").read()) version = release_api_response[0] if version["tag_name"] > get_release_tag(): is_64bit = sys.maxsize > 2 ** 32 assets = version["assets"] for asset in assets: if _platform == "win32": version["OS Target"] = "windows" if "Win" in asset["name"]: if is_64bit: if "64bit" in asset["name"]: version["asset"] = asset version["target_arch"] = "64bit" else: if "32bit" in asset["name"]: version["asset"] = asset version["target_arch"] = "32bit" elif _platform == "darwin": version["OS Target"] = "osx" if "OSX" in asset["name"]: version["asset"] = asset version["target_arch"] = "64bit" return version return False else: return False except: print "An error occurred checking for updates." return False
2,996
31.225806
177
py
MCEdit-Unified
MCEdit-Unified-master/drawable.py
""" ${NAME} """ from __future__ import absolute_import, division, print_function, unicode_literals import logging log = logging.getLogger(__name__) from OpenGL import GL class Drawable(object): def __init__(self): super(Drawable, self).__init__() self._displayList = None self.invalidList = True self.children = [] @staticmethod def setUp(): """ Set up rendering settings and view matrices :return: :rtype: """ @staticmethod def tearDown(): """ Return any settings changed in setUp to their previous states :return: :rtype: """ def drawSelf(self): """ Draw this drawable, if it has its own graphics. :return: :rtype: """ def _draw(self): self.setUp() self.drawSelf() for child in self.children: child.draw() self.tearDown() def draw(self): if self._displayList is None: self._displayList = GL.glGenLists(1) if self.invalidList: self.compileList() GL.glCallList(self._displayList) def compileList(self): GL.glNewList(self._displayList, GL.GL_COMPILE) self._draw() GL.glEndList() self.invalidList = False def invalidate(self): self.invalidList = True
1,390
20.075758
82
py
MCEdit-Unified
MCEdit-Unified-master/mcedit.py
# !/usr/bin/env python2.7 # -*- coding: utf_8 -*- # import resource_packs # not the right place, moving it a bit further #-# Modified by D.C.-G. for translation purpose #.# Marks the layout modifications. -- D.C.-G. from __future__ import unicode_literals """ mcedit.py Startup, main menu, keyboard configuration, automatic updating. """ import splash import OpenGL import sys import os if "--debug-ogl" not in sys.argv: OpenGL.ERROR_CHECKING = False import logging # Setup file and stderr logging. logger = logging.getLogger() # Set the log level up while importing OpenGL.GL to hide some obnoxious warnings about old array handlers logger.setLevel(logging.WARN) logger.setLevel(logging.DEBUG) logfile = 'mcedit.log' if sys.platform == "darwin": logfile = os.path.expanduser("~/Library/Logs/mcedit.log") else: logfile = os.path.join(os.getcwdu(), logfile) fh = logging.FileHandler(logfile, mode="w") fh.setLevel(logging.DEBUG) ch = logging.StreamHandler() ch.setLevel(logging.WARN) if "--log-info" in sys.argv: ch.setLevel(logging.INFO) if "--log-debug" in sys.argv: ch.setLevel(logging.DEBUG) class FileLineFormatter(logging.Formatter): def format(self, record): record.__dict__['fileline'] = "%(module)s.py:%(lineno)d" % record.__dict__ record.__dict__['nameline'] = "%(name)s.py:%(lineno)d" % record.__dict__ return super(FileLineFormatter, self).format(record) fmt = FileLineFormatter( '[%(levelname)8s][%(nameline)30s]:%(message)s' ) fh.setFormatter(fmt) ch.setFormatter(fmt) logger.addHandler(fh) logger.addHandler(ch) import release if __name__ == "__main__": start_msg = 'Starting MCEdit-Unified v%s' % release.TAG logger.info(start_msg) print '[ ****** ] ~~~~~~~~~~ %s' % start_msg #--------------------------------------------------------------------- # NEW FEATURES HANDLING # # The idea is to be able to implement and test/use new code without stripping off the current one. # These features/new code will be in the released stuff, but unavailable until explicitly requested. # # The new features which are under development can be enabled using the 'new_features.def' file. # This file is a plain text file with one feature to enable a line. # The file is parsed and each feature is added to the builtins using the pattern 'mcenf_<feature>'. # The value for these builtins is 'True'. # Then, in the code, just check if the builtins has the key 'mcenf_<feature>' to use the new version of the code: # # ``` # def foo_old(): # # Was 'foo', code here is the one used unless the new version is wanted. # [...] # # def foo_new(): # # This is the new version of the former 'foo' (current 'foo_old'). # [...] # # if __builtins__.get('mcenf_foo', False): # foo = foo_new # else: # foo = foo_old # # ``` # if __name__ == "__main__" and '--new-features' in sys.argv: if not os.path.exists('new_features.def'): logger.warning("New features requested, but file 'new_features.def' not found!") else: logger.warning("New features mode requested.") lines = [a.strip() for a in open('new_features.def', 'r').readlines()] for line in lines: _ln = line.strip() if _ln and not _ln.startswith("#"): setattr(__builtins__, 'mcenf_%s' % line, True) logger.warning("Activating 'mcenf_%s'" % line) logger.warning("New features list loaded.") from player_cache import PlayerCache import directories import keys import albow import locale DEF_ENC = locale.getdefaultlocale()[1] if DEF_ENC is None: DEF_ENC = "UTF-8" from albow.translate import _, getPlatInfo from albow.openglwidgets import GLViewport from albow.root import RootWidget from config import config if __name__ == "__main__": #albow.resource.resource_dir = directories.getDataDir() albow.resource.resource_dir = directories.getDataFile() def create_mocked_pyclark(): import imp class MockedPyClark(object): class Clark(object): def report(self, *args, **kwargs): pass global_clark = Clark() mod = imp.new_module('pyClark') mod = MockedPyClark() sys.modules['pyClark'] = mod return mod global pyClark pyClark = None if getattr(sys, 'frozen', False) or '--report-errors' in sys.argv: if config.settings.reportCrashes.get(): try: import pyClark pyClark.Clark('http://127.0.0.1', inject=True) logger.info('Successfully setup pyClark') except ImportError: pyClark = create_mocked_pyclark() logger.info('The \'pyClark\' module has not been installed, disabling error reporting') pass else: logger.info('User has opted out of pyClark error reporting') print type(create_mocked_pyclark()) pyClark = create_mocked_pyclark() print pyClark else: pyClark = create_mocked_pyclark() import panels import leveleditor # Building translation template if __name__ == "__main__" and "-tt" in sys.argv: sys.argv.remove('-tt') # Overwrite the default marker to have one adapted to our specific needs. albow.translate.buildTemplateMarker = """ ### THE FOLLOWING LINES HAS BEEN ADDED BY THE TEMPLATE UPDATE FUNCTION. ### Please, consider to analyze them and remove the entries referring ### to ones containing string formatting. ### ### For example, if you have a line already defined with this text: ### My %{animal} has %d legs. ### you may find lines like these below: ### My parrot has 2 legs. ### My dog has 4 legs. ### ### You also may have unwanted partial strings, especially the ones ### used in hotkeys. Delete them too. ### And, remove this paragraph, or it will be displayed in the program... """ albow.translate.buildTemplate = True albow.translate.loadTemplate() # Save the language defined in config and set en_US as current one. logging.warning('MCEdit is invoked to update the translation template.') orglang = config.settings.langCode.get() logging.warning('The actual language is %s.' % orglang) logging.warning('Setting en_US as language for this session.') config.settings.langCode.set('en_US') import mceutils import mcplatform # The two next switches '--debug-wm' and '--no-wm' are used to debug/disable the internal window handler. # They are exclusive. You can't debug if it is disabled. if __name__ == "__main__": if "--debug-wm" in sys.argv: mcplatform.DEBUG_WM = True if "--no-wm" in sys.argv: mcplatform.DEBUG_WM = False mcplatform.USE_WM = False else: mcplatform.setupWindowHandler() DEBUG_WM = mcplatform.DEBUG_WM USE_WM = mcplatform.USE_WM #-# DEBUG if mcplatform.hasXlibDisplay and DEBUG_WM: print '*** Xlib version', str(mcplatform.Xlib.__version__).replace(' ', '').replace(',', '.')[1:-1], 'found in', if os.path.expanduser('~/.local/lib/python2.7/site-packages') in mcplatform.Xlib.__file__: print 'user\'s', else: print 'system\'s', print 'libraries.' #-# from mcplatform import platform_open import numpy from pymclevel.minecraft_server import ServerJarStorage import os.path import pygame from pygame import display, rect import pymclevel import shutil import traceback import threading from utilities.gl_display_context import GLDisplayContext import mclangres from utilities import mcver_updater, mcworld_support getPlatInfo(OpenGL=OpenGL, numpy=numpy, pygame=pygame) ESCAPE = '\033' class MCEdit(GLViewport): def_enc = DEF_ENC def __init__(self, displayContext, *args): if DEBUG_WM: print "############################ __INIT__ ###########################" self.resizeAlert = config.settings.showWindowSizeWarning.get() self.maximized = config.settings.windowMaximized.get() self.saved_pos = config.settings.windowX.get(), config.settings.windowY.get() if displayContext.win and DEBUG_WM: print "* self.displayContext.win.state", displayContext.win.get_state() print "* self.displayContext.win.position", displayContext.win.get_position() self.dis = None self.win = None self.wParent = None self.wGrandParent = None self.linux = False if sys.platform == 'linux2' and mcplatform.hasXlibDisplay: self.linux = True self.dis = dis = mcplatform.Xlib.display.Display() self.win = win = dis.create_resource_object('window', display.get_wm_info()['window']) curDesk = os.environ.get('XDG_CURRENT_DESKTOP') if curDesk in ('GNOME', 'X-Cinnamon', 'Unity'): self.geomReciever = self.maximizeHandler = wParent = win.query_tree().parent self.geomSender = wGrandParent = wParent.query_tree().parent elif curDesk == 'KDE': self.maximizeHandler = win.query_tree().parent wParent = win.query_tree().parent.query_tree().parent wGrandParent = wParent.query_tree().parent.query_tree().parent self.geomReciever = self.geomSender = win.query_tree().parent.query_tree().parent.query_tree().parent else: self.maximizeHandler = self.geomReciever = self.geomSender = wGrandParent = wParent = None self.wParent = wParent self.wGrandParent = wGrandParent root = dis.screen().root windowID = root.get_full_property(dis.intern_atom('_NET_ACTIVE_WINDOW'), mcplatform.Xlib.X.AnyPropertyType).value[0] print "###\nwindowID", windowID window = dis.create_resource_object('window', windowID) print "###\nwindow.get_geometry()", window.get_geometry() print "###\nself.win", self.win.get_geometry() print "###\nself.wParent.get_geometry()", self.wParent.get_geometry() print "###\nself.wGrandParent.get_geometry()", self.wGrandParent.get_geometry() try: print "###\nself.wGrandParent.query_tree().parent.get_geometry()", self.wGrandParent.query_tree().parent.get_geometry() except: pass print "###\nself.maximizeHandler.get_geometry()", self.maximizeHandler.get_geometry() print "###\nself.geomReciever.get_geometry()", self.geomReciever.get_geometry() print "###\nself.geomSender.get_geometry()", self.geomSender.get_geometry() print "###\nself.win", self.win print "###\nself.wParent", self.wParent print "###\nself.wGrandParent", self.wGrandParent print "###\nself.maximizeHandler", self.maximizeHandler print "###\nself.geomReciever", self.geomReciever print "###\nself.geomSender", self.geomSender ws = displayContext.getWindowSize() r = rect.Rect(0, 0, ws[0], ws[1]) GLViewport.__init__(self, r) if DEBUG_WM: print "self.size", self.size, "ws", ws if displayContext.win and self.maximized: # Send a maximize event now displayContext.win.set_state(mcplatform.MAXIMIZED) # Flip pygame.display to avoid to see the splash un-centered. pygame.display.flip() self.displayContext = displayContext self.bg_color = (0, 0, 0, 1) self.anchor = 'tlbr' if not config.config.has_section("Recent Worlds"): config.config.add_section("Recent Worlds") self.setRecentWorlds([""] * 5) self.optionsPanel = panels.OptionsPanel(self) if not albow.translate.buildTemplate: self.optionsPanel.getLanguageChoices() lng = config.settings.langCode.get() if lng not in self.optionsPanel.sgnal: lng = "en_US" config.settings.langCode.set(lng) albow.translate.setLang(lng) # Set the window caption here again, since the initialization is done through several steps... display.set_caption(('MCEdit ~ ' + release.get_version() % _("for")).encode('utf-8'), 'MCEdit') self.optionsPanel.initComponents() self.graphicsPanel = panels.GraphicsPanel(self) #.# self.keyConfigPanel = keys.KeyConfigPanel(self) #.# self.droppedLevel = None self.nbtCopyBuffer = None self.reloadEditor() """ check command line for files dropped from explorer """ if len(sys.argv) > 1: for arg in sys.argv[1:]: f = arg.decode(sys.getfilesystemencoding()) if os.path.isdir(os.path.join(pymclevel.minecraftSaveFileDir, f)): f = os.path.join(pymclevel.minecraftSaveFileDir, f) self.droppedLevel = f break if os.path.exists(f): self.droppedLevel = f break self.fileOpener = albow.FileOpener(self) self.add(self.fileOpener) self.fileOpener.focus() #-# Translation live updtate preparation def set_update_ui(self, v): GLViewport.set_update_ui(self, v) if v: #&# Prototype for blocks/items names if self.editor.level: if self.editor.level.gamePlatform == "Java": # added this so the original functionality of this function does not change mclangres.buildResources(self.editor.level.gameVersionNumber, albow.translate.getLang()) else: mclangres.buildResources(self.editor.level.gamePlatform, albow.translate.getLang()) #&# self.keyConfigPanel = keys.KeyConfigPanel(self) self.graphicsPanel = panels.GraphicsPanel(self) if self.fileOpener in self.subwidgets: idx = self.subwidgets.index(self.fileOpener) self.remove(self.fileOpener) self.fileOpener = albow.FileOpener(self) if idx is not None: self.add(self.fileOpener) self.fileOpener.focus() #-# editor = None def reloadEditor(self): reload(leveleditor) level = None pos = None if self.editor: level = self.editor.level self.remove(self.editor) c = self.editor.mainViewport pos, yaw, pitch = c.position, c.yaw, c.pitch self.editor = leveleditor.LevelEditor(self) self.editor.anchor = 'tlbr' if level: self.add(self.editor) self.editor.gotoLevel(level) self.focus_switch = self.editor if pos is not None: c = self.editor.mainViewport c.position, c.yaw, c.pitch = pos, yaw, pitch def add_right(self, widget): w, h = self.size widget.centery = h // 2 widget.right = w self.add(widget) def showOptions(self): self.optionsPanel.present() def showGraphicOptions(self): self.graphicsPanel.present() def showKeyConfig(self): self.keyConfigPanel.presentControls() def loadRecentWorldNumber(self, i): worlds = list(self.recentWorlds()) if i - 1 < len(worlds): self.loadFile(worlds[i - 1]) numRecentWorlds = 5 @staticmethod def removeLevelDat(filename): if filename.endswith("level.dat"): filename = os.path.dirname(filename) return filename def recentWorlds(self): worlds = [] for i in xrange(self.numRecentWorlds): if config.config.has_option("Recent Worlds", str(i)): try: filename = (config.config.get("Recent Worlds", str(i)).decode('utf-8')) worlds.append(self.removeLevelDat(filename)) except Exception as e: logging.error(repr(e)) return list((f for f in worlds if f and os.path.exists(f))) def addRecentWorld(self, filename): filename = self.removeLevelDat(filename) rw = list(self.recentWorlds()) if filename in rw: return rw = [filename] + rw[:self.numRecentWorlds - 1] self.setRecentWorlds(rw) @staticmethod def setRecentWorlds(worlds): for i, filename in enumerate(worlds): config.config.set("Recent Worlds", str(i), filename.encode('utf-8')) def makeSideColumn1(self): def showLicense(): #platform_open(os.path.join(directories.getDataDir(), "LICENSE.txt")) platform_open(directories.getDataFile('LICENSE.txt')) def refresh(): PlayerCache().force_refresh() def update_mcver(): num = mcver_updater.run() if num is None: albow.alert("Error Updating") elif num: albow.alert("Version Definitions have been updated!\n\nPlease restart MCEdit-Unified to apply the changes") else: albow.alert("Version Definitions are already up-to-date!") hotkeys = ([("", "Controls", self.showKeyConfig), ("", "Graphics", self.showGraphicOptions), ("", "Options", self.showOptions), ("", "Homepage", lambda: platform_open("http://www.mcedit-unified.net"), "http://www.mcedit-unified.net"), ("", "About MCEdit", lambda: platform_open("http://www.mcedit-unified.net/about.html"), "http://www.mcedit-unified.net/about.html"), ("", "License", showLicense, #os.path.join(directories.getDataDir(), "LICENSE.txt")), directories.getDataFile('LICENSE.txt')), ("", "Refresh Player Names", refresh), ("", "Update Version Definitions", update_mcver) ]) c = albow.HotkeyColumn(hotkeys) return c def makeSideColumn2(self): def showCacheDir(): try: os.mkdir(directories.getCacheDir()) except OSError: pass platform_open(directories.getCacheDir()) def showScreenshotsDir(): try: os.mkdir(os.path.join(directories.getCacheDir(), "screenshots")) except OSError: pass platform_open(os.path.join(directories.getCacheDir(), "screenshots")) hotkeys = ([("", "Config Files", showCacheDir, directories.getCacheDir()), ("", "Screenshots", showScreenshotsDir, os.path.join(directories.getCacheDir(), "screenshots")) ]) c = albow.HotkeyColumn(hotkeys) return c def resized(self, dw, dh): """ Handle window resizing events. """ if DEBUG_WM: print "############################ RESIZED ############################" (w, h) = self.size config_w, config_h = config.settings.windowWidth.get(), config.settings.windowHeight.get() win = self.displayContext.win if DEBUG_WM and win: print "dw", dw, "dh", dh print "self.size (w, h) 1", self.size, "win.get_size", win.get_size() print "size 1", config_w, config_h elif DEBUG_WM and not win: print "win is None, unable to print debug messages" if win: x, y = win.get_position() if DEBUG_WM: print "position", x, y print "config pos", (config.settings.windowX.get(), config.settings.windowY.get()) if w == 0 and h == 0: # The window has been minimized, no need to draw anything. self.editor.renderer.render = False return # Mac window handling works better now, but `win` # doesn't exist. So to get this alert to show up # I'm checking if the platform is darwin. This only # works because the code block never actually references # `win`, otherwise it WOULD CRASH!!! # You cannot change further if statements like this # because they reference `win` if win or sys.platform == "darwin": # Handling too small resolutions. # Dialog texts. # "MCEdit does not support window resolutions below 1000x700.\nYou may not be able to access all functions at this resolution." # New buttons: # "Don't warn me again": disable the window popup across sessions. # Tooltip: "Disable this message. Definitively. Even the next time you start MCEdit." # "OK": dismiss the window and let go, don't pop up again for the session # Tooltip: "Continue and not see this message until you restart MCEdit" # "Cancel": resizes the window to the minimum size # Tooltip: "Resize the window to the minimum recommended resolution." # If the config showWindowSizeWarning is true and self.resizeAlert is true, show the popup if (w < 1000 or h < 680) and config.settings.showWindowSizeWarning.get(): _w = w _h = h if self.resizeAlert: answer = "_OK" # Force the size only for the dimension that needs it. if w < 1000 and h < 680: _w = 1000 _h = 680 elif w < 1000: _w = 1000 elif h < 680: _h = 680 if not albow.dialogs.ask_tied_to: answer = albow.ask( "MCEdit does not support window resolutions below 1000x700.\nYou may not be able to access all functions at this resolution.", ["Don't remind me again.", "OK", "Cancel"], default=1, cancel=1, responses_tooltips={ "Don't remind me again.": "Disable this message. Definitively. Even the next time you start MCEdit.", "OK": "Continue and not see this message until you restart MCEdit", "Cancel": "Resize the window to the minimum recommended resolution."}, tie_widget_to=True) else: if not albow.dialogs.ask_tied_to._visible: albow.dialogs.ask_tied_to._visible = True answer = albow.dialogs.ask_tied_to.present() if answer == "Don't remind me again.": config.settings.showWindowSizeWarning.set(False) self.resizeAlert = False elif answer == "OK": w, h = self.size self.resizeAlert = False elif answer == "Cancel": w, h = _w, _h else: if albow.dialogs.ask_tied_to: albow.dialogs.ask_tied_to.dismiss("_OK") del albow.dialogs.ask_tied_to albow.dialogs.ask_tied_to = None elif w >= 1000 or h >= 680: if albow.dialogs.ask_tied_tos: for ask_tied_to in albow.dialogs.ask_tied_tos: ask_tied_to._visible = False ask_tied_to.dismiss("_OK") ask_tied_to.set_parent(None) del ask_tied_to if not win: if w < 1000: config.settings.windowWidth.set(1000) w = 1000 x = config.settings.windowX.get() if h < 680: config.settings.windowHeight.set(680) h = 680 y = config.settings.windowY.get() if not self.editor.renderer.render: self.editor.renderer.render = True save_geom = True if win: maximized = win.get_state() == mcplatform.MAXIMIZED sz = map(max, win.get_size(), (w, h)) if DEBUG_WM: print "sz", sz print "maximized", maximized, "self.maximized", self.maximized if maximized: if DEBUG_WM: print "maximize, saving maximized size" config.settings.windowMaximizedWidth.set(sz[0]) config.settings.windowMaximizedHeight.set(sz[1]) config.save() self.saved_pos = config.settings.windowX.get(), config.settings.windowY.get() save_geom = False self.resizing = 0 win.set_mode(sz, self.displayContext.displayMode()) else: if DEBUG_WM: print "size 2", config.settings.windowWidth.get(), config.settings.windowHeight.get() print "config_w", config_w, "config_h", config_h print "pos", config.settings.windowX.get(), config.settings.windowY.get() if self.maximized != maximized: if DEBUG_WM: print "restoring window pos and size" print "(config.settings.windowX.get(), config.settings.windowY.get())", ( config.settings.windowX.get(), config.settings.windowY.get()) (w, h) = (config_w, config_h) win.set_state(1, (w, h), self.saved_pos) else: if DEBUG_WM: print "window resized" print "setting size to", (w, h), "and pos to", (x, y) win.set_mode((w, h), self.displayContext.displayMode()) win.set_position((x, y)) config.settings.windowMaximizedWidth.set(0) config.settings.windowMaximizedHeight.set(0) config.save() self.maximized = maximized if DEBUG_WM: print "self.size (w, h) 2", self.size, (w, h) surf = pygame.display.get_surface() print "display surf rect", surf.get_rect() if win: if hasattr(win.base_handler, 'get_geometry'): print "win.base_handler geometry", win.base_handler.get_geometry() print "win.base_handler.parent geometry", win.base_handler.query_tree().parent.get_geometry() print "win.base_handler.parent.parent geometry", win.base_handler.query_tree().parent.query_tree().parent.get_geometry() if save_geom: config.settings.windowWidth.set(w) config.settings.windowHeight.set(h) config.save() # The alert window is disabled if win is not None if not win and (dw > 20 or dh > 20): if not hasattr(self, 'resizeAlert'): self.resizeAlert = self.shouldResizeAlert if self.resizeAlert: albow.alert( "Window size increased. You may have problems using the cursor until MCEdit is restarted.") self.resizeAlert = False if win: win.sync() GLViewport.resized(self, dw, dh) shouldResizeAlert = config.settings.shouldResizeAlert.property() def loadFile(self, filename, addToRecent=True): if os.path.exists(filename): if filename.endswith(".mcworld"): filename = mcworld_support.open_world(filename) addToRecent = False try: self.editor.loadFile(filename, addToRecent=addToRecent) except NotImplementedError as e: albow.alert(e.message) return None except Exception as e: logging.error(u'Failed to load file {0}: {1!r}'.format( filename, e)) return None self.remove(self.fileOpener) self.fileOpener = None if self.editor.level: self.editor.size = self.size self.add(self.editor) self.focus_switch = self.editor def createNewWorld(self): level = self.editor.createNewLevel() if level: self.remove(self.fileOpener) self.editor.size = self.size self.add(self.editor) self.focus_switch = self.editor albow.alert( "World created. To expand this infinite world, explore the world in Minecraft or use the Chunk Control tool to add or delete chunks.") def removeEditor(self): self.remove(self.editor) self.fileOpener = albow.FileOpener(self) self.add(self.fileOpener) self.focus_switch = self.fileOpener def confirm_quit(self): #-# saving language template if hasattr(albow.translate, "saveTemplate"): albow.translate.saveTemplate() #-# self.saveWindowPosition() config.save() if self.editor.unsavedEdits: result = albow.ask(_("There are {0} unsaved changes.").format(self.editor.unsavedEdits), responses=["Save and Quit", "Quit", "Cancel"]) if result == "Save and Quit": self.saveAndQuit() elif result == "Quit": self.justQuit() elif result == "Cancel": return False else: raise SystemExit def saveAndQuit(self): self.editor.saveFile() raise SystemExit @staticmethod def justQuit(): raise SystemExit @classmethod def fetch_version(cls): with cls.version_lock: cls.version_info = release.fetch_new_version_info() def check_for_version(self): new_version = release.check_for_new_version(self.version_info) if new_version is not False: answer = albow.ask( _('Version {} is available').format(new_version["tag_name"]), [ 'Download', 'View', 'Ignore' ], default=1, cancel=2 ) if answer == "View": platform_open(new_version["html_url"]) elif answer == "Download": platform_open(new_version["asset"]["browser_download_url"]) albow.alert(_( ' {} should now be downloading via your browser. You will still need to extract the downloaded file to use the updated version.').format( new_version["asset"]["name"])) @classmethod def main(cls): PlayerCache().load() displayContext = GLDisplayContext(splash.splash, caption=( ('MCEdit ~ ' + release.get_version() % _("for")).encode('utf-8'), 'MCEdit')) os.environ['SDL_VIDEO_CENTERED'] = '0' rootwidget = RootWidget(displayContext.display) mcedit = MCEdit(displayContext) rootwidget.displayContext = displayContext rootwidget.confirm_quit = mcedit.confirm_quit rootwidget.mcedit = mcedit rootwidget.add(mcedit) rootwidget.focus_switch = mcedit if mcedit.droppedLevel: mcedit.loadFile(mcedit.droppedLevel) cls.version_lock = threading.Lock() cls.version_info = None cls.version_checked = False fetch_version_thread = threading.Thread(target=cls.fetch_version) fetch_version_thread.start() if config.settings.closeMinecraftWarning.get(): answer = albow.ask( "Warning: Only open a world in one program at a time. If you open a world at the same time in MCEdit and in Minecraft, you will lose your work and possibly damage your save file.\n\n If you are using Minecraft 1.3 or earlier, you need to close Minecraft completely before you use MCEdit.", ["Don't remind me again.", "OK"], default=1, cancel=1) if answer == "Don't remind me again.": config.settings.closeMinecraftWarning.set(False) if not config.settings.reportCrashesAsked.get(): answer = albow.ask( 'Would you like to send anonymous error reports to the MCEdit-Unified Team to help with improving future releases?\n\nError reports are stripped of any identifying user information before being sent.\n\nPyClark, the library used, is open source under the GNU LGPL v3 license and is maintained by Podshot. The source code can be located here: https://github.com/Podshot/pyClark.\n\nThere has been no modification to the library in any form.', ['Allow', 'Deny'], default=1, cancel=1 ) if answer == 'Allow': albow.alert("Error reporting will be enabled next time MCEdit-Unified is launched") config.settings.reportCrashes.set(answer == 'Allow') config.settings.reportCrashesAsked.set(True) config.save() if "update" in config.version.version.get(): answer = albow.ask( "There are new default controls. Do you want to replace your current controls with the new ones?", ["Yes", "No"]) if answer == "Yes": for configKey, k in keys.KeyConfigPanel.presets["WASD"]: config.keys[config.convert(configKey)].set(k) config.version.version.set("1.6.0.0") config.save() if "-causeError" in sys.argv: raise ValueError("Error requested via -causeError") while True: try: rootwidget.run() except (SystemExit, KeyboardInterrupt): print "Shutting down..." exc_txt = traceback.format_exc() if mcedit.editor.level: if config.settings.savePositionOnClose.get(): mcedit.editor.waypointManager.saveLastPosition(mcedit.editor.mainViewport, mcedit.editor.level.dimNo) mcedit.editor.waypointManager.save() # The following Windows specific code won't be executed if we're using '--debug-wm' switch. if not USE_WM and sys.platform == "win32" and config.settings.setWindowPlacement.get(): (flags, showCmd, ptMin, ptMax, rect) = mcplatform.win32gui.GetWindowPlacement( display.get_wm_info()['window']) X, Y, r, b = rect if (showCmd == mcplatform.win32con.SW_MINIMIZE or showCmd == mcplatform.win32con.SW_SHOWMINIMIZED): showCmd = mcplatform.win32con.SW_SHOWNORMAL config.settings.windowX.set(X) config.settings.windowY.set(Y) config.settings.windowShowCmd.set(showCmd) # Restore the previous language if we ran with '-tt' (update translation template). if albow.translate.buildTemplate: logging.warning('Restoring %s.' % orglang) config.settings.langCode.set(orglang) # config.save() mcedit.editor.renderer.discardAllChunks() mcedit.editor.deleteAllCopiedSchematics() if mcedit.editor.level: mcedit.editor.level.close() mcedit.editor.root.RemoveEditFiles() if 'SystemExit' in traceback.format_exc() or 'KeyboardInterrupt' in traceback.format_exc(): raise else: if 'SystemExit' in exc_txt: raise SystemExit if 'KeyboardInterrupt' in exc_txt: raise KeyboardInterrupt except MemoryError: traceback.print_exc() mcedit.editor.handleMemoryError() def saveWindowPosition(self): """Save the window position in the configuration handler.""" if DEBUG_WM: print "############################ EXITING ############################" win = self.displayContext.win # The following Windows specific code will not be executed if we're using '--debug-wm' switch. if not USE_WM and sys.platform == "win32" and config.settings.setWindowPlacement.get(): (flags, showCmd, ptMin, ptMax, rect) = mcplatform.win32gui.GetWindowPlacement( display.get_wm_info()['window']) X, Y, r, b = rect if (showCmd == mcplatform.win32con.SW_MINIMIZE or showCmd == mcplatform.win32con.SW_SHOWMINIMIZED): showCmd = mcplatform.win32con.SW_SHOWNORMAL config.settings.windowX.set(X) config.settings.windowY.set(Y) config.settings.windowShowCmd.set(showCmd) elif win: config.settings.windowMaximized.set(self.maximized) if not self.maximized: x, y = win.get_position() else: x, y = self.saved_pos if DEBUG_WM: print "x", x, "y", y config.settings.windowX.set(x) config.settings.windowY.set(y) def restart(self): self.saveWindowPosition() config.save() self.editor.renderer.discardAllChunks() self.editor.deleteAllCopiedSchematics() if self.editor.level: self.editor.level.close() self.editor.root.RemoveEditFiles() python = sys.executable if sys.argv[0].endswith('.exe') or hasattr(sys, 'frozen'): os.execl(python, python, *sys.argv[1:]) else: os.execl(python, python, *sys.argv) def main(argv): """ Setup display, bundled schematics. Handle unclean shutdowns. """ try: display.init() except pygame.error: os.environ['SDL_VIDEODRIVER'] = 'directx' try: display.init() except pygame.error: os.environ['SDL_VIDEODRIVER'] = 'windib' display.init() pygame.font.init() try: if not os.path.exists(directories.schematicsDir): shutil.copytree( #os.path.join(directories.getDataDir(), u'stock-schematics'), directories.getDataFile('stock-schematics'), directories.schematicsDir ) except Exception as e: logging.warning('Error copying bundled schematics: {0!r}'.format(e)) try: os.mkdir(directories.schematicsDir) except Exception as e: logging.warning('Error creating schematics folder: {0!r}'.format(e)) try: ServerJarStorage() except Exception as e: logging.warning('Error creating server jar storage folder: {0!r}'.format(e)) try: MCEdit.main() except Exception as e: print "mcedit.main MCEdit exited with errors." logging.error("MCEdit version %s", release.get_version()) display.quit() if hasattr(sys, 'frozen') and sys.platform == 'win32': logging.exception("%s", e) print "Press RETURN or close this window to dismiss." raw_input() raise return 0 def getSelectedMinecraftVersion(): profile = directories.getMinecraftProfileJSON()[directories.getSelectedProfile()] if 'lastVersionId' in profile: return profile['lastVersionId'] else: return '1.8' def getLatestMinecraftVersion(snapshots=False): import urllib2 import json versioninfo = json.loads( urllib2.urlopen("http://s3.amazonaws.com/Minecraft.Download/versions/versions.json ").read()) if snapshots: return versioninfo['latest']['snapshot'] else: return versioninfo['latest']['release'] def weird_fix(): try: from OpenGL.platform import win32 except Exception: pass class FakeStdOutErr: """Fake file object to redirect very last Python output. Used to track 'errors' not handled in MCEdit. Mimics 'write' and 'close' file objects methods. Used on Linux only.""" mode = 'a' def __init__(self, *args, **kwargs): """*args and **kwargs are ignored. Deletes the 'logger' object and reopen 'logfile' in append mode.""" global logger global logfile del logger self.fd = open(logfile, 'a') def write(self, msg): self.fd.write(msg) def close(self, *args, **kwargs): self.fd.flush() self.fd.close() if __name__ == "__main__": try: main(sys.argv) except (SystemExit, KeyboardInterrupt): # It happens that on Linux, Python tries to kill already dead processes and display errors in the console. # Redirecting them to the log file preserve them and other errors which may occur. if sys.platform == "linux2": logger.debug("MCEdit is exiting normally.") logger.debug("Lines below this one are pure Python output.") sys.stdout = sys.stderr = FakeStdOutErr() mcworld_support.close_all_temp_dirs() pass except: mcworld_support.close_all_temp_dirs() traceback.print_exc() print "" print "==================================" print "\t\t\t MCEdit has crashed" print "==================================" raw_input("Press the Enter key to close this window") pass
42,368
37.693151
457
py
MCEdit-Unified
MCEdit-Unified-master/directories.py
# -*- coding: utf-8 -*- """Copyright (c) 2010-2012 David Rio Vierra Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.""" import time t = time.time() import sys import os import json import glob import shutil from utilities.misc import unicoded def win32_utf8_argv(): """Uses shell32.GetCommandLineArgvW to get sys.argv as a list of UTF-8 strings. Versions 2.5 and older of Python don't support Unicode in sys.argv on Windows, with the underlying Windows API instead replacing multi-byte characters with '?'. Returns None on failure. Example usage: >>> def main(argv=None): ... if argv is None: ... argv = win32_utf8_argv() or sys.argv ... """ try: from ctypes import POINTER, byref, cdll, c_int, windll from ctypes.wintypes import LPCWSTR, LPWSTR GetCommandLineW = cdll.kernel32.GetCommandLineW GetCommandLineW.argtypes = [] GetCommandLineW.restype = LPCWSTR CommandLineToArgvW = windll.shell32.CommandLineToArgvW CommandLineToArgvW.argtypes = [LPCWSTR, POINTER(c_int)] CommandLineToArgvW.restype = POINTER(LPWSTR) cmd = GetCommandLineW() argc = c_int(0) argv = CommandLineToArgvW(cmd, byref(argc)) if argc.value > 0: # # Remove Python executable if present # if argc.value - len(sys.argv) == 1: # start = 1 # else: # start = 0 return [argv[i] for i in xrange(0, argc.value)] except Exception: pass def getNewDataDir(path=""): """ Returns the directory where the executable is located (This function is only ran on Windows OS's) :param path: Additional directories/files to join to the data directory path :return unicode """ dataDir = os.path.dirname(os.path.abspath(__file__)) print "Data Dir: {}".format(dataDir) #print "Dynamic: " + str(os.getcwdu()) #print "Fixed: " + str(dataDir) if len(path) > 0: return os.path.join(dataDir, path) return dataDir @unicoded def getDataFile(*args, **kwargs): bundled_lookup = kwargs.get('bundle_only_lookup', False) executable_lookup = kwargs.get('executable_only_lookup', False) if getattr(sys, 'frozen', False) and sys.platform == 'linux2': # Linux bundle uses 'sys.frozen' return os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), *args) elif not getattr(sys, 'frozen', False): return os.path.join(os.path.dirname(os.path.abspath(__file__)), *args) if executable_lookup: return os.path.join(os.path.dirname(sys.executable), *args) if bundled_lookup: return os.path.join(sys._MEIPASS, *args) executable_path = getDataFile(*args, executable_only_lookup=True) if os.path.exists(os.path.join(executable_path)): return os.path.join(executable_path) else: return os.path.join(getDataFile(*args, bundle_only_lookup=True)) def getDataFileSaveable(*args): return getDataFile(*args, executable_only_lookup=True) def getDataDir(path=""): """ Returns the folder where the executable is located. (This function is ran on non-Windows OS's) :param path: Additional directories/files to join to the data directory path :return unicode """ # if sys.platform == "win32": # def fsdecode(x): # return x.decode(sys.getfilesystemencoding()) # # dataDir = os.getcwdu() # """ # if getattr(sys, 'frozen', False): # dataDir = os.path.dirname(sys._MEIPASS) # else: # dataDir = os.path.dirname(__file__) # """ # # else: dataDir = os.getcwdu() if len(path) > 0: return os.path.join(dataDir, path) return dataDir if sys.platform == "win32": getDataDir = getNewDataDir def win32_appdata(): # try to use win32 api to get the AppData folder since python doesn't populate os.environ with unicode strings. try: import win32com.client objShell = win32com.client.Dispatch("WScript.Shell") return objShell.SpecialFolders("AppData") except Exception as e: print "Error while getting AppData folder using WScript.Shell.SpecialFolders: {0!r}".format(e) try: from win32com.shell import shell, shellcon return shell.SHGetPathFromIDListEx( shell.SHGetSpecialFolderLocation(0, shellcon.CSIDL_APPDATA) ) except Exception as e: print "Error while getting AppData folder using SHGetSpecialFolderLocation: {0!r}".format(e) return os.environ['APPDATA'].decode(sys.getfilesystemencoding()) def getMinecraftProfileJSON(): """Returns a dictionary object with the minecraft profile information""" if os.path.isfile(os.path.join(getMinecraftLauncherDirectory(), u"launcher_profiles.json")): try: with open(os.path.join(getMinecraftLauncherDirectory(), u"launcher_profiles.json"), 'rb') as jsonString: minecraftProfilesJSON = json.loads(jsonString.read().decode(sys.getfilesystemencoding())) return minecraftProfilesJSON except: return None def getMinecraftProfileDirectory(profileName): """Returns the path to the sent minecraft profile directory""" try: profileDir = getMinecraftProfileJSON()['profiles'][profileName]['gameDir'] # profileDir update to correct location. return profileDir except: return os.path.join(getMinecraftLauncherDirectory()) def getMinecraftLauncherDirectory(): """ Returns the /minecraft directory, note: may not contain the /saves folder! """ if sys.platform == "win32": return os.path.join(win32_appdata(), ".minecraft") elif sys.platform == "darwin": return os.path.expanduser("~/Library/Application Support/minecraft") else: return os.path.expanduser("~/.minecraft") def getDocumentsFolder(): if sys.platform == "win32": try: import win32com.client from win32com.shell import shell, shellcon objShell = win32com.client.Dispatch("WScript.Shell") docsFolder = objShell.SpecialFolders("MyDocuments") except Exception as e: print e try: docsFolder = shell.SHGetFolderPath(0, shellcon.CSIDL_MYDOCUMENTS, 0, 0) except Exception: userprofile = os.environ['USERPROFILE'].decode(sys.getfilesystemencoding()) docsFolder = os.path.join(userprofile, "Documents") elif sys.platform == "darwin": docsFolder = os.path.expanduser("~/Documents") else: docsFolder = os.path.expanduser("~/.mcedit") try: os.mkdir(docsFolder) except: pass return docsFolder def getSelectedProfile(): """ Gets the selected profile from the Minecraft Launcher """ try: selectedProfile = getMinecraftProfileJSON()['selectedProfile'] return selectedProfile except: return None _minecraftSaveFileDir = None def getMinecraftSaveFileDir(): global _minecraftSaveFileDir if _minecraftSaveFileDir is None: _minecraftSaveFileDir = os.path.join(getMinecraftProfileDirectory(getSelectedProfile()), u"saves") return _minecraftSaveFileDir minecraftSaveFileDir = getMinecraftSaveFileDir() ini = u"mcedit.ini" cache = u"usercache.ini" parentDir = os.path.dirname(getDataDir()) docsFolder = os.path.join(getDocumentsFolder(),'MCEdit') if sys.platform != "darwin": portableConfigFilePath = os.path.join(parentDir, ini) portableCacheFilePath = os.path.join(parentDir, cache) portableGenericSupportPath = os.path.join(parentDir) portableSchematicsDir = os.path.join(parentDir, u"Schematics") portableBrushesDir = os.path.join(parentDir, u"Brushes") portableJarStorageDir = os.path.join(parentDir, u"ServerJarStorage") portableFiltersDir = os.path.join(parentDir, u"Filters") if not os.path.exists(parentDir): os.makedirs(parentDir) fixedCacheFilePath = os.path.join(docsFolder, cache) fixedConfigFilePath = os.path.join(docsFolder, ini) fixedGenericSupportPath = os.path.join(docsFolder) fixedSchematicsDir = os.path.join(docsFolder, u"Schematics") fixedBrushesDir = os.path.join(docsFolder, u"Brushes") fixedJarStorageDir = os.path.join(docsFolder, u"ServerJarStorage") fixedFiltersDir = os.path.join(docsFolder, u"Filters") if not os.path.exists(docsFolder): os.makedirs(docsFolder) def hasPreviousPortableInstallation(): portableDirectoriesFound = (os.path.exists(portableConfigFilePath) or os.path.exists(portableCacheFilePath) or os.path.exists(portableGenericSupportPath) or os.path.exists(portableSchematicsDir) or os.path.exists(portableBrushesDir) or os.path.exists(portableJarStorageDir) or os.path.exists(portableFiltersDir)) return portableDirectoriesFound def hasPreviousFixedInstallation(): fixedDirectoriesFound = (os.path.exists(fixedConfigFilePath) or os.path.exists(fixedCacheFilePath) or os.path.exists(fixedGenericSupportPath) or os.path.exists(fixedSchematicsDir) or os.path.exists(fixedBrushesDir) or os.path.exists(fixedJarStorageDir) or os.path.exists(fixedFiltersDir)) return fixedDirectoriesFound def goPortable(useExisting): if sys.platform == "darwin": return False global configFilePath, schematicsDir, filtersDir, portable, brushesDir if not useExisting: if os.path.exists(fixedSchematicsDir): move_displace(fixedSchematicsDir, portableSchematicsDir) if os.path.exists(fixedBrushesDir): move_displace(fixedBrushesDir, portableBrushesDir) if os.path.exists(fixedConfigFilePath): move_displace(fixedConfigFilePath, portableConfigFilePath) if os.path.exists(fixedFiltersDir): move_displace(fixedFiltersDir, portableFiltersDir) if os.path.exists(fixedCacheFilePath): move_displace(fixedCacheFilePath, portableCacheFilePath) if os.path.exists(fixedJarStorageDir): move_displace(fixedJarStorageDir, portableJarStorageDir) if filtersDir in sys.path: sys.path.remove(filtersDir) schematicsDir = portableSchematicsDir brushesDir = portableBrushesDir configFilePath = portableConfigFilePath filtersDir = portableFiltersDir sys.path.append(filtersDir) portable = True return True def move_displace(src, dst): dstFolder = os.path.basename(os.path.dirname(dst)) if not os.path.exists(dst): print "Moving {0} to {1}".format(os.path.basename(src), dstFolder) shutil.move(src, dst) else: olddst = dst + ".old" i = 0 while os.path.exists(olddst): olddst = dst + ".old" + str(i) i += 1 print "{0} already found in {1}! Renamed it to {2}.".format(os.path.basename(src), dstFolder, dst) os.rename(dst, olddst) shutil.move(src, dst) return True def goFixed(useExisting): if sys.platform == "darwin": return False global configFilePath, schematicsDir, filtersDir, portable, cacheDir, brushesDir if not useExisting: if os.path.exists(portableSchematicsDir): move_displace(portableSchematicsDir, fixedSchematicsDir) if os.path.exists(portableBrushesDir): move_displace(portableBrushesDir, fixedBrushesDir) if os.path.exists(portableConfigFilePath): move_displace(portableConfigFilePath, fixedConfigFilePath) if os.path.exists(portableFiltersDir): move_displace(portableFiltersDir, fixedFiltersDir) if os.path.exists(portableCacheFilePath): move_displace(portableCacheFilePath, fixedCacheFilePath) if os.path.exists(portableJarStorageDir): move_displace(portableJarStorageDir, fixedJarStorageDir) if filtersDir in sys.path: sys.path.remove(filtersDir) schematicsDir = fixedSchematicsDir brushesDir = fixedBrushesDir configFilePath = fixedConfigFilePath filtersDir = fixedFiltersDir sys.path.append(filtersDir) portable = False def fixedConfigExists(): if sys.platform == "darwin": return True # Check for files at portable locations. Cannot be Mac because config doesn't move return os.path.exists(fixedConfigFilePath) or not os.path.exists(portableConfigFilePath) if fixedConfigExists(): print "Running in fixed mode. Support files are in your " + ( sys.platform == "darwin" and "App Support Folder (Available from the main menu of MCEdit)" or "Documents folder.") portable = False if not sys.platform == "darwin": schematicsDir = fixedSchematicsDir brushesDir = fixedBrushesDir configFilePath = fixedConfigFilePath filtersDir = fixedFiltersDir jarStorageDir = fixedJarStorageDir genericSupportDir = fixedGenericSupportPath else: print "Running in portable mode. Support files are stored next to the MCEdit directory." if not sys.platform == "darwin": schematicsDir = portableSchematicsDir brushesDir = portableBrushesDir configFilePath = portableConfigFilePath filtersDir = portableFiltersDir jarStorageDir = portableJarStorageDir genericSupportDir = portableGenericSupportPath portable = True def getAllOfAFile(file_dir, ext): """ Returns a list of all the files the direcotry with the specified file extenstion :param file_dir: Directory to search :param ext: The file extension (IE: ".py") """ return glob.glob(file_dir+"/*"+ext) def getCacheDir(): """ Returns the path to the cache folder. This folder is the Application Support folder on OS X, and the Documents Folder on Windows. :return unicode """ if sys.platform == "win32": return genericSupportDir elif sys.platform == "darwin": return os.path.expanduser("~/Library/Application Support/pymclevel") else: try: return genericSupportDir except: return os.path.expanduser("~/.pymclevel") if sys.platform == "darwin": configFilePath = os.path.expanduser("~/Library/Preferences/mcedit.ini") schematicsDir = os.path.join(getCacheDir(), u"Schematics") brushesDir = os.path.join(getCacheDir(), u"Brushes") filtersDir = os.path.join(getCacheDir(), u"Filters") if not os.path.exists(getCacheDir()): os.makedirs(getCacheDir()) # Create pymclevel folder as needed if not os.path.exists(getCacheDir()): os.makedirs(getCacheDir()) # build the structures of directories if they don't exists for directory in (filtersDir, brushesDir, schematicsDir): if not os.path.exists(directory): os.makedirs(directory) # set userCachePath userCachePath = os.path.join(getCacheDir(),'usercache.ini') # Make sure it exists try: if not os.path.exists(userCachePath): f = open(userCachePath,'w') f.write('{}') f.close() except: print "Unable to make usercache.ini at {}".format(userCachePath) def getFiltersDir(): return filtersDir
16,057
34.448124
124
py
MCEdit-Unified
MCEdit-Unified-master/splash.py
#! /usr/bin/env python # Taken from http://www.pygame.org/project-Splash+screen-1186-.html by Rock Achu (rockhachu2) # and tweaked ;) import os import directories if os.sys.platform == 'linux2': os.sys.path.insert(1, os.path.expanduser('~/.local/lib/python2.7/site-packages')) os.sys.path.insert(1, os.path.abspath('./lib')) import pygame print 'Splash load...' os.environ['SDL_VIDEO_CENTERED'] = '1' pygame.init() pygame.font.init() no_splash = False #cur_dir = directories.getDataDir() #splash_name = os.path.join(cur_dir, 'splash') splash_name = directories.getDataFile('splash') splash = None splash_img_fp = None fp = None try: found = False if os.path.exists(splash_name): splash_img_fp = open(splash_name) splash_img = splash_img_fp.read().strip() if os.path.exists(splash_img) and splash_img.split('.')[-1].lower() in ('jpg', 'png', 'bmp', 'pcx', 'tif', 'lbm', 'pbm', 'pgm', 'ppm', 'xpm'): found = True fp = open(splash_img, 'rb') splash = pygame.image.load(fp) if not found: #fp = open(os.path.join(cur_dir, "splash.png"), 'rb') fp = open(directories.getDataFile('splash.png'), 'rb') splash = pygame.image.load(fp) screen = pygame.display.set_mode(splash.get_size(), pygame.NOFRAME) screen.blit(splash, (0, 0)) except Exception as e: print e try: #fp = open(os.path.join(cur_dir, 'fonts', 'DejaVuSans-Bold.ttf'), 'rb') fp = open(directories.getDataFile('fonts', 'DejaVuSans-Bold.ttf'), 'rb') font = pygame.font.Font(fp, 48) buf = font.render("MCEdit is loading...", True, (128, 128, 128)) screen = pygame.display.set_mode((buf.get_width() + 20, buf.get_height() + 20), pygame.NOFRAME) screen.blit(buf, (10, 10)) splash = pygame.display.get_surface() except Exception as _e: print _e splash = pygame.display.set_mode((1, 1)) no_splash = True finally: if fp: fp.close() if splash_img_fp: splash_img_fp.close() if splash: pygame.display.update() #os.environ['SDL_VIDEO_CENTERED'] = '0' # Done later, when initializing MCEdit 'real' display. # Random splash # # Uses a 'splash' file to check the state. # This file contains the name of the splash to be loaded next time MCEdit starts. # No splash file means it has to be created. # An empty file means the 'splash.png' file will always be used. # write_splash = True if not os.path.exists(splash_name): splash_fp = None try: splash_fp = open(splash_name, 'w') splash_fp.write('scrap') except Exception as e: write_splash = False print "Could not create 'splash' file:", e finally: if splash_fp: splash_fp.close() if write_splash: f = open(splash_name) if len(f.read()) > 0: from random import choice #splashes_folder = os.path.join(cur_dir, 'splashes') splashes_folder = directories.getDataFile('splashes') if not os.path.exists(splashes_folder): #splashes_folder = os.path.join(cur_dir, splashes_folder) splashes_folder = directories.getDataFile(splashes_folder) if os.path.exists(splashes_folder) and os.listdir(splashes_folder): new_splash = choice(os.listdir(splashes_folder)) if new_splash.split('.')[-1].lower() in ('jpg', 'png', 'bmp', 'pcx', 'tif', 'lbm', 'pbm', 'pgm', 'ppm', 'xpm'): f2 = open(splash_name, 'w') try: #f2.write(os.path.join(cur_dir, splashes_folder, new_splash)) f2.write(directories.getDataFile(splashes_folder, new_splash)) except Exception as e: print "Could not write 'splash' file:", e finally: if f2: f2.close() f.close()
3,879
35.603774
150
py
MCEdit-Unified
MCEdit-Unified-master/ftp_client.py
import ftputil import os import shutil from ftputil.error import PermanentError class CouldNotFindPropertiesException(Exception): """ An Exception that is raised when the 'server.properties' file could not be found at the default directory of the FTP Server """ pass class CouldNotFindWorldFolderException(Exception): """ An Exception that is raised when the world directory that is specified in the the 'server.properties' cannot be found """ pass class InvalidCreditdentialsException(Exception): """ An Exception that is raised when the supplied Username/Password is denied by the FTP Server """ pass class FTPClient: """ Wrapper client to download and upload worlds to a FTP Server """ def download(self): """ Downloads all files in the current FTP directory with their corresponding paths """ for root, directory, files in self._host.walk(self._host.curdir): try: os.makedirs(os.path.join('ftp', self._worldname, root[2:])) except OSError: pass for f in files: self._host.download(self._host.path.join(root, f), os.path.join('ftp', self._worldname, root, f)) def upload_new_world(self, world): """ Uploads a new world to the current FTP server connection :param world: The InfiniteWorld object for the world to upload :type world: InfiniteWorld """ path = world.worldFolder.getFilePath("level.dat")[:-10] world_name = path.split(os.path.sep)[-1] if not self._host.path.exists(world_name): self._host.mkdir(world_name) self._host.chdir(world_name) for root, directory, files in os.walk(world.worldFolder.getFilePath("level.dat")[:-10]): for folder in directory: target = self._host.path.join(root.replace(path, ""), folder).replace("\\", "", 1).replace("\\", "/") print "Target: "+target if not "##MCEDIT.TEMP##" in target: if not self._host.path.exists(target): self._host.makedirs(target) for root, directory, files in os.walk(world.worldFolder.getFilePath("level.dat")[:-10]): for f in files: target = self._host.path.join(root.replace(path, ""), f).replace("\\", "", 1).replace("\\", "/") print target try: self._host.upload(os.path.join(root, f), target) except Exception as e: if "226" in e.message: pass else: print "Error: {0}".format(e.message) def upload(self): """ Uploads an edited world to the current FTP server connection """ for root, directory, files in os.walk(os.path.join('ftp', self._worldname)): for folder in directory: target = self._host.path.join(root, folder).replace("ftp"+os.path.sep+self._worldname+"/", "").replace("\\", "", 1).replace("\\", "/") target = target.replace("ftp"+self._worldname, "") if not "##MCEDIT.TEMP##" in target: if not self._host.path.exists(target): self._host.makedirs(target) for root, directory, files in os.walk(os.path.join('ftp', self._worldname)): for f in files: if self._host.path.join(root, f).replace("ftp"+os.path.sep+self._worldname, "").startswith("\\"): target = self._host.path.join(root, f).replace("ftp"+os.path.sep+self._worldname, "").replace("\\", "", 1) else : target = self._host.path.join(root, f).replace("ftp"+os.path.sep+self._worldname, "") if "\\" in target: target = target.replace("\\", "/") try: self._host.upload(os.path.join(root, f), target) except Exception as e: if "226" in e.message: pass def cleanup(self): """ Closes the FTP connection and removes all leftover files from the 'ftp' directory """ if hasattr(self, '_host'): self._host.close() shutil.rmtree('ftp') def safe_download(self): """ Changes the FTP client's working directory, downloads the world, then switches back to the original working directory """ old_dir = self._host.curdir self._host.chdir(self._worldname) self.download() self._host.chdir(old_dir) def get_level_path(self): """ Gets the local path to the downloaded FTP world """ return os.path.join('ftp', self._worldname) def __init__(self, ip, username='anonymous', password=''): """ Initializes an FTP client to handle uploading and downloading of a Minecraft world via FTP :param ip: The IP of the FTP Server :type ip: str :param username: The Username to use to log into the server :type username: str :param password: The Password that accompanies the supplied Username :type password: str """ try: os.mkdir("ftp") except OSError: pass try: self._host = ftputil.FTPHost(ip, username, password) except PermanentError: raise InvalidCreditdentialsException("Incorrect username or password") self._worldname = None if 'server.properties' in self._host.listdir(self._host.curdir): self._host.download('server.properties', os.path.join('ftp', 'server.properties')) with open(os.path.join('ftp', 'server.properties'), 'r') as props: content = props.readlines() if len(content) > 1: for prop in content: if prop.startswith("level-name"): self._worldname = str(prop.split("=")[1:][0]).rstrip("\n") else: for prop in content[0].split('\r'): if prop.startswith("level-name"): self._worldname = str(prop.split("=")[1:][0]).rstrip("\r") else: raise CouldNotFindPropertiesException("Could not find the server.properties file! The FTP client will not be able to download the world unless the server.properties file is in the default FTP directory") if self._worldname in self._host.listdir(self._host.curdir): try: os.mkdir(os.path.join('ftp', self._worldname)) except OSError: pass else: raise CouldNotFindWorldFolderException("Could not find the world folder from the server.properties file")
7,028
42.122699
215
py
MCEdit-Unified
MCEdit-Unified-master/waypoints.py
from pymclevel import nbt import os import logging import shutil log = logging.getLogger() class WaypointManager: ''' Class for handling the API to load and save waypoints ''' def __init__(self, worldDir=None, editor=None): self.worldDirectory = worldDir self.waypoints = {} self.waypoint_names = set() self.editor = editor self.nbt_waypoints = nbt.TAG_Compound() self.nbt_waypoints["Waypoints"] = nbt.TAG_List() self.already_saved = False self.load() def build(self): ''' Builds the raw NBT data from the 'mcedit_waypoints.dat' file to a readable dictionary, with the key being '<Name> (<X>,<Y>,<Z>)' and the values being a list of [<X>,<Y>,<Z>,<Yaw>,<Pitch>,<Dimension>] ''' for point in self.nbt_waypoints["Waypoints"]: self.waypoint_names.add(point["Name"].value) self.waypoints["{0} ({1},{2},{3})".format(point["Name"].value, int(point["Coordinates"][0].value), int(point["Coordinates"][1].value), int(point["Coordinates"][2].value))] = [ point["Coordinates"][0].value, point["Coordinates"][1].value, point["Coordinates"][2].value, point["Rotation"][0].value, point["Rotation"][1].value, point["Dimension"].value ] def load(self): ''' Loads the 'mcedit_waypoints.dat' file from the world directory if it exists. If it doesn't exist, it sets the 'Empty' waypoint ''' if self.editor.level is None: return if not os.path.exists(os.path.join(self.worldDirectory, u"mcedit_waypoints.dat")): self.build() else: try: self.nbt_waypoints = nbt.load(os.path.join(self.worldDirectory, u"mcedit_waypoints.dat")) except nbt.NBTFormatError as e: shutil.move(os.path.join(self.worldDirectory, u"mcedit_waypoints.dat"), os.path.join(self.worldDirectory, u"mcedit_waypoints_backup.dat")) log.error(e) log.warning("Waypoint data file corrupted, ignoring...") finally: self.build() if not (len(self.waypoints) > 0): self.waypoints["Empty"] = [0,0,0,0,0,0] if "LastPosition" in self.nbt_waypoints: self.editor.gotoLastWaypoint(self.nbt_waypoints["LastPosition"]) del self.nbt_waypoints["LastPosition"] def save(self): ''' Saves all waypoint information to the 'mcedit_waypoints.dat' file in the world directory ''' del self.nbt_waypoints["Waypoints"] self.nbt_waypoints["Waypoints"] = nbt.TAG_List() for waypoint in self.waypoints.keys(): if waypoint.split()[0] == "Empty": continue way = nbt.TAG_Compound() way["Name"] = nbt.TAG_String(waypoint.split()[0]) way["Dimension"] = nbt.TAG_Int(self.waypoints[waypoint][5]) coords = nbt.TAG_List() coords.append(nbt.TAG_Float(self.waypoints[waypoint][0])) coords.append(nbt.TAG_Float(self.waypoints[waypoint][1])) coords.append(nbt.TAG_Float(self.waypoints[waypoint][2])) rot = nbt.TAG_List() rot.append(nbt.TAG_Float(self.waypoints[waypoint][3])) rot.append(nbt.TAG_Float(self.waypoints[waypoint][4])) way["Coordinates"] = coords way["Rotation"] = rot self.nbt_waypoints["Waypoints"].append(way) self.nbt_waypoints.save(os.path.join(self.worldDirectory, u"mcedit_waypoints.dat")) def add_waypoint(self, name, coordinates, rotation, dimension): ''' Adds a waypoint to the current dictionary of waypoints :param name: Name of the Waypoint :type name: str :param coordinates: The coordinates of the Waypoint (in X,Y,Z order) :type coordinates: tuple :param rotation: The rotation of the current camera viewport (in Yaw,Pitch order) :type rotation: tuple :param dimension: The current dimenstion the camera viewport is in :type dimension: int ''' formatted_name = "{0} ({1},{2},{3})".format(name, coordinates[0], coordinates[1], coordinates[2]) data = coordinates + rotation + (dimension,) self.waypoint_names.add(name) self.waypoints[formatted_name] = data def delete(self, choice): ''' Deletes the specified waypoint name from the dictionary of waypoints :param choice: Name of the waypoint to delete :type choice: str ''' waypt = None for waypoint in self.waypoint_names: if choice.startswith(waypoint): waypt = waypoint if waypt: self.waypoint_names.remove(waypt) del self.waypoints[choice] self.save() if not (len(self.waypoints) > 0): self.waypoints["Empty"] = [0,0,0,0,0,0] def saveLastPosition(self, mainViewport, dimension): ''' Saves the final position of the camera viewport when the world is closed or MCEdit is exited :param mainViewport: The reference to viewport object :param dimension: The dimension the camera viewport is currently in :type dimension: int ''' log.info('Saving last position.') if "LastPosition" in self.nbt_waypoints: del self.nbt_waypoints["LastPosition"] topTag = nbt.TAG_Compound() topTag["Dimension"] = nbt.TAG_Int(dimension) pos = nbt.TAG_List() pos.append(nbt.TAG_Float(mainViewport.cameraPosition[0])) pos.append(nbt.TAG_Float(mainViewport.cameraPosition[1])) pos.append(nbt.TAG_Float(mainViewport.cameraPosition[2])) topTag["Coordinates"] = pos rot = nbt.TAG_List() rot.append(nbt.TAG_Float(mainViewport.yaw)) rot.append(nbt.TAG_Float(mainViewport.pitch)) topTag["Rotation"] = rot self.nbt_waypoints["LastPosition"] = topTag self.save() self.already_saved = True
7,249
46.385621
207
py
MCEdit-Unified
MCEdit-Unified-master/mclangres.py
# -*- coding: utf_8 -*- # # mclangres.py # # Collect the Minecraft internal translations. # """ Uses `.minecraft/assets/indexes/[version].json`. The version is the highest found by default. """ import re import os import codecs from distutils.version import LooseVersion from directories import getMinecraftLauncherDirectory, getDataDir, getDataFile import logging log = logging.getLogger(__name__) indexesDirectory = os.path.join(getMinecraftLauncherDirectory(), 'assets', 'indexes') objectsDirectory = os.path.join(getMinecraftLauncherDirectory(), 'assets', 'objects') enRes = {} serNe = {} langRes = {} serGnal = {} enMisc = {} csimNe = {} langMisc = {} csimGnal = {} # Shall this be maintained in an external resource? excludedEntries = ['tile.flower1.name',] # Used to track untranslated and out dated MCEdit resources. # Set it to true to generate/add entries to 'missingmclangres.txt' in MCEdit folder. # Note that some strings may be falsely reported. (Especialy a '7 (Source)' one...) # ! ! ! Please, pay attention to disable this befor releasing ! ! ! report_missing = False def getResourceName(name, data): match = re.findall('"minecraft/lang/%s.lang":[ ]\{\b*.*?"hash":[ ]"(.*?)",' % name, data, re.I|re.DOTALL) if match: return match[0] else: log.debug('Could not find %s resource name.' % name) def findResourceFile(name, basedir): for root, dirs, files in os.walk(basedir): if name in files: return os.path.join(basedir, root, name) def buildResources(version=None, lang=None): """Loads the resource files and builds the resource dictionnaries. Four dictionnaries are built. Two for the refering language (English), and two for the language to be used. They are 'reversed' dictionnaries; the {foo: bar} pairs of one are the {bar: foo} of the other one.""" log.debug('Building Minecraft language resources...') global enRes global serNe global langRes global serGnal global enMisc global csimEn global langMisc global csimGnal enRes = {} serNe = {} langRes = {} serGnal = {} enMisc = {} csimEn = {} langMisc = {} csimGnal = {} if not os.path.exists(indexesDirectory) or not os.path.exists(objectsDirectory): log.debug('Minecraft installation directory is not valid.') log.debug('Impossible to load the game language resources.') return _versions = os.listdir(indexesDirectory) if 'legacy.json' in _versions: _versions.remove('legacy.json') if len(_versions) == 0: log.debug("No valid versions found in minecraft install directory") return # Sort the version so '1.8' comes after '1.10'. versions = [" "] for ver_str in _versions: v1 = LooseVersion(ver_str) idx = -1 for i, cur_ver in enumerate(versions): v2 = LooseVersion(cur_ver) if v1>= v2: break versions.insert(i, ver_str) versions = versions[:-1] version_file = "%s.json" % version fName = None if version_file in versions: fName = os.path.join(indexesDirectory, version_file) elif version: # Let's try to find a corresponding file by reducing the name. # E.g: 1.10.2 don't have an asset definition file, but 1.10 have. All the same for the pre-releases... if '-' in version: version = version.split('-')[0] while '.' in version: version = version.split('.') version_file = "%s.json" % version if version_file in versions: fName = os.path.join(indexesDirectory, version_file) break if not fName: fName = os.path.join(indexesDirectory, versions[-1]) log.debug('Using %s' % fName) data = open(fName).read() name = getResourceName('en_GB', data) if name: fName = os.path.join(objectsDirectory, name[:2], name) if not os.path.exists(fName): fName = findResourceFile(name, objectsDirectory) if not fName: log.debug('Can\'t get the resource %s.' % name) log.debug('Nothing built. Aborted') return log.debug('Found %s' % name) lines = codecs.open(fName, encoding='utf_8').readlines() for line in lines: if line.split('.')[0] in ['book', 'enchantment', 'entity', 'gameMode', 'generator', 'item', 'tile'] and line.split('=')[0].strip() not in excludedEntries: enRes[line.split('=', 1)[-1].strip()] = line.split('=', 1)[0].strip() serNe[line.split('=', 1)[0].strip()] = line.split('=', 1)[-1].strip() #lines = codecs.open(os.path.join(getDataDir(), 'Items', 'en_GB'), encoding='utf_8') lines = codecs.open(getDataFile('Items', 'en_GB'), encoding='utf_8') for line in lines: if line.split('.')[0] in ['book', 'enchantment', 'entity', 'gameMode', 'generator', 'item', 'tile'] and line.split('=')[0].strip() not in excludedEntries: enRes[line.split('=', 1)[-1].strip()] = line.split('=', 1)[0].strip() serNe[line.split('=', 1)[0].strip()] = line.split('=', 1)[-1].strip() else: enMisc[line.split('=', 1)[-1].strip()] = line.split('=', 1)[0].strip() csimNe[line.split('=', 1)[0].strip()] = line.split('=', 1)[-1].strip() log.debug('... Loaded!') else: return if not lang: lang = 'en_GB' log.debug('Looking for %s resources.' % lang) name = getResourceName(lang, data) if not name: lang = 'en_GB' name = getResourceName(lang, data) if name: fName = os.path.join(objectsDirectory, name[:2], name) if not os.path.exists(fName): fName = findResourceFile(name, objectsDirectory) if not fName: log.debug('Can\'t get the resource %s.' % name) return log.debug('Found %s...' % name) lines = codecs.open(fName, encoding='utf_8').readlines() for line in lines: if line.split('.')[0] in ['book', 'enchantment', 'entity', 'gameMode', 'generator', 'item', 'tile'] and line.split('=')[0].strip() not in excludedEntries: langRes[line.split('=', 1)[0].strip()] = line.split('=', 1)[-1].strip() serGnal[line.split('=', 1)[-1].strip()] = line.split('=', 1)[0].strip() #if os.path.exists(os.path.join(getDataDir(), 'Items', lang)): if os.path.exists(getDataFile('Items', lang)): log.debug("Found Items/%s" % lang) #lines = codecs.open(os.path.join(getDataDir(), 'Items', lang), encoding='utf_8') lines = codecs.open(getDataFile('Items', lang), encoding='utf_8') for line in lines: if line.split('.')[0] in ['book', 'enchantment', 'entity', 'gameMode', 'generator', 'item', 'tile'] and line.split('=')[0].strip() not in excludedEntries: langRes[line.split('=', 1)[0].strip()] = line.split('=', 1)[-1].strip() serGnal[line.split('=', 1)[-1].strip()] = line.split('=', 1)[0].strip() else: langMisc[line.split('=', 1)[0].strip()] = line.split('=', 1)[-1].strip() csimGnal[line.split('=', 1)[-1].strip()] = line.split('=', 1)[0].strip() log.debug('... Loaded!') else: return def compound(char, string, pair=None): if pair is None: if char in '{[(': pair = '}])'['{[('.index(char)] else: pair = char name, misc = string.split(char, 1) name = name.strip() misc = [a.strip() for a in misc.strip()[:-1].split(',')] if (name not in enRes.keys() and name not in langRes.values()) and (name not in enMisc.keys() and name not in langMisc.values()): addMissing(name) head = langRes.get(enRes.get(name, name), name) for i in xrange(len(misc)): if ' ' in misc[i]: if langMisc.get(enMisc.get(misc[i], False), False): misc[i] = langMisc.get(enMisc.get(misc[i], misc[i]), misc[i]) elif langRes.get(enRes.get(misc[i], False), False): misc[i] = langRes.get(enRes.get(misc[i], misc[i]), misc[i]) else: stop = [False, False] for j in xrange(1, misc[i].count(' ') + 1): elems = misc[i].rsplit(' ', j) if not stop[0]: h = elems[0] if langMisc.get(enMisc.get(h, False), False): h = langMisc.get(enMisc.get(h, h), h) stop[0] = True elif langRes.get(enRes.get(h, False), False): h = langRes.get(enRes.get(h, h), h) stop[0] = True if not stop[1]: t = u' '.join(elems[1:]) if langMisc.get(enMisc.get(t, False), False): t = langMisc.get(enMisc.get(t, t), t) stop[1] = True elif langRes.get(enRes.get(t, False), False): t = langRes.get(enRes.get(t, t), t) stop[1] = True if stop[0]: stop[1] = True misc[i] = u' '.join((h, t)) if (h not in enRes.keys() and h not in langRes.values()) and (h not in enMisc.keys() and h not in langMisc.values()): addMissing(h, 'misc') if (t not in enRes.keys() and t not in langRes.values()) and (t not in enMisc.keys() and t not in langMisc.values()): addMissing(t, 'misc') elif u'/' in misc[i]: misc[i] = u'/'.join([langMisc.get(enMisc.get(a, a), translate(a)) for a in misc[i].split('/')]) elif '-' in misc[i]: misc[i] = u'-'.join([langMisc.get(enMisc.get(a, a), translate(a)) for a in misc[i].split('-')]) elif '_' in misc[i]: misc[i] = u'_'.join([langMisc.get(enMisc.get(a, a), translate(a)) for a in misc[i].split('_')]) else: misc[i] = langRes.get(enRes.get(misc[i], misc[i]), misc[i]) tail = u'{0}{1}{2}'.format(char, u', '.join([langMisc.get(enMisc.get(a, a), a) for a in misc]), pair) return u' '.join((head, tail)) if report_missing: def addMissing(name, cat='base'): n = u'' for a in name: if a == ' ' or a.isalnum(): n += a elems = n.split(' ', 1) head = elems[0].lower() tail = '' if len(elems) > 1: tail = ''.join([a.capitalize() for a in elems[1].split(' ') if not a.isdigit()]) if not n.isdigit(): line = 'missing.{0}.{1}{2}={3}\n'.format(cat, head, tail, name) #f = codecs.open(os.path.join(getDataDir(), 'missingmclangres.txt'), 'a+', encoding='utf_8') f = codecs.open(getDataFile('missingmclangres.txt'), 'a+', encoding='utf_8') if line not in f.read(): f.write(line) f.close() else: def addMissing(*args, **kwargs): return def translate(name): """Returns returns the translation of `name`, or `name` if no translation found. Can handle composed strings like: 'string_present_in_translations (other_string_1, other_string_2)'. Note that, in this case, the returned string may be partially translated.""" for c in '{[(': if c in name: return compound(c, name) if report_missing: print '*', (name not in enRes.keys() and name not in langRes.values()) and (name not in enMisc.keys() and name not in langMisc.values()), name if (name not in enRes.keys() and name not in langRes.values()) and (name not in enMisc.keys() and name not in langMisc.values()): addMissing(name) return langRes.get(enRes.get(name, name), name) def untranslate(name, case_sensitive=True): """Basic reverse function of `translate`.""" key = serGnal.get(name, None) value = serNe.get(key, None) return value or name def search(text, untranslate=False, capitalize=True, filters=[]): """Search for a `text` string in the resources entries. `filters` is a list of strings: they must be parts before the '=' sign in the resource files, or parts of. `filters` may be regexes. Returns a sorted list of matching elements.""" # filters may contain regexes text = text.lower() results = [] def get_result(l, w): if untranslate: if capitalize: results.append('-'.join([b.capitalize() for b in ' '.join([a.capitalize() for a in serNe[w].split(' ')]).split('-')])) else: results.append(serNe[w].lower()) else: if capitalize: results.append('-'.join([b.capitalize() for b in ' '.join([a.capitalize() for a in l.split(' ')]).split('-')])) else: results.append(l.lower()) for k, v in serGnal.items(): if text in k.lower(): if not filters or map(lambda (x,y):re.match(x,y), zip(filters, [v] * len(filters))) != [None, None]: if untranslate: if capitalize: results.append('-'.join([b.capitalize() for b in ' '.join([a.capitalize() for a in serNe[v].split(' ')]).split('-')])) else: results.append(serNe[v].lower()) else: if capitalize: results.append('-'.join([b.capitalize() for b in ' '.join([a.capitalize() for a in k.split(' ')]).split('-')])) else: results.append(k.lower()) results.sort() return results
13,861
44.006494
170
py
MCEdit-Unified
MCEdit-Unified-master/raycaster.py
import math """ This function will produce a generator that will give out the blocks visited by a raycast in sequence. It is up to the user to terminate the generator. First described here by John Amanatides http://www.cse.yorku.ca/~amana/research/grid.pdf Implementation in javascript by Kevin Reid: https://gamedev.stackexchange.com/questions/47362/cast-ray-to-select-block-in-voxel-game """ def _rawRaycast(origin, direction): def _signum(x): if x > 0: return 1 elif x < 0: return -1 else: return 0 def _intbound(s,ds): if ds<0: return _intbound(-s,-ds) else: s %= 1 return (1-s)/ds x,y,z = map(int,map(math.floor,origin)) dx,dy,dz = direction if dx == 0: #Yes, I know this is hacky. It works though. dx = 0.000000001 if dy == 0: dy = 0.000000001 if dz == 0: dz = 0.000000001 stepX,stepY,stepZ = map(_signum,direction) tMaxX,tMaxY,tMaxZ = map(_intbound,origin,(dx,dy,dz)) tDeltaX = stepX/dx tDeltaY = stepY/dy tDeltaZ = stepZ/dz if dx == 0 and dy == 0 and dz == 0: raise Exception('Infinite ray trace detected') face = None while True: yield ((x,y,z),face) if tMaxX < tMaxY: if tMaxX < tMaxZ: x += stepX tMaxX += tDeltaX face = (-stepX, 0,0) else: z += stepZ tMaxZ += tDeltaZ face = (0,0,-stepZ) else: if tMaxY < tMaxZ: y += stepY tMaxY += tDeltaY face = (0,-stepY,0) else: z += stepZ tMaxZ += tDeltaZ face = (0,0,-stepZ) """ Finds the first block from origin in the given direction by ray tracing origin is the coordinate of the camera given as a tuple direction is a vector in the direction the block wanted is from the camera given as a tuple callback an object that will be inform This method returns a (position,face) tuple pair. """ def firstBlock(origin, direction, level, radius, viewMode=None): if viewMode == "Chunk": raise TooFarException("There are no valid blocks within range") startPos = map(int, map(math.floor, origin)) block = level.blockAt(*startPos) tooMuch = 0 if block == 8 or block == 9: callback = _WaterCallback() else: callback = _StandardCallback() for i in _rawRaycast(origin, direction): tooMuch += 1 block = level.blockAt(*i[0]) if callback.check(i[0], block): return i[0],i[1] if _tooFar(origin, i[0], radius) or _tooHighOrLow(i[0]): raise TooFarException("There are no valid blocks within range") if tooMuch >= 720: return i[0], i[1] def _tooFar(origin, position, radius): x = abs(origin[0] - position[0]) y = abs(origin[1] - position[1]) z = abs(origin[2] - position[2]) result = x > radius or y > radius or z > radius return result def _tooHighOrLow(position): return position[1] > 255 or position[1] < 0 class TooFarException(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class Callback: """ Returns true if the ray tracer is to be terminated """ def check(self, position,block): pass class _WaterCallback(Callback): def __init__(self): self.escapedBlock = False def check(self, position, block): if block == 8 or block == 9: return False elif block == 0: self.escapedBlock = True return False elif self.escapedBlock and block != 0: return True return True class _StandardCallback(Callback): def __init__(self): self.escapedBlock = False def check(self, position, block): if not self.escapedBlock: if block == 0: self.escapedBlock = True return if block != 0: return True return False
4,181
25.468354
95
py
MCEdit-Unified
MCEdit-Unified-master/glutils.py
"""Copyright (c) 2010-2012 David Rio Vierra Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.""" """ glutils.py Pythonesque wrappers around certain OpenGL functions. """ from OpenGL import GL import numpy from contextlib import contextmanager import weakref from OpenGL.GL import framebufferobjects as FBO import sys class gl(object): @classmethod def ResetGL(cls): DisplayList.invalidateAllLists() @classmethod @contextmanager def glPushMatrix(cls, matrixmode): try: GL.glMatrixMode(matrixmode) GL.glPushMatrix() yield finally: GL.glMatrixMode(matrixmode) GL.glPopMatrix() @classmethod @contextmanager def glPushAttrib(cls, attribs): try: GL.glPushAttrib(attribs) yield finally: GL.glPopAttrib() @classmethod @contextmanager def glBegin(cls, type): try: GL.glBegin(type) yield finally: GL.glEnd() @classmethod @contextmanager def glEnable(cls, *enables): try: GL.glPushAttrib(GL.GL_ENABLE_BIT) for e in enables: GL.glEnable(e) yield finally: GL.glPopAttrib() @classmethod @contextmanager def glEnableClientState(cls, *enables): try: GL.glPushClientAttrib(GL.GL_CLIENT_ALL_ATTRIB_BITS) for e in enables: GL.glEnableClientState(e) yield finally: GL.glPopClientAttrib() listCount = 0 @classmethod def glGenLists(cls, n): cls.listCount += n return GL.glGenLists(n) @classmethod def glDeleteLists(cls, base, n): cls.listCount -= n return GL.glDeleteLists(base, n) class DisplayList(object): allLists = [] def __init__(self, drawFunc=None): self.drawFunc = drawFunc self._list = None def _delete(r): DisplayList.allLists.remove(r) self.allLists.append(weakref.ref(self, _delete)) def __del__(self): self.invalidate() @classmethod def invalidateAllLists(cls): allLists = [] for listref in cls.allLists: list = listref() if list: list.invalidate() allLists.append(listref) cls.allLists = allLists def invalidate(self): if self._list: gl.glDeleteLists(self._list[0], 1) self._list = None def makeList(self, drawFunc): if self._list: return drawFunc = (drawFunc or self.drawFunc) if drawFunc is None: return l = gl.glGenLists(1) GL.glNewList(l, GL.GL_COMPILE) drawFunc() # try: GL.glEndList() #except GL.GLError: # print "Error while compiling display list. Retrying display list code to pinpoint error" # self.drawFunc() self._list = numpy.array([l], 'uintc') def getList(self, drawFunc=None): self.makeList(drawFunc) return self._list if "-debuglists" in sys.argv: def call(self, drawFunc=None): drawFunc = (drawFunc or self.drawFunc) if drawFunc is None: return drawFunc() else: def call(self, drawFunc=None): self.makeList(drawFunc) GL.glCallLists(self._list) class Texture(object): allTextures = [] defaultFilter = GL.GL_NEAREST def __init__(self, textureFunc=None, minFilter=None, magFilter=None): minFilter = minFilter or self.defaultFilter magFilter = magFilter or self.defaultFilter if textureFunc is None: textureFunc = lambda: None self.textureFunc = textureFunc self._texID = GL.glGenTextures(1) def _delete(r): Texture.allTextures.remove(r) self.allTextures.append(weakref.ref(self, _delete)) self.bind() GL.glTexParameter(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, minFilter) GL.glTexParameter(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, magFilter) self.textureFunc() def __del__(self): self.delete() def delete(self): if self._texID is not None: GL.glDeleteTextures(self._texID) def bind(self): GL.glBindTexture(GL.GL_TEXTURE_2D, self._texID) def invalidate(self): self.dirty = True class FramebufferTexture(Texture): def __init__(self, width, height, drawFunc): tex = GL.glGenTextures(1) GL.glBindTexture(GL.GL_TEXTURE_2D, tex) GL.glTexParameter(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST) GL.glTexParameter(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST) GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA8, width, height, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, None) self.enabled = False self._texID = tex if bool(FBO.glGenFramebuffers) and "Intel" not in GL.glGetString(GL.GL_VENDOR): buf = FBO.glGenFramebuffers(1) depthbuffer = FBO.glGenRenderbuffers(1) FBO.glBindFramebuffer(FBO.GL_FRAMEBUFFER, buf) FBO.glBindRenderbuffer(FBO.GL_RENDERBUFFER, depthbuffer) FBO.glRenderbufferStorage(FBO.GL_RENDERBUFFER, GL.GL_DEPTH_COMPONENT, width, height) FBO.glFramebufferRenderbuffer(FBO.GL_FRAMEBUFFER, FBO.GL_DEPTH_ATTACHMENT, FBO.GL_RENDERBUFFER, depthbuffer) FBO.glFramebufferTexture2D(FBO.GL_FRAMEBUFFER, FBO.GL_COLOR_ATTACHMENT0, GL.GL_TEXTURE_2D, tex, 0) status = FBO.glCheckFramebufferStatus(FBO.GL_FRAMEBUFFER) if status != FBO.GL_FRAMEBUFFER_COMPLETE: print "glCheckFramebufferStatus", status self.enabled = False return FBO.glBindFramebuffer(FBO.GL_FRAMEBUFFER, buf) with gl.glPushAttrib(GL.GL_VIEWPORT_BIT): GL.glViewport(0, 0, width, height) drawFunc() FBO.glBindFramebuffer(FBO.GL_FRAMEBUFFER, 0) FBO.glDeleteFramebuffers(1, [buf]) FBO.glDeleteRenderbuffers(1, [depthbuffer]) self.enabled = True else: GL.glReadBuffer(GL.GL_BACK) GL.glPushAttrib( GL.GL_VIEWPORT_BIT | GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT | GL.GL_STENCIL_TEST | GL.GL_STENCIL_BUFFER_BIT) GL.glDisable(GL.GL_STENCIL_TEST) GL.glViewport(0, 0, width, height) GL.glScissor(0, 0, width, height) with gl.glEnable(GL.GL_SCISSOR_TEST): drawFunc() GL.glBindTexture(GL.GL_TEXTURE_2D, tex) GL.glReadBuffer(GL.GL_BACK) GL.glCopyTexSubImage2D(GL.GL_TEXTURE_2D, 0, 0, 0, 0, 0, width, height) GL.glPopAttrib() def debugDrawPoint(point): GL.glColor(1.0, 1.0, 0.0, 1.0) GL.glPointSize(9.0) with gl.glBegin(GL.GL_POINTS): GL.glVertex3f(*point)
7,742
28.218868
133
py
MCEdit-Unified
MCEdit-Unified-master/mce.py
# !/usr/bin/env python import pymclevel.mclevelbase import pymclevel.mclevel import pymclevel.materials import pymclevel.infiniteworld import sys import os from pymclevel.box import BoundingBox, Vector import numpy from numpy import zeros, bincount import logging import itertools import traceback import shlex import operator import codecs from math import floor mclevelbase = pymclevel.mclevelbase mclevel = pymclevel.mclevel materials = pymclevel.materials infiniteworld = pymclevel.infiniteworld try: import readline # if available, used by raw_input() except: pass class UsageError(RuntimeError): pass class BlockMatchError(RuntimeError): pass class PlayerNotFound(RuntimeError): pass class mce(object): """ Block commands: {commandPrefix}clone <sourceBox> <destPoint> [noair] [nowater] {commandPrefix}fill <blockType> [ <box> ] {commandPrefix}replace <blockType> [with] <newBlockType> [ <box> ] {commandPrefix}export <filename> <sourceBox> {commandPrefix}import <filename> <destPoint> [noair] [nowater] {commandPrefix}createChest <point> <item> [ <count> ] {commandPrefix}analyze Player commands: {commandPrefix}player [ <player> [ <point> ] ] {commandPrefix}spawn [ <point> ] Entity commands: {commandPrefix}removeEntities [ <EntityID> ] {commandPrefix}dumpSigns [ <filename> ] {commandPrefix}dumpChests [ <filename> ] Chunk commands: {commandPrefix}createChunks <box> {commandPrefix}deleteChunks <box> {commandPrefix}prune <box> {commandPrefix}relight [ <box> ] World commands: {commandPrefix}create <filename> {commandPrefix}dimension [ <dim> ] {commandPrefix}degrief {commandPrefix}time [ <time> ] {commandPrefix}worldsize {commandPrefix}heightmap <filename> {commandPrefix}randomseed [ <seed> ] {commandPrefix}gametype [ <player> [ <gametype> ] ] Editor commands: {commandPrefix}save {commandPrefix}reload {commandPrefix}load <filename> | <world number> {commandPrefix}execute <filename> {commandPrefix}quit Informational: {commandPrefix}blocks [ <block name> | <block ID> ] {commandPrefix}help [ <command> ] **IMPORTANT** {commandPrefix}box Type 'box' to learn how to specify points and areas. """ random_seed = os.getenv('MCE_RANDOM_SEED', None) 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) return func.__doc__ commands = [ "clone", "fill", "replace", "export", "execute", "import", "createchest", "player", "spawn", "removeentities", "dumpsigns", "dumpchests", "createchunks", "deletechunks", "prune", "relight", "create", "degrief", "time", "worldsize", "heightmap", "randomseed", "gametype", "save", "load", "reload", "dimension", "repair", "quit", "exit", "help", "blocks", "analyze", "region", "debug", "log", "box", ] debug = False needsSave = False @staticmethod def readInt(command): try: val = int(command.pop(0)) except ValueError: raise UsageError("Cannot understand numeric input") return val @staticmethod def prettySplit(command): cmdstring = " ".join(command) lex = shlex.shlex(cmdstring) lex.whitespace_split = True lex.whitespace += "()," command[:] = list(lex) def readBox(self, command): self.prettySplit(command) sourcePoint = self.readIntPoint(command) if command[0].lower() == "to": command.pop(0) sourcePoint2 = self.readIntPoint(command) sourceSize = sourcePoint2 - sourcePoint else: 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): point = self.readPoint(command, isPoint) point = map(int, map(floor, point)) return Vector(*point) 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) if len(command) and command[0].lower() == "delta": command.pop(0) try: x += int(command.pop(0)) y += int(command.pop(0)) z += int(command.pop(0)) except ValueError: raise UsageError("Error decoding point input (expected a number).") return x, y, z except IndexError: raise UsageError("Error decoding point input (expected more values).") try: try: x = float(word) except ValueError: if isPoint: raise PlayerNotFound(word) raise y = float(command.pop(0)) z = float(command.pop(0)) except ValueError: raise UsageError("Error decoding point input (expected a number).") except IndexError: raise UsageError("Error decoding point input (expected more values).") return x, y, z def readBlockInfo(self, command): keyword = command.pop(0) matches = self.level.materials.blocksMatching(keyword) blockInfo = None if len(matches): if len(matches) == 1: blockInfo = matches[0] # eat up more words that possibly specify a block. stop eating when 0 matching blocks. while len(command): newMatches = self.level.materials.blocksMatching(keyword + " " + command[0]) if len(newMatches) == 1: blockInfo = newMatches[0] if len(newMatches) > 0: matches = newMatches keyword = keyword + " " + command.pop(0) else: break else: try: data = 0 if ":" in keyword: blockID, data = map(int, keyword.split(":")) else: blockID = int(keyword) blockInfo = self.level.materials.blockWithID(blockID, data) except ValueError: blockInfo = None if blockInfo is None: print "Ambiguous block specifier: ", keyword if len(matches): print "Matches: " for m in matches: if m == self.level.materials.defaultName: continue print "{0:3}:{1:<2} : {2}".format(m.ID, m.blockData, m.name) else: print "No blocks matched." raise BlockMatchError return blockInfo @staticmethod def readBlocksToCopy(command): blocksToCopy = range(materials.id_limit) while len(command): word = command.pop() if word == "noair": blocksToCopy.remove(0) if word == "nowater": blocksToCopy.remove(8) blocksToCopy.remove(9) return blocksToCopy @staticmethod def _box(command): """ Boxes: Many commands require a <box> as arguments. A box can be specified with a point and a size: (12, 5, 15), (5, 5, 5) or with two points, making sure to put the keyword "to" between them: (12, 5, 15) to (17, 10, 20) The commas and parentheses are not important. You may add them for improved readability. Points: Points and sizes are triplets of numbers ordered X Y Z. X is position north-south, increasing southward. Y is position up-down, increasing upward. Z is position east-west, increasing westward. Players: A player's name can be used as a point - it will use the position of the player's head. Use the keyword 'delta' after the name to specify a point near the player. Example: codewarrior delta 0 5 0 This refers to a point 5 blocks above codewarrior's head. """ raise UsageError def _debug(self, command): self.debug = not self.debug print "Debug", ("disabled", "enabled")[self.debug] @staticmethod def _log(command): """ log [ <number> ] Get or set the log threshold. 0 logs everything; 50 only logs major errors. """ if len(command): try: logging.getLogger().level = int(command[0]) except ValueError: raise UsageError("Cannot understand numeric input.") else: print "Log level: {0}".format(logging.getLogger().level) def _clone(self, command): """ clone <sourceBox> <destPoint> [noair] [nowater] Clone blocks in a cuboid starting at sourcePoint and extending for sourceSize blocks in each direction. Blocks and entities in the area are cloned at destPoint. """ if len(command) == 0: self.printUsage("clone") return box = self.readBox(command) destPoint = self.readPoint(command) destPoint = map(int, map(floor, destPoint)) blocksToCopy = self.readBlocksToCopy(command) tempSchematic = self.level.extractSchematic(box) self.level.copyBlocksFrom(tempSchematic, BoundingBox((0, 0, 0), box.origin), destPoint, blocksToCopy) self.needsSave = True print "Cloned 0 blocks." def _fill(self, command): """ fill <blockType> [ <box> ] Fill blocks with blockType in a cuboid starting at point and extending for size blocks in each direction. Without a destination, fills the whole world. blockType and may be a number from 0-255 or a name listed by the 'blocks' command. """ if len(command) == 0: self.printUsage("fill") return blockInfo = self.readBlockInfo(command) if len(command): box = self.readBox(command) else: box = None print "Filling with {0}".format(blockInfo.name) self.level.fillBlocks(box, blockInfo) self.needsSave = True print "Filled {0} blocks.".format("all" if box is None else box.volume) def _replace(self, command): """ replace <blockType> [with] <newBlockType> [ <box> ] Replace all blockType blocks with newBlockType in a cuboid starting at point and extending for size blocks in each direction. Without a destination, replaces blocks over the whole world. blockType and newBlockType may be numbers from 0-255 or names listed by the 'blocks' command. """ if len(command) == 0: self.printUsage("replace") return blockInfo = self.readBlockInfo(command) if command[0].lower() == "with": command.pop(0) newBlockInfo = self.readBlockInfo(command) if len(command): box = self.readBox(command) else: box = None print "Replacing {0} with {1}".format(blockInfo.name, newBlockInfo.name) self.level.fillBlocks(box, newBlockInfo, blocksToReplace=[blockInfo]) self.needsSave = True print "Done." def _createchest(self, command): """ createChest <point> <item> [ <count> ] Create a chest filled with the specified item. Stacks are 64 if count is not given. """ point = map(lambda x: int(floor(float(x))), self.readPoint(command)) itemID = self.readInt(command) count = 64 if len(command): count = self.readInt(command) chest = mclevel.MCSchematic.chestWithItemID(itemID, count) self.level.copyBlocksFrom(chest, chest.bounds, point) self.needsSave = True def _analyze(self, command): """ analyze Counts all of the block types in every chunk of the world. """ blockCounts = zeros((65536,), 'uint64') print "Analyzing {0} chunks...".format(self.level.chunkCount) # for input to bincount, create an array of uint16s by # shifting the data left and adding the blocks for i, cPos in enumerate(self.level.allChunks, 1): ch = self.level.getChunk(*cPos) btypes = numpy.array(ch.Data.ravel(), dtype='uint16') btypes <<= 12 btypes += ch.Blocks.ravel() counts = bincount(btypes) blockCounts[:counts.shape[0]] += counts if i % 100 == 0: logging.info("Chunk {0}...".format(i)) for blockID in range(materials.id_limit): for data in range(16): i = (data << 12) + blockID if blockCounts[i]: idstring = "({id}:{data})".format(id=blockID, data=data) print "{idstring:9} {name:30}: {count:<10}".format( idstring=idstring, name=self.level.materials.blockWithID(blockID, data).name, count=blockCounts[i]) self.needsSave = True def _export(self, command): """ export <filename> <sourceBox> Exports blocks in the specified region to a file in schematic format. This file can be imported with mce or MCEdit. """ if len(command) == 0: self.printUsage("export") return filename = command.pop(0) box = self.readBox(command) tempSchematic = self.level.extractSchematic(box) tempSchematic.saveToFile(filename) print "Exported {0} blocks.".format(tempSchematic.bounds.volume) def _import(self, command): """ import <filename> <destPoint> [noair] [nowater] Imports a level or schematic into this world, beginning at destPoint. Supported formats include - Alpha single or multiplayer world folder containing level.dat, - Zipfile containing Alpha world folder, - Classic single-player .mine, - Classic multiplayer server_level.dat, - Indev .mclevel - Schematic from RedstoneSim, MCEdit, mce - .inv from INVEdit (appears as a chest) """ if len(command) == 0: self.printUsage("import") return filename = command.pop(0) destPoint = self.readPoint(command) blocksToCopy = self.readBlocksToCopy(command) importLevel = mclevel.fromFile(filename) self.level.copyBlocksFrom(importLevel, importLevel.bounds, destPoint, blocksToCopy, create=True) self.needsSave = True print "Imported {0} blocks.".format(importLevel.bounds.volume) def _player(self, command): """ player [ <player> [ <point> ] ] Move the named player to the specified point. Without a point, prints the named player's position. Without a player, prints all players and positions. In a single-player world, the player is named Player. """ if len(command) == 0: print "Players: " for player in self.level.players: print " {0}: {1}".format(player, self.level.getPlayerPosition(player)) return player = command.pop(0) if len(command) == 0: print "Player {0}: {1}".format(player, self.level.getPlayerPosition(player)) return point = self.readPoint(command) self.level.setPlayerPosition(point, player) self.needsSave = True print "Moved player {0} to {1}".format(player, point) def _spawn(self, command): """ spawn [ <point> ] Move the world's spawn point. Without a point, prints the world's spawn point. """ if len(command): point = self.readPoint(command) point = map(int, map(floor, point)) self.level.setPlayerSpawnPosition(point) self.needsSave = True print "Moved spawn point to ", point else: print "Spawn point: ", self.level.playerSpawnPosition() def _dumpsigns(self, command): """ dumpSigns [ <filename> ] Saves the text and location of every sign in the world to a text file. With no filename, saves signs to <worldname>.signs Output is newline-delimited. 5 lines per sign. Coordinates are on the first line, followed by four lines of sign text. For example: [229, 118, -15] "To boldly go where no man has gone before." Coordinates are ordered the same as point inputs: [North/South, Down/Up, East/West] """ if len(command): filename = command[0] else: filename = self.level.displayName + ".signs" # We happen to encode the output file in UTF-8 too, although # we could use another UTF encoding. The '-sig' encoding puts # a signature at the start of the output file that tools such # as Microsoft Windows Notepad and Emacs understand to mean # the file has UTF-8 encoding. outFile = codecs.open(filename, "w", encoding='utf-8-sig') print "Dumping signs..." signCount = 0 for i, cPos in enumerate(self.level.allChunks): try: chunk = self.level.getChunk(*cPos) except mclevelbase.ChunkMalformed: continue for tileEntity in chunk.TileEntities: if tileEntity["id"].value == "Sign": signCount += 1 outFile.write(str(map(lambda x: tileEntity[x].value, "xyz")) + "\n") for i in range(4): signText = tileEntity["Text{0}".format(i + 1)].value outFile.write(signText + u"\n") if i % 100 == 0: print "Chunk {0}...".format(i) print "Dumped {0} signs to {1}".format(signCount, filename) outFile.close() def _region(self, command): """ region [rx rz] List region files in this world. """ level = self.level assert (isinstance(level, mclevel.MCInfdevOldLevel)) assert level.version def getFreeSectors(rf): runs = [] start = None count = 0 for i, free in enumerate(rf.freeSectors): if free: if start is None: start = i count = 1 else: count += 1 else: if start is None: pass else: runs.append((start, count)) start = None count = 0 return runs def printFreeSectors(runs): for i, (start, count) in enumerate(runs): if i % 4 == 3: print "" print "{start:>6}+{count:<4}".format(**locals()), print "" if len(command): if len(command) > 1: rx, rz = map(int, command[:2]) print "Calling allChunks to preload region files: %d chunks" % len(level.allChunks) rf = level.regionFiles.get((rx, rz)) if rf is None: print "Region {rx},{rz} not found.".format(**locals()) return print "Region {rx:6}, {rz:6}: {used}/{sectors} sectors".format(used=rf.usedSectors, sectors=rf.sectorCount) print "Offset Table:" for cx in range(32): for cz in range(32): if cz % 4 == 0: print "" print "{0:3}, {1:3}: ".format(cx, cz), off = rf.getOffset(cx, cz) sector, length = off >> 8, off & 0xff print "{sector:>6}+{length:<2} ".format(**locals()), print "" runs = getFreeSectors(rf) if len(runs): print "Free sectors:", printFreeSectors(runs) else: if command[0] == "free": print "Calling allChunks to preload region files: %d chunks" % len(level.allChunks) for (rx, rz), rf in level.regionFiles.iteritems(): runs = getFreeSectors(rf) if len(runs): print "R {0:3}, {1:3}:".format(rx, rz), printFreeSectors(runs) else: print "Calling allChunks to preload region files: %d chunks" % len(level.allChunks) coords = (r for r in level.regionFiles) for i, (rx, rz) in enumerate(coords): print "({rx:6}, {rz:6}): {count}, ".format(count=level.regionFiles[rx, rz].chunkCount), if i % 5 == 4: print "" def _repair(self, command): """ repair Attempt to repair inconsistent region files. MAKE A BACKUP. WILL DELETE YOUR DATA. Scans for and repairs errors in region files: Deletes chunks whose sectors overlap with another chunk Rearranges chunks that are in the wrong slot in the offset table Deletes completely unreadable chunks Only usable with region-format saves. """ if self.level.version: self.level.preloadRegions() for rf in self.level.regionFiles.itervalues(): rf.repair() def _dumpchests(self, command): """ dumpChests [ <filename> ] Saves the content and location of every chest in the world to a text file. With no filename, saves signs to <worldname>.chests Output is delimited by brackets and newlines. A set of coordinates in brackets begins a chest, followed by a line for each inventory slot. For example: [222, 51, 22] 2 String 3 String 3 Iron bar Coordinates are ordered the same as point inputs: [North/South, Down/Up, East/West] """ from pymclevel.items import items if len(command): filename = command[0] else: filename = self.level.displayName + ".chests" outFile = file(filename, "w") print "Dumping chests..." chestCount = 0 for i, cPos in enumerate(self.level.allChunks): try: chunk = self.level.getChunk(*cPos) except mclevelbase.ChunkMalformed: continue for tileEntity in chunk.TileEntities: if tileEntity["id"].value == "Chest": chestCount += 1 outFile.write(str(map(lambda x: tileEntity[x].value, "xyz")) + "\n") itemsTag = tileEntity["Items"] if len(itemsTag): for itemTag in itemsTag: try: id = itemTag["id"].value damage = itemTag["Damage"].value item = items.findItem(id, damage) itemname = item.name except KeyError: itemname = "Unknown Item {0}".format(itemTag) except Exception, e: itemname = repr(e) outFile.write("{0} {1}:{2}\n".format(itemTag["Count"].value, itemname, itemTag["Damage"].value)) else: outFile.write("Empty Chest\n") if i % 100 == 0: print "Chunk {0}...".format(i) print "Dumped {0} chests to {1}".format(chestCount, filename) outFile.close() def _removeentities(self, command): """ removeEntities [ [except] [ <EntityID> [ <EntityID> ... ] ] ] Remove all entities matching one or more entity IDs. With the except keyword, removes all entities not matching one or more entity IDs. Without any IDs, removes all entities in the world, except for Paintings. Known Mob Entity IDs: Mob Monster Creeper Skeleton Spider Giant Zombie Slime Pig Sheep Cow Chicken Known Item Entity IDs: Item Arrow Snowball Painting Known Vehicle Entity IDs: Minecart Boat Known Dynamic Tile Entity IDs: PrimedTnt FallingSand """ ENT_MATCHTYPE_ANY = 0 ENT_MATCHTYPE_EXCEPT = 1 ENT_MATCHTYPE_NONPAINTING = 2 def match(entityID, matchType, matchWords): if ENT_MATCHTYPE_ANY == matchType: return entityID.lower() in matchWords elif ENT_MATCHTYPE_EXCEPT == matchType: return not (entityID.lower() in matchWords) else: # ENT_MATCHTYPE_EXCEPT == matchType return entityID != "Painting" removedEntities = {} match_words = [] if len(command): if command[0].lower() == "except": command.pop(0) print "Removing all entities except ", command match_type = ENT_MATCHTYPE_EXCEPT else: print "Removing {0}...".format(", ".join(command)) match_type = ENT_MATCHTYPE_ANY match_words = map(lambda x: x.lower(), command) else: print "Removing all entities except Painting..." match_type = ENT_MATCHTYPE_NONPAINTING for cx, cz in self.level.allChunks: chunk = self.level.getChunk(cx, cz) entitiesRemoved = 0 for entity in list(chunk.Entities): entityID = entity["id"].value if match(entityID, match_type, match_words): removedEntities[entityID] = removedEntities.get(entityID, 0) + 1 chunk.Entities.remove(entity) entitiesRemoved += 1 if entitiesRemoved: chunk.chunkChanged(False) if len(removedEntities) == 0: print "No entities to remove." else: print "Removed entities:" for entityID in sorted(removedEntities.keys()): print " {0}: {1:6}".format(entityID, removedEntities[entityID]) self.needsSave = True def _createchunks(self, command): """ createChunks <box> Creates any chunks not present in the specified region. New chunks are filled with only air. New chunks are written to disk immediately. """ if len(command) == 0: self.printUsage("createchunks") return box = self.readBox(command) chunksCreated = self.level.createChunksInBox(box) print "Created {0} chunks.".format(len(chunksCreated)) self.needsSave = True def _deletechunks(self, command): """ deleteChunks <box> Removes all chunks contained in the specified region. Chunks are deleted from disk immediately. """ if len(command) == 0: self.printUsage("deletechunks") return box = self.readBox(command) deletedChunks = self.level.deleteChunksInBox(box) print "Deleted {0} chunks.".format(len(deletedChunks)) def _prune(self, command): """ prune <box> Removes all chunks not contained in the specified region. Useful for enforcing a finite map size. Chunks are deleted from disk immediately. """ if len(command) == 0: self.printUsage("prune") return box = self.readBox(command) 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 print "Pruned {0} chunks.".format(i) def _relight(self, command): """ relight [ <box> ] Recalculates lights in the region specified. If omitted, recalculates the entire world. """ if len(command): box = self.readBox(command) chunks = itertools.product(range(box.mincx, box.maxcx), range(box.mincz, box.maxcz)) else: chunks = self.level.allChunks self.level.generateLights(chunks) print "Relit 0 chunks." self.needsSave = True def _create(self, command): """ create [ <filename> ] Create and load a new Minecraft Alpha world. This world will have no chunks and a random terrain seed. If run from the shell, filename is not needed because you already specified a filename earlier in the command. For example: mce.py MyWorld create """ if len(command) < 1: raise UsageError("Expected a filename") filename = command[0] if not os.path.exists(filename): os.mkdir(filename) if not os.path.isdir(filename): raise IOError("{0} already exists".format(filename)) if mclevel.MCInfdevOldLevel.isLevel(filename): raise IOError("{0} is already a Minecraft Alpha world".format(filename)) level = mclevel.MCInfdevOldLevel(filename, create=True) self.level = level def _degrief(self, command): """ degrief [ <height> ] Reverse a few forms of griefing by removing Adminium, Obsidian, Fire, and Lava wherever they occur above the specified height. Without a height, uses height level 32. Removes natural surface lava. Also see removeEntities """ box = self.level.bounds box = BoundingBox(box.origin + (0, 32, 0), box.size - (0, 32, 0)) if len(command): try: box.miny = int(command[0]) except ValueError: pass print "Removing grief matter and surface lava above height {0}...".format(box.miny) self.level.fillBlocks(box, self.level.materials.Air, blocksToReplace=[self.level.materials.Bedrock, self.level.materials.Obsidian, self.level.materials.Fire, self.level.materials.LavaActive, self.level.materials.Lava, ] ) self.needsSave = True def _time(self, command): """ time [time of day] Set or display the time of day. Acceptable values are "morning", "noon", "evening", "midnight", or a time of day such as 8:02, 12:30 PM, or 16:45. """ ticks = self.level.Time timeOfDay = ticks % 24000 ageInTicks = ticks - timeOfDay if len(command) == 0: days = ageInTicks / 24000 hours = timeOfDay / 1000 clockHours = (hours + 6) % 24 ampm = ("AM", "PM")[clockHours > 11] minutes = (timeOfDay % 1000) / 60 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] minutes = 0 if word in times: hours = times[word] else: try: if ":" in word: h, m = word.split(":") hours = int(h) minutes = int(m) else: hours = int(word) except Exception, e: raise UsageError(("Cannot interpret time, ", e)) if len(command) > 1: if command[1].lower() == "pm": hours += 12 ticks = ageInTicks + hours * 1000 + minutes * 1000 / 60 - 6000 if ticks < 0: ticks += 18000 ampm = ("AM", "PM")[11 < hours < 24] print "Changed time to {0}:{1:02} {2}".format(hours % 12 or 12, minutes, ampm) self.level.Time = ticks self.needsSave = True def _randomseed(self, command): """ randomseed [ <seed> ] Set or display the world's random seed, a 64-bit integer that uniquely defines the world's terrain. """ if len(command): try: seed = long(command[0]) except ValueError: raise UsageError("Expected a long integer.") self.level.RandomSeed = seed self.needsSave = True else: print "Random Seed: ", self.level.RandomSeed def _gametype(self, command): """ gametype [ <player> [ <gametype> ] ] Set or display the player's game type, an integer that identifies whether their game is survival (0) or creative (1). On single-player worlds, the player is just 'Player'. """ if len(command) == 0: print "Players: " for player in self.level.players: print " {0}: {1}".format(player, self.level.getPlayerGameType(player)) return player = command.pop(0) if len(command) == 0: print "Player {0}: {1}".format(player, self.level.getPlayerGameType(player)) return try: gametype = int(command[0]) except ValueError: raise UsageError("Expected an integer.") self.level.setPlayerGameType(gametype, player) self.needsSave = True def _worldsize(self, command): """ worldsize Computes and prints the dimensions of the world. For infinite worlds, also prints the most negative corner. """ bounds = self.level.bounds if isinstance(self.level, mclevel.MCInfdevOldLevel): print "\nWorld size: \n {0[0]:7} north to south\n {0[2]:7} east to west\n".format(bounds.size) print "Smallest and largest points: ({0[0]},{0[2]}), ({1[0]},{1[2]})".format(bounds.origin, bounds.maximum) 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): """ heightmap <filename> Takes a png and imports it as the terrain starting at chunk 0,0. Data is internally converted to greyscale and scaled to the maximum height. The game will fill the terrain with trees and mineral deposits the next time you play the level. Please please please try out a small test image before using a big source. Using the levels tool to get a good heightmap is an art, not a science. A smaller map lets you experiment and get it right before having to blow all night generating the really big map. Requires the PIL library. """ if len(command) == 0: self.printUsage("heightmap") return if not sys.stdin.isatty() or raw_input( "This will destroy a large portion of the map and may take a long time. Did you really want to do this?" ).lower() in ("yes", "y", "1", "true"): from PIL import Image import datetime filename = command.pop(0) imgobj = Image.open(filename) greyimg = imgobj.convert("L") # luminance del imgobj width, height = greyimg.size water_level = 64 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) except: pass c = self.level.getChunk(cx, cz) imgarray = numpy.asarray(greyimg.crop((cz * 16, cx * 16, cz * 16 + 16, cx * 16 + 16))) 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: # world dimension X goes north-south # first array axis goes up-down 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 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, 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("Done with mapping!") self.needsSave = True stop = datetime.datetime.now() 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))) def _execute(self, command): """ execute <filename> Execute all commands in a file and save. """ if len(command) == 0: print "You must give the file with commands to execute" else: commandFile = open(command[0], "r") commandsFromFile = commandFile.readlines() for commandFromFile in commandsFromFile: print commandFromFile self.processCommand(commandFromFile) self._save("") def _quit(self, command): """ quit [ yes | no ] Quits the program. Without 'yes' or 'no', prompts to save before quitting. In batch mode, an end of file automatically saves the level. """ if len(command) == 0 or not (command[0].lower() in ("yes", "no")): if raw_input("Save before exit? ").lower() in ("yes", "y", "1", "true"): self._save(command) raise SystemExit if len(command) and command[0].lower == "yes": self._save(command) raise SystemExit def _exit(self, command): self._quit(command) def _save(self, command): if self.needsSave: self.level.generateLights() self.level.saveInPlace() self.needsSave = False def _load(self, command): """ load [ <filename> | <world number> ] Loads another world, discarding all changes to this world. """ if len(command) == 0: self.printUsage("load") self.loadWorld(command[0]) def _reload(self, command): self.level = mclevel.fromFile(self.level.filename) def _dimension(self, command): """ dimension [ <dim> ] Load another dimension, a sub-world of this level. Without options, lists all of the dimensions found in this world. <dim> can be a number or one of these keywords: nether, hell, slip: DIM-1 earth, overworld, parent: parent world end: DIM1 """ if len(command): if command[0].lower() in ("earth", "overworld", "parent"): if self.level.parentWorld: self.level = self.level.parentWorld return else: print "You are already on earth." return elif command[0].lower() in ("hell", "nether", "slip"): dimNo = -1 elif command[0].lower() == "end": dimNo = 1 else: dimNo = self.readInt(command) if dimNo in self.level.dimensions: self.level = self.level.dimensions[dimNo] return if self.level.parentWorld: print u"Parent world: {0} ('dimension parent' to return)".format(self.level.parentWorld.displayName) if len(self.level.dimensions): print u"Dimensions in {0}:".format(self.level.displayName) for k in self.level.dimensions: print "{0}: {1}".format(k, infiniteworld.MCAlphaDimension.dimensionNames.get(k, "Unknown")) def _help(self, command): if len(command): self.printUsage(command[0]) else: self.printUsage() def _blocks(self, command): """ blocks [ <block name> | <block ID> ] Prints block IDs matching the name, or the name matching the ID. With nothing, prints a list of all blocks. """ if len(command): searchName = " ".join(command) try: searchNumber = int(searchName) except ValueError: matches = self.level.materials.blocksMatching(searchName) else: matches = [b for b in self.level.materials.allBlocks if b.ID == searchNumber] # print "{0:3}: {1}".format(searchNumber, self.level.materials.names[searchNumber]) # return else: matches = self.level.materials.allBlocks print "{id:9} : {name} {aka}".format(id="(ID:data)", name="Block name", aka="[Other names]") for b in sorted(matches): idstring = "({ID}:{data})".format(ID=b.ID, data=b.blockData) aka = b.aka and " [{aka}]".format(aka=b.aka) or "" print "{idstring:9} : {name} {aka}".format(idstring=idstring, name=b.name, aka=aka) 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]) def printUsageAndQuit(self): self.printUsage() raise SystemExit def loadWorld(self, world): worldpath = os.path.expanduser(world) if os.path.exists(worldpath): self.level = mclevel.fromFile(worldpath) else: self.level = mclevel.loadWorld(world) level = None batchMode = False def run(self): logging.basicConfig(format=u'%(levelname)s:%(message)s') logging.getLogger().level = logging.INFO sys.argv.pop(0) if len(sys.argv): world = sys.argv.pop(0) if world.lower() in ("-h", "--help"): self.printUsageAndQuit() if len(sys.argv) and sys.argv[0].lower() == "create": # accept the syntax, "mce world3 create" self._create([world]) print "Created world {0}".format(world) sys.exit(0) else: self.loadWorld(world) else: self.batchMode = True self.printUsage() while True: try: world = raw_input("Please enter world name or path to world folder: ") self.loadWorld(world) except EOFError: print "End of input." raise SystemExit except Exception, e: print "Cannot open {0}: {1}".format(world, e) else: break if len(sys.argv): # process one command from command line try: self.processCommand(" ".join(sys.argv)) except UsageError: self.printUsageAndQuit() self._save([]) else: # process many commands on standard input, maybe interactively self.batchMode = True while True: try: command = raw_input(u"{0}> ".format(self.level.displayName)) print self.processCommand(command) except EOFError: print "End of file. Saving automatically." self._save([]) raise SystemExit except Exception, e: if self.debug: traceback.print_exc() print 'Exception during command: {0!r}'.format(e) print "Use 'debug' to enable tracebacks." # self.printUsage() def processCommand(self, command): command = command.strip() if len(command) == 0: return if command[0] == "#": return commandWords = command.split() keyword = commandWords.pop(0).lower() if keyword not in self.commands: matches = filter(lambda x: x.startswith(keyword), self.commands) if len(matches) == 1: keyword = matches[0] elif len(matches): print "Ambiguous command. Matches: " for k in matches: print " ", k return else: raise UsageError("Command {0} not recognized.".format(keyword)) func = getattr(self, "_" + keyword) try: func(commandWords) except PlayerNotFound, e: print "Cannot find player {0}".format(e.args[0]) self._player([]) except UsageError, e: print e if self.debug: traceback.print_exc() self.printUsage(keyword) def main(argv): profile = os.getenv("MCE_PROFILE", None) editor = mce() if profile: print "Profiling enabled" import cProfile cProfile.runctx('editor.run()', locals(), globals(), profile) else: editor.run() return 0 if __name__ == '__main__': sys.exit(main(sys.argv))
47,382
30.60974
124
py
MCEdit-Unified
MCEdit-Unified-master/frustum.py
"""View frustum modeling as series of clipping planes The Frustum object itself is only responsible for extracting the clipping planes from an OpenGL model-view matrix. The bulk of the frustum-culling algorithm is implemented in the bounding volume objects found in the OpenGLContext.scenegraph.boundingvolume module. Based on code from: http://www.markmorley.com/opengl/frustumculling.html """ import logging import numpy from OpenGL import GL context_log = logging.getLogger() def viewingMatrix(projection=None, model=None): """Calculate the total viewing matrix from given data projection -- the projection matrix, if not provided than the result of glGetDoublev( GL_PROJECTION_MATRIX) will be used. model -- the model-view matrix, if not provided than the result of glGetDoublev( GL_MODELVIEW_MATRIX ) will be used. Note: Unless there is a valid projection and model-view matrix, the function will raise a RuntimeError """ if projection is None: projection = GL.glGetDoublev(GL.GL_PROJECTION_MATRIX) if model is None: model = GL.glGetDoublev(GL.GL_MODELVIEW_MATRIX) # hmm, this will likely fail on 64-bit platforms :( if projection is None or model is None: context_log.warn( """A NULL matrix was returned from glGetDoublev: proj=%s modelView=%s""", projection, model, ) if projection: return projection if model: return model else: return numpy.identity(4, 'd') if numpy.allclose(projection, -1.79769313e+308): context_log.warn( """Attempt to retrieve projection matrix when uninitialised %s, model=%s""", projection, model, ) return model if numpy.allclose(model, -1.79769313e+308): context_log.warn( """Attempt to retrieve model-view matrix when uninitialised %s, projection=%s""", model, projection, ) return projection return numpy.dot(model, projection) class Frustum(object): """Holder for frustum specification for intersection tests Note: the Frustum can include an arbitrary number of clipping planes, though the most common usage is to define 6 clipping planes from the OpenGL model-view matrices. """ def visible(self, points, radius): """Determine whether this sphere is visible in frustum frustum -- Frustum object holding the clipping planes for the view matrix -- a matrix which transforms the local coordinates to the (world-space) coordinate system in which the frustum is defined. This version of the method uses a pure-python loop to do the actual culling once the points are multiplied by the matrix. (i.e. it does not use the frustcullaccel C extension module) """ distances = numpy.sum(self.planes[numpy.newaxis, :, :] * points[:, numpy.newaxis, :], -1) return ~numpy.any(distances < -radius, -1) def visible1(self, point, radius): # return self.visible(array(point[numpy.newaxis, :]), radius) distance = numpy.sum(self.planes * point, -1) vis = ~numpy.any(distance < -radius, -1) #assert vis == self.visible(array(point)[numpy.newaxis, :], radius) return vis @classmethod def fromViewingMatrix(cls, matrix=None, normalize=1): """Extract and calculate frustum clipping planes from OpenGL The default initializer allows you to create Frustum objects with arbitrary clipping planes, while this alternate initializer provides automatic clipping-plane extraction from the model-view matrix. matrix -- the combined model-view matrix normalize -- whether to normalize the plane equations to allow for sphere bounding-volumes and use of distance equations for LOD-style operations. """ if matrix is None: matrix = viewingMatrix() clip = numpy.ravel(matrix) frustum = numpy.zeros((6, 4), 'd') # right frustum[0][0] = clip[3] - clip[0] frustum[0][1] = clip[7] - clip[4] frustum[0][2] = clip[11] - clip[8] frustum[0][3] = clip[15] - clip[12] # left frustum[1][0] = clip[3] + clip[0] frustum[1][1] = clip[7] + clip[4] frustum[1][2] = clip[11] + clip[8] frustum[1][3] = clip[15] + clip[12] # bottoming frustum[2][0] = clip[3] + clip[1] frustum[2][1] = clip[7] + clip[5] frustum[2][2] = clip[11] + clip[9] frustum[2][3] = clip[15] + clip[13] # top frustum[3][0] = clip[3] - clip[1] frustum[3][1] = clip[7] - clip[5] frustum[3][2] = clip[11] - clip[9] frustum[3][3] = clip[15] - clip[13] # far frustum[4][0] = clip[3] - clip[2] frustum[4][1] = clip[7] - clip[6] frustum[4][2] = clip[11] - clip[10] frustum[4][3] = clip[15] - clip[14] # near frustum[5][0] = clip[3] + clip[2] frustum[5][1] = clip[7] + clip[6] frustum[5][2] = clip[11] + clip[10] frustum[5][3] = (clip[15] + clip[14]) if normalize: frustum = cls.normalize(frustum) obj = cls() obj.planes = frustum obj.matrix = matrix return obj @classmethod def normalize(cls, frustum): """Normalize clipping plane equations""" magnitude = numpy.sqrt( frustum[:, 0] * frustum[:, 0] + frustum[:, 1] * frustum[:, 1] + frustum[:, 2] * frustum[:, 2]) # eliminate any planes which have 0-length vectors, # those planes can't be used for excluding anything anyway... frustum = numpy.compress(magnitude, frustum, 0) magnitude = numpy.compress(magnitude, magnitude, 0) magnitude = numpy.reshape(magnitude.astype('d'), (len(frustum), 1)) return frustum / magnitude
6,077
34.964497
106
py
MCEdit-Unified
MCEdit-Unified-master/png.py
#!/usr/bin/env python from __future__ import print_function # png.py - PNG encoder/decoder in pure Python # # Copyright (C) 2006 Johann C. Rocholl <[email protected]> # Portions Copyright (C) 2009 David Jones <[email protected]> # And probably portions Copyright (C) 2006 Nicko van Someren <[email protected]> # # Original concept by Johann C. Rocholl. # # LICENCE (MIT) # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Software, # and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. """ Pure Python PNG Reader/Writer This Python module implements support for PNG images (see PNG specification at http://www.w3.org/TR/2003/REC-PNG-20031110/ ). It reads and writes PNG files with all allowable bit depths (1/2/4/8/16/24/32/48/64 bits per pixel) and colour combinations: greyscale (1/2/4/8/16 bit); RGB, RGBA, LA (greyscale with alpha) with 8/16 bits per channel; colour mapped images (1/2/4/8 bit). Adam7 interlacing is supported for reading and writing. A number of optional chunks can be specified (when writing) and understood (when reading): ``tRNS``, ``bKGD``, ``gAMA``. For help, type ``import png; help(png)`` in your python interpreter. A good place to start is the :class:`Reader` and :class:`Writer` classes. Requires Python 2.3. Limited support is available for Python 2.2, but not everything works. Best with Python 2.4 and higher. Installation is trivial, but see the ``README.txt`` file (with the source distribution) for details. This file can also be used as a command-line utility to convert `Netpbm <http://netpbm.sourceforge.net/>`_ PNM files to PNG, and the reverse conversion from PNG to PNM. The interface is similar to that of the ``pnmtopng`` program from Netpbm. Type ``python png.py --help`` at the shell prompt for usage and a list of options. A note on spelling and terminology ---------------------------------- Generally British English spelling is used in the documentation. So that's "greyscale" and "colour". This not only matches the author's native language, it's also used by the PNG specification. The major colour models supported by PNG (and hence by PyPNG) are: greyscale, RGB, greyscale--alpha, RGB--alpha. These are sometimes referred to using the abbreviations: L, RGB, LA, RGBA. In this case each letter abbreviates a single channel: *L* is for Luminance or Luma or Lightness which is the channel used in greyscale images; *R*, *G*, *B* stand for Red, Green, Blue, the components of a colour image; *A* stands for Alpha, the opacity channel (used for transparency effects, but higher values are more opaque, so it makes sense to call it opacity). A note on formats ----------------- When getting pixel data out of this module (reading) and presenting data to this module (writing) there are a number of ways the data could be represented as a Python value. Generally this module uses one of three formats called "flat row flat pixel", "boxed row flat pixel", and "boxed row boxed pixel". Basically the concern is whether each pixel and each row comes in its own little tuple (box), or not. Consider an image that is 3 pixels wide by 2 pixels high, and each pixel has RGB components: Boxed row flat pixel:: list([R,G,B, R,G,B, R,G,B], [R,G,B, R,G,B, R,G,B]) Each row appears as its own list, but the pixels are flattened so that three values for one pixel simply follow the three values for the previous pixel. This is the most common format used, because it provides a good compromise between space and convenience. PyPNG regards itself as at liberty to replace any sequence type with any sufficiently compatible other sequence type; in practice each row is an array (from the array module), and the outer list is sometimes an iterator rather than an explicit list (so that streaming is possible). Flat row flat pixel:: [R,G,B, R,G,B, R,G,B, R,G,B, R,G,B, R,G,B] The entire image is one single giant sequence of colour values. Generally an array will be used (to save space), not a list. Boxed row boxed pixel:: list([ (R,G,B), (R,G,B), (R,G,B) ], [ (R,G,B), (R,G,B), (R,G,B) ]) Each row appears in its own list, but each pixel also appears in its own tuple. A serious memory burn in Python. In all cases the top row comes first, and for each row the pixels are ordered from left-to-right. Within a pixel the values appear in the order, R-G-B-A (or L-A for greyscale--alpha). There is a fourth format, mentioned because it is used internally, is close to what lies inside a PNG file itself, and has some support from the public API. This format is called packed. When packed, each row is a sequence of bytes (integers from 0 to 255), just as it is before PNG scanline filtering is applied. When the bit depth is 8 this is essentially the same as boxed row flat pixel; when the bit depth is less than 8, several pixels are packed into each byte; when the bit depth is 16 (the only value more than 8 that is supported by the PNG image format) each pixel value is decomposed into 2 bytes (and `packed` is a misnomer). This format is used by the :meth:`Writer.write_packed` method. It isn't usually a convenient format, but may be just right if the source data for the PNG image comes from something that uses a similar format (for example, 1-bit BMPs, or another PNG file). And now, my famous members -------------------------- """ __version__ = "0.0.18" import itertools import math import re # http://www.python.org/doc/2.4.4/lib/module-operator.html import operator import struct import sys # http://www.python.org/doc/2.4.4/lib/module-warnings.html import warnings import zlib from array import array from functools import reduce # Test CLI switch # This is used to force exception raising if cpngfilters binary can' be found. test_clib = False if '--test-clib' in sys.argv: test_clib = True sys.argv.remove('--test-clib') try: # `cpngfilters` is a Cython module: it must be compiled by # Cython for this import to work. # If this import does work, then it overrides pure-python # filtering functions defined later in this file (see `class # pngfilters`). import cpngfilters as pngfilters except ImportError as ix: if test_clib: raise ix else: pass __all__ = ['Image', 'Reader', 'Writer', 'write_chunks', 'from_array'] # The PNG signature. # http://www.w3.org/TR/PNG/#5PNG-file-signature _signature = struct.pack('8B', 137, 80, 78, 71, 13, 10, 26, 10) _adam7 = ((0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2)) def group(s, n): # See http://www.python.org/doc/2.6/library/functions.html#zip return list(zip(*[iter(s)] * n)) def isarray(x): return isinstance(x, array) def tostring(row): return row.tostring() def interleave_planes(ipixels, apixels, ipsize, apsize): """ Interleave (colour) planes, e.g. RGB + A = RGBA. Return an array of pixels consisting of the `ipsize` elements of data from each pixel in `ipixels` followed by the `apsize` elements of data from each pixel in `apixels`. Conventionally `ipixels` and `apixels` are byte arrays so the sizes are bytes, but it actually works with any arrays of the same type. The returned array is the same type as the input arrays which should be the same type as each other. """ itotal = len(ipixels) atotal = len(apixels) newtotal = itotal + atotal newpsize = ipsize + apsize # Set up the output buffer # See http://www.python.org/doc/2.4.4/lib/module-array.html#l2h-1356 out = array(ipixels.typecode) # It's annoying that there is no cheap way to set the array size :-( out.extend(ipixels) out.extend(apixels) # Interleave in the pixel data for i in range(ipsize): out[i:newtotal:newpsize] = ipixels[i:itotal:ipsize] for i in range(apsize): out[i + ipsize:newtotal:newpsize] = apixels[i:atotal:apsize] return out def check_palette(palette): """Check a palette argument (to the :class:`Writer` class) for validity. Returns the palette as a list if okay; raises an exception otherwise. """ # None is the default and is allowed. if palette is None: return None p = list(palette) if not (0 < len(p) <= 256): raise ValueError("a palette must have between 1 and 256 entries") seen_triple = False for i, t in enumerate(p): if len(t) not in (3, 4): raise ValueError( "palette entry %d: entries must be 3- or 4-tuples." % i) if len(t) == 3: seen_triple = True if seen_triple and len(t) == 4: raise ValueError( "palette entry %d: all 4-tuples must precede all 3-tuples" % i) for x in t: if int(x) != x or not (0 <= x <= 255): raise ValueError( "palette entry %d: values must be integer: 0 <= x <= 255" % i) return p def check_sizes(size, width, height): """Check that these arguments, in supplied, are consistent. Return a (width, height) pair. """ if not size: return width, height if len(size) != 2: raise ValueError( "size argument should be a pair (width, height)") if width is not None and width != size[0]: raise ValueError( "size[0] (%r) and width (%r) should match when both are used." % (size[0], width)) if height is not None and height != size[1]: raise ValueError( "size[1] (%r) and height (%r) should match when both are used." % (size[1], height)) return size def check_color(c, greyscale, which): """Checks that a colour argument for transparent or background options is the right form. Returns the colour (which, if it's a bar integer, is "corrected" to a 1-tuple). """ if c is None: return c if greyscale: try: len(c) except TypeError: c = (c,) if len(c) != 1: raise ValueError("%s for greyscale must be 1-tuple" % which) if not isinteger(c[0]): raise ValueError( "%s colour for greyscale must be integer" % which) else: if not (len(c) == 3 and isinteger(c[0]) and isinteger(c[1]) and isinteger(c[2])): raise ValueError( "%s colour must be a triple of integers" % which) return c class Error(Exception): def __str__(self): return self.__class__.__name__ + ': ' + ' '.join(self.args) class FormatError(Error): """Problem with input file format. In other words, PNG file does not conform to the specification in some way and is invalid. """ class ChunkError(FormatError): pass class Writer: """ PNG encoder in pure Python. """ def __init__(self, width=None, height=None, size=None, greyscale=False, alpha=False, bitdepth=8, palette=None, transparent=None, background=None, gamma=None, compression=None, interlace=False, bytes_per_sample=None, # deprecated planes=None, colormap=None, maxval=None, chunk_limit=2 ** 20, x_pixels_per_unit=None, y_pixels_per_unit=None, unit_is_meter=False): """ Create a PNG encoder object. Arguments: width, height Image size in pixels, as two separate arguments. size Image size (w,h) in pixels, as single argument. greyscale Input data is greyscale, not RGB. alpha Input data has alpha channel (RGBA or LA). bitdepth Bit depth: from 1 to 16. palette Create a palette for a colour mapped image (colour type 3). transparent Specify a transparent colour (create a ``tRNS`` chunk). background Specify a default background colour (create a ``bKGD`` chunk). gamma Specify a gamma value (create a ``gAMA`` chunk). compression zlib compression level: 0 (none) to 9 (more compressed); default: -1 or None. interlace Create an interlaced image. chunk_limit Write multiple ``IDAT`` chunks to save memory. x_pixels_per_unit Number of pixels a unit along the x axis (write a `pHYs` chunk). y_pixels_per_unit Number of pixels a unit along the y axis (write a `pHYs` chunk). Along with `x_pixel_unit`, this gives the pixel size ratio. unit_is_meter `True` to indicate that the unit (for the `pHYs` chunk) is metre. The image size (in pixels) can be specified either by using the `width` and `height` arguments, or with the single `size` argument. If `size` is used it should be a pair (*width*, *height*). `greyscale` and `alpha` are booleans that specify whether an image is greyscale (or colour), and whether it has an alpha channel (or not). `bitdepth` specifies the bit depth of the source pixel values. Each source pixel value must be an integer between 0 and ``2**bitdepth-1``. For example, 8-bit images have values between 0 and 255. PNG only stores images with bit depths of 1,2,4,8, or 16. When `bitdepth` is not one of these values, the next highest valid bit depth is selected, and an ``sBIT`` (significant bits) chunk is generated that specifies the original precision of the source image. In this case the supplied pixel values will be rescaled to fit the range of the selected bit depth. The details of which bit depth / colour model combinations the PNG file format supports directly, are somewhat arcane (refer to the PNG specification for full details). Briefly: "small" bit depths (1,2,4) are only allowed with greyscale and colour mapped images; colour mapped images cannot have bit depth 16. For colour mapped images (in other words, when the `palette` argument is specified) the `bitdepth` argument must match one of the valid PNG bit depths: 1, 2, 4, or 8. (It is valid to have a PNG image with a palette and an ``sBIT`` chunk, but the meaning is slightly different; it would be awkward to press the `bitdepth` argument into service for this.) The `palette` option, when specified, causes a colour mapped image to be created: the PNG colour type is set to 3; `greyscale` must not be set; `alpha` must not be set; `transparent` must not be set; the bit depth must be 1,2,4, or 8. When a colour mapped image is created, the pixel values are palette indexes and the `bitdepth` argument specifies the size of these indexes (not the size of the colour values in the palette). The palette argument value should be a sequence of 3- or 4-tuples. 3-tuples specify RGB palette entries; 4-tuples specify RGBA palette entries. If both 4-tuples and 3-tuples appear in the sequence then all the 4-tuples must come before all the 3-tuples. A ``PLTE`` chunk is created; if there are 4-tuples then a ``tRNS`` chunk is created as well. The ``PLTE`` chunk will contain all the RGB triples in the same sequence; the ``tRNS`` chunk will contain the alpha channel for all the 4-tuples, in the same sequence. Palette entries are always 8-bit. If specified, the `transparent` and `background` parameters must be a tuple with three integer values for red, green, blue, or a simple integer (or singleton tuple) for a greyscale image. If specified, the `gamma` parameter must be a positive number (generally, a `float`). A ``gAMA`` chunk will be created. Note that this will not change the values of the pixels as they appear in the PNG file, they are assumed to have already been converted appropriately for the gamma specified. The `compression` argument specifies the compression level to be used by the ``zlib`` module. Values from 1 to 9 specify compression, with 9 being "more compressed" (usually smaller and slower, but it doesn't always work out that way). 0 means no compression. -1 and ``None`` both mean that the default level of compession will be picked by the ``zlib`` module (which is generally acceptable). If `interlace` is true then an interlaced image is created (using PNG's so far only interace method, *Adam7*). This does not affect how the pixels should be presented to the encoder, rather it changes how they are arranged into the PNG file. On slow connexions interlaced images can be partially decoded by the browser to give a rough view of the image that is successively refined as more image data appears. .. note :: Enabling the `interlace` option requires the entire image to be processed in working memory. `chunk_limit` is used to limit the amount of memory used whilst compressing the image. In order to avoid using large amounts of memory, multiple ``IDAT`` chunks may be created. """ # At the moment the `planes` argument is ignored; # its purpose is to act as a dummy so that # ``Writer(x, y, **info)`` works, where `info` is a dictionary # returned by Reader.read and friends. # Ditto for `colormap`. width, height = check_sizes(size, width, height) del size if width <= 0 or height <= 0: raise ValueError("width and height must be greater than zero") if not isinteger(width) or not isinteger(height): raise ValueError("width and height must be integers") # http://www.w3.org/TR/PNG/#7Integers-and-byte-order if width > 2 ** 32 - 1 or height > 2 ** 32 - 1: raise ValueError("width and height cannot exceed 2**32-1") if alpha and transparent is not None: raise ValueError( "transparent colour not allowed with alpha channel") if bytes_per_sample is not None: warnings.warn('please use bitdepth instead of bytes_per_sample', DeprecationWarning) if bytes_per_sample not in (0.125, 0.25, 0.5, 1, 2): raise ValueError( "bytes per sample must be .125, .25, .5, 1, or 2") bitdepth = int(8 * bytes_per_sample) del bytes_per_sample if not isinteger(bitdepth) or bitdepth < 1 or 16 < bitdepth: raise ValueError("bitdepth (%r) must be a positive integer <= 16" % bitdepth) self.rescale = None palette = check_palette(palette) if palette: if bitdepth not in (1, 2, 4, 8): raise ValueError("with palette, bitdepth must be 1, 2, 4, or 8") if transparent is not None: raise ValueError("transparent and palette not compatible") if alpha: raise ValueError("alpha and palette not compatible") if greyscale: raise ValueError("greyscale and palette not compatible") else: # No palette, check for sBIT chunk generation. if alpha or not greyscale: if bitdepth not in (8, 16): targetbitdepth = (8, 16)[bitdepth > 8] self.rescale = (bitdepth, targetbitdepth) bitdepth = targetbitdepth del targetbitdepth else: assert greyscale assert not alpha if bitdepth not in (1, 2, 4, 8, 16): if bitdepth > 8: targetbitdepth = 16 elif bitdepth == 3: targetbitdepth = 4 else: assert bitdepth in (5, 6, 7) targetbitdepth = 8 self.rescale = (bitdepth, targetbitdepth) bitdepth = targetbitdepth del targetbitdepth if bitdepth < 8 and (alpha or not greyscale and not palette): raise ValueError( "bitdepth < 8 only permitted with greyscale or palette") if bitdepth > 8 and palette: raise ValueError( "bit depth must be 8 or less for images with palette") transparent = check_color(transparent, greyscale, 'transparent') background = check_color(background, greyscale, 'background') # It's important that the true boolean values (greyscale, alpha, # colormap, interlace) are converted to bool because Iverson's # convention is relied upon later on. self.width = width self.height = height self.transparent = transparent self.background = background self.gamma = gamma self.greyscale = bool(greyscale) self.alpha = bool(alpha) self.colormap = bool(palette) self.bitdepth = int(bitdepth) self.compression = compression self.chunk_limit = chunk_limit self.interlace = bool(interlace) self.palette = palette self.x_pixels_per_unit = x_pixels_per_unit self.y_pixels_per_unit = y_pixels_per_unit self.unit_is_meter = bool(unit_is_meter) self.color_type = 4 * self.alpha + 2 * (not greyscale) + 1 * self.colormap assert self.color_type in (0, 2, 3, 4, 6) self.color_planes = (3, 1)[self.greyscale or self.colormap] self.planes = self.color_planes + self.alpha # :todo: fix for bitdepth < 8 self.psize = (self.bitdepth / 8) * self.planes def make_palette(self): """Create the byte sequences for a ``PLTE`` and if necessary a ``tRNS`` chunk. Returned as a pair (*p*, *t*). *t* will be ``None`` if no ``tRNS`` chunk is necessary. """ p = array('B') t = array('B') for x in self.palette: p.extend(x[0:3]) if len(x) > 3: t.append(x[3]) p = tostring(p) t = tostring(t) if t: return p, t return p, None def write(self, outfile, rows): """Write a PNG image to the output file. `rows` should be an iterable that yields each row in boxed row flat pixel format. The rows should be the rows of the original image, so there should be ``self.height`` rows of ``self.width * self.planes`` values. If `interlace` is specified (when creating the instance), then an interlaced PNG file will be written. Supply the rows in the normal image order; the interlacing is carried out internally. .. note :: Interlacing will require the entire image to be in working memory. """ if self.interlace: fmt = 'BH'[self.bitdepth > 8] a = array(fmt, itertools.chain(*rows)) return self.write_array(outfile, a) nrows = self.write_passes(outfile, rows) if nrows != self.height: raise ValueError( "rows supplied (%d) does not match height (%d)" % (nrows, self.height)) def write_passes(self, outfile, rows, packed=False): """ Write a PNG image to the output file. Most users are expected to find the :meth:`write` or :meth:`write_array` method more convenient. The rows should be given to this method in the order that they appear in the output file. For straightlaced images, this is the usual top to bottom ordering, but for interlaced images the rows should have already been interlaced before passing them to this function. `rows` should be an iterable that yields each row. When `packed` is ``False`` the rows should be in boxed row flat pixel format; when `packed` is ``True`` each row should be a packed sequence of bytes. """ # http://www.w3.org/TR/PNG/#5PNG-file-signature outfile.write(_signature) # http://www.w3.org/TR/PNG/#11IHDR write_chunk(outfile, b'IHDR', struct.pack("!2I5B", self.width, self.height, self.bitdepth, self.color_type, 0, 0, self.interlace)) # See :chunk:order # http://www.w3.org/TR/PNG/#11gAMA if self.gamma is not None: write_chunk(outfile, b'gAMA', struct.pack("!L", int(round(self.gamma * 1e5)))) # See :chunk:order # http://www.w3.org/TR/PNG/#11sBIT if self.rescale: write_chunk(outfile, b'sBIT', struct.pack('%dB' % self.planes, *[self.rescale[0]] * self.planes)) # :chunk:order: Without a palette (PLTE chunk), ordering is # relatively relaxed. With one, gAMA chunk must precede PLTE # chunk which must precede tRNS and bKGD. # See http://www.w3.org/TR/PNG/#5ChunkOrdering if self.palette: p, t = self.make_palette() write_chunk(outfile, b'PLTE', p) if t: # tRNS chunk is optional. Only needed if palette entries # have alpha. write_chunk(outfile, b'tRNS', t) # http://www.w3.org/TR/PNG/#11tRNS if self.transparent is not None: if self.greyscale: write_chunk(outfile, b'tRNS', struct.pack("!1H", *self.transparent)) else: write_chunk(outfile, b'tRNS', struct.pack("!3H", *self.transparent)) # http://www.w3.org/TR/PNG/#11bKGD if self.background is not None: if self.greyscale: write_chunk(outfile, b'bKGD', struct.pack("!1H", *self.background)) else: write_chunk(outfile, b'bKGD', struct.pack("!3H", *self.background)) # http://www.w3.org/TR/PNG/#11pHYs if self.x_pixels_per_unit is not None and self.y_pixels_per_unit is not None: tup = (self.x_pixels_per_unit, self.y_pixels_per_unit, int(self.unit_is_meter)) write_chunk(outfile, b'pHYs', struct.pack("!LLB", *tup)) # http://www.w3.org/TR/PNG/#11IDAT if self.compression is not None: compressor = zlib.compressobj(self.compression) else: compressor = zlib.compressobj() # Choose an extend function based on the bitdepth. The extend # function packs/decomposes the pixel values into bytes and # stuffs them onto the data array. data = array('B') if self.bitdepth == 8 or packed: extend = data.extend elif self.bitdepth == 16: # Decompose into bytes def extend(sl): fmt = '!%dH' % len(sl) data.extend(array('B', struct.pack(fmt, *sl))) else: # Pack into bytes assert self.bitdepth < 8 # samples per byte spb = int(8 / self.bitdepth) def extend(sl): a = array('B', sl) # Adding padding bytes so we can group into a whole # number of spb-tuples. l = float(len(a)) extra = math.ceil(l / float(spb)) * spb - l a.extend([0] * int(extra)) # Pack into bytes l = group(a, spb) l = [reduce(lambda x, y: (x << self.bitdepth) + y, e) for e in l] data.extend(l) if self.rescale: oldextend = extend factor = \ float(2 ** self.rescale[1] - 1) / float(2 ** self.rescale[0] - 1) def extend(sl): oldextend([int(round(factor * x)) for x in sl]) # Build the first row, testing mostly to see if we need to # changed the extend function to cope with NumPy integer types # (they cause our ordinary definition of extend to fail, so we # wrap it). See # http://code.google.com/p/pypng/issues/detail?id=44 enumrows = enumerate(rows) del rows # First row's filter type. data.append(0) # :todo: Certain exceptions in the call to ``.next()`` or the # following try would indicate no row data supplied. # Should catch. i, row = next(enumrows) try: # If this fails... extend(row) except: # ... try a version that converts the values to int first. # Not only does this work for the (slightly broken) NumPy # types, there are probably lots of other, unknown, "nearly" # int types it works for. def wrapmapint(f): return lambda sl: f([int(x) for x in sl]) extend = wrapmapint(extend) del wrapmapint extend(row) for i, row in enumrows: # Add "None" filter type. Currently, it's essential that # this filter type be used for every scanline as we do not # mark the first row of a reduced pass image; that means we # could accidentally compute the wrong filtered scanline if # we used "up", "average", or "paeth" on such a line. data.append(0) extend(row) if len(data) > self.chunk_limit: compressed = compressor.compress(tostring(data)) if len(compressed): write_chunk(outfile, b'IDAT', compressed) # Because of our very witty definition of ``extend``, # above, we must re-use the same ``data`` object. Hence # we use ``del`` to empty this one, rather than create a # fresh one (which would be my natural FP instinct). del data[:] if len(data): compressed = compressor.compress(tostring(data)) else: compressed = b'' flushed = compressor.flush() if len(compressed) or len(flushed): write_chunk(outfile, b'IDAT', compressed + flushed) # http://www.w3.org/TR/PNG/#11IEND write_chunk(outfile, b'IEND') return i + 1 def write_array(self, outfile, pixels): """ Write an array in flat row flat pixel format as a PNG file on the output file. See also :meth:`write` method. """ if self.interlace: self.write_passes(outfile, self.array_scanlines_interlace(pixels)) else: self.write_passes(outfile, self.array_scanlines(pixels)) def write_packed(self, outfile, rows): """ Write PNG file to `outfile`. The pixel data comes from `rows` which should be in boxed row packed format. Each row should be a sequence of packed bytes. Technically, this method does work for interlaced images but it is best avoided. For interlaced images, the rows should be presented in the order that they appear in the file. This method should not be used when the source image bit depth is not one naturally supported by PNG; the bit depth should be 1, 2, 4, 8, or 16. """ if self.rescale: raise Error("write_packed method not suitable for bit depth %d" % self.rescale[0]) return self.write_passes(outfile, rows, packed=True) def convert_pnm(self, infile, outfile): """ Convert a PNM file containing raw pixel data into a PNG file with the parameters set in the writer object. Works for (binary) PGM, PPM, and PAM formats. """ if self.interlace: pixels = array('B') pixels.fromfile(infile, (self.bitdepth / 8) * self.color_planes * self.width * self.height) self.write_passes(outfile, self.array_scanlines_interlace(pixels)) else: self.write_passes(outfile, self.file_scanlines(infile)) def convert_ppm_and_pgm(self, ppmfile, pgmfile, outfile): """ Convert a PPM and PGM file containing raw pixel data into a PNG outfile with the parameters set in the writer object. """ pixels = array('B') pixels.fromfile(ppmfile, (self.bitdepth / 8) * self.color_planes * self.width * self.height) apixels = array('B') apixels.fromfile(pgmfile, (self.bitdepth / 8) * self.width * self.height) pixels = interleave_planes(pixels, apixels, (self.bitdepth / 8) * self.color_planes, (self.bitdepth / 8)) if self.interlace: self.write_passes(outfile, self.array_scanlines_interlace(pixels)) else: self.write_passes(outfile, self.array_scanlines(pixels)) def file_scanlines(self, infile): """ Generates boxed rows in flat pixel format, from the input file `infile`. It assumes that the input file is in a "Netpbm-like" binary format, and is positioned at the beginning of the first pixel. The number of pixels to read is taken from the image dimensions (`width`, `height`, `planes`) and the number of bytes per value is implied by the image `bitdepth`. """ # Values per row vpr = self.width * self.planes row_bytes = vpr if self.bitdepth > 8: assert self.bitdepth == 16 row_bytes *= 2 fmt = '>%dH' % vpr def line(): return array('H', struct.unpack(fmt, infile.read(row_bytes))) else: def line(): scanline = array('B', infile.read(row_bytes)) return scanline for y in range(self.height): yield line() def array_scanlines(self, pixels): """ Generates boxed rows (flat pixels) from flat rows (flat pixels) in an array. """ # Values per row vpr = self.width * self.planes stop = 0 for y in range(self.height): start = stop stop = start + vpr yield pixels[start:stop] def array_scanlines_interlace(self, pixels): """ Generator for interlaced scanlines from an array. `pixels` is the full source image in flat row flat pixel format. The generator yields each scanline of the reduced passes in turn, in boxed row flat pixel format. """ # http://www.w3.org/TR/PNG/#8InterlaceMethods # Array type. fmt = 'BH'[self.bitdepth > 8] # Value per row vpr = self.width * self.planes for xstart, ystart, xstep, ystep in _adam7: if xstart >= self.width: continue # Pixels per row (of reduced image) ppr = int(math.ceil((self.width - xstart) / float(xstep))) # number of values in reduced image row. row_len = ppr * self.planes for y in range(ystart, self.height, ystep): if xstep == 1: offset = y * vpr yield pixels[offset:offset + vpr] else: row = array(fmt) # There's no easier way to set the length of an array row.extend(pixels[0:row_len]) offset = y * vpr + xstart * self.planes end_offset = (y + 1) * vpr skip = self.planes * xstep for i in range(self.planes): row[i::self.planes] = \ pixels[offset + i:end_offset:skip] yield row def write_chunk(outfile, tag, data=b''): """ Write a PNG chunk to the output file, including length and checksum. """ # http://www.w3.org/TR/PNG/#5Chunk-layout outfile.write(struct.pack("!I", len(data))) outfile.write(tag) outfile.write(data) checksum = zlib.crc32(tag) checksum = zlib.crc32(data, checksum) checksum &= 2 ** 32 - 1 outfile.write(struct.pack("!I", checksum)) def write_chunks(out, chunks): """Create a PNG file by writing out the chunks.""" out.write(_signature) for chunk in chunks: write_chunk(out, *chunk) def filter_scanline(type, line, fo, prev=None): """Apply a scanline filter to a scanline. `type` specifies the filter type (0 to 4); `line` specifies the current (unfiltered) scanline as a sequence of bytes; `prev` specifies the previous (unfiltered) scanline as a sequence of bytes. `fo` specifies the filter offset; normally this is size of a pixel in bytes (the number of bytes per sample times the number of channels), but when this is < 1 (for bit depths < 8) then the filter offset is 1. """ assert 0 <= type < 5 # The output array. Which, pathetically, we extend one-byte at a # time (fortunately this is linear). out = array('B', [type]) def sub(): ai = -fo for x in line: if ai >= 0: x = (x - line[ai]) & 0xff out.append(x) ai += 1 def up(): for i, x in enumerate(line): x = (x - prev[i]) & 0xff out.append(x) def average(): ai = -fo for i, x in enumerate(line): if ai >= 0: x = (x - ((line[ai] + prev[i]) >> 1)) & 0xff else: x = (x - (prev[i] >> 1)) & 0xff out.append(x) ai += 1 def paeth(): # http://www.w3.org/TR/PNG/#9Filter-type-4-Paeth ai = -fo # also used for ci for i, x in enumerate(line): a = 0 b = prev[i] c = 0 if ai >= 0: a = line[ai] c = prev[ai] p = a + b - c pa = abs(p - a) pb = abs(p - b) pc = abs(p - c) if pa <= pb and pa <= pc: Pr = a elif pb <= pc: Pr = b else: Pr = c x = (x - Pr) & 0xff out.append(x) ai += 1 if not prev: # We're on the first line. Some of the filters can be reduced # to simpler cases which makes handling the line "off the top" # of the image simpler. "up" becomes "none"; "paeth" becomes # "left" (non-trivial, but true). "average" needs to be handled # specially. if type == 2: # "up" type = 0 elif type == 3: prev = [0] * len(line) elif type == 4: # "paeth" type = 1 if type == 0: out.extend(line) elif type == 1: sub() elif type == 2: up() elif type == 3: average() else: # type == 4 paeth() return out # Regex for decoding mode string RegexModeDecode = re.compile("(LA?|RGBA?);?([0-9]*)", flags=re.IGNORECASE) def from_array(a, mode=None, info={}): """Create a PNG :class:`Image` object from a 2- or 3-dimensional array. One application of this function is easy PIL-style saving: ``png.from_array(pixels, 'L').save('foo.png')``. Unless they are specified using the *info* parameter, the PNG's height and width are taken from the array size. For a 3 dimensional array the first axis is the height; the second axis is the width; and the third axis is the channel number. Thus an RGB image that is 16 pixels high and 8 wide will use an array that is 16x8x3. For 2 dimensional arrays the first axis is the height, but the second axis is ``width*channels``, so an RGB image that is 16 pixels high and 8 wide will use a 2-dimensional array that is 16x24 (each row will be 8*3 = 24 sample values). *mode* is a string that specifies the image colour format in a PIL-style mode. It can be: ``'L'`` greyscale (1 channel) ``'LA'`` greyscale with alpha (2 channel) ``'RGB'`` colour image (3 channel) ``'RGBA'`` colour image with alpha (4 channel) The mode string can also specify the bit depth (overriding how this function normally derives the bit depth, see below). Appending ``';16'`` to the mode will cause the PNG to be 16 bits per channel; any decimal from 1 to 16 can be used to specify the bit depth. When a 2-dimensional array is used *mode* determines how many channels the image has, and so allows the width to be derived from the second array dimension. The array is expected to be a ``numpy`` array, but it can be any suitable Python sequence. For example, a list of lists can be used: ``png.from_array([[0, 255, 0], [255, 0, 255]], 'L')``. The exact rules are: ``len(a)`` gives the first dimension, height; ``len(a[0])`` gives the second dimension; ``len(a[0][0])`` gives the third dimension, unless an exception is raised in which case a 2-dimensional array is assumed. It's slightly more complicated than that because an iterator of rows can be used, and it all still works. Using an iterator allows data to be streamed efficiently. The bit depth of the PNG is normally taken from the array element's datatype (but if *mode* specifies a bitdepth then that is used instead). The array element's datatype is determined in a way which is supposed to work both for ``numpy`` arrays and for Python ``array.array`` objects. A 1 byte datatype will give a bit depth of 8, a 2 byte datatype will give a bit depth of 16. If the datatype does not have an implicit size, for example it is a plain Python list of lists, as above, then a default of 8 is used. The *info* parameter is a dictionary that can be used to specify metadata (in the same style as the arguments to the :class:`png.Writer` class). For this function the keys that are useful are: height overrides the height derived from the array dimensions and allows *a* to be an iterable. width overrides the width derived from the array dimensions. bitdepth overrides the bit depth derived from the element datatype (but must match *mode* if that also specifies a bit depth). Generally anything specified in the *info* dictionary will override any implicit choices that this function would otherwise make, but must match any explicit ones. For example, if the *info* dictionary has a ``greyscale`` key then this must be true when mode is ``'L'`` or ``'LA'`` and false when mode is ``'RGB'`` or ``'RGBA'``. """ # We abuse the *info* parameter by modifying it. Take a copy here. # (Also typechecks *info* to some extent). info = dict(info) # Syntax check mode string. match = RegexModeDecode.match(mode) if not match: raise Error("mode string should be 'RGB' or 'L;16' or similar.") mode, bitdepth = match.groups() alpha = 'A' in mode if bitdepth: bitdepth = int(bitdepth) # Colour format. if 'greyscale' in info: if bool(info['greyscale']) != ('L' in mode): raise Error("info['greyscale'] should match mode.") info['greyscale'] = 'L' in mode if 'alpha' in info: if bool(info['alpha']) != alpha: raise Error("info['alpha'] should match mode.") info['alpha'] = alpha # Get bitdepth from *mode* if possible. if bitdepth: if info.get("bitdepth") and bitdepth != info['bitdepth']: raise Error("bitdepth (%d) should match bitdepth of info (%d)." % (bitdepth, info['bitdepth'])) info['bitdepth'] = bitdepth # Fill in and/or check entries in *info*. # Dimensions. if 'size' in info: assert len(info["size"]) == 2 # Check width, height, size all match where used. for dimension, axis in [('width', 0), ('height', 1)]: if dimension in info: if info[dimension] != info['size'][axis]: raise Error( "info[%r] should match info['size'][%r]." % (dimension, axis)) info['width'], info['height'] = info['size'] if 'height' not in info: try: info['height'] = len(a) except TypeError: raise Error("len(a) does not work, supply info['height'] instead.") planes = len(mode) if 'planes' in info: if info['planes'] != planes: raise Error("info['planes'] should match mode.") # In order to work out whether we the array is 2D or 3D we need its # first row, which requires that we take a copy of its iterator. # We may also need the first row to derive width and bitdepth. a, t = itertools.tee(a) row = next(t) del t try: row[0][0] threed = True testelement = row[0] except (IndexError, TypeError): threed = False testelement = row if 'width' not in info: if threed: width = len(row) else: width = len(row) // planes info['width'] = width if threed: # Flatten the threed rows a = (itertools.chain.from_iterable(x) for x in a) if 'bitdepth' not in info: try: dtype = testelement.dtype # goto the "else:" clause. Sorry. except AttributeError: try: # Try a Python array.array. bitdepth = 8 * testelement.itemsize except AttributeError: # We can't determine it from the array element's # datatype, use a default of 8. bitdepth = 8 else: # If we got here without exception, we now assume that # the array is a numpy array. if dtype.kind == 'b': bitdepth = 1 else: bitdepth = 8 * dtype.itemsize info['bitdepth'] = bitdepth for thing in ["width", "height", "bitdepth", "greyscale", "alpha"]: assert thing in info return Image(a, info) # So that refugee's from PIL feel more at home. Not documented. fromarray = from_array class Image: """A PNG image. You can create an :class:`Image` object from an array of pixels by calling :meth:`png.from_array`. It can be saved to disk with the :meth:`save` method. """ def __init__(self, rows, info): """ .. note :: The constructor is not public. Please do not call it. """ self.rows = rows self.info = info def save(self, file): """Save the image to *file*. If *file* looks like an open file descriptor then it is used, otherwise it is treated as a filename and a fresh file is opened. In general, you can only call this method once; after it has been called the first time and the PNG image has been saved, the source data will have been streamed, and cannot be streamed again. """ w = Writer(**self.info) try: file.write def close(): pass except AttributeError: file = open(file, 'wb') def close(): file.close() try: w.write(file, self.rows) finally: close() class _readable: """ A simple file-like interface for strings and arrays. """ def __init__(self, buf): self.buf = buf self.offset = 0 def read(self, n): r = self.buf[self.offset:self.offset + n] if isarray(r): r = r.tostring() self.offset += n return r try: str(b'dummy', 'ascii') except TypeError: as_str = str else: def as_str(x): return str(x, 'ascii') class Reader: """ PNG decoder in pure Python. """ def __init__(self, _guess=None, **kw): """ Create a PNG decoder object. The constructor expects exactly one keyword argument. If you supply a positional argument instead, it will guess the input type. You can choose among the following keyword arguments: filename Name of input file (a PNG file). file A file-like object (object with a read() method). bytes ``array`` or ``string`` with PNG data. """ if ((_guess is not None and len(kw) != 0) or (_guess is None and len(kw) != 1)): raise TypeError("Reader() takes exactly 1 argument") # Will be the first 8 bytes, later on. See validate_signature. self.signature = None self.transparent = None # A pair of (len,type) if a chunk has been read but its data and # checksum have not (in other words the file position is just # past the 4 bytes that specify the chunk type). See preamble # method for how this is used. self.atchunk = None if _guess is not None: if isarray(_guess): kw["bytes"] = _guess elif isinstance(_guess, (str, unicode)): kw["filename"] = _guess elif hasattr(_guess, 'read'): kw["file"] = _guess if "filename" in kw: self.file = open(kw["filename"], "rb") elif "file" in kw: self.file = kw["file"] elif "bytes" in kw: self.file = _readable(kw["bytes"]) else: raise TypeError("expecting filename, file or bytes array") def chunk(self, seek=None, lenient=False): """ Read the next PNG chunk from the input file; returns a (*type*, *data*) tuple. *type* is the chunk's type as a byte string (all PNG chunk types are 4 bytes long). *data* is the chunk's data content, as a byte string. If the optional `seek` argument is specified then it will keep reading chunks until it either runs out of file or finds the type specified by the argument. Note that in general the order of chunks in PNGs is unspecified, so using `seek` can cause you to miss chunks. If the optional `lenient` argument evaluates to `True`, checksum failures will raise warnings rather than exceptions. """ self.validate_signature() while True: # http://www.w3.org/TR/PNG/#5Chunk-layout if not self.atchunk: self.atchunk = self.chunklentype() length, type = self.atchunk self.atchunk = None data = self.file.read(length) if len(data) != length: raise ChunkError('Chunk %s too short for required %i octets.' % (type, length)) checksum = self.file.read(4) if len(checksum) != 4: raise ChunkError('Chunk %s too short for checksum.' % type) if seek and type != seek: continue verify = zlib.crc32(type) verify = zlib.crc32(data, verify) # Whether the output from zlib.crc32 is signed or not varies # according to hideous implementation details, see # http://bugs.python.org/issue1202 . # We coerce it to be positive here (in a way which works on # Python 2.3 and older). verify &= 2 ** 32 - 1 verify = struct.pack('!I', verify) if checksum != verify: (a,) = struct.unpack('!I', checksum) (b,) = struct.unpack('!I', verify) message = "Checksum error in %s chunk: 0x%08X != 0x%08X." % (type, a, b) if lenient: warnings.warn(message, RuntimeWarning) else: raise ChunkError(message) return type, data def chunks(self): """Return an iterator that will yield each chunk as a (*chunktype*, *content*) pair. """ while True: t, v = self.chunk() yield t, v if t == b'IEND': break def undo_filter(self, filter_type, scanline, previous): """Undo the filter for a scanline. `scanline` is a sequence of bytes that does not include the initial filter type byte. `previous` is decoded previous scanline (for straightlaced images this is the previous pixel row, but for interlaced images, it is the previous scanline in the reduced image, which in general is not the previous pixel row in the final image). When there is no previous scanline (the first row of a straightlaced image, or the first row in one of the passes in an interlaced image), then this argument should be ``None``. The scanline will have the effects of filtering removed, and the result will be returned as a fresh sequence of bytes. """ # :todo: Would it be better to update scanline in place? # Yes, with the Cython extension making the undo_filter fast, # updating scanline inplace makes the code 3 times faster # (reading 50 images of 800x800 went from 40s to 16s) result = scanline if filter_type == 0: return result if filter_type not in (1, 2, 3, 4): raise FormatError('Invalid PNG Filter Type.' ' See http://www.w3.org/TR/2003/REC-PNG-20031110/#9Filters .') # Filter unit. The stride from one pixel to the corresponding # byte from the previous pixel. Normally this is the pixel # size in bytes, but when this is smaller than 1, the previous # byte is used instead. fu = max(1, self.psize) # For the first line of a pass, synthesize a dummy previous # line. An alternative approach would be to observe that on the # first line 'up' is the same as 'null', 'paeth' is the same # as 'sub', with only 'average' requiring any special case. if not previous: previous = array('B', [0] * len(scanline)) def sub(): """Undo sub filter.""" ai = 0 # Loop starts at index fu. Observe that the initial part # of the result is already filled in correctly with # scanline. for i in range(fu, len(result)): x = scanline[i] a = result[ai] result[i] = (x + a) & 0xff ai += 1 def up(): """Undo up filter.""" for i in range(len(result)): x = scanline[i] b = previous[i] result[i] = (x + b) & 0xff def average(): """Undo average filter.""" ai = -fu for i in range(len(result)): x = scanline[i] if ai < 0: a = 0 else: a = result[ai] b = previous[i] result[i] = (x + ((a + b) >> 1)) & 0xff ai += 1 def paeth(): """Undo Paeth filter.""" # Also used for ci. ai = -fu for i in range(len(result)): x = scanline[i] if ai < 0: a = c = 0 else: a = result[ai] c = previous[ai] b = previous[i] p = a + b - c pa = abs(p - a) pb = abs(p - b) pc = abs(p - c) if pa <= pb and pa <= pc: pr = a elif pb <= pc: pr = b else: pr = c result[i] = (x + pr) & 0xff ai += 1 # Call appropriate filter algorithm. Note that 0 has already # been dealt with. (None, pngfilters.undo_filter_sub, pngfilters.undo_filter_up, pngfilters.undo_filter_average, pngfilters.undo_filter_paeth)[filter_type](fu, scanline, previous, result) return result def deinterlace(self, raw): """ Read raw pixel data, undo filters, deinterlace, and flatten. Return in flat row flat pixel format. """ # Values per row (of the target image) vpr = self.width * self.planes # Make a result array, and make it big enough. Interleaving # writes to the output array randomly (well, not quite), so the # entire output array must be in memory. fmt = 'BH'[self.bitdepth > 8] a = array(fmt, [0] * vpr * self.height) source_offset = 0 for xstart, ystart, xstep, ystep in _adam7: if xstart >= self.width: continue # The previous (reconstructed) scanline. None at the # beginning of a pass to indicate that there is no previous # line. recon = None # Pixels per row (reduced pass image) ppr = int(math.ceil((self.width - xstart) / float(xstep))) # Row size in bytes for this pass. row_size = int(math.ceil(self.psize * ppr)) for y in range(ystart, self.height, ystep): filter_type = raw[source_offset] source_offset += 1 scanline = raw[source_offset:source_offset + row_size] source_offset += row_size recon = self.undo_filter(filter_type, scanline, recon) # Convert so that there is one element per pixel value flat = self.serialtoflat(recon, ppr) if xstep == 1: assert xstart == 0 offset = y * vpr a[offset:offset + vpr] = flat else: offset = y * vpr + xstart * self.planes end_offset = (y + 1) * vpr skip = self.planes * xstep for i in range(self.planes): a[offset + i:end_offset:skip] = \ flat[i::self.planes] return a def iterboxed(self, rows): """Iterator that yields each scanline in boxed row flat pixel format. `rows` should be an iterator that yields the bytes of each row in turn. """ def asvalues(raw): """Convert a row of raw bytes into a flat row. Result will be a freshly allocated object, not shared with argument. """ if self.bitdepth == 8: return raw if self.bitdepth == 16: raw = tostring(raw) return array('H', struct.unpack('!%dH' % (len(raw) // 2), raw)) assert self.bitdepth < 8 width = self.width # Samples per byte spb = 8 // self.bitdepth out = array('B') mask = 2 ** self.bitdepth - 1 shifts = [self.bitdepth * i for i in reversed(list(range(spb)))] for o in raw: out.extend([mask & (o >> i) for i in shifts]) return out[:width] return map(asvalues, rows) def serialtoflat(self, bytes, width=None): """Convert serial format (byte stream) pixel data to flat row flat pixel. """ if self.bitdepth == 8: return bytes if self.bitdepth == 16: bytes = tostring(bytes) return array('H', struct.unpack('!%dH' % (len(bytes) // 2), bytes)) assert self.bitdepth < 8 if width is None: width = self.width # Samples per byte spb = 8 // self.bitdepth out = array('B') mask = 2 ** self.bitdepth - 1 shifts = list(map(self.bitdepth.__mul__, reversed(list(range(spb))))) l = width for o in bytes: out.extend([(mask & (o >> s)) for s in shifts][:l]) l -= spb if l <= 0: l = width return out def iterstraight(self, raw): """Iterator that undoes the effect of filtering, and yields each row in serialised format (as a sequence of bytes). Assumes input is straightlaced. `raw` should be an iterable that yields the raw bytes in chunks of arbitrary size. """ # length of row, in bytes rb = self.row_bytes a = array('B') # The previous (reconstructed) scanline. None indicates first # line of image. recon = None for some in raw: a.extend(some) while len(a) >= rb + 1: filter_type = a[0] scanline = a[1:rb + 1] del a[:rb + 1] recon = self.undo_filter(filter_type, scanline, recon) yield recon if len(a) != 0: # :file:format We get here with a file format error: # when the available bytes (after decompressing) do not # pack into exact rows. raise FormatError( 'Wrong size for decompressed IDAT chunk.') assert len(a) == 0 def validate_signature(self): """If signature (header) has not been read then read and validate it; otherwise do nothing. """ if self.signature: return self.signature = self.file.read(8) if self.signature != _signature: raise FormatError("PNG file has invalid signature.") def preamble(self, lenient=False): """ Extract the image metadata by reading the initial part of the PNG file up to the start of the ``IDAT`` chunk. All the chunks that precede the ``IDAT`` chunk are read and either processed for metadata or discarded. If the optional `lenient` argument evaluates to `True`, checksum failures will raise warnings rather than exceptions. """ self.validate_signature() while True: if not self.atchunk: self.atchunk = self.chunklentype() if self.atchunk is None: raise FormatError( 'This PNG file has no IDAT chunks.') if self.atchunk[1] == b'IDAT': return self.process_chunk(lenient=lenient) def chunklentype(self): """Reads just enough of the input to determine the next chunk's length and type, returned as a (*length*, *type*) pair where *type* is a string. If there are no more chunks, ``None`` is returned. """ x = self.file.read(8) if not x: return None if len(x) != 8: raise FormatError( 'End of file whilst reading chunk length and type.') length, type = struct.unpack('!I4s', x) if length > 2 ** 31 - 1: raise FormatError('Chunk %s is too large: %d.' % (type, length)) return length, type def process_chunk(self, lenient=False): """Process the next chunk and its data. This only processes the following chunk types, all others are ignored: ``IHDR``, ``PLTE``, ``bKGD``, ``tRNS``, ``gAMA``, ``sBIT``, ``pHYs``. If the optional `lenient` argument evaluates to `True`, checksum failures will raise warnings rather than exceptions. """ type, data = self.chunk(lenient=lenient) method = '_process_' + as_str(type) m = getattr(self, method, None) if m: m(data) def _process_IHDR(self, data): # http://www.w3.org/TR/PNG/#11IHDR if len(data) != 13: raise FormatError('IHDR chunk has incorrect length.') (self.width, self.height, self.bitdepth, self.color_type, self.compression, self.filter, self.interlace) = struct.unpack("!2I5B", data) check_bitdepth_colortype(self.bitdepth, self.color_type) if self.compression != 0: raise Error("unknown compression method %d" % self.compression) if self.filter != 0: raise FormatError("Unknown filter method %d," " see http://www.w3.org/TR/2003/REC-PNG-20031110/#9Filters ." % self.filter) if self.interlace not in (0, 1): raise FormatError("Unknown interlace method %d," " see http://www.w3.org/TR/2003/REC-PNG-20031110/#8InterlaceMethods ." % self.interlace) # Derived values # http://www.w3.org/TR/PNG/#6Colour-values colormap = bool(self.color_type & 1) greyscale = not (self.color_type & 2) alpha = bool(self.color_type & 4) color_planes = (3, 1)[greyscale or colormap] planes = color_planes + alpha self.colormap = colormap self.greyscale = greyscale self.alpha = alpha self.color_planes = color_planes self.planes = planes self.psize = float(self.bitdepth) / float(8) * planes if int(self.psize) == self.psize: self.psize = int(self.psize) self.row_bytes = int(math.ceil(self.width * self.psize)) # Stores PLTE chunk if present, and is used to check # chunk ordering constraints. self.plte = None # Stores tRNS chunk if present, and is used to check chunk # ordering constraints. self.trns = None # Stores sbit chunk if present. self.sbit = None def _process_PLTE(self, data): # http://www.w3.org/TR/PNG/#11PLTE if self.plte: warnings.warn("Multiple PLTE chunks present.") self.plte = data if len(data) % 3 != 0: raise FormatError( "PLTE chunk's length should be a multiple of 3.") if len(data) > (2 ** self.bitdepth) * 3: raise FormatError("PLTE chunk is too long.") if len(data) == 0: raise FormatError("Empty PLTE is not allowed.") def _process_bKGD(self, data): try: if self.colormap: if not self.plte: warnings.warn( "PLTE chunk is required before bKGD chunk.") self.background = struct.unpack('B', data) else: self.background = struct.unpack("!%dH" % self.color_planes, data) except struct.error: raise FormatError("bKGD chunk has incorrect length.") def _process_tRNS(self, data): # http://www.w3.org/TR/PNG/#11tRNS self.trns = data if self.colormap: if not self.plte: warnings.warn("PLTE chunk is required before tRNS chunk.") else: if len(data) > len(self.plte) / 3: # Was warning, but promoted to Error as it # would otherwise cause pain later on. raise FormatError("tRNS chunk is too long.") else: if self.alpha: raise FormatError( "tRNS chunk is not valid with colour type %d." % self.color_type) try: self.transparent = \ struct.unpack("!%dH" % self.color_planes, data) except struct.error: raise FormatError("tRNS chunk has incorrect length.") def _process_gAMA(self, data): try: self.gamma = struct.unpack("!L", data)[0] / 100000.0 except struct.error: raise FormatError("gAMA chunk has incorrect length.") def _process_sBIT(self, data): self.sbit = data if (self.colormap and len(data) != 3 or not self.colormap and len(data) != self.planes): raise FormatError("sBIT chunk has incorrect length.") def _process_pHYs(self, data): # http://www.w3.org/TR/PNG/#11pHYs self.phys = data fmt = "!LLB" if len(data) != struct.calcsize(fmt): raise FormatError("pHYs chunk has incorrect length.") self.x_pixels_per_unit, self.y_pixels_per_unit, unit = struct.unpack(fmt, data) self.unit_is_meter = bool(unit) def read(self, lenient=False): """ Read the PNG file and decode it. Returns (`width`, `height`, `pixels`, `metadata`). May use excessive memory. `pixels` are returned in boxed row flat pixel format. If the optional `lenient` argument evaluates to True, checksum failures will raise warnings rather than exceptions. """ def iteridat(): """Iterator that yields all the ``IDAT`` chunks as strings.""" while True: try: type, data = self.chunk(lenient=lenient) except ValueError as e: raise ChunkError(e.args[0]) if type == b'IEND': # http://www.w3.org/TR/PNG/#11IEND break if type != b'IDAT': continue # type == b'IDAT' # http://www.w3.org/TR/PNG/#11IDAT if self.colormap and not self.plte: warnings.warn("PLTE chunk is required before IDAT chunk") yield data def iterdecomp(idat): """Iterator that yields decompressed strings. `idat` should be an iterator that yields the ``IDAT`` chunk data. """ # Currently, with no max_length parameter to decompress, # this routine will do one yield per IDAT chunk: Not very # incremental. d = zlib.decompressobj() # Each IDAT chunk is passed to the decompressor, then any # remaining state is decompressed out. for data in idat: # :todo: add a max_length argument here to limit output # size. yield array('B', d.decompress(data)) yield array('B', d.flush()) self.preamble(lenient=lenient) raw = iterdecomp(iteridat()) if self.interlace: raw = array('B', itertools.chain(*raw)) arraycode = 'BH'[self.bitdepth > 8] # Like :meth:`group` but producing an array.array object for # each row. pixels = map(lambda *row: array(arraycode, row), *[iter(self.deinterlace(raw))] * self.width * self.planes) else: pixels = self.iterboxed(self.iterstraight(raw)) meta = dict() for attr in 'greyscale alpha planes bitdepth interlace'.split(): meta[attr] = getattr(self, attr) meta['size'] = (self.width, self.height) for attr in 'gamma transparent background'.split(): a = getattr(self, attr, None) if a is not None: meta[attr] = a if self.plte: meta['palette'] = self.palette() return self.width, self.height, pixels, meta def read_flat(self): """ Read a PNG file and decode it into flat row flat pixel format. Returns (*width*, *height*, *pixels*, *metadata*). May use excessive memory. `pixels` are returned in flat row flat pixel format. See also the :meth:`read` method which returns pixels in the more stream-friendly boxed row flat pixel format. """ x, y, pixel, meta = self.read() arraycode = 'BH'[meta['bitdepth'] > 8] pixel = array(arraycode, itertools.chain(*pixel)) return x, y, pixel, meta def palette(self, alpha='natural'): """Returns a palette that is a sequence of 3-tuples or 4-tuples, synthesizing it from the ``PLTE`` and ``tRNS`` chunks. These chunks should have already been processed (for example, by calling the :meth:`preamble` method). All the tuples are the same size: 3-tuples if there is no ``tRNS`` chunk, 4-tuples when there is a ``tRNS`` chunk. Assumes that the image is colour type 3 and therefore a ``PLTE`` chunk is required. If the `alpha` argument is ``'force'`` then an alpha channel is always added, forcing the result to be a sequence of 4-tuples. """ if not self.plte: raise FormatError( "Required PLTE chunk is missing in colour type 3 image.") plte = group(array('B', self.plte), 3) if self.trns or alpha == 'force': trns = array('B', self.trns or []) trns.extend([255] * (len(plte) - len(trns))) plte = list(map(operator.add, plte, group(trns, 1))) return plte def asDirect(self): """Returns the image data as a direct representation of an ``x * y * planes`` array. This method is intended to remove the need for callers to deal with palettes and transparency themselves. Images with a palette (colour type 3) are converted to RGB or RGBA; images with transparency (a ``tRNS`` chunk) are converted to LA or RGBA as appropriate. When returned in this format the pixel values represent the colour value directly without needing to refer to palettes or transparency information. Like the :meth:`read` method this method returns a 4-tuple: (*width*, *height*, *pixels*, *meta*) This method normally returns pixel values with the bit depth they have in the source image, but when the source PNG has an ``sBIT`` chunk it is inspected and can reduce the bit depth of the result pixels; pixel values will be reduced according to the bit depth specified in the ``sBIT`` chunk (PNG nerds should note a single result bit depth is used for all channels; the maximum of the ones specified in the ``sBIT`` chunk. An RGB565 image will be rescaled to 6-bit RGB666). The *meta* dictionary that is returned reflects the `direct` format and not the original source image. For example, an RGB source image with a ``tRNS`` chunk to represent a transparent colour, will have ``planes=3`` and ``alpha=False`` for the source image, but the *meta* dictionary returned by this method will have ``planes=4`` and ``alpha=True`` because an alpha channel is synthesized and added. *pixels* is the pixel data in boxed row flat pixel format (just like the :meth:`read` method). All the other aspects of the image data are not changed. """ self.preamble() # Simple case, no conversion necessary. if not self.colormap and not self.trns and not self.sbit: return self.read() x, y, pixels, meta = self.read() if self.colormap: meta['colormap'] = False meta['alpha'] = bool(self.trns) meta['bitdepth'] = 8 meta['planes'] = 3 + bool(self.trns) plte = self.palette() def iterpal(pixels): for row in pixels: row = [plte[x] for x in row] yield array('B', itertools.chain(*row)) pixels = iterpal(pixels) elif self.trns: # It would be nice if there was some reasonable way # of doing this without generating a whole load of # intermediate tuples. But tuples does seem like the # easiest way, with no other way clearly much simpler or # much faster. (Actually, the L to LA conversion could # perhaps go faster (all those 1-tuples!), but I still # wonder whether the code proliferation is worth it) it = self.transparent maxval = 2 ** meta['bitdepth'] - 1 planes = meta['planes'] meta['alpha'] = True meta['planes'] += 1 typecode = 'BH'[meta['bitdepth'] > 8] def itertrns(pixels): for row in pixels: # For each row we group it into pixels, then form a # characterisation vector that says whether each # pixel is opaque or not. Then we convert # True/False to 0/maxval (by multiplication), # and add it as the extra channel. row = group(row, planes) opa = map(it.__ne__, row) opa = map(maxval.__mul__, opa) opa = list(zip(opa)) # convert to 1-tuples yield array(typecode, itertools.chain(*map(operator.add, row, opa))) pixels = itertrns(pixels) targetbitdepth = None if self.sbit: sbit = struct.unpack('%dB' % len(self.sbit), self.sbit) targetbitdepth = max(sbit) if targetbitdepth > meta['bitdepth']: raise Error('sBIT chunk %r exceeds bitdepth %d' % (sbit, self.bitdepth)) if min(sbit) <= 0: raise Error('sBIT chunk %r has a 0-entry' % sbit) if targetbitdepth == meta['bitdepth']: targetbitdepth = None if targetbitdepth: shift = meta['bitdepth'] - targetbitdepth meta['bitdepth'] = targetbitdepth def itershift(pixels): for row in pixels: yield [p >> shift for p in row] pixels = itershift(pixels) return x, y, pixels, meta def asFloat(self, maxval=1.0): """Return image pixels as per :meth:`asDirect` method, but scale all pixel values to be floating point values between 0.0 and *maxval*. """ x, y, pixels, info = self.asDirect() sourcemaxval = 2 ** info['bitdepth'] - 1 del info['bitdepth'] info['maxval'] = float(maxval) factor = float(maxval) / float(sourcemaxval) def iterfloat(): for row in pixels: yield [factor * p for p in row] return x, y, iterfloat(), info def _as_rescale(self, get, targetbitdepth): """Helper used by :meth:`asRGB8` and :meth:`asRGBA8`.""" width, height, pixels, meta = get() maxval = 2 ** meta['bitdepth'] - 1 targetmaxval = 2 ** targetbitdepth - 1 factor = float(targetmaxval) / float(maxval) meta['bitdepth'] = targetbitdepth def iterscale(): for row in pixels: yield [int(round(x * factor)) for x in row] if maxval == targetmaxval: return width, height, pixels, meta else: return width, height, iterscale(), meta def asRGB8(self): """Return the image data as an RGB pixels with 8-bits per sample. This is like the :meth:`asRGB` method except that this method additionally rescales the values so that they are all between 0 and 255 (8-bit). In the case where the source image has a bit depth < 8 the transformation preserves all the information; where the source image has bit depth > 8, then rescaling to 8-bit values loses precision. No dithering is performed. Like :meth:`asRGB`, an alpha channel in the source image will raise an exception. This function returns a 4-tuple: (*width*, *height*, *pixels*, *metadata*). *width*, *height*, *metadata* are as per the :meth:`read` method. *pixels* is the pixel data in boxed row flat pixel format. """ return self._as_rescale(self.asRGB, 8) def asRGBA8(self): """Return the image data as RGBA pixels with 8-bits per sample. This method is similar to :meth:`asRGB8` and :meth:`asRGBA`: The result pixels have an alpha channel, *and* values are rescaled to the range 0 to 255. The alpha channel is synthesized if necessary (with a small speed penalty). """ return self._as_rescale(self.asRGBA, 8) def asRGB(self): """Return image as RGB pixels. RGB colour images are passed through unchanged; greyscales are expanded into RGB triplets (there is a small speed overhead for doing this). An alpha channel in the source image will raise an exception. The return values are as for the :meth:`read` method except that the *metadata* reflect the returned pixels, not the source image. In particular, for this method ``metadata['greyscale']`` will be ``False``. """ width, height, pixels, meta = self.asDirect() if meta['alpha']: raise Error("will not convert image with alpha channel to RGB") if not meta['greyscale']: return width, height, pixels, meta meta['greyscale'] = False typecode = 'BH'[meta['bitdepth'] > 8] def iterrgb(): for row in pixels: a = array(typecode, [0]) * 3 * width for i in range(3): a[i::3] = row yield a return width, height, iterrgb(), meta def asRGBA(self): """Return image as RGBA pixels. Greyscales are expanded into RGB triplets; an alpha channel is synthesized if necessary. The return values are as for the :meth:`read` method except that the *metadata* reflect the returned pixels, not the source image. In particular, for this method ``metadata['greyscale']`` will be ``False``, and ``metadata['alpha']`` will be ``True``. """ width, height, pixels, meta = self.asDirect() if meta['alpha'] and not meta['greyscale']: return width, height, pixels, meta typecode = 'BH'[meta['bitdepth'] > 8] maxval = 2 ** meta['bitdepth'] - 1 maxbuffer = struct.pack('=' + typecode, maxval) * 4 * width def newarray(): return array(typecode, maxbuffer) if meta['alpha'] and meta['greyscale']: # LA to RGBA def convert(): for row in pixels: # Create a fresh target row, then copy L channel # into first three target channels, and A channel # into fourth channel. a = newarray() pngfilters.convert_la_to_rgba(row, a) yield a elif meta['greyscale']: # L to RGBA def convert(): for row in pixels: a = newarray() pngfilters.convert_l_to_rgba(row, a) yield a else: assert not meta['alpha'] and not meta['greyscale'] # RGB to RGBA def convert(): for row in pixels: a = newarray() pngfilters.convert_rgb_to_rgba(row, a) yield a meta['alpha'] = True meta['greyscale'] = False return width, height, convert(), meta def check_bitdepth_colortype(bitdepth, colortype): """Check that `bitdepth` and `colortype` are both valid, and specified in a valid combination. Returns if valid, raise an Exception if not valid. """ if bitdepth not in (1, 2, 4, 8, 16): raise FormatError("invalid bit depth %d" % bitdepth) if colortype not in (0, 2, 3, 4, 6): raise FormatError("invalid colour type %d" % colortype) # Check indexed (palettized) images have 8 or fewer bits # per pixel; check only indexed or greyscale images have # fewer than 8 bits per pixel. if colortype & 1 and bitdepth > 8: raise FormatError( "Indexed images (colour type %d) cannot" " have bitdepth > 8 (bit depth %d)." " See http://www.w3.org/TR/2003/REC-PNG-20031110/#table111 ." % (bitdepth, colortype)) if bitdepth < 8 and colortype not in (0, 3): raise FormatError("Illegal combination of bit depth (%d)" " and colour type (%d)." " See http://www.w3.org/TR/2003/REC-PNG-20031110/#table111 ." % (bitdepth, colortype)) def isinteger(x): try: return int(x) == x except (TypeError, ValueError): return False # === Support for users without Cython === try: pngfilters except NameError: class pngfilters(object): def undo_filter_sub(filter_unit, scanline, previous, result): """Undo sub filter.""" ai = 0 # Loops starts at index fu. Observe that the initial part # of the result is already filled in correctly with # scanline. for i in range(filter_unit, len(result)): x = scanline[i] a = result[ai] result[i] = (x + a) & 0xff ai += 1 undo_filter_sub = staticmethod(undo_filter_sub) def undo_filter_up(filter_unit, scanline, previous, result): """Undo up filter.""" for i in range(len(result)): x = scanline[i] b = previous[i] result[i] = (x + b) & 0xff undo_filter_up = staticmethod(undo_filter_up) def undo_filter_average(filter_unit, scanline, previous, result): """Undo up filter.""" ai = -filter_unit for i in range(len(result)): x = scanline[i] if ai < 0: a = 0 else: a = result[ai] b = previous[i] result[i] = (x + ((a + b) >> 1)) & 0xff ai += 1 undo_filter_average = staticmethod(undo_filter_average) def undo_filter_paeth(filter_unit, scanline, previous, result): """Undo Paeth filter.""" # Also used for ci. ai = -filter_unit for i in range(len(result)): x = scanline[i] if ai < 0: a = c = 0 else: a = result[ai] c = previous[ai] b = previous[i] p = a + b - c pa = abs(p - a) pb = abs(p - b) pc = abs(p - c) if pa <= pb and pa <= pc: pr = a elif pb <= pc: pr = b else: pr = c result[i] = (x + pr) & 0xff ai += 1 undo_filter_paeth = staticmethod(undo_filter_paeth) def convert_la_to_rgba(row, result): for i in range(3): result[i::4] = row[0::2] result[3::4] = row[1::2] convert_la_to_rgba = staticmethod(convert_la_to_rgba) def convert_l_to_rgba(row, result): """Convert a grayscale image to RGBA. This method assumes the alpha channel in result is already correctly initialized. """ for i in range(3): result[i::4] = row convert_l_to_rgba = staticmethod(convert_l_to_rgba) def convert_rgb_to_rgba(row, result): """Convert an RGB image to RGBA. This method assumes the alpha channel in result is already correctly initialized. """ for i in range(3): result[i::4] = row[i::3] convert_rgb_to_rgba = staticmethod(convert_rgb_to_rgba) # === Command Line Support === def read_pam_header(infile): """ Read (the rest of a) PAM header. `infile` should be positioned immediately after the initial 'P7' line (at the beginning of the second line). Returns are as for `read_pnm_header`. """ # Unlike PBM, PGM, and PPM, we can read the header a line at a time. header = dict() while True: l = infile.readline().strip() if l == b'ENDHDR': break if not l: raise EOFError('PAM ended prematurely') if l[0] == b'#': continue l = l.split(None, 1) if l[0] not in header: header[l[0]] = l[1] else: header[l[0]] += b' ' + l[1] required = [b'WIDTH', b'HEIGHT', b'DEPTH', b'MAXVAL'] WIDTH, HEIGHT, DEPTH, MAXVAL = required present = [x for x in required if x in header] if len(present) != len(required): raise Error('PAM file must specify WIDTH, HEIGHT, DEPTH, and MAXVAL') width = int(header[WIDTH]) height = int(header[HEIGHT]) depth = int(header[DEPTH]) maxval = int(header[MAXVAL]) if (width <= 0 or height <= 0 or depth <= 0 or maxval <= 0): raise Error( 'WIDTH, HEIGHT, DEPTH, MAXVAL must all be positive integers') return 'P7', width, height, depth, maxval def read_pnm_header(infile, supported=(b'P5', b'P6')): """ Read a PNM header, returning (format,width,height,depth,maxval). `width` and `height` are in pixels. `depth` is the number of channels in the image; for PBM and PGM it is synthesized as 1, for PPM as 3; for PAM images it is read from the header. `maxval` is synthesized (as 1) for PBM images. """ # Generally, see http://netpbm.sourceforge.net/doc/ppm.html # and http://netpbm.sourceforge.net/doc/pam.html # Technically 'P7' must be followed by a newline, so by using # rstrip() we are being liberal in what we accept. I think this # is acceptable. type = infile.read(3).rstrip() if type not in supported: raise NotImplementedError('file format %s not supported' % type) if type == b'P7': # PAM header parsing is completely different. return read_pam_header(infile) # Expected number of tokens in header (3 for P4, 4 for P6) expected = 4 pbm = (b'P1', b'P4') if type in pbm: expected = 3 header = [type] # We have to read the rest of the header byte by byte because the # final whitespace character (immediately following the MAXVAL in # the case of P6) may not be a newline. Of course all PNM files in # the wild use a newline at this point, so it's tempting to use # readline; but it would be wrong. def getc(): c = infile.read(1) if not c: raise Error('premature EOF reading PNM header') return c c = getc() while True: # Skip whitespace that precedes a token. while c.isspace(): c = getc() # Skip comments. while c == '#': while c not in b'\n\r': c = getc() if not c.isdigit(): raise Error('unexpected character %s found in header' % c) # According to the specification it is legal to have comments # that appear in the middle of a token. # This is bonkers; I've never seen it; and it's a bit awkward to # code good lexers in Python (no goto). So we break on such # cases. token = b'' while c.isdigit(): token += c c = getc() # Slight hack. All "tokens" are decimal integers, so convert # them here. header.append(int(token)) if len(header) == expected: break # Skip comments (again) while c == '#': while c not in '\n\r': c = getc() if not c.isspace(): raise Error('expected header to end with whitespace, not %s' % c) if type in pbm: # synthesize a MAXVAL header.append(1) depth = (1, 3)[type == b'P6'] return header[0], header[1], header[2], depth, header[3] def write_pnm(file, width, height, pixels, meta): """Write a Netpbm PNM/PAM file. """ bitdepth = meta['bitdepth'] maxval = 2 ** bitdepth - 1 # Rudely, the number of image planes can be used to determine # whether we are L (PGM), LA (PAM), RGB (PPM), or RGBA (PAM). planes = meta['planes'] # Can be an assert as long as we assume that pixels and meta came # from a PNG file. assert planes in (1, 2, 3, 4) if planes in (1, 3): if 1 == planes: # PGM # Could generate PBM if maxval is 1, but we don't (for one # thing, we'd have to convert the data, not just blat it # out). fmt = 'P5' else: # PPM fmt = 'P6' header = '%s %d %d %d\n' % (fmt, width, height, maxval) if planes in (2, 4): # PAM # See http://netpbm.sourceforge.net/doc/pam.html if 2 == planes: tupltype = 'GRAYSCALE_ALPHA' else: tupltype = 'RGB_ALPHA' header = ('P7\nWIDTH %d\nHEIGHT %d\nDEPTH %d\nMAXVAL %d\n' 'TUPLTYPE %s\nENDHDR\n' % (width, height, planes, maxval, tupltype)) file.write(header.encode('ascii')) # Values per row vpr = planes * width # struct format fmt = '>%d' % vpr if maxval > 0xff: fmt = fmt + 'H' else: fmt = fmt + 'B' for row in pixels: file.write(struct.pack(fmt, *row)) file.flush() def color_triple(color): """ Convert a command line colour value to a RGB triple of integers. FIXME: Somewhere we need support for greyscale backgrounds etc. """ if color.startswith('#') and len(color) == 4: return (int(color[1], 16), int(color[2], 16), int(color[3], 16)) if color.startswith('#') and len(color) == 7: return (int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16)) elif color.startswith('#') and len(color) == 13: return (int(color[1:5], 16), int(color[5:9], 16), int(color[9:13], 16)) def _add_common_options(parser): """Call *parser.add_option* for each of the options that are common between this PNG--PNM conversion tool and the gen tool. """ parser.add_option("-i", "--interlace", default=False, action="store_true", help="create an interlaced PNG file (Adam7)") parser.add_option("-t", "--transparent", action="store", type="string", metavar="#RRGGBB", help="mark the specified colour as transparent") parser.add_option("-b", "--background", action="store", type="string", metavar="#RRGGBB", help="save the specified background colour") parser.add_option("-g", "--gamma", action="store", type="float", metavar="value", help="save the specified gamma value") parser.add_option("-c", "--compression", action="store", type="int", metavar="level", help="zlib compression level (0-9)") return parser def _main(argv): """ Run the PNG encoder with options from the command line. """ # Parse command line arguments from optparse import OptionParser version = '%prog ' + __version__ parser = OptionParser(version=version) parser.set_usage("%prog [options] [imagefile]") parser.add_option('-r', '--read-png', default=False, action='store_true', help='Read PNG, write PNM') parser.add_option("-a", "--alpha", action="store", type="string", metavar="pgmfile", help="alpha channel transparency (RGBA)") _add_common_options(parser) (options, args) = parser.parse_args(args=argv[1:]) # Convert options if options.transparent is not None: options.transparent = color_triple(options.transparent) if options.background is not None: options.background = color_triple(options.background) # Prepare input and output files if len(args) == 0: infilename = '-' infile = sys.stdin elif len(args) == 1: infilename = args[0] infile = open(infilename, 'rb') else: parser.error("more than one input file") outfile = sys.stdout if sys.platform == "win32": import msvcrt, os msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) if options.read_png: # Encode PNG to PPM png = Reader(file=infile) width, height, pixels, meta = png.asDirect() write_pnm(outfile, width, height, pixels, meta) else: # Encode PNM to PNG format, width, height, depth, maxval = \ read_pnm_header(infile, (b'P5', b'P6', b'P7')) # When it comes to the variety of input formats, we do something # rather rude. Observe that L, LA, RGB, RGBA are the 4 colour # types supported by PNG and that they correspond to 1, 2, 3, 4 # channels respectively. So we use the number of channels in # the source image to determine which one we have. We do not # care about TUPLTYPE. greyscale = depth <= 2 pamalpha = depth in (2, 4) supported = [2 ** x - 1 for x in range(1, 17)] try: mi = supported.index(maxval) except ValueError: raise NotImplementedError( 'your maxval (%s) not in supported list %s' % (maxval, str(supported))) bitdepth = mi + 1 writer = Writer(width, height, greyscale=greyscale, bitdepth=bitdepth, interlace=options.interlace, transparent=options.transparent, background=options.background, alpha=bool(pamalpha or options.alpha), gamma=options.gamma, compression=options.compression) if options.alpha: pgmfile = open(options.alpha, 'rb') format, awidth, aheight, adepth, amaxval = \ read_pnm_header(pgmfile, 'P5') if amaxval != '255': raise NotImplementedError( 'maxval %s not supported for alpha channel' % amaxval) if (awidth, aheight) != (width, height): raise ValueError("alpha channel image size mismatch" " (%s has %sx%s but %s has %sx%s)" % (infilename, width, height, options.alpha, awidth, aheight)) writer.convert_ppm_and_pgm(infile, pgmfile, outfile) else: writer.convert_pnm(infile, outfile) if __name__ == '__main__': try: _main(sys.argv) except Error as e: print(e, file=sys.stderr)
101,130
36.400518
100
py
MCEdit-Unified
MCEdit-Unified-master/resource_packs.py
# -*- coding: utf-8 -*- #!# If the comman line parameter '--debug-packs' is given, the logging level is set to debug. #!# Otherwise, it is set to critical. from PIL import Image import zipfile import directories import os import shutil from config import config from cStringIO import StringIO import locale import traceback from utilities.misc import Singleton DEF_ENC = locale.getdefaultlocale()[1] if DEF_ENC is None: DEF_ENC = "UTF-8" try: import resource # @UnresolvedImport resource.setrlimit(resource.RLIMIT_NOFILE, (500,-1)) except: pass #!# Debugging .zip resource pack not loaded bug. import logging level = 50 if '--debug-packs' in os.sys.argv: level = 10 log = logging.getLogger(__name__) log.setLevel(level) #!# def step(slot): ''' Utility method for multiplying the slot by 16 :param slot: Texture slot :type slot: int ''' return slot << 4 ''' Empty comment lines like: # are for texture spaces that I don't know what should go there ''' textureSlots = { # Start Top Row "grass_top": (step(0),step(0)), "stone": (step(1),step(0)), "dirt": (step(2),step(0)), "grass_side": (step(3),step(0)), "planks_oak": (step(4),step(0)), "stone_slab_side": (step(5),step(0)), "stone_slab_top": (step(6),step(0)), "brick": (step(7),step(0)), "tnt_side": (step(8),step(0)), "tnt_top": (step(9),step(0)), "tnt_bottom": (step(10),step(0)), "web": (step(11),step(0)), "flower_rose": (step(12),step(0)), "flower_dandelion": (step(13),step(0)), # "sapling_oak": (step(15),step(0)), "flower_blue_orchid": (step(16),step(0)), "flower_allium": (step(17),step(0)), "flower_houstonia": (step(18),step(0)), "flower_tulip_red": (step(19),step(0)), "sapling_roofed_oak": (step(20),step(0)), # End Top Row # Start Second Row "cobblestone": (step(0),step(1)), "bedrock": (step(1),step(1)), "sand": (step(2),step(1)), "gravel": (step(3),step(1)), "log_oak": (step(4),step(1)), "log_oak_top": (step(5),step(1)), "iron_block": (step(6),step(1)), "gold_block": (step(7),step(1)), "diamond_block": (step(8),step(1)), "emerald_block": (step(9),step(1)), # "red_sand": (step(11),step(1)), "mushroom_red": (step(12),step(1)), "mushroom_brown": (step(13),step(1)), "sapling_jungle": (step(14),step(1)), "fire_layer_0": (step(15),step(1)), "flower_tulip_orange": (step(16),step(1)), "flower_tulip_white": (step(17),step(1)), "flower_tulip_pink": (step(18),step(1)), "flower_oxeye_daisy": (step(19),step(1)), "sapling_acacia": (step(20),step(1)), # End Second Row # Start Third Row "gold_ore": (step(0),step(2)), "iron_ore": (step(1),step(2)), "coal_ore": (step(2),step(2)), "bookshelf": (step(3),step(2)), "cobblestone_mossy": (step(4),step(2)), "obsidian": (step(5),step(2)), # "tallgrass": (step(7),step(2)), # "beacon": (step(9),step(2)), "dropper_front_horizontal": (step(10),step(2)), "crafting_table_top": (step(11),step(2)), "furnace_front_off": (step(12),step(2)), "furnace_side": (step(13),step(2)), "dispenser_front_horizontal": (step(14),step(2)), "fire_layer_1": (step(15),step(2)), # # # # "daylight_detector_side": (step(20),step(2)), # End Third Row # Start Fourth Row "sponge": (step(0), step(3)), "glass": (step(1), step(3)), "diamond_ore": (step(2), step(3)), "redstone_ore": (step(3), step(3)), # # "stonebrick": (step(6), step(3)), "deadbush": (step(7), step(3)), "fern": (step(8), step(3)), "dirt_podzol_top": (step(9), step(3)), "dirt_podzol_side": (step(10), step(3)), "crafting_table_side": (step(11), step(3)), "crafting_table_front": (step(12), step(3)), "furnace_front_on": (step(13), step(3)), "furnace_top": (step(14), step(3)), "sapling_spruce": (step(15), step(3)), # # # # # End Fourth Row # Start Fifth Row "wool_colored_white": (step(0), step(4)), "mob_spawner": (step(1), step(4)), "snow": (step(2), step(4)), "ice": (step(3), step(4)), "grass_side_snowed": (step(4), step(4)), "cactus_top": (step(5), step(4)), "cactus_side": (step(6), step(4)), "cactus_bottom": (step(7), step(4)), "clay": (step(8), step(4)), "reeds": (step(9), step(4)), "jukebox_side": (step(10), step(4)), "jukebox_top": (step(11), step(4)), "waterlily": (step(12), step(4)), "mycelium_side": (step(13), step(4)), "mycelium_top": (step(14), step(4)), "sapling_birch": (step(15), step(4)), # # "dropper_front_vertical": (step(18), step(4)), "daylight_detector_inverted_top": (step(19), step(4)), # End Fifth Row # Start Sixth Row "torch_on": (step(0), step(5)), "door_wood_upper": (step(1), step(5)), "door_iron_upper": (step(2), step(5)), "ladder": (step(3), step(5)), "trapdoor": (step(4), step(5)), "iron_bars": (step(5), step(5)), "farmland_wet": (step(6), step(5)), "farmland_dry": (step(7), step(5)), "wheat_stage_0": (step(8), step(5)), "wheat_stage_1": (step(9), step(5)), "wheat_stage_2": (step(10), step(5)), "wheat_stage_3": (step(11), step(5)), "wheat_stage_4": (step(12), step(5)), "wheat_stage_5": (step(13), step(5)), "wheat_stage_6": (step(14), step(5)), "wheat_stage_7": (step(15), step(5)), # # "dispenser_front_vertical": (step(18), step(5)), # # End Sixth Row # Start Seventh Row "lever": (step(0), step(6)), "door_wood_lower": (step(1), step(6)), "door_iron_lower": (step(2), step(6)), "redstone_torch_on": (step(3), step(6)), "stonebrick_mossy": (step(4), step(6)), "stonebrick_cracked": (step(5), step(6)), "pumpkin_top": (step(6), step(6)), "netherrack": (step(7), step(6)), "soul_sand": (step(8), step(6)), "glowstone": (step(9), step(6)), "piston_top_sticky": (step(10), step(6)), "piston_top_normal": (step(11), step(6)), "piston_side": (step(12), step(6)), "piston_bottom": (step(13), step(6)), "piston_inner": (step(14), step(6)), "pumpkin_stem_disconnected": (step(15), step(6)), # # # # End Seventh Row # Start Eigth Row "rail_normal_turned": (step(0),step(7)), "wool_colored_black": (step(1),step(7)), "wool_colored_gray": (step(2),step(7)), "redstone_torch_off": (step(3),step(7)), "log_spruce": (step(4),step(7)), "log_birch": (step(5),step(7)), "pumpkin_side": (step(6),step(7)), "pumpkin_face_off": (step(7),step(7)), "pumpkin_face_on": (step(8),step(7)), "cake_top": (step(9),step(7)), "cake_side": (step(10),step(7)), "cake_inner": (step(11),step(7)), "cake_bottom": (step(12),step(7)), "mushroom_block_skin_red": (step(13),step(7)), "mushroom_block_skin_brown": (step(14),step(7)), "pumpkin_stem_connected": (step(15),step(7)), # # "repeater_off_west": (step(18),step(7)), # # End Eigth Row # Start Ninth Row "rail_normal": (step(0),step(8)), "wool_colored_red": (step(1),step(8)), "wool_colored_magenta": (step(2),step(8)), "repeater_off_south": (step(3),step(8)), "leaves_spruce": (step(4),step(8)), # "bed_feet_top": (step(6),step(8)), "bed_head_top": (step(7),step(8)), "melon_side": (step(8),step(8)), "melon_top": (step(9),step(8)), # # # "mushroom_block_skin_stem": (step(13),step(8)), "mushroom_block_inside": (step(14),step(8)), "vine": (step(15),step(8)), # # "repeater_off_north": (step(18),step(8)), # # End Ninth Row # Start Tenth Row "lapis_block": (step(0),step(9)), "wool_colored_green": (step(1),step(9)), "wool_colored_lime": (step(2),step(9)), "repeater_on_south": (step(3),step(9)), # "bed_feet_end": (step(5),step(9)), "bed_feet_side": (step(6),step(9)), "bed_head_side": (step(7),step(9)), "bed_head_end": (step(8),step(9)), "log_jungle": (step(9),step(9)), "cauldron_side": (step(10),step(9)), "cauldron_bottom": (step(11),step(9)), "brewing_stand_base": (step(12),step(9)), "brewing_stand": (step(13),step(9)), "endframe_top": (step(14),step(9)), "endframe_side": (step(15),step(9)), "double_plant_sunflower_bottom": (step(16),step(9)), # "repeater_off_east": (step(18),step(9)), "structure_block_data": (step(19),step(9)), "structure_block_corner": (step(20),step(9)), # End Tenth Row # Start Eleventh Row "lapis_ore": (step(0),step(10)), "wool_colored_brown": (step(1),step(10)), "wool_colored_yellow": (step(2),step(10)), "rail_golden": (step(3),step(10)), "redstone_dust_cross": (step(4),step(10)), # "enchanting_table_top": (step(6),step(10)), "dragon_egg": (step(7),step(10)), "cocoa_stage_2": (step(8),step(10)), "cocoa_stage_1": (step(9),step(10)), "cocoa_stage_0": (step(10),step(10)), "emerald_ore": (step(11),step(10)), "trip_wire_source": (step(12),step(10)), "trip_wire": (step(13),step(10)), "endframe_eye": (step(14),step(10)), "end_stone": (step(15),step(10)), "double_plant_syringa_bottom": (step(16),step(10)), "double_plant_syringa_top": (step(17),step(10)), "repeater_on_west": (step(18),step(10)), "structure_block_save": (step(19),step(10)), "structure_block_load": (step(20),step(10)), # End Eleventh Row # Start Twelfth Row "sandstone_top": (step(0),step(11)), "wool_colored_blue": (step(1),step(11)), "wool_colored_light_blue": (step(2),step(11)), "rail_golden_powered": (step(3),step(11)), # "redstone_dust_line": (step(5),step(11)), "enchanting_table_side": (step(6),step(11)), "enchanting_table_bottom": (step(7),step(11)), "command_block": (step(8),step(11)), "itemframe_backround": (step(9),step(11)), "flower_pot": (step(10),step(11)), "comparator_off_south": (step(11),step(11)), "comparator_on_south": (step(12),step(11)), "daylight_detector_top": (step(13),step(11)), "redstone_block": (step(14),step(11)), "quartz_ore": (step(15),step(11)), "double_plant_grass_bottom": (step(16),step(11)), "double_plant_grass_top": (step(17),step(11)), "repeater_on_north": (step(18),step(11)), "command_block_back": (step(19),step(11)), "command_block_conditional": (step(20),step(11)), "command_block_front": (step(21),step(11)), "command_block_side": (step(22),step(11)), "bone_block_top": (step(19),step(11)), # End Twelfth Row # Start Thriteenth Row "sandstone_normal": (step(0),step(12)), "wool_colored_purple": (step(1),step(12)), "wool_colored_pink": (step(2),step(12)), "rail_detector": (step(3),step(12)), "leaves_jungle": (step(4),step(12)), # "planks_spruce": (step(6),step(12)), "planks_jungle": (step(7),step(12)), "carrots_stage_0": (step(8),step(12)), "carrots_stage_1": (step(9),step(12)), "carrots_stage_2": (step(10),step(12)), "carrots_stage_3": (step(11),step(12)), "potatoes_stage_3": (step(12),step(12)), # "piston_right": (step(14),step(12)), "piston_down": (step(15),step(12)), "double_plant_fern_bottom": (step(16),step(12)), "double_plant_fern_top": (step(17),step(12)), "repeater_on_east": (step(18),step(12)), "repeating_command_block_back": (step(19),step(12)), "repeating_command_block_conditional": (step(20),step(12)), "repeating_command_block_front": (step(21),step(12)), "repeating_command_block_side": (step(22),step(12)), "bone_block_side": (step(19),step(12)), # End Thriteenth Row # Start Fourteenth Row "sandstone_bottom": (step(0),step(13)), "wool_colored_cyan": (step(1),step(13)), "wool_colored_orange": (step(2),step(13)), "redstone_lamp_off": (step(3),step(13)), "redstone_lamp_on": (step(4),step(13)), "stonebrick_carved": (step(5),step(13)), "planks_birch": (step(6),step(13)), "anvil_base": (step(7),step(13)), "anvil_top_damaged_1": (step(8),step(13)), "quatrz_block_top": (step(9),step(13)), "rail_activator": (step(10),step(13)), "rail_activator_powered": (step(11),step(13)), "coal_block": (step(12),step(13)), "log_acacia_top": (step(13),step(13)), "piston_left": (step(14),step(13)), "magma": (step(18),step(13)), # "double_plant_rose_bottom": (step(16),step(13)), "double_plant_rose_top": (step(17),step(13)), "chain_command_block_back": (step(19),step(11)), "chain_command_block_conditional": (step(20),step(11)), "chain_command_block_front": (step(21),step(11)), "chain_command_block_side": (step(22),step(11)), # End Fourteenth Row # Start Fifteenth Row "nether_brick": (step(0),step(14)), "wool_colored_silver": (step(1),step(14)), "nether_wart_stage_0": (step(2),step(14)), "nether_wart_stage_1": (step(3),step(14)), "nether_wart_stage_2": (step(4),step(14)), "sandstone_carved": (step(5),step(14)), "sandstone_smooth": (step(6),step(14)), "anvil_top_damaged_0": (step(7),step(14)), "anvil_top_damaged_2": (step(8),step(14)), "log_spruce_top": (step(9),step(14)), "log_birch_top": (step(10),step(14)), "log_jungle_top": (step(11),step(14)), "log_big_oak_top": (step(12),step(14)), "lava_still": (step(13),step(14)), # # "double_plant_paeonia_bottom": (step(16),step(14)), "double_plant_paeonia_top": (step(17),step(14)), "nether_wart_block": (step(18),step(14)), # End Fifteenth Row # Start Sixteenth Row "planks_acacia": (step(0),step(15)), "planks_big_oak": (step(1),step(15)), # "log_acacia": (step(3),step(15)), "log_big_oak": (step(4),step(15)), "hardened_clay": (step(5),step(15)), "portal": (step(6),step(15)), # "quatrz_block_chiseled": (step(8),step(15)), "quartz_block_chiseled_top": (step(9),step(15)), "quartz_block_lines": (step(10),step(15)), "quartz_block_lines_top": (step(11),step(15)), # # # # # "slime": (step(17),step(15)), "red_nether_brick": (step(18),step(15)), # End Sixteenth Row # Start Seventeenth Row "ice_packed": (step(0),step(16)), "hay_block_side": (step(1),step(16)), "hay_block_top": (step(2),step(16)), "iron_trapdoor": (step(3),step(16)), "stone_granite": (step(4),step(16)), "stone_grantie_smooth": (step(5),step(16)), "stone_diorite": (step(6),step(16)), "stone_diorite_smooth": (step(7),step(16)), "stone_andesite": (step(8),step(16)), "stone_andesite_smooth": (step(9),step(16)), # # # # # # # # # "frosted_ice_0": (step(19), step(16)), # End Seventeenth Row # Start Eigteenth Row # # # # # # # # # # # # # # # # "prismarine_bricks": (step(16),step(17)), "prismarine_dark": (step(17),step(17)), "prismarine_rough": (step(18),step(17)), "purpur_pillar": (step(19),step(17)), # End Eigteenth Row # Start Ninteenth Row "hardened_clay_stained_white": (step(0),step(18)), "hardened_clay_stained_orange": (step(1),step(18)), "hardened_clay_stained_magenta": (step(2),step(18)), "hardened_clay_stained_light_blue": (step(3),step(18)), "hardened_clay_stained_yellow": (step(4),step(18)), "hardened_clay_stained_lime": (step(5),step(18)), "hardened_clay_stained_pink": (step(6),step(18)), "hardened_clay_stained_gray": (step(7),step(18)), "hardened_clay_stained_silver": (step(8),step(18)), "hardened_clay_stained_cyan": (step(9),step(18)), "hardened_clay_stained_purple": (step(10),step(18)), "hardened_clay_stained_blue": (step(11),step(18)), "hardened_clay_stained_brown": (step(12),step(18)), "hardened_clay_stained_green": (step(13),step(18)), "hardened_clay_stained_red": (step(14),step(18)), "hardened_clay_stained_black": (step(15),step(18)), "sponge_wet": (step(16),step(18)), "sea_lantern": (step(17),step(18)), "end_bricks": (step(18),step(18)), "purpur_pillar_top": (step(19),step(18)), # End Ninteenth Row # Start Twentieth Row # # # # # # # # # # # # # # # # "hay_block_side_rotated": (step(16),step(19)), "quartz_block_lines_rotated": (step(17),step(19)), "purpur_block": (step(18),step(19)), # End Twentieth Row # Start Twentyfirst Row "red_sandstone_bottom": (step(0),step(20)), "red_sandstone_carved": (step(1),step(20)), "red_sandstone_normal": (step(2),step(20)), "red_sandstone_smooth": (step(3),step(20)), "red_sandstone_top": (step(4),step(20)), "door_spruce_upper": (step(5),step(20)), "door_birch_upper": (step(6),step(20)), "door_jungle_upper": (step(7),step(20)), "door_acacia_upper": (step(8),step(20)), "door_dark_oak_upper": (step(9),step(20)), # # # # # # # # "chorus_plant": (step(13),step(20)), "chorus_flower_dead": (step(14),step(20)), "chorus_flower": (step(15),step(20)), "end_rod": (step(16),step(20)), # End Twentyfirst Row # Start MISC # Start More Bed Textures "bed_head_side_flipped": (step(1),step(21)), "bed_feet_side_flipped": (step(2),step(21)), "bed_head_top_flipped": (step(1),step(22)), "bed_feet_top_flipped": (step(2),step(22)), "bed_feet_top_bottom": (step(3),step(21)), "bed_head_top_bottom": (step(3),step(22)), "bed_feet_top_top": (step(4),step(22)), "bed_head_top_top": (step(4),step(21)), # End More Bed Textures # Start Comparator Block } class MultipartTexture(object): def __init__(self, texture_objects): self.subclasses = [] self.runAnyways = [] self.texture_dict = {} for subcls in self.__class__.__subclasses__(): # This is why I love Python self.subclasses.append(subcls) for cls in self.subclasses: instance = cls(texture_objects) if instance.runAnyway: self.runAnyways.append(instance) else: self.texture_dict[instance.target] = instance class LeverTexture(MultipartTexture): target = "lever" runAnyway = False def __init__(self, texture_objects): self.texture_objects = texture_objects def parse_texture(self): if "lever" not in self.texture_objects or "cobblestone" not in self.texture_objects: return None lever = self.texture_objects["lever"].copy() cobblestone = self.texture_objects["cobblestone"].copy() base_1 = cobblestone.crop((5, 4, 11, 12)) lever.paste(base_1, (10, 0, 16, 8)) base_2 = cobblestone.crop((5, 0, 11, 3)) lever.paste(base_2, (10, 8, 16, 11)) base_3 = cobblestone.crop((4, 0, 12, 3)) lever.paste(base_3, (2, 0, 10, 3)) return lever class StandingSignTexture(MultipartTexture): target = "" runAnyway = True position = (step(20), step(5)) def __init__(self, texture_objects): self.texture_objects = texture_objects def parse_texture(self): if "planks_oak" not in self.texture_objects or "log_oak" not in self.texture_objects: return None planks = self.texture_objects["planks_oak"].copy() log_tex = self.texture_objects["log_oak"].copy() sign = planks.crop((0, 7, 16, 16)) log_tex.paste(sign, (0, 7, 16, 16)) if log_tex.mode != "RGBA": log_tex = log_tex.convert("RGBA") return log_tex class IResourcePack(object): ''' Sets all base variables for a Resource Pack ''' def __init__(self): self.__stop = False texture_path = os.path.join(directories.parentDir, "textures", self._pack_name) self.texture_path = texture_path self._isEmpty = False self._too_big = False self.big_textures_counted = 0 self.big_textures_max = 10 self.block_image = {} self.propogated_textures = [] self.all_texture_slots = [] #self.old_terrain = Image.open(os.path.join(directories.getDataDir(), 'terrain.png')) self.old_terrain = Image.open(directories.getDataFile('terrain.png')) for texx in xrange(0,33): for texy in xrange(0,33): self.all_texture_slots.append((step(texx),step(texy))) self._terrain_name = self._pack_name.replace(" ", "_")+".png" #self._terrain_path = os.path.join("terrain-textures", self._terrain_name.replace(" ", "_")) self._terrain_path = directories.getDataFile(u'terrain-textures', self._terrain_name.replace(u' ', u'_')) @property def pack_name(self): ''' The name of the Resource Pack ''' return self._pack_name @property def terrain_name(self): ''' Name of the parsed texture PNG file ''' return self._terrain_name def terrain_path(self): ''' Path to the parsed PNG file ''' return self._terrain_path @property def isEmpty(self): ''' Returns true if the Resource Pack doesn't replace the minimum amount of textures ''' return self._isEmpty @property def tooBig(self): ''' Returns true if the Resource Pack has a greater resolution than 32x32 ''' return self._too_big def parse_terrain_png(self): ''' Parses each block texture into a usable PNG file like terrain.png ''' multiparts = MultipartTexture(self.block_image) log.debug("Parsing terrain.png") new_terrain = Image.new("RGBA", (512, 512), None) for tex in self.block_image.keys(): if not self.__stop and tex in textureSlots.keys(): try: if tex not in multiparts.texture_dict: image = self.block_image[tex] else: image = multiparts.texture_dict[tex].parse_texture() if image is None: continue log.debug(" Image is %s"%tex) log.debug(" Image mode: %s"%image.mode) if image.mode != "RGBA": try: image = image.convert("RGBA") log.debug(" Image converted to RGBA.") except Exception as ee: print "* * *", tex, ee slot = textureSlots[tex] try: new_terrain.paste(image, slot, image) except Exception as eee: print "* * * new_terrain error:", eee self.propogated_textures.append(slot) log.debug(" Image pasted and propagated.") except Exception as e: try: # Print the resource pack 'raw' name. print "An Exception occurred while trying to parse textures for {}".format(self._pack_name) log.debug("An Exception occurred while trying to parse textures for {}".format(self._pack_name)) except: # I for a reason it fails, print the 'representation' of it. print "An Exception occurred while trying to parse textures for {}".format(repr(self._pack_name)) log.debug("An Exception occurred while trying to parse textures for {}".format(repr(self._pack_name))) traceback.print_stack() print "Exception Message: "+str(e) log.debug("Exception Message: "+str(e)) print "Exception type: "+str(type(e)) log.debug("Exception type: "+str(type(e))) print e self.__stop = True self._isEmpty = True log.debug("Parsing stopped.") log.debug("Resource pack considered as empty.") pass for runAnyway in multiparts.runAnyways: parsed_texture = runAnyway.parse_texture() if parsed_texture is not None: new_terrain.paste(parsed_texture, runAnyway.position, parsed_texture) self.propogated_textures.append(runAnyway.position) copy = self.old_terrain.copy() log.debug("Correcting textures...") for t in self.all_texture_slots: if t not in self.propogated_textures: old_tex = copy.crop((t[0],t[1],t[0]+16,t[1]+16)) new_terrain.paste(old_tex, t, old_tex) log.debug(" Done.") log.debug("Saving %s."%self._terrain_path) new_terrain.save(self._terrain_path) log.debug(" Done.") try: os.remove(self._pack_name.replace(" ", "_")+".png") except: pass if not self.propogated_textures: os.remove(self._terrain_path) self._isEmpty = True log.debug("No propagated textures.\nTexture pack considered as empty.") #print u"{} did not replace any textures".format(self._pack_name) del self.block_image if hasattr(self, 'fps'): log.debug(" Closing file descriptors.") for f in self.fps: f.close() log.debug(" Done") log.debug("Parsing terrain.png ended.") def handle_too_big_packs(self): ''' Removes the parsed PNG file ''' self._too_big = True log.debug("Resource pack is too big.") try: os.remove(self._terrain_path) except: pass del self.block_image class ZipResourcePack(IResourcePack): ''' Represents a single Resource Pack that is in a zip file ''' def __init__(self, zipfileFile, noEncConvert=False): self.zipfile = zipfileFile log.debug("Zip file: %s"%zipfileFile) self._pack_name = os.path.splitext(os.path.split(zipfileFile)[-1])[0] log.debug("Pack name: %s"%self._pack_name) # Define a list of opened textures file objects to be cleaned when operations are finished. self.fps = [] IResourcePack.__init__(self) if not os.path.exists(self._terrain_path): try: self.open_pack() except Exception as e: if 'seek' not in e: print "Error while trying to load one of the resource packs: {}".format(e) def open_pack(self): ''' Opens the zip file and puts texture data into a dictionary, where the key is the texture file name, and the value is a PIL.Image instance ''' zfile = zipfile.ZipFile(self.zipfile) self.fps = [] for name in zfile.infolist(): if name.filename.endswith(".png") and not name.filename.split(os.path.sep)[-1].startswith("._"): filename = "assets/minecraft/textures/blocks" if name.filename.startswith(filename) and name.filename.replace(filename+"/", "").replace(".png","") in textureSlots: log.debug(" Is a possible texture.") block_name = os.path.normpath(name.filename).split(os.path.sep)[-1] block_name = block_name.split(".")[0] log.debug(" Block name: %s"%block_name) log.debug(" Opening %s"%name) fp = zfile.open(name) #!# Sending this 'fp' file descriptor to PIL.Image does not work, because such #!# descriptors are not seekable. #!# But, reading the fd data and writing it to a temporary file seem to work... log.debug(" Done. (%s, seekable: %s, readable: %s)"%(type(fp), fp.seekable(), fp.readable())) log.debug(" Saving fp data to temp file.") fp1 = StringIO() fp1.write(fp.read()) fp.close() fp1.seek(0) log.debug(" Done.") try: possible_texture = Image.open(fp1) log.debug(" File descriptor for %s opened."%block_name) log.debug(" Is %s."%repr(possible_texture.size)) except Exception as e: log.debug(" Can't open descriptor for %s"%block_name) log.debug(" System said:") log.debug(" %s"%repr(e)) if possible_texture.size == (16, 16): self.block_image[block_name] = possible_texture if block_name.startswith("repeater_") or block_name.startswith("comparator_"): self.block_image[block_name+"_west"] = possible_texture.rotate(-90) self.block_image[block_name+"_north"] = possible_texture.rotate(180) self.block_image[block_name+"_east"] = possible_texture.rotate(90) self.block_image[block_name+"_south"] = possible_texture if block_name == "piston_side": self.block_image["piston_up"] = possible_texture self.block_image["piston_left"] = possible_texture.rotate(90) self.block_image["piston_down"] = possible_texture.rotate(180) self.block_image["piston_right"] = possible_texture.rotate(-90) if block_name == "hay_block_side": self.block_image["hay_block_side_rotated"] = possible_texture.rotate(-90) if block_name == "quartz_block_lines": self.block_image["quartz_block_lines_rotated"] = possible_texture.rotate(-90) if block_name.startswith("bed_"): if block_name == "bed_head_side": self.block_image["bed_head_side_flipped"] = possible_texture.transpose(Image.FLIP_LEFT_RIGHT) if block_name == "bed_feet_side": self.block_image["bed_feet_side_flipped"] = possible_texture.transpose(Image.FLIP_LEFT_RIGHT) if block_name == "bed_head_top": self.block_image["bed_head_top_flipped"] = possible_texture.transpose(Image.FLIP_LEFT_RIGHT) self.block_image["bed_head_top_bottom"] = possible_texture.rotate(-90) self.block_image["bed_head_top_top"] = possible_texture.rotate(90) if block_name == "bed_feet_top": self.block_image["bed_feet_top_flipped"] = possible_texture.transpose(Image.FLIP_LEFT_RIGHT) self.block_image["bed_feet_top_bottom"] = possible_texture.rotate(-90) self.block_image["bed_feet_top_top"] = possible_texture.rotate(90) log.debug(" Is loaded.") else: if possible_texture.size == (32, 32): self.block_image[block_name] = possible_texture.resize((16, 16)) log.debug(" Is loaded.") elif possible_texture.size == (64, 64) or possible_texture.size == (128, 128) or possible_texture.size == (256, 256): self.big_textures_counted += 1 log.debug(" Is too big.") else: self.block_image[block_name] = possible_texture.crop((0,0,16,16)) log.debug(" Is loaded.") self.fps.append(fp1) if self.big_textures_counted >= self.big_textures_max: self.handle_too_big_packs() else: try: self.parse_terrain_png() except Exception: traceback.print_exc() log.warning('Encountered an Exception while parsing terrain texture') self._too_big = True pass class FolderResourcePack(IResourcePack): def __init__(self, folder, noEncConvert=False): self._folder = folder self._pack_name = self._folder.replace(" ", "_") IResourcePack.__init__(self) self._full_path = os.path.join(directories.getMinecraftProfileDirectory(directories.getSelectedProfile()), "resourcepacks", self._folder) self.texture_path = os.path.join(directories.parentDir, "textures", self._pack_name) if not os.path.exists(self._terrain_path): self.add_textures() def add_textures(self): ''' Scraps the block textures folder and puts texture data into a dictionary with exactly identical structure as ZipResourcePack ''' base_path = os.path.join(self._full_path, "assets", "minecraft", "textures", "blocks") if os.path.exists(base_path): files = os.listdir(base_path) for tex_file in files: if tex_file.endswith(".png") and not tex_file.startswith("._") and tex_file.replace(".png","") in textureSlots: possible_texture = Image.open(os.path.join(base_path, tex_file)) block_name = tex_file[:-4] if possible_texture.size == (16, 16): self.block_image[block_name] = possible_texture if block_name.startswith("repeater_") or block_name.startswith("comparator_"): self.block_image[block_name+"_west"] = possible_texture.rotate(-90) self.block_image[block_name+"_north"] = possible_texture.rotate(180) self.block_image[block_name+"_east"] = possible_texture.rotate(90) self.block_image[block_name+"_south"] = possible_texture if block_name == "piston_side": self.block_image["piston_up"] = possible_texture self.block_image["piston_left"] = possible_texture.rotate(90) self.block_image["piston_down"] = possible_texture.rotate(180) self.block_image["piston_right"] = possible_texture.rotate(-90) if block_name == "hay_block_side": self.block_image["hay_block_side_rotated"] = possible_texture.rotate(-90) if block_name == "quartz_block_lines": self.block_image["quartz_block_lines_rotated"] = possible_texture.rotate(-90) if block_name.startswith("bed_"): if block_name == "bed_head_side": self.block_image["bed_head_side_flipped"] = possible_texture.transpose(Image.FLIP_LEFT_RIGHT) if block_name == "bed_feet_side": self.block_image["bed_feet_side_flipped"] = possible_texture.transpose(Image.FLIP_LEFT_RIGHT) if block_name == "bed_head_top": self.block_image["bed_head_top_flipped"] = possible_texture.transpose(Image.FLIP_LEFT_RIGHT) self.block_image["bed_head_top_bottom"] = possible_texture.rotate(-90) self.block_image["bed_head_top_top"] = possible_texture.rotate(90) if block_name == "bed_feet_top": self.block_image["bed_feet_top_flipped"] = possible_texture.transpose(Image.FLIP_LEFT_RIGHT) self.block_image["bed_feet_top_bottom"] = possible_texture.rotate(-90) self.block_image["bed_feet_top_top"] = possible_texture.rotate(90) else: if possible_texture.size == (32, 32): self.block_image[block_name] = possible_texture.resize((16, 16)) if possible_texture.size == (64, 64) or possible_texture.size == (128, 128) or possible_texture.size == (256, 256): self.big_textures_counted += 1 else: self.block_image[block_name] = possible_texture.crop((0,0,16,16)) if self.big_textures_counted >= self.big_textures_max: self.handle_too_big_packs() else: try: self.parse_terrain_png() except Exception: traceback.print_exc() log.warning('Encountered an Exception while parsing terrain texture') self._too_big = True pass class DefaultResourcePack(IResourcePack): ''' Represents the default Resource Pack that is always present ''' def __init__(self): self._isEmpty = False self._too_big = False #self._terrain_path = os.path.join(directories.getDataDir(), "terrain.png") self._terrain_path = directories.getDataFile('terrain.png') self._pack_name = "Default" def terrain_path(self): return self._terrain_path @property def isEmpty(self): return self._isEmpty @property def tooBig(self): return self._too_big @Singleton class ResourcePackHandler: ''' A single point to manage which Resource Pack is being used and to provide the paths to each parsed PNG ''' Instance = None def setup_reource_packs(self): ''' Handles parsing of Resource Packs and removing ones that are either have to0 high of a resolution, or don't replace any textures ''' log.debug("Setting up the resource packs.") self._resource_packs = {} try: os.mkdir("terrain-textures") except OSError: pass self._resource_packs["Default Resource Pack"] = DefaultResourcePack() if os.path.exists(os.path.join(directories.getMinecraftProfileDirectory(directories.getSelectedProfile()), "resourcepacks")): log.debug("Gathering zipped packs...") zipResourcePacks = directories.getAllOfAFile(unicode(os.path.join(directories.getMinecraftProfileDirectory(directories.getSelectedProfile()), "resourcepacks")), ".zip") log.debug("Gatering folder packs...") folderResourcePacks = os.listdir(unicode(os.path.join(directories.getMinecraftProfileDirectory(directories.getSelectedProfile()), "resourcepacks"))) log.debug("Processing zipped packs...") for zip_tex_pack in zipResourcePacks: zrp = ZipResourcePack(zip_tex_pack) if not zrp.isEmpty: if not zrp.tooBig: self._resource_packs[zrp.pack_name] = zrp log.debug("Processing folder packs...") for folder_tex_pack in folderResourcePacks: if os.path.isdir(os.path.join(directories.getMinecraftProfileDirectory(directories.getSelectedProfile()), "resourcepacks", folder_tex_pack)): frp = FolderResourcePack(folder_tex_pack) if not frp.isEmpty: if not frp.tooBig: self._resource_packs[frp.pack_name] = frp for tex in self._resource_packs.keys(): pack = self._resource_packs[tex] if not os.path.exists(pack.terrain_path()): del self._resource_packs[tex] try: shutil.rmtree(os.path.join(directories.parentDir, "textures")) except: print "Could not remove \"textures\" directory" pass def __init__(self): try: os.mkdir(os.path.join(directories.parentDir, "textures")) except OSError: pass self.setup_reource_packs() self._selected_resource_pack = config.settings.resourcePack.get() if self._selected_resource_pack not in self._resource_packs.keys(): self.set_selected_resource_pack_name("Default Resource Pack") @property def resource_packs(self): ''' A dictionary of Resource Packs, where the key is the pack's file/folder name, and the value is the path to the parsed PNG ''' return self._resource_packs def get_available_resource_packs(self): ''' Returns the names of all the Resource Packs that can be used ''' return self._resource_packs.keys() def reload_resource_packs(self): ''' Reparses all Resource Packs ''' self.setup_resource_packs() def reparse_resource_pack(self, packName): if packName in self._resource_packs: pack = self._resource_packs[packName] if isinstance(pack, FolderResourcePack): pack.add_textures() elif isinstance(pack, ZipResourcePack): pack.open_pack() def get_selected_resource_pack_name(self): ''' Returns the currently selected Resource Pack's name ''' return self._selected_resource_pack def set_selected_resource_pack_name(self, name): ''' Sets the currently selected Resource Pack :param name: Name of the Resource Pack ''' config.settings.resourcePack.set(name) self._selected_resource_pack = name def get_selected_resource_pack(self): ''' Returns the selected Resource Pack instance. Can be an instance of either DefaultResourcePack, ZipResourcePack or FolderResourcePack ''' return self._resource_packs[self._selected_resource_pack]
42,430
37.963269
180
py
MCEdit-Unified
MCEdit-Unified-master/pkgutil.py
"""Utilities to support packages.""" # NOTE: This module must remain compatible with Python 2.3, as it is shared # by setuptools for distribution with Python 2.3 and up. import os import sys import imp import os.path from types import ModuleType __all__ = [ 'get_importer', 'iter_importers', 'get_loader', 'find_loader', 'walk_packages', 'iter_modules', 'get_data', 'ImpImporter', 'ImpLoader', 'read_code', 'extend_path', ] def read_code(stream): # This helper is needed in order for the PEP 302 emulation to # correctly handle compiled files import marshal magic = stream.read(4) if magic != imp.get_magic(): return None stream.read(4) # Skip timestamp return marshal.load(stream) def simplegeneric(func): """Make a trivial single-dispatch generic function""" registry = {} def wrapper(*args, **kw): ob = args[0] try: cls = ob.__class__ except AttributeError: cls = type(ob) try: mro = cls.__mro__ except AttributeError: try: class cls(cls, object): pass mro = cls.__mro__[1:] except TypeError: mro = object, # must be an ExtensionClass or some such :( for t in mro: if t in registry: return registry[t](*args, **kw) else: return func(*args, **kw) try: wrapper.__name__ = func.__name__ except (TypeError, AttributeError): pass # Python 2.3 doesn't allow functions to be renamed def register(typ, func=None): if func is None: return lambda f: register(typ, f) registry[typ] = func return func wrapper.__dict__ = func.__dict__ wrapper.__doc__ = func.__doc__ wrapper.register = register return wrapper def walk_packages(path=None, prefix='', onerror=None): """Yields (module_loader, name, ispkg) for all modules recursively on path, or, if path is None, all accessible modules. 'path' should be either None or a list of paths to look for modules in. 'prefix' is a string to output on the front of every module name on output. Note that this function must import all *packages* (NOT all modules!) on the given path, in order to access the __path__ attribute to find submodules. 'onerror' is a function which gets called with one argument (the name of the package which was being imported) if any exception occurs while trying to import a package. If no onerror function is supplied, ImportErrors are caught and ignored, while all other exceptions are propagated, terminating the search. Examples: # list all modules python can access walk_packages() # list all submodules of ctypes walk_packages(ctypes.__path__, ctypes.__name__+'.') """ def seen(p, m={}): if p in m: return True m[p] = True for importer, name, ispkg in iter_modules(path, prefix): yield importer, name, ispkg if ispkg: try: __import__(name) except ImportError: if onerror is not None: onerror(name) except Exception: if onerror is not None: onerror(name) else: raise else: path = getattr(sys.modules[name], '__path__', None) or [] # don't traverse path items we've seen before path = [p for p in path if not seen(p)] for item in walk_packages(path, name+'.', onerror): yield item def iter_modules(path=None, prefix=''): """Yields (module_loader, name, ispkg) for all submodules on path, or, if path is None, all top-level modules on sys.path. 'path' should be either None or a list of paths to look for modules in. 'prefix' is a string to output on the front of every module name on output. """ if path is None: importers = iter_importers() else: importers = map(get_importer, path) yielded = {} for i in importers: for name, ispkg in iter_importer_modules(i, prefix): if name not in yielded: yielded[name] = 1 yield i, name, ispkg #@simplegeneric def iter_importer_modules(importer, prefix=''): if not hasattr(importer, 'iter_modules'): return [] return importer.iter_modules(prefix) iter_importer_modules = simplegeneric(iter_importer_modules) class ImpImporter: """PEP 302 Importer that wraps Python's "classic" import algorithm ImpImporter(dirname) produces a PEP 302 importer that searches that directory. ImpImporter(None) produces a PEP 302 importer that searches the current sys.path, plus any modules that are frozen or built-in. Note that ImpImporter does not currently support being used by placement on sys.meta_path. """ def __init__(self, path=None): self.path = path def find_module(self, fullname, path=None): # Note: we ignore 'path' argument since it is only used via meta_path subname = fullname.split(".")[-1] if subname != fullname and self.path is None: return None if self.path is None: path = None else: path = [os.path.realpath(self.path)] try: file, filename, etc = imp.find_module(subname, path) except ImportError: return None return ImpLoader(fullname, file, filename, etc) def iter_modules(self, prefix=''): if self.path is None or not os.path.isdir(self.path): return yielded = {} import inspect try: filenames = os.listdir(self.path) except OSError: # ignore unreadable directories like import does filenames = [] filenames.sort() # handle packages before same-named modules for fn in filenames: modname = inspect.getmodulename(fn) if modname=='__init__' or modname in yielded: continue path = os.path.join(self.path, fn) ispkg = False if not modname and os.path.isdir(path) and '.' not in fn: modname = fn try: dircontents = os.listdir(path) except OSError: # ignore unreadable directories like import does dircontents = [] for fn in dircontents: subname = inspect.getmodulename(fn) if subname=='__init__': ispkg = True break else: continue # not a package if modname and '.' not in modname: yielded[modname] = 1 yield prefix + modname, ispkg class ImpLoader: """PEP 302 Loader that wraps Python's "classic" import algorithm """ code = source = None def __init__(self, fullname, file, filename, etc): self.file = file self.filename = filename self.fullname = fullname self.etc = etc def load_module(self, fullname): self._reopen() try: mod = imp.load_module(fullname, self.file, self.filename, self.etc) finally: if self.file: self.file.close() # Note: we don't set __loader__ because we want the module to look # normal; i.e. this is just a wrapper for standard import machinery return mod @staticmethod def get_data(pathname): return open(pathname, "rb").read() def _reopen(self): if self.file and self.file.closed: mod_type = self.etc[2] if mod_type==imp.PY_SOURCE: self.file = open(self.filename, 'rU') elif mod_type in (imp.PY_COMPILED, imp.C_EXTENSION): self.file = open(self.filename, 'rb') def _fix_name(self, fullname): if fullname is None: fullname = self.fullname elif fullname != self.fullname: raise ImportError("Loader for module %s cannot handle " "module %s" % (self.fullname, fullname)) return fullname def is_package(self, fullname): return self.etc[2]==imp.PKG_DIRECTORY def get_code(self, fullname=None): fullname = self._fix_name(fullname) if self.code is None: mod_type = self.etc[2] if mod_type==imp.PY_SOURCE: source = self.get_source(fullname) self.code = compile(source, self.filename, 'exec') elif mod_type==imp.PY_COMPILED: self._reopen() try: self.code = read_code(self.file) finally: self.file.close() elif mod_type==imp.PKG_DIRECTORY: self.code = self._get_delegate().get_code() return self.code def get_source(self, fullname=None): if self.source is None: mod_type = self.etc[2] if mod_type==imp.PY_SOURCE: self._reopen() try: self.source = self.file.read() finally: self.file.close() elif mod_type==imp.PY_COMPILED: if os.path.exists(self.filename[:-1]): f = open(self.filename[:-1], 'rU') self.source = f.read() f.close() elif mod_type==imp.PKG_DIRECTORY: self.source = self._get_delegate().get_source() return self.source def _get_delegate(self): return ImpImporter(self.filename).find_module('__init__') def get_filename(self, fullname=None): if self.etc[2]==imp.PKG_DIRECTORY: return self._get_delegate().get_filename() elif self.etc[2] in (imp.PY_SOURCE, imp.PY_COMPILED, imp.C_EXTENSION): return self.filename return None try: import zipimport from zipimport import zipimporter def iter_zipimport_modules(importer, prefix=''): dirlist = zipimport._zip_directory_cache[importer.archive].keys() dirlist.sort() _prefix = importer.prefix plen = len(_prefix) yielded = {} import inspect for fn in dirlist: if not fn.startswith(_prefix): continue fn = fn[plen:].split(os.sep) if len(fn)==2 and fn[1].startswith('__init__.py'): if fn[0] not in yielded: yielded[fn[0]] = 1 yield fn[0], True if len(fn)!=1: continue modname = inspect.getmodulename(fn[0]) if modname=='__init__': continue if modname and '.' not in modname and modname not in yielded: yielded[modname] = 1 yield prefix + modname, False iter_importer_modules.register(zipimporter, iter_zipimport_modules) except ImportError: pass def get_importer(path_item): """Retrieve a PEP 302 importer for the given path item The returned importer is cached in sys.path_importer_cache if it was newly created by a path hook. If there is no importer, a wrapper around the basic import machinery is returned. This wrapper is never inserted into the importer cache (None is inserted instead). The cache (or part of it) can be cleared manually if a rescan of sys.path_hooks is necessary. """ if type(path_item) == unicode: path_item = path_item.encode(sys.getfilesystemencoding()) try: importer = sys.path_importer_cache[path_item] except KeyError: for path_hook in sys.path_hooks: try: importer = path_hook(path_item) break except ImportError: pass else: importer = None sys.path_importer_cache.setdefault(path_item, importer) if importer is None: try: importer = ImpImporter(path_item) except ImportError: importer = None return importer def iter_importers(fullname=""): """Yield PEP 302 importers for the given module name If fullname contains a '.', the importers will be for the package containing fullname, otherwise they will be importers for sys.meta_path, sys.path, and Python's "classic" import machinery, in that order. If the named module is in a package, that package is imported as a side effect of invoking this function. Non PEP 302 mechanisms (e.g. the Windows registry) used by the standard import machinery to find files in alternative locations are partially supported, but are searched AFTER sys.path. Normally, these locations are searched BEFORE sys.path, preventing sys.path entries from shadowing them. For this to cause a visible difference in behaviour, there must be a module or package name that is accessible via both sys.path and one of the non PEP 302 file system mechanisms. In this case, the emulation will find the former version, while the builtin import mechanism will find the latter. Items of the following types can be affected by this discrepancy: imp.C_EXTENSION, imp.PY_SOURCE, imp.PY_COMPILED, imp.PKG_DIRECTORY """ if fullname.startswith('.'): raise ImportError("Relative module names not supported") if '.' in fullname: # Get the containing package's __path__ pkg = '.'.join(fullname.split('.')[:-1]) if pkg not in sys.modules: __import__(pkg) path = getattr(sys.modules[pkg], '__path__', None) or [] else: for importer in sys.meta_path: yield importer path = sys.path for item in path: yield get_importer(item) if '.' not in fullname: yield ImpImporter() def get_loader(module_or_name): """Get a PEP 302 "loader" object for module_or_name If the module or package is accessible via the normal import mechanism, a wrapper around the relevant part of that machinery is returned. Returns None if the module cannot be found or imported. If the named module is not already imported, its containing package (if any) is imported, in order to establish the package __path__. This function uses iter_importers(), and is thus subject to the same limitations regarding platform-specific special import locations such as the Windows registry. """ if module_or_name in sys.modules: module_or_name = sys.modules[module_or_name] if isinstance(module_or_name, ModuleType): module = module_or_name loader = getattr(module, '__loader__', None) if loader is not None: return loader fullname = module.__name__ else: fullname = module_or_name return find_loader(fullname) def find_loader(fullname): """Find a PEP 302 "loader" object for fullname If fullname contains dots, path must be the containing package's __path__. Returns None if the module cannot be found or imported. This function uses iter_importers(), and is thus subject to the same limitations regarding platform-specific special import locations such as the Windows registry. """ for importer in iter_importers(fullname): loader = importer.find_module(fullname) if loader is not None: return loader return None def extend_path(path, name): """Extend a package's path. Intended use is to place the following code in a package's __init__.py: from pkgutil import extend_path __path__ = extend_path(__path__, __name__) This will add to the package's __path__ all subdirectories of directories on sys.path named after the package. This is useful if one wants to distribute different parts of a single logical package as multiple directories. It also looks for *.pkg files beginning where * matches the name argument. This feature is similar to *.pth files (see site.py), except that it doesn't special-case lines starting with 'import'. A *.pkg file is trusted at face value: apart from checking for duplicates, all entries found in a *.pkg file are added to the path, regardless of whether they are exist the filesystem. (This is a feature.) If the input path is not a list (as is the case for frozen packages) it is returned unchanged. The input path is not modified; an extended copy is returned. Items are only appended to the copy at the end. It is assumed that sys.path is a sequence. Items of sys.path that are not (unicode or 8-bit) strings referring to existing directories are ignored. Unicode items of sys.path that cause errors when used as filenames may cause this function to raise an exception (in line with os.path.isdir() behavior). """ if not isinstance(path, list): # This could happen e.g. when this is called from inside a # frozen package. Return the path unchanged in that case. return path pname = os.path.join(*name.split('.')) # Reconstitute as relative path # Just in case os.extsep != '.' sname = os.extsep.join(name.split('.')) sname_pkg = sname + os.extsep + "pkg" init_py = "__init__" + os.extsep + "py" path = path[:] # Start with a copy of the existing path for dir in sys.path: if not isinstance(dir, basestring) or not os.path.isdir(dir): continue subdir = os.path.join(dir, pname) # XXX This may still add duplicate entries to path on # case-insensitive filesystems initfile = os.path.join(subdir, init_py) if subdir not in path and os.path.isfile(initfile): path.append(subdir) # XXX Is this the right thing for subpackages like zope.app? # It looks for a file named "zope.app.pkg" pkgfile = os.path.join(dir, sname_pkg) if os.path.isfile(pkgfile): try: f = open(pkgfile) except IOError, msg: sys.stderr.write("Can't open %s: %s\n" % (pkgfile, msg)) else: for line in f: line = line.rstrip('\n') if not line or line.startswith('#'): continue path.append(line) # Don't check for existence! f.close() return path def get_data(package, resource): """Get a resource from a package. This is a wrapper round the PEP 302 loader get_data API. The package argument should be the name of a package, in standard module format (foo.bar). The resource argument should be in the form of a relative filename, using '/' as the path separator. The parent directory name '..' is not allowed, and nor is a rooted name (starting with a '/'). The function returns a binary string, which is the contents of the specified resource. For packages located in the filesystem, which have already been imported, this is the rough equivalent of d = os.path.dirname(sys.modules[package].__file__) data = open(os.path.join(d, resource), 'rb').read() If the package cannot be located or loaded, or it uses a PEP 302 loader which does not support get_data(), then None is returned. """ loader = get_loader(package) if loader is None or not hasattr(loader, 'get_data'): return None mod = sys.modules.get(package) or loader.load_module(package) if mod is None or not hasattr(mod, '__file__'): return None # Modify the resource name to be compatible with the loader.get_data # signature - an os.path format "filename" starting with the dirname of # the package's __file__ parts = resource.split('/') parts.insert(0, os.path.dirname(mod.__file__)) resource_name = os.path.join(*parts) return loader.get_data(resource_name)
20,304
33.12605
79
py
MCEdit-Unified
MCEdit-Unified-master/depths.py
"""Copyright (c) 2010-2012 David Rio Vierra Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.""" class DepthOffset(object): ChunkMarkers = 2 Renderer = 1 PreviewRenderer = 0 TerrainWire = -1 ClonePreview = -2 Selection = -1 SelectionCorners = -2 PotentialSelection = -3 SelectionReticle = -4 FillMarkers = -3 CloneMarkers = -3 CloneReticle = -3
1,043
35
72
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/box.py
from collections import namedtuple import itertools import math _Vector = namedtuple("_Vector", ("x", "y", "z")) class Vector(_Vector): __slots__ = () def __add__(self, other): return Vector(self[0] + other[0], self[1] + other[1], self[2] + other[2]) def __sub__(self, other): return Vector(self[0] - other[0], self[1] - other[1], self[2] - other[2]) def __mul__(self, other): if isinstance(other, (int, float)): return Vector(self[0] * other, self[1] * other, self[2] * other) return Vector(self[0] * other[0], self[1] * other[1], self[2] * other[2]) def __truediv__(self, other): if isinstance(other, (int, float)): return Vector(self[0] / other, self[1] / other, self[2] / other) return Vector(self[0] / other[0], self[1] / other[1], self[2] / other[2]) __div__ = __truediv__ def length(self): return math.sqrt(self[0] * self[0] + self[1] * self[1] + self[2] * self[2]) def normalize(self): l = self.length() if l == 0: return self return self / l def intfloor(self): return Vector(*[int(math.floor(p)) for p in self]) class BoundingBox(object): type = int def __init__(self, origin=(0, 0, 0), size=(0, 0, 0)): if isinstance(origin, BoundingBox): self._origin = origin._origin self._size = origin._size else: self._origin, self._size = Vector(*(self.type(a) for a in origin)), Vector(*(self.type(a) for a in size)) def __repr__(self): return "BoundingBox({0}, {1})".format(self.origin, self.size) @property def origin(self): "The smallest position in the box" return self._origin @property def size(self): "The size of the box" return self._size @property def width(self): "The dimension along the X axis" return self._size.x @property def height(self): "The dimension along the Y axis" return self._size.y @property def length(self): "The dimension along the Z axis" return self._size.z @property def minx(self): return self.origin.x @property def miny(self): return self.origin.y @property def minz(self): return self.origin.z @property def maxx(self): return self.origin.x + self.size.x @property def maxy(self): return self.origin.y + self.size.y @property def maxz(self): return self.origin.z + self.size.z @property def maximum(self): "The largest point of the box; origin plus size." return self._origin + self._size @property def volume(self): "The volume of the box in blocks" return self.size.x * self.size.y * self.size.z @property def positions(self): """iterate through all of the positions within this selection box""" return itertools.product( xrange(self.minx, self.maxx), xrange(self.miny, self.maxy), xrange(self.minz, self.maxz) ) def intersect(self, box): """ Return a box containing the area self and box have in common. Box will have zero volume if there is no common area. :param box: The intersecting box :type box: pymclevel.box.BoundingBox :return: A box of the resulting intersection of the two boxes :rtype: pymclevel.box.BoundingBox """ if (self.minx > box.maxx or self.maxx < box.minx or self.miny > box.maxy or self.maxy < box.miny or self.minz > box.maxz or self.maxz < box.minz): # Zero size intersection. return BoundingBox() origin = Vector( max(self.minx, box.minx), max(self.miny, box.miny), max(self.minz, box.minz), ) maximum = Vector( min(self.maxx, box.maxx), min(self.maxy, box.maxy), min(self.maxz, box.maxz), ) # print "Intersect of {0} and {1}: {2}".format(self, box, newbox) return BoundingBox(origin, maximum - origin) def union(self, box): ''' Return a box large enough to contain both self and box. :param box: The box to add to the current box (self) :type box: pymclevel.box.BoundingBox :return: A box that contains all of the positions of original box along with the supplied box :rtype: pymclevel.box.BoundingBox ''' origin = Vector( min(self.minx, box.minx), min(self.miny, box.miny), min(self.minz, box.minz), ) maximum = Vector( max(self.maxx, box.maxx), max(self.maxy, box.maxy), max(self.maxz, box.maxz), ) return BoundingBox(origin, maximum - origin) def expand(self, dx, dy=None, dz=None): ''' Return a new box with boundaries expanded by dx, dy, dz. If only dx is passed, expands by dx in all dimensions :param dx: The direction to expand on the X axis :type dx: int :param dy: The direction to expand on the Y axis :type dy: int :param dz: The direction to expand on the Z axis :type dz: int :return: A new box with the dimensions expanded by the specified values :rtype: pymclevel.box.BoundingBox ''' if dz is None: dz = dx if dy is None: dy = dx origin = self.origin - (dx, dy, dz) size = self.size + (dx * 2, dy * 2, dz * 2) return BoundingBox(origin, size) def __contains__(self, pos): x, y, z = pos if x < self.minx or x >= self.maxx: return False if y < self.miny or y >= self.maxy: return False if z < self.minz or z >= self.maxz: return False return True def __cmp__(self, b): return cmp((self.origin, self.size), (b.origin, b.size)) # --- Chunk positions --- @property def mincx(self): "The smallest chunk position contained in this box" return self.origin.x >> 4 @property def mincz(self): "The smallest chunk position contained in this box" return self.origin.z >> 4 @property def maxcx(self): "The largest chunk position contained in this box" return ((self.origin.x + self.size.x - 1) >> 4) + 1 @property def maxcz(self): "The largest chunk position contained in this box" return ((self.origin.z + self.size.z - 1) >> 4) + 1 def chunkBox(self, level): """Returns this box extended to the chunk boundaries of the given level""" box = self return BoundingBox((box.mincx << 4, 0, box.mincz << 4), (box.maxcx - box.mincx << 4, level.Height, box.maxcz - box.mincz << 4)) @property def chunkPositions(self): # iterate through all of the chunk positions within this selection box return itertools.product(xrange(self.mincx, self.maxcx), xrange(self.mincz, self.maxcz)) @property def chunkCount(self): return (self.maxcx - self.mincx) * (self.maxcz - self.mincz) @property def isChunkAligned(self): return (self.origin.x & 0xf == 0) and (self.origin.z & 0xf == 0) class FloatBox(BoundingBox): type = float
7,517
28.252918
118
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/id_definitions.py
# id_definitions.py # # D.C.-G. (LaChal) 2016 # # Load the data according to the game version from the versioned resources. # """ The logic here is to load the JSON definitions for blocks, entities and tile entities for a given game version. Data for each game platform is contained in subfolders of the 'mcver' one and subsequent subfolders for each game version number: mcver/ + Java/ + 1.2/ - blocks.json - entities.json - tileentities.json + 1.2.3/ - blocks.json - entities.json - tileentities.json + PE/ + 1.2/ - blocks.json - entities.json - tileentities.json + 1.4/ - blocks.json - entities.json - tileentities.json [etc.] The JSON files can contain all the definitions for a version, or partial ones. If definitions are partial, other game version files can be loaded by referencing this version in a "load" object like this: ''' { "load": "1.2", "blocks": [snip...] } ''' Using the directory structure above, and assuming the code snippet comes from the 'block.json' file in the 'Java/1.2.3' subfolder, the data in 'blocks.json' in the 'Java/1.2' subfolder will be loaded before the data in 'blocks.json' in 'Java/1.2.3'. So the '1.2.3' data will override the '1.2' data. """ import os import json from logging import getLogger from pymclevel import MCEDIT_DEFS, MCEDIT_IDS import pymclevel import re import collections import sys from distutils.version import LooseVersion log = getLogger(__name__) def update(orig_dict, new_dict): for key, val in new_dict.iteritems(): if isinstance(val, collections.Mapping): if orig_dict.get(key, {}) == val: continue tmp = update(orig_dict.get(key, { }), val) orig_dict[key] = tmp elif isinstance(val, list): if orig_dict.get(key, []) == val: continue orig_dict[key] = (orig_dict.get(key, []) + val) else: if orig_dict.get(key, None) == new_dict[key]: continue orig_dict[key] = new_dict[key] return orig_dict def _parse_data(data, prefix, namespace, defs_dict, ids_dict, ignore_load=False): """Parse the JSON data and build objects accordingly. :data: JSON data. :prefix: unicode: the prefix to be used, basically 'blocks', 'entities' or 'tileentities'. :defs_dict: dict: the object to be populated with definitions; basically 'MCEDIT_DEFS' dict. :ids_dict: dict: the object to be populated with IDs; basically 'MCEDIT_IDS' dict. :ignore_load: bool: whether to break on the 'load' object if encountered in the JSON data. Used to track and load dependencies in the right order. Default to False. Return the 'load' object value if :ignore_load: is False and the object is present, or a tuple containing the updated 'defs_dict' and ids_dict' objects.""" if not ignore_load and 'load' in data.keys(): return data['load'] # Find if "autobuild" items are defined autobuilds = data.get("autobuild", {}) for a_name, a_value in autobuilds.items(): p = re.findall(r"(^|[ ])%s\['(\w+)'" % prefix, a_value) if p: for a in p[0][1:]: if a not in data.keys(): log.error("Found wrong reference while parsing autobuilds for %s: %s" % (prefix, a)) autobuilds.pop(a_name) else: autobuilds[a_name] = a_value.replace("%s[" % prefix, "data[") else: # Just remove stuff which is not related to data internal stuff autobuilds.pop(a_name) for definition, value in data.iteritems(): if definition == prefix: # We're parsing the block/entity/whatever data for item in value: _name = item.get('_name', item.get('idStr', u'%s' % item['id'])) entry_name = "DEF_%s_%s" % (prefix.upper(), _name.upper()) defs_dict[entry_name] = item ids_dict[item['id']] = ids_dict[_name] = entry_name if item.get('idStr'): ids_dict[u'%s:%s' % (namespace, item['idStr'])] = ids_dict[item['idStr']] = entry_name for a_name, a_value in autobuilds.items(): try: v = eval(a_value) # print "###", a_name, a_value, v defs_dict[entry_name][a_name] = eval(a_value) ids_dict[v] = entry_name except Exception as e: log.error("An error occurred while autobuilding definitions %s (value: \"%s\": %s" % (a_name, a_value, e)) else: # Build extra info in other defs defs_dict[definition] = value return defs_dict, ids_dict def _get_data(file_name): data = {} try: fp = open(file_name) data = json.loads(fp.read()) fp.close() except Exception as e: log.error("Could not load data from %s" % file_name) log.error("Error is: %s" % e) return data def ids_loader(gamePlatform, gameVersionNumber, namespace=u"minecraft", json_dict=False, timestamps=False): """Load the whole files from mcver directory. :game_version: str/unicode: the game version for which the resources will be loaded. :namespace: unicode: the name to be put in front of some IDs. default to 'minecraft'. :json_dict: bool: Whether to return a ran dict from the JSon file(s) instead of the (MCEDIT_DEFS, MCEDIT_IDS) pair. :timestamp: bool: wheter the return also the loaded file timestamp.""" log.info("Loading resources for MC {} {}".format(gamePlatform, gameVersionNumber)) global MCEDIT_DEFS global MCEDIT_IDS MCEDIT_DEFS = {} MCEDIT_IDS = {} if json_dict: _json = {} if timestamps: _timestamps = {} d = os.path.join('mcver', gamePlatform, gameVersionNumber) # If version 1.2.4 files are not found, try to load the one for the closest # lower version (like 1.2.3 or 1.2). if not os.path.isdir(d) and gameVersionNumber != "Unknown": log.info("No definitions found for MC {} {}. Trying to find ones for the closest lower version.".format(gamePlatform, gameVersionNumber)) ver_dirs = os.listdir(os.path.join('mcver', gamePlatform)) ver_dirs.append(gameVersionNumber) ver_dirs.sort(key=LooseVersion) idx = ver_dirs.index(gameVersionNumber) - 1 ver = ver_dirs[idx] d = os.path.join('mcver', gamePlatform, ver) log.info("Closest lower version found is MC {} {}.".format(gamePlatform, ver)) if os.path.isdir(d): for file_name in os.listdir(d): if os.path.splitext(file_name)[-1].lower() == '.json': log.info("Found %s" % file_name) path_name = os.path.join(d, file_name) data = _get_data(path_name) if timestamps: _timestamps[path_name] = os.stat(path_name).st_mtime if data: # We use here names coming from the 'minecraft:name_of_the_stuff' ids # The second part of the name is present in the first file used (for MC 1.11) in the 'idStr' value). # The keys of MCEDIT_DEFS are built by concatenating the file base name and the idStr # References to MCEDIT_DEFS elements are stored in MCEDIT_IDS dict. # If an element "load" is defined in the JSON data, it must be a string corresponding to another game version. # The corresponding file will be loaded before parsing the data. log.info("Loading...") prefix = os.path.splitext(file_name)[0] deps = [] r = '' _data = {} first = True while type(r) in (str, unicode): if first: r = _parse_data(data, prefix, namespace, MCEDIT_DEFS, MCEDIT_IDS) if json_dict: _json.update(data) first = False else: r = _parse_data(_data, prefix, namespace, MCEDIT_DEFS, MCEDIT_IDS) if json_dict: _json.update(_data) if isinstance(r, (str, unicode)): v = gameVersionNumber if len(deps): v = deps[-1] log.info("Found dependency for %s %s"%(v, prefix)) deps.append(r) _data = _get_data(os.path.join('mcver', gamePlatform, r, file_name)) else: defs, ids = r MCEDIT_DEFS.update(defs) MCEDIT_IDS.update(ids) if deps: deps.reverse() log.info("Loading definitions dependencies") _data = {} for dep in deps: _file_name = os.path.join('mcver', gamePlatform, dep, file_name) if os.path.exists(_file_name): log.info("Found %s"%_file_name) #_data.update(_get_data(_file_name)) update(_data, _get_data(_file_name)) if timestamps: _timestamps[_file_name] = os.stat(_file_name).st_mtime else: log.info("Could not find %s"%_file_name) update(_data, data) #_data.update(data) _defs, _ids = _parse_data(_data, prefix, namespace, MCEDIT_DEFS, MCEDIT_IDS, ignore_load=True) update(MCEDIT_DEFS, _defs) update(MCEDIT_IDS, _ids) #MCEDIT_DEFS.update(_defs) #MCEDIT_IDS.update(_ids) if json_dict: _json.update(_data) log.info("Done") else: log.info("MC {} {} resources not found.".format(gamePlatform, gameVersionNumber)) # Override the module objects to expose them outside when (re)importing. pymclevel.MCEDIT_DEFS = MCEDIT_DEFS pymclevel.MCEDIT_IDS = MCEDIT_IDS log.info("Loaded %s defs and %s ids"%(len(MCEDIT_DEFS), len(MCEDIT_IDS))) toreturn = (MCEDIT_DEFS, MCEDIT_IDS) if json_dict: toreturn = _json if '--dump-defs' in sys.argv: dump_f_name = 'defs_ids-{}-{}.json'.format(gamePlatform, gameVersionNumber) log.info("Dumping definitions as JSON data in '%s'." % dump_f_name) with open(dump_f_name, 'w') as f: f.write("#" * 80) f.write("\nDEFS\n") f.write(json.dumps(MCEDIT_DEFS, indent=4)) f.write("\n\n" + "#" * 80) f.write("\nIDS\n") f.write(json.dumps(MCEDIT_IDS, indent=4)) f.close() if timestamps: toreturn += (_timestamps,) return toreturn version_defs_ids = {} class MCEditDefsIds(object): """Class to handle MCEDIT_DEFS and MCEDIT_IDS dicts.""" def __init__(self, gamePlatform, gameVersionNumber, namespace=u"minecraft"): """:game_version, namespace: See 'ids_loader() docstring'.""" global version_defs_ids self.mcedit_defs, self.mcedit_ids, self.timestamps = ids_loader(gamePlatform, gameVersionNumber, namespace, timestamps=True) if gamePlatform not in version_defs_ids: version_defs_ids[gamePlatform] = {} version_defs_ids[gamePlatform][gameVersionNumber] = self def check_timestamps(self, timestamps): """Compare the stored and current modification time stamp of files. :timestamps: dict: {"file_path": <modification timestamp>} Returns a list of files which has'nt same timestamp as stored.""" result = [] for file_name, ts in timestamps.items(): if os.stat(file_name).st_mtime != ts: result.append(file_name) return result def get_id(self, obj_id): """Acts like MCEDIT_IDS[obj_id]""" return self.mcedit_ids[obj_id] def get_def(self, def_id): """Acts like MCEDIT_DEFS[def_id]""" return self.mcedit_defs[def_id] def get_defs_ids(gamePlatform, gameVersionNumber, namespace=u"minecraft"): """Create a MCEditDefsIds instance only if one for the game version does not already exists, or a definition file has been changed. See MCEditDefsIds doc. Returns a MCEditDefsIds instance.""" if gamePlatform in version_defs_ids.keys() and gameVersionNumber in version_defs_ids[gamePlatform].keys(): obj = version_defs_ids[gamePlatform][gameVersionNumber] timestamps = obj.timestamps if not obj.check_timestamps(timestamps): return obj else: return MCEditDefsIds(gamePlatform, gameVersionNumber, namespace=namespace)
13,302
43.196013
168
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/faces.py
FaceXIncreasing = 0 FaceXDecreasing = 1 FaceYIncreasing = 2 FaceYDecreasing = 3 FaceZIncreasing = 4 FaceZDecreasing = 5 MaxDirections = 6 faceDirections = ( (FaceXIncreasing, (1, 0, 0)), (FaceXDecreasing, (-1, 0, 0)), (FaceYIncreasing, (0, 1, 0)), (FaceYDecreasing, (0, -1, 0)), (FaceZIncreasing, (0, 0, 1)), (FaceZDecreasing, (0, 0, -1)) )
366
20.588235
34
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/nbt.py
# vim:set sw=2 sts=2 ts=2: """ Named Binary Tag library. Serializes and deserializes TAG_* objects to and from binary data. Load a Minecraft level by calling nbt.load(). Create your own TAG_* objects and set their values. Save a TAG_* object to a file or StringIO object. Read the test functions at the end of the file to get started. This library requires Numpy. Get it here: http://new.scipy.org/download.html Official NBT documentation is here: http://www.minecraft.net/docs/NBT.txt Copyright 2010 David Rio Vierra """ import collections from contextlib import contextmanager import gzip import itertools import logging import struct import zlib from cStringIO import StringIO import numpy from numpy import array, zeros, fromstring #----------------------------------------------------------------------------- # TRACKING PE ERRORS # # DEBUG_PE and dump_fName are overridden by leveldbpocket module import sys DEBUG_PE = False dump_fName = 'dump_pe.txt' log = logging.getLogger(__name__) class NBTFormatError(RuntimeError): pass TAG_BYTE = 1 TAG_SHORT = 2 TAG_INT = 3 TAG_LONG = 4 TAG_FLOAT = 5 TAG_DOUBLE = 6 TAG_BYTE_ARRAY = 7 TAG_STRING = 8 TAG_LIST = 9 TAG_COMPOUND = 10 TAG_INT_ARRAY = 11 TAG_LONG_ARRAY = 12 TAG_SHORT_ARRAY = -1 class TAG_Value(object): """Simple values. Subclasses override fmt to change the type and size. Subclasses may set data_type instead of overriding setValue for automatic data type coercion""" __slots__ = ('_name', '_value') def __init__(self, value=0, name=""): self.value = value self.name = name fmt = struct.Struct("b") tagID = NotImplemented data_type = NotImplemented _name = None _value = None def __str__(self): return nested_string(self) @property def value(self): return self._value @value.setter def value(self, newVal): """Change the TAG's value. Data types are checked and coerced if needed.""" self._value = self.data_type(newVal) @property def name(self): return self._name @name.setter def name(self, newVal): """Change the TAG's name. Coerced to a unicode.""" self._name = unicode(newVal) @classmethod def load_from(cls, ctx): data = ctx.data[ctx.offset:] # 'data' may be empty or not have the required length. Shall we bypass? value = None try: (value,) = cls.fmt.unpack_from(data) except Exception as e: if DEBUG_PE: fp = open(dump_fName) n_lines = len(fp.readlines()) + 1 fp.close() msg = ("*** NBT support could not load data\n" "{e}\n" "----------\nctx.data (length: {lcd}):\n{cd}\n" "..........\ndata (length: {lrd}):\n{rd}\n" "''''''''''\nctx.offset:\n{co}\n" "^^^^^^^^^^\ncls.fmt.format: {cf}\n***\n".format(e=e, cd=repr(ctx.data), rd=repr(data), co=ctx.offset, cf=cls.fmt.format, lcd=len(ctx.data), lrd=len(data) ) ) fp1 = open(dump_fName, 'a') fp1.write(msg) fp1.close() added_n_lines = len(msg.splitlines()) log.warning("Could not unpack NBT data: information written in {fn}, from line {b} to line {e}".format(fn=dump_fName, b=n_lines, e=(n_lines + added_n_lines - 1))) else: raise e if value == None: self = cls() self.name = 'Unknown' else: self = cls(value=value) ctx.offset += self.fmt.size return self def __repr__(self): return "<%s name=\"%s\" value=%r>" % (str(self.__class__.__name__), self.name, self.value) def write_tag(self, buf): buf.write(chr(self.tagID)) def write_name(self, buf): if self.name is not None: write_string(self.name, buf) def write_value(self, buf): buf.write(self.fmt.pack(self.value)) def isCompound(self): return False class TAG_Byte(TAG_Value): __slots__ = ('_name', '_value') tagID = TAG_BYTE fmt = struct.Struct(">b") data_type = int class TAG_Short(TAG_Value): __slots__ = ('_name', '_value') tagID = TAG_SHORT fmt = struct.Struct(">h") data_type = int class TAG_Int(TAG_Value): __slots__ = ('_name', '_value') tagID = TAG_INT fmt = struct.Struct(">i") data_type = int class TAG_Long(TAG_Value): __slots__ = ('_name', '_value') tagID = TAG_LONG fmt = struct.Struct(">q") data_type = long class TAG_Float(TAG_Value): __slots__ = ('_name', '_value') tagID = TAG_FLOAT fmt = struct.Struct(">f") data_type = float class TAG_Double(TAG_Value): __slots__ = ('_name', '_value') tagID = TAG_DOUBLE fmt = struct.Struct(">d") data_type = float class TAG_Byte_Array(TAG_Value): """Like a string, but for binary data. Four length bytes instead of two. Value is a numpy array, and you can change its elements""" tagID = TAG_BYTE_ARRAY def __init__(self, value=None, name=""): if value is None: value = zeros(0, self.dtype) self.name = name self.value = value def __repr__(self): return "<%s name=%s length=%d>" % (self.__class__, self.name, len(self.value)) __slots__ = ('_name', '_value') def data_type(self, value): return array(value, self.dtype) dtype = numpy.dtype('uint8') @classmethod def load_from(cls, ctx): data = ctx.data[ctx.offset:] (string_len,) = TAG_Int.fmt.unpack_from(data) value = fromstring(data[4:string_len * cls.dtype.itemsize + 4], cls.dtype) self = cls(value) ctx.offset += string_len * cls.dtype.itemsize + 4 return self def write_value(self, buf): value_str = self.value.tostring() buf.write(struct.pack(">I%ds" % (len(value_str),), self.value.size, value_str)) class TAG_Int_Array(TAG_Byte_Array): """An array of big-endian 32-bit integers""" tagID = TAG_INT_ARRAY __slots__ = ('_name', '_value') dtype = numpy.dtype('>u4') class TAG_Short_Array(TAG_Int_Array): """An array of big-endian 16-bit integers. Not official, but used by some mods.""" tagID = TAG_SHORT_ARRAY __slots__ = ('_name', '_value') dtype = numpy.dtype('>u2') class TAG_Long_Array(TAG_Int_Array): tagID = TAG_LONG_ARRAY __slots__ = ('_name', '_value') dtype = numpy.dtype('>q') class TAG_String(TAG_Value): """String in UTF-8 The value parameter must be a 'unicode' or a UTF-8 encoded 'str' """ tagID = TAG_STRING def __init__(self, value="", name=""): if name: self.name = name self.value = value _decodeCache = {} __slots__ = ('_name', '_value') def data_type(self, value): if isinstance(value, unicode): return value else: decoded = self._decodeCache.get(value) if decoded is None: decoded = value.decode('utf-8') self._decodeCache[value] = decoded return decoded @classmethod def load_from(cls, ctx): value = load_string(ctx) return cls(value) def write_value(self, buf): write_string(self._value, buf) string_len_fmt = struct.Struct(">H") def load_string(ctx): data = ctx.data[ctx.offset:] (string_len,) = string_len_fmt.unpack_from(data) value = data[2:string_len + 2].tostring() ctx.offset += string_len + 2 return value def write_string(string, buf): encoded = string.encode('utf-8') buf.write(struct.pack(">h%ds" % (len(encoded),), len(encoded), encoded)) # noinspection PyMissingConstructor class TAG_Compound(TAG_Value, collections.MutableMapping): """A heterogenous list of named tags. Names must be unique within the TAG_Compound. Add tags to the compound using the subscript operator []. This will automatically name the tags.""" tagID = TAG_COMPOUND ALLOW_DUPLICATE_KEYS = False __slots__ = ('_name', '_value') def __init__(self, value=None, name=""): self.value = value or [] self.name = name def __repr__(self): return "<%s name='%s' keys=%r>" % (str(self.__class__.__name__), self.name, self.keys()) def data_type(self, val): for i in val: self.check_value(i) return list(val) @staticmethod def check_value(val): if not isinstance(val, TAG_Value): raise TypeError("Invalid type for TAG_Compound element: %s" % val.__class__.__name__) if not val.name: raise ValueError("Tag needs a name to be inserted into TAG_Compound: %s" % val) @classmethod def load_from(cls, ctx): self = cls() while ctx.offset < len(ctx.data): tag_type = ctx.data[ctx.offset] ctx.offset += 1 if tag_type == 0: break tag_name = load_string(ctx) tag = tag_classes[tag_type].load_from(ctx) tag.name = tag_name self._value.append(tag) return self def save(self, filename_or_buf=None, compressed=True): """ Save the TAG_Compound element to a file. Since this element is the root tag, it can be named. Pass a filename to save the data to a file. Pass a file-like object (with a read() method) to write the data to that object. Pass nothing to return the data as a string. """ if self.name is None: self.name = "" buf = StringIO() self.write_tag(buf) self.write_name(buf) self.write_value(buf) data = buf.getvalue() if compressed: gzio = StringIO() gz = gzip.GzipFile(fileobj=gzio, mode='wb') gz.write(data) gz.close() data = gzio.getvalue() if filename_or_buf is None: return data if isinstance(filename_or_buf, basestring): f = open(filename_or_buf, "wb") f.write(data) f.close() else: filename_or_buf.write(data) def write_value(self, buf): for tag in self.value: tag.write_tag(buf) tag.write_name(buf) tag.write_value(buf) buf.write("\x00") # --- collection functions --- def __getitem__(self, key): # hits=filter(lambda x: x.name==key, self.value) # if(len(hits)): return hits[0] for tag in self.value: if tag.name == key: return tag raise KeyError("Key {0} not found".format(key)) def __iter__(self): return itertools.imap(lambda x: x.name, self.value) def __contains__(self, key): return key in map(lambda x: x.name, self.value) def __len__(self): return self.value.__len__() def __setitem__(self, key, item): """Automatically wraps lists and tuples in a TAG_List, and wraps strings and unicodes in a TAG_String.""" if isinstance(item, (list, tuple)): item = TAG_List(item) elif isinstance(item, basestring): item = TAG_String(item) item.name = key self.check_value(item) # remove any items already named "key". if not self.ALLOW_DUPLICATE_KEYS: self._value = filter(lambda x: x.name != key, self._value) self._value.append(item) def __delitem__(self, key): self.value.__delitem__(self.value.index(self[key])) def add(self, value): if value.name is None: raise ValueError("Tag %r must have a name." % value) self[value.name] = value def get_all(self, key): return [v for v in self._value if v.name == key] def isCompound(self): return True class TAG_List(TAG_Value, collections.MutableSequence): """A homogenous list of unnamed data of a single TAG_* type. Once created, the type can only be changed by emptying the list and adding an element of the new type. If created with no arguments, returns a list of TAG_Compound Empty lists in the wild have been seen with type TAG_Byte""" tagID = 9 def __init__(self, value=None, name="", list_type=TAG_BYTE): # can be created from a list of tags in value, with an optional # name, or created from raw tag data, or created with list_type # taken from a TAG class or instance self.name = name self.list_type = list_type self.value = value or [] __slots__ = ('_name', '_value') def __repr__(self): return "<%s name='%s' list_type=%r length=%d>" % (self.__class__.__name__, self.name, tag_classes[self.list_type], len(self)) def data_type(self, val): if val: self.list_type = val[0].tagID assert all([x.tagID == self.list_type for x in val]) return list(val) @classmethod def load_from(cls, ctx): self = cls() self.list_type = ctx.data[ctx.offset] ctx.offset += 1 (list_length,) = TAG_Int.fmt.unpack_from(ctx.data, ctx.offset) ctx.offset += TAG_Int.fmt.size for i in xrange(list_length): tag = tag_classes[self.list_type].load_from(ctx) self.append(tag) return self def write_value(self, buf): buf.write(chr(self.list_type)) buf.write(TAG_Int.fmt.pack(len(self.value))) for i in self.value: i.write_value(buf) def check_tag(self, value): if value.tagID != self.list_type: raise TypeError("Invalid type %s for TAG_List(%s)" % (value.__class__, tag_classes[self.list_type])) # --- collection methods --- def __iter__(self): return iter(self.value) def __contains__(self, tag): return tag in self.value def __getitem__(self, index): return self.value[index] def __len__(self): return len(self.value) def __setitem__(self, index, value): if isinstance(index, slice): for tag in value: self.check_tag(tag) else: self.check_tag(value) self.value[index] = value def __delitem__(self, index): del self.value[index] def insert(self, index, value): if len(self) == 0: self.list_type = value.tagID else: self.check_tag(value) value.name = "" self.value.insert(index, value) tag_classes = {} for c in ( TAG_Byte, TAG_Short, TAG_Int, TAG_Long, TAG_Float, TAG_Double, TAG_String, TAG_Byte_Array, TAG_List, TAG_Compound, TAG_Int_Array, TAG_Long_Array, TAG_Short_Array): tag_classes[c.tagID] = c def gunzip(data): return gzip.GzipFile(fileobj=StringIO(data)).read() def try_gunzip(data): try: data = gunzip(data) except IOError as zlib.error: pass return data def load(filename="", buf=None): """ Unserialize data from an NBT file and return the root TAG_Compound object. If filename is passed, reads from the file, otherwise uses data from buf. Buf can be a buffer object with a read() method or a string containing NBT data. """ if filename: buf = open(filename, "rb") data = buf if hasattr(buf, "read"): data = buf.read() result = _load_buffer(try_gunzip(data)) if hasattr(buf, "close"): buf.close() return result class load_ctx(object): pass def _load_buffer(buf): if isinstance(buf, str): buf = fromstring(buf, 'uint8') data = buf if not len(data): raise NBTFormatError("Asked to load root tag of zero length") tag_type = data[0] if tag_type != 10: magic = data[:4] raise NBTFormatError('Not an NBT file with a root TAG_Compound ' '(file starts with "%s" (0x%08x)' % (magic.tostring(), magic.view(dtype='uint32'))) ctx = load_ctx() ctx.offset = 1 ctx.data = data tag_name = load_string(ctx) tag = TAG_Compound.load_from(ctx) # For PE debug try: tag.name = tag_name except: pass return tag __all__ = [a.__name__ for a in tag_classes.itervalues()] + ["load", "gunzip"] @contextmanager def littleEndianNBT(): """ Pocket edition NBT files are encoded in little endian, instead of big endian. This sets all the required paramaters to read little endian NBT, and makes sure they get set back after usage. :return: None """ # We need to override the function to access the hard-coded endianness. def override_write_string(string, buf): encoded = string.encode('utf-8') buf.write(struct.pack("<h%ds" % (len(encoded),), len(encoded), encoded)) def reset_write_string(string, buf): encoded = string.encode('utf-8') buf.write(struct.pack(">h%ds" % (len(encoded),), len(encoded), encoded)) def override_byte_array_write_value(self, buf): value_str = self.value.tostring() buf.write(struct.pack("<I%ds" % (len(value_str),), self.value.size, value_str)) def reset_byte_array_write_value(self, buf): value_str = self.value.tostring() buf.write(struct.pack(">I%ds" % (len(value_str),), self.value.size, value_str)) global string_len_fmt string_len_fmt = struct.Struct("<H") TAG_Byte.fmt = struct.Struct("<b") TAG_Short.fmt = struct.Struct("<h") TAG_Int.fmt = struct.Struct("<i") TAG_Long.fmt = struct.Struct("<q") TAG_Float.fmt = struct.Struct("<f") TAG_Double.fmt = struct.Struct("<d") TAG_Int_Array.dtype = numpy.dtype("<u4") TAG_Long_Array.dtype = numpy.dtype("<q") TAG_Short_Array.dtype = numpy.dtype("<u2") global write_string write_string = override_write_string TAG_Byte_Array.write_value = override_byte_array_write_value yield string_len_fmt = struct.Struct(">H") TAG_Byte.fmt = struct.Struct(">b") TAG_Short.fmt = struct.Struct(">h") TAG_Int.fmt = struct.Struct(">i") TAG_Long.fmt = struct.Struct(">q") TAG_Float.fmt = struct.Struct(">f") TAG_Double.fmt = struct.Struct(">d") TAG_Int_Array.dtype = numpy.dtype(">u4") TAG_Long_Array.dtype = numpy.dtype(">q") TAG_Short_Array.dtype = numpy.dtype(">u2") write_string = reset_write_string TAG_Byte_Array.write_value = reset_byte_array_write_value def nested_string(tag, indent_string=" ", indent=0): result = "" if tag.tagID == TAG_COMPOUND: result += 'TAG_Compound({\n' indent += 1 for key, value in tag.iteritems(): result += indent_string * indent + '"%s": %s,\n' % (key, nested_string(value, indent_string, indent)) indent -= 1 result += indent_string * indent + '})' elif tag.tagID == TAG_LIST: result += 'TAG_List([\n' indent += 1 for index, value in enumerate(tag): result += indent_string * indent + nested_string(value, indent_string, indent) + ",\n" indent -= 1 result += indent_string * indent + '])' else: result += "%s(%r)" % (tag.__class__.__name__, tag.value) return result try: # noinspection PyUnresolvedReferences # Inhibit the _nbt import if we're debugging the PE support errors, because we need to get information concerning NBT malformed data... # if DEBUG_PE or '--debug-pe' in sys.argv: # log.warning("PE support debug mode is activated. Using full Python NBT support!") # else: from _nbt import (load, TAG_Byte, TAG_Short, TAG_Int, TAG_Long, TAG_Float, TAG_Double, TAG_String, TAG_Byte_Array, TAG_List, TAG_Compound, TAG_Int_Array, TAG_Long_Array, TAG_Short_Array, NBTFormatError, littleEndianNBT, nested_string, gunzip, hexdump) except ImportError as err: log.error("Failed to import Cythonized nbt file. Running on (very slow) pure-python nbt fallback.") log.error("(Did you forget to run 'setup.py build_ext --inplace'?)") log.error("%s"%err)
20,429
27.896747
178
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/leveldbpocket.py
dimension = '' #overworld # dimension = '\x01\x00\x00\x00' #nether # dimension = '\x02\x00\x00\x00' #end import itertools import time from math import floor, ceil, log from level import FakeChunk, MCLevel import logging from materials import pocketMaterials import os from mclevelbase import ChunkNotPresent, ChunkMalformed import nbt import numpy import struct from infiniteworld import ChunkedLevelMixin, SessionLockLost, AnvilChunkData, AnvilWorldFolder, unpackNibbleArray, packNibbleArray from level import LightedChunk from contextlib import contextmanager from pymclevel import entity, BoundingBox, Entity, TileEntity import traceback import shutil logger = logging.getLogger(__name__) # Support for PE 0.9.0 to 1.0.0 leveldb_available = True leveldb_mcpe = None try: import leveldb as leveldb_mcpe except Exception as e: trace_msg = traceback.format_exc().splitlines() logger.warn("Error while trying to import leveldb:") [logger.warn(a) for a in trace_msg] try: if leveldb_mcpe is None: import leveldb_mcpe leveldb_mcpe.Options() except Exception as e: logger.info("Error while trying to import leveldb_mcpe ({0})".format(e)) #--------------------------------------------------------------------- # TRACKING ERRORS # # Some debug messages will be displayed in the console, and a file will be used to put more information. import sys DEBUG_PE = False dump_fName = 'dump_pe.txt' longest_complist_len = 0 longest_complist = '' shortest_complist_len = sys.maxint shortest_complist = '' if '--debug-pe' in sys.argv: sys.argv.remove('--debug-pe') DEBUG_PE = True # Override nbt module DEBUG_PE and dump_fName nbt.DEBUG_PE = DEBUG_PE nbt.dump_fName = dump_fName # Check if the --debug-pe CLI option is given several times to set a higher verbose level. # 'True' is considered being 1, so let set DEBUG_PE to 2 if it's found a secondtime on the CLI # and add 1 to the value each time it's found. while '--debug-pe' in sys.argv: sys.argv.remove('--debug-pe') if DEBUG_PE is True: DEBUG_PE = 2 else: DEBUG_PE += 1 if DEBUG_PE: open(dump_fName, 'w').close() def write_dump(msg): """Helper function to write data to the PE dump file when using '--debug-pe' CLI option.""" open(dump_fName, 'a').write(msg) # ===================================================================== def loadNBTCompoundList(data, littleEndian=True, partNBT=False, count=None): """ Loads a list of NBT Compound tags from a bunch of data. Uses sep to determine where the next Compound tag starts. :param data: str, the NBT to load from :param littleEndian: bool. Determines endianness :param partNBT: bool. If part of the data is NBT (begins with NBT), the function will return the list of compounds with the rest of the data that was not NBT :return: list of TAG_Compounds """ def load(_data, _partNBT, _count): compound_list = [] idx = 0 count = 0 while idx < len(_data) and (_count is None or count < _count): try: __data = nbt.load(buf=_data[idx:]) idx += len(nbt.gunzip(__data.save())) count += 1 except Exception as e: if _partNBT: return compound_list, _data[idx:] msg1 = "PE support could not read compound list data:" msg2 = "Data dump:" msg3 = "Data length: %s" logger.error(msg1) logger.error(e) if len(_data[idx:]) > 80: logger.error("Partial data dump:") logger.error("%s [...] %s", repr(_data[:idx + 40]), repr(_data[-40:])) else: logger.error(msg2) logger.error(repr(_data[idx:])) logger.error(msg3, len(data)) if DEBUG_PE: try: dump_line = len(open(dump_fName).read().splitlines()) + 1 dump_msg = "**********\n{m1}\n{e}\n{m2}\n{d}\n{m3} {l}".format(m1=msg1, e=e, m2=msg2, d=repr(_data[idx:]), m3=msg3, l=len(data)) msg_len = len(dump_msg.splitlines()) write_dump(dump_msg) logger.warn("Error info and data dumped to %s at line %s (%s lines long)", dump_fName, dump_line, msg_len) except Exception as _e: logger.error("Could not dump PE debug info:") logger.error(_e) raise e if DEBUG_PE == 2: write_dump("++++++++++\nloadNBTCompoundList_new parsed data:\n{d}\nis compound ? {ic}\n".format(d=__data, ic=__data.isCompound())) compound_list.append(__data) if _partNBT: return compound_list, _data[idx:] return compound_list if littleEndian: with nbt.littleEndianNBT(): return load(data, partNBT, count) else: return load(data, partNBT, count) # ===================================================================== def TagProperty(tagName, tagType, default_or_func=None): """ Copied from infiniteworld.py. Custom property object to handle NBT-tag properties. :param tagName: str, Name of the NBT-tag :param tagType: int, (nbt.TAG_TYPE) Type of the NBT-tag :param default_or_func: function or default value. If function, function should return the default. :return: property """ def getter(self): root_tag = self.root_tag["Data"] if tagName not in root_tag: if hasattr(default_or_func, "__call__"): default = default_or_func(self) else: default = default_or_func root_tag[tagName] = tagType(default) return root_tag[tagName].value def setter(self, val): self.root_tag[tagName] = tagType(value=val) return property(getter, setter) class InvalidPocketLevelDBWorldException(Exception): pass # ===================================================================== def get_blocks_storage_from_blocks_and_data(blocks, data): blocksCombined = numpy.stack((blocks, data)) uniqueBlocks = numpy.transpose(numpy.unique(blocksCombined, axis=1)) palette = [] numpy_blocks = numpy.zeros(4096, 'uint16') for index, (blockID, blockData) in enumerate(uniqueBlocks): try: if blockID != 0: block_string = "minecraft:" + pocketMaterials.idStr[blockID] block_data = blockData else: block_string = "minecraft:air" block_data = blockData except: block_string = "minecraft:air" block_data = 0 with nbt.littleEndianNBT(): block_nbt = nbt.TAG_Compound([nbt.TAG_String(block_string, "name"), nbt.TAG_Short(block_data, "val")]).save(compressed=False) if block_nbt not in palette: palette.append(block_nbt) position = palette.index(block_nbt) numpy_blocks[(blocksCombined[0]==blockID) & (blocksCombined[1]==blockData)] = position max_bits = len('{0:b}'.format(numpy_blocks.max())) possible_bits_per_blocks = [1, 2, 3, 4, 5, 6, 8, 16] bits_per_block = possible_bits_per_blocks[numpy.searchsorted(possible_bits_per_blocks, max_bits, side='left')] word_size = 32 blocks_per_word = int(floor(32 / bits_per_block)) word_count = int(ceil(4096 / float(blocks_per_word))) blocks_binary = (numpy_blocks.reshape(-1, 1) >> numpy.arange(bits_per_block)[::-1] & 1).astype(bool) bits_per_word = bits_per_block * blocks_per_word bits_missing = bits_per_word - (blocks_binary.shape[0] * blocks_binary.shape[1]) % bits_per_word if bits_missing == bits_per_word: bits_missing = 0 final_blocks_binary = numpy.concatenate([blocks_binary, numpy.array([False] * bits_missing).reshape(-1, bits_per_block)]) clean_blocks_binary = final_blocks_binary.reshape(-1, word_size / bits_per_block, bits_per_block)[:, ::-1].reshape(-1, blocks_per_word * bits_per_block) full_blocks_binary = numpy.hstack([numpy.empty([word_count, word_size - bits_per_word], dtype=bool), clean_blocks_binary]) flat_blocks_binary = full_blocks_binary.reshape(-1, word_size / 8, 8)[:, ::-1, :].ravel() blocks_in_bytes = numpy.packbits(flat_blocks_binary.astype(int)).tobytes() palette_size = struct.pack("<i", len(palette)) palette_string = "".join(palette) return chr(bits_per_block << 1) + blocks_in_bytes + palette_size + palette_string class PocketLeveldbDatabase(object): """ Not to be confused with leveldb.DB A PocketLeveldbDatabase is an interface around leveldb_mcpe.DB, providing various functions to load/write chunk data, and access the level.dat file. The leveldb_mcpe.DB object handles the actual leveldb database. To access the actual database, world_db() should be called. """ holdDatabaseOpen = True _world_db = None world_version = None # to be set to 'pre1.0' or '1.plus' def __open_db(self): """Opens a DB and return the associated object.""" pth = os.path.join(self.path, 'db').encode(sys.getfilesystemencoding()) compressors = self.compressors if not compressors: compressors = (2,) if ord(self.dat_world_version) >= 6: compressors = (4, 2) if DEBUG_PE: write_dump("Binary world version: %s; compressor: %s\n" % (repr(self.dat_world_version), compressors)) return self.ldb.DB(self.options, pth, compressors=compressors) @contextmanager def world_db(self, compressors=None): """ Opens a leveldb and keeps it open until editing finished. :param compressors: None or tuple of ints: The compressor type(s) to be used. If None, the value is decided according to the 'dat_world_version'. :yield: DB """ if not self.compressors: self.compressors = compressors if PocketLeveldbDatabase.holdDatabaseOpen: if self._world_db is None: self._world_db = self.__open_db() yield self._world_db pass else: db = self.__open_db() yield db del db def __init__(self, path, level, create=False, world_version=None, dat_world_version=None, compressors=None): """ :param path: string, path to file. :param level: parent PocketLeveldbWorld instance. :param create: bool, wheter to create the world. Defaults to False. :param world_version: string or None, world version. Defaults to None. :param dat_world_version: char or None, binary world version as stored on the disk. :param compressors: None or tuple of ints: The compressor type(s) to be used. If None, the value is decided according to the 'dat_world_version'. :return: None """ if not world_version: raise TypeError("Wrong world version sent: %s"%world_version) self.world_version = world_version self.dat_world_version = dat_world_version self.path = path if not os.path.exists(path): file(path, 'w').close() self.level = level self.compressors = compressors self.options = leveldb_mcpe.Options() self.writeOptions = leveldb_mcpe.WriteOptions() self.readOptions = leveldb_mcpe.ReadOptions() self.ldb = leveldb_mcpe if create: # Rework this, because leveldb.Options() is a function... #self.options.create_if_missing = True # The database will be created once needed first. return needsRepair = False try: # Let's try to 'magicaly' find the right compression for the world. compressors_list = (None, (4,), (2,)) i = 0 while True: compressors = compressors_list[i] with self.world_db(compressors) as db: try: it = db.NewIterator(self.readOptions) it.SeekToFirst() if not db.Get(self.readOptions, it.key()) == it.value(): needsRepair = True it.status() del it break except leveldb_mcpe.ZipCompressionError: if i < len(compressors_list) - 1: i += 1 self._world_db.close() self._world_db = None self.compressors = None else: raise except RuntimeError as err: logger.error("Error while opening world database from %s (%s)"%(path, err)) needsRepair = True if needsRepair: logger.info("Trying to repair world %s"%path) try: self.ldb.RepairWrapper(os.path.join(path, 'db')) except RuntimeError as err: logger.error("Error while repairing world %s %s"%(path, err)) def close(self): """ Should be called before deleting this instance of the level. Not calling this method may result in corrupted worlds :return: None """ if PocketLeveldbDatabase.holdDatabaseOpen: if self._world_db is not None: del self._world_db self._world_db = None def _readChunk_pre1_0(self, cx, cz, readOptions=None, key=None): """ :param cx, cz: int Coordinates of the chunk :param readOptions: ReadOptions :return: None """ if key is None: key = struct.pack('<i', cx) + struct.pack('<i', cz) + dimension with self.world_db() as db: rop = self.readOptions if readOptions is None else readOptions # Only way to see if value exists is by failing db.Get() try: terrain = db.Get(rop, key + "0") except RuntimeError: return None try: tile_entities = db.Get(rop, key + "1") except RuntimeError: tile_entities = None try: entities = db.Get(rop, key + "2") except RuntimeError: entities = None if len(terrain) != 83200: raise ChunkMalformed(str(len(terrain))) return terrain, tile_entities, entities def _readSubChunk_1plus(self, cx, cz, y, readOptions=None, key=None): """Read PE 1.0+ subchunk cx, cz: int: coordinates of the chunk. y: int: 'height' index of the subchunk, generaly a0 to 15 number. readOptions: object: Pocket DB read options container to be used with the data base. Default to 'None'. Automatically gathered if the default 'None' value is used. key: str: binary form of the key to request data for. Default to 'None'. Automatically calculated from cx and cz if the default 'None' value is used. """ if key is None: key = struct.pack('<i', cx) + struct.pack('<i', cz)+dimension with self.world_db() as db: rop = self.readOptions if readOptions is None else readOptions c = chr(y) try: terrain = db.Get(rop, key + "\x2f" + c) except RuntimeError: if DEBUG_PE: write_dump("!!! No terrain found for sub-chunk (%s, %s, %s)\n" % (cx, cz, y)) terrain = None except Exception as e: if DEBUG_PE: write_dump("!!! An unhandled error occured when loading sub-chunk (%s, %s, %s) terrain.\n" % (cx, cz, y)) write_dump("%s" % e) terrain = None if y == 0: try: tile_entities = db.Get(rop, key + "\x31") except RuntimeError: tile_entities = None try: entities = db.Get(rop, key + "\x32") except RuntimeError: entities = None else: tile_entities = entities = None return terrain, tile_entities, entities def _readChunk(self, cx, cz, world, readOptions=None): """ :param cx, cz: int Coordinates of the chunk :param readOptions: ReadOptions :return: chunk data in a tuple: (terrain, tile_entities, entities) """ # PE 1+ worlds can contain pre 1.0 chunks. # Let check which version of the chunk we have before doing anything else. with self.world_db() as db: rop = self.readOptions if readOptions is None else readOptions key = struct.pack('<i', cx) + struct.pack('<i', cz)+dimension raise_err = False try: chunk_version = db.Get(rop, key + chr(118)) if chunk_version is None: raise_err = True except: raise_err = True if raise_err: raise ChunkNotPresent((cx, cz, self)) if DEBUG_PE: write_dump("** Loading chunk ({x}, {z}) for PE {vs} ({v}).\n".format(x=cx, z=cz, vs={"\x02": "pre 1.0", "\x03": "1.0", "\x04": "1.1"}.get(chunk_version, 'Unknown'), v=repr(chunk_version))) if chunk_version == "\x02": # We have a pre 1.0 chunk data = self._readChunk_pre1_0(cx, cz, rop, key) if data is None: raise ChunkNotPresent((cx, cz, self)) chunk = PocketLeveldbChunkPre1(cx, cz, world, data, world_version=self.world_version) # Let assume that any chunk wich version is greater or equal to 3 in a PE 1+ one. elif ord(chunk_version) >= 3: # PE 1+ chunk detected. Iterate through the subchunks to rebuild the whole data. # If the world version was set o pre1.0 during initialization, change it for 1+. # Change also the world height to 256... if world.world_version == 'pre1.0': logger.info("Detected pre 1.0 world, but 1.0+ chunk found. Changing world version and height accordingly.") world.world_version = '1.plus' world.Height = 256 self.world_version = '1.plus' # Reload the 'allChunks' object world._allChunks = None world.allChunks chunk = PocketLeveldbChunk1Plus(cx, cz, world, world_version=self.world_version, chunk_version=chunk_version) d2d = db.Get(rop, key + "\x2d") if d2d: # data_2d contains the heightmap (currently computed dynamically, may change) # and the biome information of the chunk on the last 256 bytes. chunk.data_2d = d2d biomes = numpy.fromstring(d2d[512:], 'uint8') biomes.shape = (16, 16) chunk.Biomes = biomes for i in range(16): tr, te, en = self._readSubChunk_1plus(cx, cz, i, rop, key) chunk.add_data(terrain=tr, tile_entities=te, entities=en, subchunk=i) # Generate the lights if we have a PE 1.1 chunk. if ord(chunk.chunk_version) >= 4: chunk.genFastLights() if DEBUG_PE: write_dump(">>> Chunk (%s, %s) sub-chunks: %s\n" % (cx, cz, repr(chunk.subchunks))) elif chunk_version is not None: raise AttributeError("Unknown PE chunk version %s" % repr(chunk_version)) elif chunk_version is None: if DEBUG_PE: write_dump("Chunk (%s, %s) version seem to be 'None'. Do this chunk exists in this world?" % (cx, cz)) return None else: if DEBUG_PE: write_dump("Unknown chunk version detected for chunk (%s, %s): %s" % (cx, cz, repr(chunk_version))) raise AttributeError("Unknown chunk version detected for chunk (%s, %s): %s" % (cx, cz, repr(chunk_version))) logger.debug("CHUNK LOAD %s %s" % (cx, cz)) return chunk def _saveChunk_pre1_0(self, chunk, batch=None, writeOptions=None): """ :param chunk: PocketLeveldbChunk :param batch: WriteBatch :param writeOptions: WriteOptions :return: None """ cx, cz = chunk.chunkPosition data = chunk.savedData() key = struct.pack('<i', cx) + struct.pack('<i', cz)+dimension if batch is None: with self.world_db() as db: wop = self.writeOptions if writeOptions is None else writeOptions db.Put(wop, key + "0", data[0]) if data[1] is not None: db.Put(wop, key + "1", data[1]) if data[2] is not None: db.Put(wop, key + "2", data[2]) else: batch.Put(key + "0", data[0]) if data[1] is not None: batch.Put(key + "1", data[1]) if data[2] is not None: batch.Put(key + "2", data[2]) def _saveChunk_1plus(self, chunk, batch=None, writeOptions=None): """ :param chunk: PocketLeveldbChunk :param batch: WriteBatch :param writeOptions: WriteOptions :return: None """ cx, cz = chunk.chunkPosition key = struct.pack('<i', cx) + struct.pack('<i', cz) + dimension with nbt.littleEndianNBT(): mcedit_defs = self.level.defsIds.mcedit_defs defs_get = mcedit_defs.get ids_get = self.level.defsIds.mcedit_ids.get tileEntityData = '' for ent in chunk.TileEntities: tileEntityData += ent.save(compressed=False) entityData = '' for ent in chunk.Entities: if 'identifier' in ent: v = 'see "identifier"' if "id" in ent: v = ent["id"].value del ent["id"] entityData += ent.save(compressed=False) ent["id"] = nbt.TAG_String(v) else: try: v = ent["id"].value ent_data = defs_get(ids_get(v, v), {'id': -1}) id = ent_data['id'] ent['id'] = nbt.TAG_Int(id + mcedit_defs['entity_types'].get(ent_data.get('type', None),0)) entityData += ent.save(compressed=False) # We have to re-invert after saving otherwise the next save will fail. ent["id"] = nbt.TAG_String(v) except Exception as e: logger.warning("An error occured while saving entity ID:") logger.warning(e) logger.warning("Entity has been skipped") wop = self.writeOptions if writeOptions is None else writeOptions chunk._Blocks.update_subchunks() chunk._Data.subchunks = chunk._Blocks.subchunks chunk._Data.update_subchunks() chunk._extra_blocks.subchunks = chunk._Blocks.subchunks chunk._extra_blocks_data.subchunks = chunk._Blocks.subchunks chunk._extra_blocks.update_subchunks() chunk._extra_blocks_data.update_subchunks() data_2d = getattr(chunk, 'data_2d', '\x00'*768) if hasattr(chunk, 'Biomes') and data_2d: data_2d = data_2d[:512] + chunk.Biomes.tostring() if chunk.chunk_version == "\x03": chunk._SkyLight.subchunks = chunk._Blocks.subchunks chunk._SkyLight.update_subchunks() chunk._BlockLight.subchunks = chunk._Blocks.subchunks chunk._BlockLight.update_subchunks() chunk.subchunks = chunk._Blocks.subchunks for y in chunk.subchunks: c = chr(y) ver = chr(8) if chunk._Blocks.binary_data[y] is None or chunk._Data.binary_data[y] is None: continue blocks = chunk._Blocks.binary_data[y].ravel() blockData = chunk._Data.binary_data[y].ravel() blocks_storage = get_blocks_storage_from_blocks_and_data(blocks, blockData) if hasattr(chunk, "_extra_blocks") and chunk._extra_blocks.binary_data[y].max() > 0: extra_blocks = chunk._extra_blocks.binary_data[y].ravel() extra_blocks_data = chunk._extra_blocks_data.binary_data[y].ravel() extra_blocks_storage = get_blocks_storage_from_blocks_and_data(extra_blocks, extra_blocks_data) num_of_storages = 2 else: extra_blocks_storage = "" num_of_storages = 1 terrain = ver + chr(num_of_storages) + blocks_storage + extra_blocks_storage if batch is None: with self.world_db() as db: if blocks is None or blockData is None or (numpy.all(chunk._Blocks.binary_data[y] == 0) and numpy.all(chunk._Data.binary_data[y] == 0)): db.Delete(key + "\x2f" + c) else: db.Put(wop, key + "\x2f" + c, terrain) if y == 0: db.Put(wop, key + '\x76', chunk.chunk_version) if len(chunk.TileEntities) > 0: db.Put(wop, key + '\x31', tileEntityData) else: db.Delete(key + '\x31') if len(chunk.Entities) > 0: db.Put(wop, key + '\x32', entityData) else: db.Delete(key + '\x32') if data_2d: db.Put(wop, key + '\x2d', data_2d) else: if blocks is None or blockData is None or (numpy.all(chunk._Blocks.binary_data[y] == 0) and numpy.all(chunk._Data.binary_data[y] == 0)): batch.Delete(key + "\x2f" + c) else: batch.Put(key + "\x2f" + c, terrain) if y == 0: batch.Put(key + '\x76', chunk.chunk_version) if len(chunk.TileEntities) > 0: batch.Put(key + '\x31', tileEntityData) else: batch.Delete(key + '\x31') if len(chunk.Entities) > 0: batch.Put(key + '\x32', entityData) else: batch.Delete(key + '\x32') if data_2d: batch.Put(key + '\x2d', data_2d) def saveChunk(self, chunk, batch=None, writeOptions=None): """ Wrapper for the methods corresponding to the world version. :param chunk: PocketLeveldbChunk :param batch: WriteBatch :param writeOptions: WriteOptions :return: None """ # Check the chunk version, since PE 1.0+ can contain pre 1.0+ chunks ver = chunk.chunk_version if ver == "\x02": self._saveChunk_pre1_0(chunk, batch, writeOptions) elif ord(ver) >= 3: self._saveChunk_1plus(chunk, batch, writeOptions) else: raise AttributeError("Unknown version %s for chunk %s"%(ver, chunk.chunkPosition())) def loadChunk(self, cx, cz, world): """ :param cx, cz: int Coordinates of the chunk :param world: PocketLeveldbWorld :return: PocketLeveldbChunk """ chunk = self._readChunk(cx, cz, world) return chunk _allChunks = None def deleteChunk(self, cx, cz, batch=None): if self.world_version == 'pre1.0': keys = [struct.pack('<i', cx) + struct.pack('<i', cz) + "0"] else: keys = [] keys_append = keys.append coords_str = struct.pack('<i', cx) + struct.pack('<i', cz)+dimension for i in xrange(16): keys_append(coords_str + "\x2f" + chr(i)) for k in ("\x2d", "\x2e", "\x30", "\x31", "\x32", "\x33", "\x34", "\x35", "\x36", "\x76"): keys_append(coords_str + k) if batch is None: with self.world_db() as db: for key in keys: db.Delete(key) else: for key in keys: batch.Delete(key) logger.debug("DELETED CHUNK %s %s" % (cx, cz)) def getAllChunks(self, readOptions=None, world_version=None): """ Returns a list of all chunks that have terrain data in the database. Chunks with only Entities or TileEntities are ignored. :param readOptions: ReadOptions :param world_version: game version to read the data for. Default: None. :return: list """ allChunks = set() with self.world_db() as db: if not world_version: world_version = self.world_version rop = self.readOptions if readOptions is None else readOptions it = db.NewIterator(rop) it.SeekToFirst() if it.Valid(): firstKey = it.key() else: # ie the database is empty return [] it.SeekToLast() key = '' while key[0:8] != firstKey[0:8]: key = it.key() if len(key) >= 8: try: if world_version == 'pre1.0': val = db.Get(rop, key[:8] + '\x30') elif world_version == '1.plus': val = db.Get(rop, key[:8]+dimension+'\x76') # if the above key exists it is a valid chunk so add it if val is not None: allChunks.add(struct.unpack('<2i', key[:8])) except RuntimeError: pass # seek to the first key with this beginning and go one further it.seek(key[:8]) it.stepBackward() it.status() # All this does is cause an exception if something went wrong. Might be unneeded? del it return allChunks def getAllPlayerData(self, readOptions=None): """ Returns the raw NBT data of all players in the database. Every player is stored as player_<player-id>. The single-player player is stored as ~local_player :param readOptions: :return: dictonary key, value: key: player-id, value = player nbt data as str """ with self.world_db() as db: allPlayers = {} rop = self.readOptions if readOptions is None else readOptions try: allPlayers["~local_player"] = db.Get(rop, "~local_player") except RuntimeError: pass it = db.NewIterator(rop) it.seek("player_") key = it.key() while it.Valid() and key.startswith("player_"): allPlayers[key] = it.value() it.stepForward() key = it.key() del it return allPlayers def savePlayer(self, player, playerData, batch=None, writeOptions=None): if writeOptions is None: writeOptions = self.writeOptions if batch is None: with self.world_db() as db: db.Put(writeOptions, player, playerData) else: batch.Put(player, playerData) # ===================================================================== class PocketLeveldbWorld(ChunkedLevelMixin, MCLevel): # Methods are missing and prvent some parts of MCEdit to work properly. # brush.py need copyChunkFrom() # Height = 128 # Let that being defined by the world version Width = 0 Length = 0 isInfinite = True materials = pocketMaterials noTileTicks = True _bounds = None oldPlayerFolderFormat = False _allChunks = None # An array of cx, cz pairs. _loadedChunks = {} # A dictionary of actual PocketLeveldbChunk objects mapped by (cx, cz) _playerData = None playerTagCache = {} _playerList = None entityClass = entity.PocketEntity world_version = None # to be set to 'pre1.0' or '1.plus' # It may happen that 1+ world has a an internale .dat version set to pre 1 (0x04). # Let store this internal .dat version to be able to deal with mixed pre 1 and 1+ chunks. dat_world_version = None _gamePlatform = 'PE' @property def LevelName(self): root_tag = self.root_tag["Data"] if "LevelName" not in root_tag: with open(os.path.join(self.worldFile.path, "levelname.txt"), 'r') as f: name = f.read() if name is None: name = os.path.basename(self.worldFile.path) root_tag["LevelName"] = name return root_tag["LevelName"].value @LevelName.setter def LevelName(self, name): self.root_tag["Data"]["LevelName"] = nbt.TAG_String(value=name) with open(os.path.join(self.worldFile.path, "levelname.txt"), 'w') as f: f.write(name) @property def allChunks(self): """ :return: list with all chunks in the world. """ if self._allChunks is None: self._allChunks = self.worldFile.getAllChunks() if self.world_version == '1.plus' and self.dat_world_version == '\x04': self._allChunks.union(self.worldFile.getAllChunks(world_version='pre1.0')) return self._allChunks @property def chunkCount(self): """Returns the number of chunks in the level. May initiate a costly chunk scan.""" if len(self._loadedChunks) != 0: return len(self._loadedChunks) else: return len(self.allChunks) @property def players(self): if self._playerList is None: self._playerList = [] for key in self.playerData.keys(): self._playerList.append(key) return self._playerList @property def playerData(self): if self._playerData is None: self._playerData = self.worldFile.getAllPlayerData() return self._playerData @staticmethod def getPlayerPath(player, dim=0): """ player.py loads players from files, but PE caches them differently. This is necessary to make it work. :param player: str :param dim: int :return: str """ if dim == 0: return player def __init__(self, filename=None, create=False, random_seed=None, last_played=None, readonly=False, height=None): """ :param filename: path to the root dir of the level :param create: bool or hexstring/int: wether to create the level. If bool, only False is allowed. Hex strings or ints must reflect a valid PE world version as '\x02' or 5. :return: """ if not os.path.isdir(filename): filename = os.path.dirname(filename) # Can we rely on this to know which version of PE was used to create the world? # Looks like that 1+ world can also have a storage version equal to 4... if not create: self.dat_world_version = open(os.path.join(filename, 'level.dat')).read(1) if ord(self.dat_world_version) >= 5: self.world_version = '1.plus' self.Height = 256 else: self.world_version = 'pre1.0' self.Height = 128 logger.info('PE world verion found: %s (%s)' % (self.world_version, repr(self.dat_world_version))) else: self.world_version = create if height is not None: self.Height = height logger.info('Creating PE world version %s (%s)' % (self.world_version, repr(self.dat_world_version))) self.filename = filename self.worldFile = PocketLeveldbDatabase(filename, self, create=create, world_version=self.world_version, dat_world_version=self.dat_world_version) self.world_version = self.worldFile.world_version self.readonly = readonly self.loadLevelDat(create, random_seed, last_played) self.worldFolder = AnvilWorldFolder(filename) workFolderPath2 = self.worldFolder.getFolderPath("##MCEDIT.TEMP2##") if os.path.exists(workFolderPath2): shutil.rmtree(workFolderPath2, True) self.fileEditsFolder = AnvilWorldFolder(workFolderPath2) self.editFileNumber = 1 def _createLevelDat(self, random_seed, last_played): """ Creates a new level.dat root_tag, and puts it in self.root_tag. To write it to the disk, self.save() should be called. :param random_seed: long :param last_played: long :return: None """ with nbt.littleEndianNBT(): root_tag = nbt.TAG_Compound() root_tag["Data"] = nbt.TAG_Compound() root_tag["Data"]["SpawnX"] = nbt.TAG_Int(0) root_tag["Data"]["SpawnY"] = nbt.TAG_Int(2) root_tag["Data"]["SpawnZ"] = nbt.TAG_Int(0) if last_played is None: last_played = long(time.time() * 100) if random_seed is None: random_seed = long(numpy.random.random() * 0xffffffffffffffffL) - 0x8000000000000000L self.root_tag = root_tag self.LastPlayed = long(last_played) self.RandomSeed = long(random_seed) self.SizeOnDisk = 0 self.Time = 1 self.LevelName = os.path.basename(self.worldFile.path) def loadLevelDat(self, create=False, random_seed=None, last_played=None): """ Loads the level.dat from the worldfolder. :param create: bool. If it's True, a fresh level.dat will be created instead. :param random_seed: long :param last_played: long :return: None """ def _loadLevelDat(filename): root_tag_buf = open(filename, 'rb').read() magic, length, root_tag_buf = root_tag_buf[:4], root_tag_buf[4:8], root_tag_buf[8:] if struct.Struct('<i').unpack(magic)[0] < 3: logger.info("Found an old level.dat file. Aborting world load") raise InvalidPocketLevelDBWorldException() # Maybe try convert/load old PE world? if len(root_tag_buf) != struct.Struct('<i').unpack(length)[0]: raise nbt.NBTFormatError() self.root_tag = nbt.TAG_Compound() level_nbt_data = nbt.load(buf=root_tag_buf) if "Data" in level_nbt_data: self.root_tag = level_nbt_data else: self.root_tag["Data"] = nbt.load(buf=root_tag_buf) if create: print "Creating PE level.dat" self._createLevelDat(random_seed, last_played) return try: with nbt.littleEndianNBT(): _loadLevelDat(os.path.join(self.worldFile.path, "level.dat")) return except (nbt.NBTFormatError, IOError) as err: logger.info("Failed to load level.dat, trying to load level.dat_old ({0})".format(err)) try: with nbt.littleEndianNBT(): _loadLevelDat(os.path.join(self.worldFile.path, "level.dat_old")) return except (nbt.NBTFormatError, IOError) as err: logger.info("Failed to load level.dat_old, creating new level.dat ({0})".format(err)) self._createLevelDat(random_seed, last_played) # --- NBT Tag variables --- SizeOnDisk = TagProperty('SizeOnDisk', nbt.TAG_Int, 0) RandomSeed = TagProperty('RandomSeed', nbt.TAG_Long, 0) # TODO PE worlds have a different day length, this has to be changed to that. Time = TagProperty('Time', nbt.TAG_Long, 0) LastPlayed = TagProperty('LastPlayed', nbt.TAG_Long, lambda self: long(time.time() * 1000)) GeneratorName = TagProperty('Generator', nbt.TAG_String, 'Infinite') GameType = TagProperty('GameType', nbt.TAG_Int, 0) def defaultDisplayName(self): return os.path.basename(os.path.dirname(self.filename)) def __str__(self): """ How to represent this level :return: str """ return "PocketLeveldbWorld(\"%s\")" % os.path.basename(os.path.dirname(self.worldFile.path)) def getChunk(self, cx, cz): """ Used to obtain a chunk from the database. :param cx, cz: cx, cz coordinates of the chunk :return: PocketLeveldbChunk """ if DEBUG_PE: write_dump("*** Getting chunk %s,%s\n"%(cx, cz)) c = self._loadedChunks.get((cx, cz)) if c is None: if DEBUG_PE: write_dump(" Not loaded, loading\n") c = self.worldFile.loadChunk(cx, cz, self) self._loadedChunks[(cx, cz)] = c if DEBUG_PE: write_dump("*** Loaded chunks num.: %s\n" % len(self._loadedChunks)) return c def unload(self): """ Unload all chunks and close all open file-handlers. """ self._loadedChunks.clear() self._allChunks = None self.worldFile.close() def close(self): """ Unload all chunks and close all open file-handlers. Discard any unsaved data. """ self.playerTagCache.clear() self.unload() try: shutil.rmtree(self.fileEditsFolder.filename, True) # Setup a way to close a work-folder? except SessionLockLost: pass def deleteChunk(self, cx, cz, batch=None): """ Deletes a chunk at given cx, cz. Deletes using the batch if batch is given, uses world_db() otherwise. :param cx, cz Coordinates of the chunk :param batch WriteBatch :return: None """ self.worldFile.deleteChunk(cx, cz, batch=batch) try: del self._loadedChunks[(cx, cz)] except: pass try: self.allChunks.remove((cx, cz)) except: pass def deleteChunksInBox(self, box): """ Deletes all chunks in a given box. :param box pymclevel.box.BoundingBox :return: None """ logger.info(u"Deleting {0} chunks in {1}".format((box.maxcx - box.mincx) * (box.maxcz - box.mincz), ((box.mincx, box.mincz), (box.maxcx, box.maxcz)))) i = 0 ret = [] batch = leveldb_mcpe.WriteBatch() for cx, cz in itertools.product(xrange(box.mincx, box.maxcx), xrange(box.mincz, box.maxcz)): i += 1 if self.containsChunk(cx, cz): self.deleteChunk(cx, cz, batch=batch) ret.append((cx, cz)) assert not self.containsChunk(cx, cz), "Just deleted {0} but it didn't take".format((cx, cz)) if i % 100 == 0: logger.info(u"Chunk {0}...".format(i)) with self.worldFile.world_db() as db: wop = self.worldFile.writeOptions db.Write(wop, batch) del batch return ret @property def bounds(self): """ Returns a boundingbox containing the entire level :return: pymclevel.box.BoundingBox """ if self._bounds is None: self._bounds = self._getWorldBounds() return self._bounds @property def size(self): return self.bounds.size def _getWorldBounds(self): allChunks = self.allChunks if not allChunks: return BoundingBox((0, 0, 0), (0, 0, 0)) allChunks = numpy.array(list(allChunks)) min_cx = (allChunks[:, 0]).min() max_cx = (allChunks[:, 0]).max() min_cz = (allChunks[:, 1]).min() max_cz = (allChunks[:, 1]).max() origin = (min_cx << 4, 0, min_cz << 4) size = ((max_cx - min_cx + 1) << 4, self.Height, (max_cz - min_cz + 1) << 4) return BoundingBox(origin, size) @classmethod def _isLevel(cls, filename): """ Determines whether or not the path in filename has a Pocket Edition 0.9.0 or later in it :param filename string with path to level root directory. """ clp = ("db", "level.dat") if not os.path.isdir(filename): f = os.path.basename(filename) if f not in clp: return False filename = os.path.dirname(filename) return all([os.path.exists(os.path.join(filename, fl)) for fl in clp]) def saveInPlaceGen(self): """ Save all chunks to the database, and write the root_tag back to level.dat. """ if DEBUG_PE: open(dump_fName, 'a').write("*** saveInPlaceGen\n") self.saving = True batch = leveldb_mcpe.WriteBatch() dirtyChunkCount = 0 for c in self.chunksNeedingLighting: self.getChunk(*c).genFastLights() for chunkCoords in self._loadedChunks.keys(): chunk = self._loadedChunks[chunkCoords] if chunk.dirty: dirtyChunkCount += 1 self.worldFile.saveChunk(chunk, batch=batch) chunk.dirty = False yield with nbt.littleEndianNBT(): for p in self.players: # The player data may not be in the cache if we have multi-player game. # So, accessing the cache using the player as key crashes the program... playerData = self.playerTagCache.get(p) if playerData is not None: playerData = playerData.save(compressed=False) # It will get compressed in the DB itself self.worldFile.savePlayer(p, playerData, batch=batch) with self.worldFile.world_db() as db: wop = self.worldFile.writeOptions db.Write(wop, batch) self.saving = False logger.info(u"Saved {0} chunks to the database".format(dirtyChunkCount)) path = os.path.join(self.worldFile.path, 'level.dat') with nbt.littleEndianNBT(): rootTagData = self.root_tag["Data"].save(compressed=False) # if self.world_version == '1.plus': # magic = 5 # else: # magic = 4 magic = self.dat_world_version if isinstance(magic, (str, unicode)): magic = ord(magic) rootTagData = struct.Struct('<i').pack(magic) + struct.Struct('<i').pack(len(rootTagData)) + rootTagData with open(path, 'wb') as f: f.write(rootTagData) def containsChunk(self, cx, cz): """ Determines if the chunk exist in this world. :param cx, cz: int, Coordinates of the chunk :return: bool (if chunk exists) """ return (cx, cz) in self.allChunks def createChunk(self, cx, cz): """ Creates an empty chunk at given cx, cz coordinates, and stores it in self._loadedChunks :param cx, cz: int, Coordinates of the chunk :return: """ if self.containsChunk(cx, cz): raise ValueError("{0}:Chunk {1} already present!".format(self, (cx, cz))) if self.allChunks is not None: self.allChunks.add((cx, cz)) if self.world_version == 'pre1.0': self._loadedChunks[(cx, cz)] = PocketLeveldbChunkPre1(cx, cz, self, create=True, world_version=self.world_version) else: self._loadedChunks[(cx, cz)] = PocketLeveldbChunk1Plus(cx, cz, self, create=True, world_version=self.world_version) self._bounds = None def saveGeneratedChunk(self, cx, cz, tempChunkBytes): """ Chunks get generated using Anvil generation. This is a (slow) way of importing anvil chunk bytes and converting them to MCPE chunk data. Could definitely use some improvements, but at least it works. :param cx, cx: Coordinates of the chunk :param tempChunkBytes: str. Raw MCRegion chunk data. :return: """ loaded_data = nbt.load(buf=tempChunkBytes) class fake: def __init__(self): self.Height = 128 tempChunk = AnvilChunkData(fake(), (0, 0), loaded_data) if not self.containsChunk(cx, cz): self.createChunk(cx, cz) chunk = self.getChunk(cx, cz) chunk.Blocks = numpy.array(tempChunk.Blocks, dtype='uint16') chunk.Data = numpy.array(tempChunk.Data, dtype='uint8') chunk.SkyLight = numpy.array(tempChunk.SkyLight, dtype='uint8') chunk.BlockLight = numpy.array(tempChunk.BlockLight, dtype='uint8') chunk.dirty = True self.worldFile.saveChunk(chunk) else: logger.info("Tried to import generated chunk at %s, %s but the chunk already existed."%(cx, cz)) @property def chunksNeedingLighting(self): """ Generator containing all chunks that need lighting. :yield: int (cx, cz) Coordinates of the chunk """ for chunkCoords in self._loadedChunks.keys(): chunk = self._loadedChunks[chunkCoords] if chunk.needsLighting: yield chunk.chunkPosition # -- Entity Stuff -- # A lot of this code got copy-pasted from MCInfDevOldLevel # Slight modifications to make it work with MCPE def getTileEntitiesInBox(self, box): """ Returns the Tile Entities in given box. :param box: pymclevel.box.BoundingBox :return: list of nbt.TAG_Compound """ tileEntites = [] for chunk, slices, point in self.getChunkSlices(box): tileEntites += chunk.getTileEntitiesInBox(box) return tileEntites def getEntitiesInBox(self, box): """ Returns the Entities in given box. :param box: pymclevel.box.BoundingBox :return: list of nbt.TAG_Compound """ entities = [] for chunk, slices, point in self.getChunkSlices(box): entities += chunk.getEntitiesInBox(box) return entities def getTileTicksInBox(self, box): """ Always returns None, as MCPE has no TileTicks. :param box: pymclevel.box.BoundingBox :return: list """ return [] def addEntity(self, entityTag): """ Adds an entity to the level. :param entityTag: nbt.TAG_Compound containing the entity's data. :return: """ assert isinstance(entityTag, nbt.TAG_Compound) x, y, z = map(lambda p: int(floor(p)), Entity.pos(entityTag)) try: chunk = self.getChunk(x >> 4, z >> 4) except (ChunkNotPresent, ChunkMalformed): return chunk.addEntity(entityTag) chunk.dirty = True def addTileEntity(self, tileEntityTag): """ Adds an entity to the level. :param tileEntityTag: nbt.TAG_Compound containing the Tile entity's data. :return: """ assert isinstance(tileEntityTag, nbt.TAG_Compound) if 'x' not in tileEntityTag: return x, y, z = TileEntity.pos(tileEntityTag) try: chunk = self.getChunk(x >> 4, z >> 4) except (ChunkNotPresent, ChunkMalformed): return chunk.addTileEntity(tileEntityTag) chunk.dirty = True def addTileTick(self, tickTag): """ MCPE doesn't have Tile Ticks, so this can't be added. :param tickTag: nbt.TAG_Compound :return: None """ return def tileEntityAt(self, x, y, z): """ Retrieves a tile entity at given x, y, z coordinates :param x: int :param y: int :param z: int :return: nbt.TAG_Compound or None """ chunk = self.getChunk(x >> 4, z >> 4) return chunk.tileEntityAt(x, y, z) def removeEntitiesInBox(self, box): """ Removes all entities in given box :param box: pymclevel.box.BoundingBox :return: int, count of entities removed """ count = 0 for chunk, slices, point in self.getChunkSlices(box): count += chunk.removeEntitiesInBox(box) logger.info("Removed {0} entities".format(count)) return count def removeTileEntitiesInBox(self, box): """ Removes all tile entities in given box :param box: pymclevel.box.BoundingBox :return: int, count of tile entities removed """ count = 0 for chunk, slices, point in self.getChunkSlices(box): count += chunk.removeTileEntitiesInBox(box) logger.info("Removed {0} tile entities".format(count)) return count def removeTileTicksInBox(self, box): """ MCPE doesn't have TileTicks, so this does nothing. :param box: pymclevel.box.BoundingBox :return: int, count of TileTicks removed. """ return 0 # -- Player and spawn stuff def playerSpawnPosition(self, player=None): """ Returns the default spawn position for the world. If player is given, the players spawn is returned instead. :param player: nbt.TAG_Compound, root tag of the player. :return: tuple int (x, y, z), coordinates of the spawn. """ dataTag = self.root_tag["Data"] if player is None: playerSpawnTag = dataTag else: playerSpawnTag = self.getPlayerTag(player) return [playerSpawnTag.get(i, dataTag[i]).value for i in ("SpawnX", "SpawnY", "SpawnZ")] def setPlayerSpawnPosition(self, pos, player=None): """ Sets the worlds spawn point to pos. If player is given, sets that players spawn point instead. :param pos: tuple int (x, y, z) :param player: nbt.TAG_Compound, root tag of the player :return: None """ if player is None: playerSpawnTag = self.root_tag["Data"] else: playerSpawnTag = self.getPlayerTag(player) for name, val in zip(("SpawnX", "SpawnY", "SpawnZ"), pos): playerSpawnTag[name] = nbt.TAG_Int(val) def getPlayerTag(self, player='Player'): """ Obtains a player from the world. :param player: string of the name of the player. "Player" for SSP player, player_<client-id> for SMP player. :return: nbt.TAG_Compound, root tag of the player. """ if player == '[No players]': # Apparently this is being called somewhere? return None if player == 'Player': player = '~local_player' _player = self.playerTagCache.get(player) if _player is not None: return _player playerData = self.playerData[player] with nbt.littleEndianNBT(): _player = nbt.load(buf=playerData) self.playerTagCache[player] = _player return _player def getPlayerDimension(self, player="Player"): """ Always returns 0, as MCPE only has the overworld dimension. :param player: string of the name of the player. "Player" for SSP player, player_<client-id> for SMP player. :return: int """ return 0 def setPlayerPosition(self, (x, y, z), player="Player"): """ Sets the players position to x, y, z :param (x, y, z): tuple of the coordinates of the player :param player: string of the name of the player. "Player" for SSP player, player_<client-id> for SMP player. :return: """ playerTag = self.getPlayerTag(player) nbt_type = type(playerTag["Pos"][0]) posList = nbt.TAG_List([nbt_type(p) for p in (x, y - 1.75, z)]) playerTag["Pos"] = posList def getPlayerPosition(self, player="Player"): """ Gets the players position :param player: string of the name of the player. "Player" for SSP player, player_<client-id> for SMP player. :return: tuple int (x, y, z): Coordinates of the player. """ playerTag = self.getPlayerTag(player) posList = playerTag["Pos"] x, y, z = map(lambda c: c.value, posList) return x, y + 1.75, z def setPlayerOrientation(self, yp, player="Player"): """ Gets the players orientation. :param player: string of the name of the player. "Player" for SSP player, player_<client-id> for SMP player. :param yp: int tuple (yaw, pitch) :return: None """ self.getPlayerTag(player)["Rotation"] = nbt.TAG_List([nbt.TAG_Float(p) for p in yp]) def getPlayerOrientation(self, player="Player"): """ Gets the players orientation. :param player: string of the name of the player. "Player" for SSP player, player_<client-id> for SMP player. :return: tuple int (yaw, pitch) """ yp = map(lambda x: x.value, self.getPlayerTag(player)["Rotation"]) y, p = yp if p == 0: p = 0.000000001 if p == 180.0: p -= 0.000000001 yp = y, p return numpy.array(yp) @staticmethod # Editor keeps putting this in. Probably unnecesary def setPlayerAbilities(gametype, player="Player"): """ This method is just to override the standard one, as MCPE has no abilities, as it seems. :parm gametype, int of gamemode player gets set at. :param player: string of the name of the player. "Player" for SSP player, player_<client-id> for SMP player. """ pass def setPlayerGameType(self, gametype, player="Player"): """ Sets the game type for player :param gametype: int (0=survival, 1=creative, 2=adventure, 3=spectator) :param player: string of the name of the player. "Player" for SSP player, player_<client-id> for SMP player. :return: None """ # This annoyingly works differently between single- and multi-player. if player == "Player": self.GameType = gametype self.setPlayerAbilities(gametype, player) else: playerTag = self.getPlayerTag(player) playerTag['playerGameType'] = nbt.TAG_Int(gametype) self.setPlayerAbilities(gametype, player) def getPlayerGameType(self, player="Player"): """ Obtains the players gametype. :param player: string of the name of the player. "Player" for SSP player, player_<client-id> for SMP player. :return: int (0=survival, 1=creative, 2=adventure, 3=spectator) """ if player == "Player": return self.GameType else: playerTag = self.getPlayerTag(player) return playerTag["playerGameType"].value def markDirtyChunk(self, cx, cz): self.getChunk(cx, cz).chunkChanged() def markDirtyBox(self, box): for cx, cz in box.chunkPositions: self.markDirtyChunk(cx, cz) def setSpawnerData(self, tile_entity, mob_id): """Set the data in a given mob spawner. tile_entity: TileEntity object: the mob spawner to update. mod_id: str/unicode: the mob string id to update the spawner with. Return tile_entity """ fullid = self.defsIds.mcedit_defs.get(self.defsIds.mcedit_ids.get(mob_id, "Unknown"), {}).get("fullid", None) # print fullid if fullid is not None: # This is mostly a copy of what we have in camera.py. # Has to be optimized for PE... if "EntityId" in tile_entity: tile_entity["EntityId"] = nbt.TAG_Int(fullid) if "SpawnData" in tile_entity: # Try to not clear the spawn data, but only update the mob id tag_id = nbt.TAG_Int(fullid) if "id" in tile_entity["SpawnData"]: tag_id.name = "id" tile_entity["SpawnData"]["id"] = tag_id if "EntityId" in tile_entity["SpawnData"]: tile_entity["SpawnData"]["EntityId"] = tag_id if "SpawnPotentials" in tile_entity: for potential in tile_entity["SpawnPotentials"]: if "Entity" in potential: # MC 1.9+ if potential["Entity"]["id"].value == id or ("EntityId" in potential["Entity"] and potential["Entity"]["EntityId"].value == id): potential["Entity"] = nbt.TAG_Compound() potential["Entity"]["id"] = nbt.TAG_Int(fullid) elif "Properties" in potential: # MC before 1.9 if "Type" in potential and potential["Type"].value == id: potential["Type"] = nbt.TAG_Int(fullid) else: raise AttributeError("Could not find entity data for '%s' in MCEDIT_DEFS"%mob_id) return tile_entity # ===================================================================== class PocketLeveldbChunkPre1(LightedChunk): HeightMap = FakeChunk.HeightMap Height = 128 _Entities = nbt.TAG_List() _TileEntities = nbt.TAG_List() dirty = False chunk_version = "\x02" def __init__(self, cx, cz, world, data=None, create=False, world_version=None): """ :param cx, cz int, int Coordinates of the chunk :param data List of 3 strings. (83200 bytes of terrain data, tile-entity data, entity data) :param world PocketLeveldbWorld, instance of the world the chunk belongs too """ self.world_version = world_version # For info and tracking self.chunkPosition = (cx, cz) self.world = world if create: self.Blocks = numpy.zeros(32768, 'uint16') self.Data = numpy.zeros(16384, 'uint8') self.SkyLight = numpy.zeros(16384, 'uint8') self.BlockLight = numpy.zeros(16384, 'uint8') self.DirtyColumns = numpy.zeros(256, 'uint8') self.GrassColors = numpy.zeros(1024, 'uint8') self.TileEntities = nbt.TAG_List() self.Entities = nbt.TAG_List() else: terrain = numpy.fromstring(data[0], dtype='uint8') if data[1] is not None: if DEBUG_PE: write_dump(('/' * 80) + '\nParsing TileEntities in chunk %s,%s\n' % (cx, cz)) TileEntities = loadNBTCompoundList(data[1]) self.TileEntities = nbt.TAG_List(TileEntities, list_type=nbt.TAG_COMPOUND) if data[2] is not None: if DEBUG_PE: write_dump(('\\' * 80) + '\nParsing Entities in chunk %s,%s\n' % (cx, cz)) Entities = loadNBTCompoundList(data[2]) # PE saves entities with their int ID instead of string name. We swap them to make it work in mcedit. # Whenever we save an entity, we need to make sure to swap back. defs_get = self.world.defsIds.mcedit_defs.get ids_get = self.world.defsIds.mcedit_ids.get for ent in Entities: # Get the string id, or a build one # ! For PE debugging try: v = ent["id"].value except Exception as e: logger.warning("An error occured while getting entity ID:") logger.warning(e) logger.warning("Default 'Unknown' ID is used...") v = 'Unknown' id = defs_get(ids_get(v, 'Unknown'), {'name': 'Unknown Entity %s' % v, 'idStr': 'Unknown Entity %s' % v, 'id': -1} )['name'] ent["id"] = nbt.TAG_String(id) self.Entities = nbt.TAG_List(Entities, list_type=nbt.TAG_COMPOUND) self.Blocks, terrain = terrain[:32768], terrain[32768:] self.Data, terrain = terrain[:16384], terrain[16384:] self.SkyLight, terrain = terrain[:16384], terrain[16384:] self.BlockLight, terrain = terrain[:16384], terrain[16384:] self.DirtyColumns, terrain = terrain[:256], terrain[256:] # Unused at the moment. Might need a special editor? Maybe hooked up to biomes? self.GrassColors = terrain[:1024] self._unpackChunkData() self.shapeChunkData() def _unpackChunkData(self): """ Unpacks the terrain data to match mcedit's formatting. """ for key in ('SkyLight', 'BlockLight', 'Data'): dataArray = getattr(self, key) dataArray.shape = (16, 16, 64) s = dataArray.shape unpackedData = numpy.zeros((s[0], s[1], s[2] * 2), dtype='uint8') unpackedData[:, :, ::2] = dataArray unpackedData[:, :, ::2] &= 0xf unpackedData[:, :, 1::2] = dataArray unpackedData[:, :, 1::2] >>= 4 setattr(self, key, unpackedData) def shapeChunkData(self): """ Determines the shape of the terrain data. :return: """ chunkSize = 16 self.Blocks.shape = (chunkSize, chunkSize, self.Height) self.SkyLight.shape = (chunkSize, chunkSize, self.Height) self.BlockLight.shape = (chunkSize, chunkSize, self.Height) self.Data.shape = (chunkSize, chunkSize, self.Height) self.DirtyColumns.shape = chunkSize, chunkSize def savedData(self): """ Returns the data of the chunk to save to the database. :return: str of 83200 bytes of chunk data. """ def packData(dataArray): """ Repacks the terrain data to Mojang's leveldb library's format. """ assert dataArray.shape[2] == self.Height data = numpy.array(dataArray).reshape(16, 16, self.Height / 2, 2) data[..., 1] <<= 4 data[..., 1] |= data[..., 0] return numpy.array(data[:, :, :, 1]) if self.dirty: # elements of DirtyColumns are bitfields. Each bit corresponds to a # 16-block segment of the column. We set all of the bits because # we only track modifications at the chunk level. self.DirtyColumns[:] = 255 with nbt.littleEndianNBT(): entityData = "" tileEntityData = "" defs_get = self.world.defsIds.mcedit_defs.get ids_get = self.world.defsIds.mcedit_ids.get for ent in self.TileEntities: tileEntityData += ent.save(compressed=False) for ent in self.Entities: v = ent["id"].value # ent["id"] = nbt.TAG_Int(entity.PocketEntity.entityList[v]) # id = entity.PocketEntity.getNumId(v) # print v, id, MCEDIT_DEFS.get(MCEDIT_IDS.get(v, v), {'id': -1})['id'] id = defs_get(ids_get(v, v), {'id': -1})['id'] if id >= 1000: print id print type(ent) print ent ent['id'] = nbt.TAG_Int(id) entityData += ent.save(compressed=False) # We have to re-invert after saving otherwise the next save will fail. ent["id"] = nbt.TAG_String(v) terrain = ''.join([self.Blocks.tostring(), packData(self.Data).tostring(), packData(self.SkyLight).tostring(), packData(self.BlockLight).tostring(), self.DirtyColumns.tostring(), self.GrassColors.tostring(), ]) return terrain, tileEntityData, entityData # -- Entities and TileEntities @property def Entities(self): return self._Entities @Entities.setter def Entities(self, Entities): """ :param Entities: list :return: """ self._Entities = Entities @property def TileEntities(self): return self._TileEntities @TileEntities.setter def TileEntities(self, TileEntities): """ :param TileEntities: list :return: """ self._TileEntities = TileEntities @property def TileTicks(self): return nbt.TAG_List() # ===================================================================== class PE1PlusDataContainer: """Container for subchunks data for MCPE 1.0+.""" def __init__(self, subdata_length, bin_type, name='none', shape=None, chunk_height=256): """subdata_length: int: the length for the underlying numpy objects. bin_type: str: the binary data type, like uint8 destination: numpy array class (not instance): destination object to be used by other MCEdit objects as 'chunk.Blocks', or 'chunk.Data' If a subchunk does not exists, the corresponding 'destination' aera is filled with zeros The 'destination is initialized filled and shaped here. name: str: the interna name used mainly for debug display shape: tuple: the subchunk array shape, unused """ self.name = name self.subdata_length = subdata_length self.bin_type = bin_type # the first two argument for the shape always are 16 if shape is None: self.shape = (16, 16, subdata_length / (16 * 16)) else: self.shape = shape self.destination = numpy.zeros(subdata_length * (chunk_height / 16), bin_type) self.destination.shape = (self.shape[0], self.shape[1], chunk_height) self.subchunks = [] # Store here the valid subchunks as ints self.binary_data = [None] * 16 # Has to be a numpy arrays. This list is indexed using the subchunks content. def __repr__(self): return "PE1PlusDataContainer { subdata_length: %s, bin_type: %s, shape: %s, subchunks: %s }" % (self.subdata_length, self.bin_type, self.shape, self.subchunks) def __getitem__(self, x, z, y): subchunk = y / 16 if subchunk in self.subchunks: binary_data = self.binary_data[subchunk] return binary_data[x, z, y - (subchunk * 16)] def __setitem__(self, x, z, y, data): subchunk = y / 16 if subchunk in self.subchunks: binary_data = self.binary_data[subchunk] binary_data[x, z, y - (subchunk * 16)] = data def __len__(self): return len(self.subchunks) * self.subdata_length def add_data(self, y, data): """Add data to 'y' subchunk. y: int: the subchunk to add data to data: ndarray: data to be added. Must be 4096 numbers long. Does not raise an error if the subchunk already has data. The old data is overriden. Creates the subchunk if it does not exists. """ self.binary_data[y] = data if len(data) != self.subdata_length: raise ValueError("%s: Data does not match the required %s bytes length: %s bytes"%(self.name, self.subdata_length, len(data))) try: self.binary_data[y].shape = self.shape except ValueError as e: a = list(e.args) a[0] += '%s %s: Required: %s, got: %s'%(a[0], self.name, self.shape, self.binary_data[y].shape) e.args = tuple(a) raise e self.destination[:, :, y * 16:16 + (y * 16)] = self.binary_data[y][:, :, :] if y not in self.subchunks: self.subchunks.append(y) def update_subchunks(self): """Auto-updates the existing subchunks data using the 'destination' one.""" for y in range(16): sub = self.destination[:, :, y * 16:16 + (y * 16)] if self.destination[:, :, y * 16:].any() or self.binary_data[y] is not None or y in self.subchunks: self.binary_data[y] = sub if y not in self.subchunks: self.subchunks.append(y) self.subchunks.sort() # ===================================================================== class PocketLeveldbChunk1Plus(LightedChunk): HeightMap = FakeChunk.HeightMap Height = 256 _Entities = nbt.TAG_List() _TileEntities = nbt.TAG_List() dirty = False chunk_version = "\x04" def __init__(self, cx, cz, world, data=None, create=False, world_version=None, chunk_version=None): """ cx, cz: int: coordinates of the chunk. world: PocketLeveldbWorld object: instance of the world the chunk belongs too. data: list of str: terrain, entities and tile entities data. Defaults to 'None'. Unused, but kept for compatibility. create: bool: wether to create the chunk. Defaults to 'False'. Unused, but kept for compatibility. world_version: str: used to track if the 'world' is a pre 1.0 or 1.0+ PE one. Defaults to 'None'. Initialize the subchunbk containers. """ self.world_version = world_version # For info and tracking if chunk_version: self.chunk_version = chunk_version self.chunkPosition = (cx, cz) self.world = world self.subchunks = [] self.subchunks_versions = {} possible_dtypes = [2 ** x for x in range(3, 8)] max_blocks_dtype = int(ceil(log(max([i for i,x in enumerate(pocketMaterials.idStr) if x]), 2))) max_blocks_dtype = next(possible_dtype for possible_dtype in possible_dtypes if possible_dtype >= max_blocks_dtype) max_data_dtype = int(ceil(log(max([x[1] for x in pocketMaterials.blocksByID.keys()]), 2))) max_data_dtype = next(possible_dtype for possible_dtype in possible_dtypes if possible_dtype >= max_data_dtype) self._Blocks = PE1PlusDataContainer(4096, 'uint'+str(max_blocks_dtype), name='Blocks', chunk_height=self.Height) self.Blocks = self._Blocks.destination self._Data = PE1PlusDataContainer(4096, 'uint'+str(max_data_dtype), name='Data') self.Data = self._Data.destination self._SkyLight = PE1PlusDataContainer(4096, 'uint8', name='SkyLight') self.SkyLight = self._SkyLight.destination self.SkyLight[:] = 15 self._BlockLight = PE1PlusDataContainer(4096, 'uint8', name='BlockLight') self.BlockLight = self._BlockLight.destination self.TileEntities = nbt.TAG_List(list_type=nbt.TAG_COMPOUND) self.Entities = nbt.TAG_List(list_type=nbt.TAG_COMPOUND) self.Biomes = numpy.zeros((16, 16), 'uint8') self.data2d = None self._extra_blocks = PE1PlusDataContainer(4096, 'uint' + str(max_blocks_dtype), name='extra_blocks', chunk_height=self.Height) self.extra_blocks = self._extra_blocks.destination self._extra_blocks_data = PE1PlusDataContainer(4096, 'uint' + str(max_data_dtype), name='extra_blocks_data') self.extra_blocks_data = self._extra_blocks_data.destination def _read_block_storage(self, storage): bits_per_block, storage = ord(storage[0]) >> 1, storage[1:] blocks_per_word = int(floor(32 / bits_per_block)) word_count = int(ceil(4096 / float(blocks_per_word))) raw_blocks, storage = storage[:word_count * 4], storage[word_count * 4:] word_size = 32 bin_arr = numpy.unpackbits(numpy.frombuffer(bytearray(raw_blocks), dtype='uint8')).astype(bool) # cut redundant bits word_arr = bin_arr.reshape(-1, word_size/8, 8) word_arr = word_arr[:, ::-1, :] word_arr = word_arr.reshape(-1, word_size) redundant_bits = word_size % bits_per_block clean_word_arr = word_arr[:, redundant_bits:] # convert blocks to uint clean_word_arr = clean_word_arr.reshape(-1, word_size / bits_per_block, bits_per_block)[:, ::-1] block_arr = clean_word_arr.reshape(-1, bits_per_block) block_size = max(bits_per_block, 8) blocks_before_palette = block_arr.dot(2**numpy.arange(block_arr.shape[1]-1, -1, -1))[:4096] blocks_before_palette = blocks_before_palette.astype("uint"+str(block_size)) # This might be varint and not just 4 bytes, need to make sure palette_size, palette = struct.unpack("<i", storage[:4])[0], storage[4:] palette_nbt, storage = loadNBTCompoundList(palette, partNBT=True, count=palette_size) if not hasattr(pocketMaterials, 'tempBlockID'): pocketMaterials.tempBlockID = max([numID for numID, item in enumerate(pocketMaterials.idStr) if item]) + 1 ids = [] data = [] for item in palette_nbt: idStr = item["name"].value.split(':',1)[-1] if idStr == '': idStr = 'air' item["val"] = nbt.TAG_Short(0) if idStr != 'air' and idStr not in pocketMaterials.idStr: pocketMaterials.addJSONBlock({"id": pocketMaterials.tempBlockID, "name": idStr, "idStr": idStr, "mapcolor": [214, 127, 255], "data": {n: {"name": idStr} for n in range(16)}}) pocketMaterials.tempBlockID += 1 if idStr == 'air': ids.append(0) elif idStr in pocketMaterials.idStr: ids.append(pocketMaterials.idStr.index(idStr)) else: ids.append(255) data.append(item["val"].value) blocks = numpy.asarray(ids, dtype=self._Blocks.bin_type)[blocks_before_palette] data = numpy.asarray(data, dtype=self._Data.bin_type)[blocks_before_palette] return blocks, data, storage def add_data(self, terrain=None, tile_entities=None, entities=None, subchunk=None): """Add terrain to chunk. terrain, tile_entities, entities: str: 4096 long string. Defaults to 'None'. subchunk: int: subchunk 'height'; generaly 0 to 15 number. """ if type(subchunk) != int: raise TypeError("Bad subchunk type. Must be an int, got %s (%s)"%(type(subchunk), subchunk)) if terrain: self.subchunks.append(subchunk) subchunk_version, terrain = ord(terrain[0]), terrain[1:] if subchunk_version in [0, 2, 3, 4, 5, 6, 7]: blocks, terrain = terrain[:4096], terrain[4096:] data, terrain = terrain[:2048], terrain[2048:] skyLight, terrain = terrain[:2048], terrain[2048:] blockLight, terrain = terrain[:2048], terrain[2048:] # 'Computing' data is needed before sending it to the data holders. self._Blocks.add_data(subchunk, numpy.fromstring(blocks, "uint8").astype(self._Blocks.bin_type)) # for k, v in ((self._Data, data), (self._SkyLight, skyLight), (self._BlockLight, blockLight)): # a = numpy.fromstring(v, k.bin_type) # a.shape = (16, 16, len(v) / 256) # k.add_data(subchunk, unpackNibbleArray(a).tostring()) a = numpy.fromstring(data, "uint8") a.shape = (16, 16, len(data) / 256) self._Data.add_data(subchunk, numpy.fromstring(unpackNibbleArray(a).tostring(), "uint8").astype(self._Data.bin_type)) if self.chunk_version == "\x03": for k, v in ((self._SkyLight, skyLight), (self._BlockLight, blockLight)): a = numpy.fromstring(v, "uint8") a.shape = (16, 16, len(v) / 256) k.add_data(subchunk, numpy.fromstring(unpackNibbleArray(a).tostring(), "uint8").astype(k.bin_type)) elif subchunk_version == 1: blocks, data, terrain = self._read_block_storage(terrain) self._Blocks.add_data(subchunk, blocks) self._Data.add_data(subchunk, data) elif subchunk_version == 8: num_of_storages, terrain = ord(terrain[0]), terrain[1:] blocks, data, terrain = self._read_block_storage(terrain) self._Blocks.add_data(subchunk, blocks) self._Data.add_data(subchunk, data) if num_of_storages > 1: extraBlocks, extraData, ignored_data = self._read_block_storage(terrain) self._extra_blocks.add_data(subchunk, extraBlocks) self._extra_blocks_data.add_data(subchunk, extraData) # Only support for one layer of extra blocks is in place else: raise NotImplementedError("Not implemented this new type of world format yet") self.subchunks_versions[subchunk] = subchunk_version # if DEBUG_PE: # write_dump("--- sub-chunk (%s, %s, %s) version: %s\n" % (self.chunkPosition[0], self.chunkPosition[1], subchunk, version)) # write_dump("--- sub-chunk (%s, %s, %s) blocks: %s\n length: %s\n" % (self.chunkPosition[0], self.chunkPosition[1], subchunk, repr(blocks), len(blocks))) else: if subchunk == 0 and DEBUG_PE: write_dump("!!! No terrain for sub-chunk (%s, %s, %s)\n" % (self.chunkPosition[0], self.chunkPosition[1], subchunk)) if tile_entities: if DEBUG_PE: write_dump(('/' * 80) + '\nParsing TileEntities in chunk %s,%s\n' % (self.chunkPosition[0], self.chunkPosition[1])) if DEBUG_PE == 2: write_dump("+ begin tile_entities raw data\n%s\n- end tile_entities raw data\n" % nbt.hexdump(tile_entities, length=16)) for tile_entity in loadNBTCompoundList(tile_entities): self.TileEntities.insert(-1, tile_entity) if entities: mcedit_defs = self.world.defsIds.mcedit_defs defs_get = mcedit_defs.get ids_get = self.world.defsIds.mcedit_ids.get if DEBUG_PE: write_dump(('\\' * 80) + '\nParsing Entities in chunk %s,%s\n' % (self.chunkPosition[0], self.chunkPosition[1])) try: Entities = loadNBTCompoundList(entities) except Exception as exc: logger.error("The entities data for chunk %s:%s may be corrupted. The error is:\n%s" % (self.chunkPosition[0], self.chunkPosition[1], exc)) Entities = nbt.TAG_List() # PE saves entities with their int ID instead of string name. We swap them to make it work in mcedit. # Whenever we save an entity, we need to make sure to swap back. # invertEntities = {v: k for k, v in entity.PocketEntity.entityList.items()} for ent in Entities: if 'identifier' in ent: ent["id"] = nbt.TAG_String('see "identifier"') else: try: v = ent["id"].value if DEBUG_PE: _v = int(v) v = int(v) & 0xFF except Exception as e: logger.warning("An error occured while getting entity ID:") logger.warning(e) logger.warning("Default 'Unknown' ID is used...") v = 'Unknown' # ! # id = invertEntities.get(v, "Entity %s"%v) # Add the built one to the entities # if id not in entity.PocketEntity.entityList.keys(): # logger.warning("Found unknown entity '%s'"%v) # entity.PocketEntity.entityList[id] = v try: id = defs_get(ids_get(v, 'Unknown'), {'name': 'Unknown Entity %s' % v, 'idStr': 'Unknown Entity %s' % v, 'id': -1, 'type': 'Unknown'} )['name'] except: continue if DEBUG_PE: ent_def = defs_get(ids_get(v, 'Unknown'), {'name': 'Unknown Entity %s' % v, 'idStr': 'Unknown Entity %s' % v, 'id': -1, 'type': 'Unknown'} ) _tn = ent_def.get('type', 'Unknown') _tv = mcedit_defs['entity_types'].get(_tn, 'Unknown') write_dump("* Internal ID: {id}, raw ID: {_v}, filtered ID: {_fid}, filter: {_f1} ({_f2}), type name {_tn}, type value: {_tv}\n".format( id=id, _v=_v, _fid= _v & 0xff, _f1= _v & 0xff00, _f2= _v - (_v & 0xff), _tn=_tn, _tv=_tv) ) ent["id"] = nbt.TAG_String(id) self.Entities.insert(-1, ent) def savedData(self): """Unused, raises NotImplementedError().""" # Not used for PE 1+ worlds... May change :) raise NotImplementedError() def genFastLights(self): pass # -- Entities and TileEntities @property def Entities(self): return self._Entities @Entities.setter def Entities(self, Entities): """ :param Entities: list :return: """ self._Entities = Entities @property def TileEntities(self): return self._TileEntities @TileEntities.setter def TileEntities(self, TileEntities): """ :param TileEntities: list :return: """ self._TileEntities = TileEntities @property def TileTicks(self): return nbt.TAG_List()
87,248
40.389469
204
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/setup.py
from setuptools import setup from setuptools.extension import Extension from Cython.Distutils import build_ext import numpy version = '0.1' install_requires = [ # -*- Extra requirements: -*- "numpy", "pyyaml", ] ext_modules = [Extension("_nbt", ["_nbt.pyx"])] setup(name='pymclevel', version=version, description="Python library for reading Minecraft levels", long_description=open("./README.txt", "r").read(), # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Console", "Intended Audience :: End Users/Desktop", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python :: 2.7", "Topic :: Utilities", "License :: OSI Approved :: MIT License", ], keywords='minecraft', author='David Vierra', author_email='[email protected]', url='https://github.com/mcedit/pymclevel', license='MIT License', package_dir={'pymclevel': '.'}, packages=["pymclevel"], ext_modules=ext_modules, include_dirs=numpy.get_include(), include_package_data=True, zip_safe=False, install_requires=install_requires, cmdclass={'build_ext': build_ext}, entry_points=""" # -*- Entry points: -*- [console_scripts] mce.py=pymclevel.mce:main """, )
1,439
26.692308
77
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/cachefunc.py
# From http://code.activestate.com/recipes/498245/ import collections import functools from itertools import ifilterfalse from heapq import nsmallest from operator import itemgetter class Counter(dict): 'Mapping where default values are zero' @staticmethod def __missing__(key): return 0 def lru_cache(maxsize=100): '''Least-recently-used cache decorator. Arguments to the cached function must be hashable. Cache performance statistics stored in f.hits and f.misses. Clear the cache with f.clear(). http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used ''' maxqueue = maxsize * 10 def decorating_function(user_function, len=len, iter=iter, tuple=tuple, sorted=sorted, KeyError=KeyError): cache = {} # mapping of args to results queue = collections.deque() # order that keys have been used refcount = Counter() # times each key is in the queue sentinel = object() # marker for looping around the queue kwd_mark = object() # separate positional and keyword args # lookup optimizations (ugly but fast) queue_append, queue_popleft = queue.append, queue.popleft queue_appendleft, queue_pop = queue.appendleft, queue.pop @functools.wraps(user_function) def wrapper(*args, **kwds): # cache key records both positional and keyword args key = args if kwds: key += (kwd_mark,) + tuple(sorted(kwds.items())) # record recent use of this key queue_append(key) refcount[key] += 1 # get cache entry or compute if not found try: result = cache[key] wrapper.hits += 1 except KeyError: result = user_function(*args, **kwds) cache[key] = result wrapper.misses += 1 # purge least recently used cache entry if len(cache) > maxsize: key = queue_popleft() refcount[key] -= 1 while refcount[key]: key = queue_popleft() refcount[key] -= 1 del cache[key], refcount[key] # periodically compact the queue by eliminating duplicate keys # while preserving order of most recent access if len(queue) > maxqueue: refcount.clear() queue_appendleft(sentinel) for key in ifilterfalse(refcount.__contains__, iter(queue_pop, sentinel)): queue_appendleft(key) refcount[key] = 1 return result def clear(): cache.clear() queue.clear() refcount.clear() wrapper.hits = wrapper.misses = 0 wrapper.hits = wrapper.misses = 0 wrapper.clear = clear return wrapper return decorating_function def lfu_cache(maxsize=100): '''Least-frequenty-used cache decorator. Arguments to the cached function must be hashable. Cache performance statistics stored in f.hits and f.misses. Clear the cache with f.clear(). http://en.wikipedia.org/wiki/Least_Frequently_Used ''' def decorating_function(user_function): cache = {} # mapping of args to results use_count = Counter() # times each key has been accessed kwd_mark = object() # separate positional and keyword args @functools.wraps(user_function) def wrapper(*args, **kwds): key = args if kwds: key += (kwd_mark,) + tuple(sorted(kwds.items())) use_count[key] += 1 # get cache entry or compute if not found try: result = cache[key] wrapper.hits += 1 except KeyError: result = user_function(*args, **kwds) cache[key] = result wrapper.misses += 1 # purge least frequently used cache entry if len(cache) > maxsize: for key, _ in nsmallest(maxsize // 10, use_count.iteritems(), key=itemgetter(1)): del cache[key], use_count[key] return result def clear(): cache.clear() use_count.clear() wrapper.hits = wrapper.misses = 0 wrapper.hits = wrapper.misses = 0 wrapper.clear = clear return wrapper return decorating_function if __name__ == '__main__': @lru_cache(maxsize=20) def f_lru(x, y): return 3 * x + y domain = range(5) from random import choice for i in xrange(1000): r = f_lru(choice(domain), choice(domain)) print(f_lru.hits, f_lru.misses) @lfu_cache(maxsize=20) def f_lfu(x, y): return 3 * x + y domain = range(5) from random import choice for i in xrange(1000): r = f_lfu(choice(domain), choice(domain)) print(f_lfu.hits, f_lfu.misses)
5,237
29.631579
95
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/biome_types.py
biome_types = { -1: '(Uncalculated)', 0: 'Ocean', 1: 'Plains', 2: 'Desert', 3: 'Extreme Hills', 4: 'Forest', 5: 'Taiga', 6: 'Swamppland', 7: 'River', 8: 'Hell (Nether)', 9: 'Sky (End)', 10: 'Frozen Ocean', 11: 'Frozen River', 12: 'Ice Plains', 13: 'Ice Mountains', 14: 'Mushroom Island', 15: 'Mushroom Island Shore', 16: 'Beach', 17: 'Desert Hills', 18: 'Forest Hills', 19: 'Taiga Hills', 20: 'Extreme Hills Edge', 21: 'Jungle', 22: 'Jungle Hills', 23: 'Jungle Edge', 24: 'Deep Ocean', 25: 'Stone Beach', 26: 'Cold Beach', 27: 'Birch Forest', 28: 'Birch Forest Hills', 29: 'Roofed Forest', 30: 'Cold Taiga', 31: 'Cold Taiga Hills', 32: 'Mega Taiga', 33: 'Mega Taiga Hills', 34: 'Extreme Hills+', 35: 'Savanna', 36: 'Savanna Plateau', 37: 'Messa', 38: 'Messa Plateau F', 39: 'Messa Plateau', 127: 'The Void', 129: 'Sunflower Plains', 130: 'Desert M', 131: 'Extreme Hills M', 132: 'Flower Forest', 133: 'Taiga M', 134: 'Swampland M', 140: 'Ice Plains Spikes', 141: 'Ice Mountains Spikes', 149: 'Jungle M', 151: 'JungleEdge M', 155: 'Birch Forest M', 156: 'Birch Forest Hills M', 157: 'Roofed Forest M', 158: 'Cold Taiga M', 160: 'Mega Spruce Taiga', 161: 'Mega Spruce Taiga 2', 162: 'Extreme Hills+ M', 163: 'Savanna M', 164: 'Savanna Plateau M', 165: 'Mesa (Bryce)', 166: 'Mesa Plateau F M', 167: 'Mesa Plateau M' }
1,571
22.462687
32
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/indev.py
""" Created on Jul 22, 2011 @author: Rio Indev levels: TAG_Compound "MinecraftLevel" { TAG_Compound "Environment" { TAG_Short "SurroundingGroundHeight"// Height of surrounding ground (in blocks) TAG_Byte "SurroundingGroundType" // Block ID of surrounding ground TAG_Short "SurroundingWaterHeight" // Height of surrounding water (in blocks) TAG_Byte "SurroundingWaterType" // Block ID of surrounding water TAG_Short "CloudHeight" // Height of the cloud layer (in blocks) TAG_Int "CloudColor" // Hexadecimal value for the color of the clouds TAG_Int "SkyColor" // Hexadecimal value for the color of the sky TAG_Int "FogColor" // Hexadecimal value for the color of the fog TAG_Byte "SkyBrightness" // The brightness of the sky, from 0 to 100 } TAG_List "Entities" { TAG_Compound { // One of these per entity on the map. // These can change a lot, and are undocumented. // Feel free to play around with them, though. // The most interesting one might be the one with ID "LocalPlayer", which contains the player inventory } } TAG_Compound "Map" { // To access a specific block from either byte array, use the following algorithm: // Index = x + (y * Depth + z) * Width TAG_Short "Width" // Width of the level (along X) TAG_Short "Height" // Height of the level (along Y) TAG_Short "Length" // Length of the level (along Z) TAG_Byte_Array "Blocks" // An array of Length*Height*Width bytes specifying the block types TAG_Byte_Array "Data" // An array of Length*Height*Width bytes with data for each blocks TAG_List "Spawn" // Default spawn position { TAG_Short x // These values are multiplied by 32 before being saved TAG_Short y // That means that the actual values are x/32.0, y/32.0, z/32.0 TAG_Short z } } TAG_Compound "About" { TAG_String "Name" // Level name TAG_String "Author" // Name of the player who made the level TAG_Long "CreatedOn" // Timestamp when the level was first created } } """ from entity import TileEntity from level import MCLevel from logging import getLogger from materials import indevMaterials from numpy import array, swapaxes import nbt import os log = getLogger(__name__) MinecraftLevel = "MinecraftLevel" Environment = "Environment" SurroundingGroundHeight = "SurroundingGroundHeight" SurroundingGroundType = "SurroundingGroundType" SurroundingWaterHeight = "SurroundingWaterHeight" SurroundingWaterType = "SurroundingWaterType" CloudHeight = "CloudHeight" CloudColor = "CloudColor" SkyColor = "SkyColor" FogColor = "FogColor" SkyBrightness = "SkyBrightness" About = "About" Name = "Name" Author = "Author" CreatedOn = "CreatedOn" Spawn = "Spawn" __all__ = ["MCIndevLevel"] from level import EntityLevel class MCIndevLevel(EntityLevel): """ IMPORTANT: self.Blocks and self.Data are indexed with [x,z,y] via axis swapping to be consistent with infinite levels.""" materials = indevMaterials _gamePlatform = 'indev' def setPlayerSpawnPosition(self, pos, player=None): assert len(pos) == 3 self.Spawn = array(pos) def playerSpawnPosition(self, player=None): return self.Spawn def setPlayerPosition(self, pos, player="Ignored"): self.LocalPlayer["Pos"] = nbt.TAG_List([nbt.TAG_Float(p) for p in pos]) def getPlayerPosition(self, player="Ignored"): return array(map(lambda x: x.value, self.LocalPlayer["Pos"])) def setPlayerOrientation(self, yp, player="Ignored"): self.LocalPlayer["Rotation"] = nbt.TAG_List([nbt.TAG_Float(p) for p in yp]) def getPlayerOrientation(self, player="Ignored"): """ returns (yaw, pitch) """ return array(map(lambda x: x.value, self.LocalPlayer["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 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] 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] def __repr__(self): return u"MCIndevLevel({0}): {1}W {2}L {3}H".format(self.filename, self.Width, self.Length, self.Height) @classmethod def _isTagLevel(cls, root_tag): return "MinecraftLevel" == root_tag.name 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.filename = filename if root_tag: self.root_tag = root_tag mapTag = root_tag["Map"] self.Width = mapTag["Width"].value self.Length = mapTag["Length"].value self.Height = mapTag["Height"].value mapTag["Blocks"].value.shape = (self.Height, self.Length, self.Width) self.Blocks = swapaxes(mapTag["Blocks"].value, 0, 2) mapTag["Data"].value.shape = (self.Height, self.Length, self.Width) self.Data = swapaxes(mapTag["Data"].value, 0, 2) self.BlockLight = self.Data & 0xf self.Data >>= 4 self.Spawn = [mapTag[Spawn][i].value for i in xrange(3)] if "Entities" not in root_tag: root_tag["Entities"] = nbt.TAG_List() self.Entities = root_tag["Entities"] # xxx fixup Motion and Pos to match infdev format def numbersToDoubles(ent): for attr in "Motion", "Pos": if attr in ent: ent[attr] = nbt.TAG_List([nbt.TAG_Double(t.value) for t in ent[attr]]) for ent in self.Entities: numbersToDoubles(ent) if "TileEntities" not in root_tag: root_tag["TileEntities"] = nbt.TAG_List() self.TileEntities = root_tag["TileEntities"] # xxx fixup TileEntities positions to match infdev format for te in self.TileEntities: pos = te["Pos"].value (x, y, z) = self.decodePos(pos) TileEntity.setpos(te, (x, y, z)) localPlayerList = [tag for tag in root_tag["Entities"] if tag['id'].value == 'LocalPlayer'] if len(localPlayerList) == 0: # omen doesn't make a player entity playerTag = nbt.TAG_Compound() playerTag['id'] = nbt.TAG_String('LocalPlayer') playerTag['Pos'] = nbt.TAG_List([nbt.TAG_Float(0.), nbt.TAG_Float(64.), nbt.TAG_Float(0.)]) playerTag['Rotation'] = nbt.TAG_List([nbt.TAG_Float(0.), nbt.TAG_Float(45.)]) self.LocalPlayer = playerTag else: self.LocalPlayer = localPlayerList[0] else: log.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 # self.SurroundingWaterHeight = root_tag[Environment][SurroundingGroundHeight].value # self.SurroundingWaterType = root_tag[Environment][SurroundingWaterType].value # self.CloudHeight = root_tag[Environment][CloudHeight].value # self.CloudColor = root_tag[Environment][CloudColor].value # self.SkyColor = root_tag[Environment][SkyColor].value # self.FogColor = root_tag[Environment][FogColor].value # self.SkyBrightness = root_tag[Environment][SkyBrightness].value # self.TimeOfDay = root_tag[Environment]["TimeOfDay"].value # # # self.Name = self.root_tag[About][Name].value # self.Author = self.root_tag[About][Author].value # self.CreatedOn = self.root_tag[About][CreatedOn].value def rotateLeft(self): MCLevel.rotateLeft(self) self.Data = swapaxes(self.Data, 1, 0)[:, ::-1, :] # x=y; y=-x torchRotation = array([0, 4, 3, 1, 2, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) torchIndexes = (self.Blocks == self.materials.Torch.ID) log.info(u"Rotating torches: {0}".format(len(torchIndexes.nonzero()[0]))) self.Data[torchIndexes] = torchRotation[self.Data[torchIndexes]] @staticmethod def decodePos(v): b = 10 m = (1 << b) - 1 return v & m, (v >> b) & m, (v >> (2 * b)) @staticmethod def encodePos(x, y, z): b = 10 return x + (y << b) + (z << (2 * b)) def saveToFile(self, filename=None): if filename is None: filename = self.filename if filename is None: log.warn(u"Attempted to save an unnamed file in place") return # you fool! self.Data <<= 4 self.Data |= (self.BlockLight & 0xf) self.Blocks = swapaxes(self.Blocks, 0, 2) self.Data = swapaxes(self.Data, 0, 2) mapTag = nbt.TAG_Compound() mapTag["Width"] = nbt.TAG_Short(self.Width) mapTag["Height"] = nbt.TAG_Short(self.Height) mapTag["Length"] = nbt.TAG_Short(self.Length) mapTag["Blocks"] = nbt.TAG_Byte_Array(self.Blocks) mapTag["Data"] = nbt.TAG_Byte_Array(self.Data) self.Blocks = swapaxes(self.Blocks, 0, 2) self.Data = swapaxes(self.Data, 0, 2) mapTag[Spawn] = nbt.TAG_List([nbt.TAG_Short(i) for i in self.Spawn]) self.root_tag["Map"] = mapTag self.Entities.append(self.LocalPlayer) # fix up Entities imported from Alpha worlds def numbersToFloats(ent): for attr in "Motion", "Pos": if attr in ent: ent[attr] = nbt.TAG_List([nbt.TAG_Double(t.value) for t in ent[attr]]) for ent in self.Entities: numbersToFloats(ent) # fix up TileEntities imported from Alpha worlds. for ent in self.TileEntities: if "Pos" not in ent and all(c in ent for c in 'xyz'): ent["Pos"] = nbt.TAG_Int(self.encodePos(ent['x'].value, ent['y'].value, ent['z'].value)) # output_file = gzip.open(self.filename, "wb", compresslevel=1) try: os.rename(filename, filename + ".old") except Exception: pass try: self.root_tag.save(filename) except: os.rename(filename + ".old", filename) try: os.remove(filename + ".old") except Exception: pass self.Entities.remove(self.LocalPlayer) self.BlockLight = self.Data & 0xf self.Data >>= 4
11,565
34.697531
111
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/mclevelbase.py
''' Created on Jul 22, 2011 @author: Rio ''' from contextlib import contextmanager from logging import getLogger log = getLogger(__name__) @contextmanager def notclosing(f): yield f class PlayerNotFound(Exception): pass class ChunkNotPresent(Exception): pass class RegionMalformed(Exception): pass class ChunkMalformed(ChunkNotPresent): pass class ChunkConcurrentException(Exception): """Exception that is raised when a chunk is being modified while saving is taking place""" pass class ChunkAccessDenied(ChunkNotPresent): """Exception that is raised when a chunk is trying to be read from disk while saving is taking place""" pass def exhaust(_iter): """Functions named ending in "Iter" return an iterable object that does long-running work and yields progress information on each call. exhaust() is used to implement the non-Iter equivalents""" i = None for i in _iter: pass return i
980
17.509434
81
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/regionfile.py
import logging import os import struct import zlib from numpy import fromstring import time from mclevelbase import notclosing, RegionMalformed, ChunkNotPresent import nbt log = logging.getLogger(__name__) __author__ = 'Rio' def deflate(data): return zlib.compress(data, 2) def inflate(data): return zlib.decompress(data) class MCRegionFile(object): holdFileOpen = False # if False, reopens and recloses the file on each access @property def file(self): openfile = lambda: open(self.path, "rb+") if MCRegionFile.holdFileOpen: if self._file is None: self._file = openfile() return notclosing(self._file) else: return openfile() def close(self): if MCRegionFile.holdFileOpen: self._file.close() self._file = None def __del__(self): self.close() def __init__(self, path, regionCoords): self.path = path self.regionCoords = regionCoords self._file = None if not os.path.exists(path): open(path, "w").close() with self.file as f: filesize = os.path.getsize(path) if filesize & 0xfff: filesize = (filesize | 0xfff) + 1 f.truncate(filesize) if filesize == 0: filesize = self.SECTOR_BYTES * 2 f.truncate(filesize) f.seek(0) offsetsData = f.read(self.SECTOR_BYTES) modTimesData = f.read(self.SECTOR_BYTES) self.freeSectors = [True] * (filesize / self.SECTOR_BYTES) self.freeSectors[0:2] = False, False self.offsets = fromstring(offsetsData, dtype='>u4') self.modTimes = fromstring(modTimesData, dtype='>u4') needsRepair = False for offset in self.offsets: sector = offset >> 8 count = offset & 0xff for i in xrange(sector, sector + count): if i >= len(self.freeSectors): # raise RegionMalformed("Region file offset table points to sector {0} (past the end of the file)".format(i)) print "Region file offset table points to sector {0} (past the end of the file)".format(i) needsRepair = True break if self.freeSectors[i] is False: needsRepair = True self.freeSectors[i] = False if needsRepair: self.repair() log.info("Found region file {file} with {used}/{total} sectors used and {chunks} chunks present".format( file=os.path.basename(path), used=self.usedSectors, total=self.sectorCount, chunks=self.chunkCount)) def __repr__(self): return "%s(\"%s\")" % (self.__class__.__name__, self.path) @property def usedSectors(self): return len(self.freeSectors) - sum(self.freeSectors) @property def sectorCount(self): return len(self.freeSectors) @property def chunkCount(self): return sum(self.offsets > 0) def repair(self): lostAndFound = {} _freeSectors = [True] * len(self.freeSectors) _freeSectors[0] = _freeSectors[1] = False deleted = 0 recovered = 0 log.info("Beginning repairs on {file} ({chunks} chunks)".format(file=os.path.basename(self.path), chunks=sum(self.offsets > 0))) rx, rz = self.regionCoords for index, offset in enumerate(self.offsets): if offset: cx = index & 0x1f cz = index >> 5 cx += rx << 5 cz += rz << 5 sectorStart = offset >> 8 sectorCount = offset & 0xff try: if sectorStart + sectorCount > len(self.freeSectors): raise RegionMalformed( "Offset {start}:{end} ({offset}) at index {index} pointed outside of the file".format( start=sectorStart, end=sectorStart + sectorCount, index=index, offset=offset)) data = self.readChunk(cx, cz) if data is None: raise RegionMalformed("Failed to read chunk data for {0}".format((cx, cz))) chunkTag = nbt.load(buf=data) lev = chunkTag["Level"] xPos = lev["xPos"].value zPos = lev["zPos"].value overlaps = False for i in xrange(sectorStart, sectorStart + sectorCount): if _freeSectors[i] is False: overlaps = True _freeSectors[i] = False if xPos != cx or zPos != cz or overlaps: lostAndFound[xPos, zPos] = data if (xPos, zPos) != (cx, cz): raise RegionMalformed( "Chunk {found} was found in the slot reserved for {expected}".format(found=(xPos, zPos), expected=(cx, cz))) else: raise RegionMalformed( "Chunk {found} (in slot {expected}) has overlapping sectors with another chunk!".format( found=(xPos, zPos), expected=(cx, cz))) except Exception as e: log.info("Unexpected chunk data at sector {sector} ({exc})".format(sector=sectorStart, exc=e)) self.setOffset(cx, cz, 0) deleted += 1 for cPos, foundData in lostAndFound.iteritems(): cx, cz = cPos if self.getOffset(cx, cz) == 0: log.info("Found chunk {found} and its slot is empty, recovering it".format(found=cPos)) self.saveChunk(cx, cz, foundData) recovered += 1 log.info("Repair complete. Removed {0} chunks, recovered {1} chunks, net {2}".format(deleted, recovered, recovered - deleted)) def _readChunk(self, cx, cz): cx &= 0x1f cz &= 0x1f offset = self.getOffset(cx, cz) if offset == 0: raise ChunkNotPresent((cx, cz)) sectorStart = offset >> 8 numSectors = offset & 0xff if numSectors == 0: raise ChunkNotPresent((cx, cz)) if sectorStart + numSectors > len(self.freeSectors): raise ChunkNotPresent((cx, cz)) with self.file as f: f.seek(sectorStart * self.SECTOR_BYTES) data = f.read(numSectors * self.SECTOR_BYTES) if len(data) < 5: raise RegionMalformed("Chunk data is only %d bytes long (expected 5)" % len(data)) # log.debug("REGION LOAD {0},{1} sector {2}".format(cx, cz, sectorStart)) length = struct.unpack_from(">I", data)[0] format = struct.unpack_from("B", data, 4)[0] data = data[5:length + 5] return data, format def readChunk(self, cx, cz): data, format = self._readChunk(cx, cz) if format == self.VERSION_GZIP: return nbt.gunzip(data) if format == self.VERSION_DEFLATE: return inflate(data) raise IOError("Unknown compress format: {0}".format(format)) def copyChunkFrom(self, regionFile, cx, cz): """ Silently fails if regionFile does not contain the requested chunk. """ try: data, format = regionFile._readChunk(cx, cz) self._saveChunk(cx, cz, data, format) except ChunkNotPresent: pass def saveChunk(self, cx, cz, uncompressedData): data = deflate(uncompressedData) try: self._saveChunk(cx, cz, data, self.VERSION_DEFLATE) except ChunkTooBig as e: raise ChunkTooBig(e.message + " (%d uncompressed)" % len(uncompressedData)) def _saveChunk(self, cx, cz, data, format): cx &= 0x1f cz &= 0x1f offset = self.getOffset(cx, cz) sectorNumber = offset >> 8 sectorsAllocated = offset & 0xff sectorsNeeded = (len(data) + self.CHUNK_HEADER_SIZE) / self.SECTOR_BYTES + 1 if sectorsNeeded >= 256: raise ChunkTooBig("Chunk too big! %d bytes exceeds 1MB" % len(data)) if sectorNumber != 0 and sectorsAllocated >= sectorsNeeded: log.debug("REGION SAVE {0},{1} rewriting {2}b".format(cx, cz, len(data))) self.writeSector(sectorNumber, data, format) else: # we need to allocate new sectors # mark the sectors previously used for this chunk as free for i in xrange(sectorNumber, sectorNumber + sectorsAllocated): self.freeSectors[i] = True runLength = 0 runStart = 0 try: runStart = self.freeSectors.index(True) for i in xrange(runStart, len(self.freeSectors)): if runLength: if self.freeSectors[i]: runLength += 1 else: runLength = 0 elif self.freeSectors[i]: runStart = i runLength = 1 if runLength >= sectorsNeeded: break except ValueError: pass # we found a free space large enough if runLength >= sectorsNeeded: log.debug("REGION SAVE {0},{1}, reusing {2}b".format(cx, cz, len(data))) sectorNumber = runStart self.setOffset(cx, cz, sectorNumber << 8 | sectorsNeeded) self.writeSector(sectorNumber, data, format) self.freeSectors[sectorNumber:sectorNumber + sectorsNeeded] = [False] * sectorsNeeded else: # no free space large enough found -- we need to grow the # file log.debug("REGION SAVE {0},{1}, growing by {2}b".format(cx, cz, len(data))) with self.file as f: f.seek(0, 2) filesize = f.tell() sectorNumber = len(self.freeSectors) assert sectorNumber * self.SECTOR_BYTES == filesize filesize += sectorsNeeded * self.SECTOR_BYTES f.truncate(filesize) self.freeSectors += [False] * sectorsNeeded self.setOffset(cx, cz, sectorNumber << 8 | sectorsNeeded) self.writeSector(sectorNumber, data, format) self.setTimestamp(cx, cz) def writeSector(self, sectorNumber, data, format): with self.file as f: log.debug("REGION: Writing sector {0}".format(sectorNumber)) f.seek(sectorNumber * self.SECTOR_BYTES) f.write(struct.pack(">I", len(data) + 1)) # // chunk length f.write(struct.pack("B", format)) # // chunk version number f.write(data) # // chunk data # f.flush() def containsChunk(self, cx, cz): return self.getOffset(cx, cz) != 0 def getOffset(self, cx, cz): cx &= 0x1f cz &= 0x1f return self.offsets[cx + cz * 32] def setOffset(self, cx, cz, offset): cx &= 0x1f cz &= 0x1f self.offsets[cx + cz * 32] = offset with self.file as f: f.seek(0) f.write(self.offsets.tostring()) def getTimestamp(self, cx, cz): cx &= 0x1f cz &= 0x1f return self.modTimes[cx + cz * 32] def setTimestamp(self, cx, cz, timestamp=None): if timestamp is None: timestamp = time.time() cx &= 0x1f cz &= 0x1f self.modTimes[cx + cz * 32] = timestamp with self.file as f: f.seek(self.SECTOR_BYTES) f.write(self.modTimes.tostring()) SECTOR_BYTES = 4096 SECTOR_INTS = SECTOR_BYTES / 4 CHUNK_HEADER_SIZE = 5 VERSION_GZIP = 1 VERSION_DEFLATE = 2 compressMode = VERSION_DEFLATE class ChunkTooBig(ValueError): pass
12,451
33.977528
129
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/pocket.py
from level import FakeChunk import logging from materials import pocketMaterials from mclevelbase import ChunkNotPresent, notclosing from nbt import TAG_List from numpy import array, fromstring, zeros import os import struct # values are usually little-endian, unlike Minecraft PC logger = logging.getLogger(__name__) class PocketChunksFile(object): holdFileOpen = False # if False, reopens and recloses the file on each access SECTOR_BYTES = 4096 CHUNK_HEADER_SIZE = 4 @property def file(self): openfile = lambda: file(self.path, "rb+") if PocketChunksFile.holdFileOpen: if self._file is None: self._file = openfile() return notclosing(self._file) else: return openfile() def close(self): if PocketChunksFile.holdFileOpen: self._file.close() self._file = None def __init__(self, path): self.path = path self._file = None if not os.path.exists(path): file(path, "w").close() with self.file as f: filesize = os.path.getsize(path) if filesize & 0xfff: filesize = (filesize | 0xfff) + 1 f.truncate(filesize) if filesize == 0: filesize = self.SECTOR_BYTES f.truncate(filesize) f.seek(0) offsetsData = f.read(self.SECTOR_BYTES) self.freeSectors = [True] * (filesize / self.SECTOR_BYTES) self.freeSectors[0] = False self.offsets = fromstring(offsetsData, dtype='<u4') needsRepair = False for index, offset in enumerate(self.offsets): sector = offset >> 8 count = offset & 0xff for i in xrange(sector, sector + count): if i >= len(self.freeSectors): # raise RegionMalformed("Region file offset table points to sector {0} (past the end of the file)".format(i)) print "Region file offset table points to sector {0} (past the end of the file)".format(i) needsRepair = True break if self.freeSectors[i] is False: logger.debug("Double-allocated sector number %s (offset %s @ %s)", i, offset, index) needsRepair = True self.freeSectors[i] = False if needsRepair: self.repair() logger.info("Found region file {file} with {used}/{total} sectors used and {chunks} chunks present".format( file=os.path.basename(path), used=self.usedSectors, total=self.sectorCount, chunks=self.chunkCount)) @property def usedSectors(self): return len(self.freeSectors) - sum(self.freeSectors) @property def sectorCount(self): return len(self.freeSectors) @property def chunkCount(self): return sum(self.offsets > 0) def repair(self): pass # lostAndFound = {} # _freeSectors = [True] * len(self.freeSectors) # _freeSectors[0] = _freeSectors[1] = False # deleted = 0 # recovered = 0 # logger.info("Beginning repairs on {file} ({chunks} chunks)".format(file=os.path.basename(self.path), chunks=sum(self.offsets > 0))) # rx, rz = self.regionCoords # for index, offset in enumerate(self.offsets): # if offset: # cx = index & 0x1f # cz = index >> 5 # cx += rx << 5 # cz += rz << 5 # sectorStart = offset >> 8 # sectorCount = offset & 0xff # try: # # if sectorStart + sectorCount > len(self.freeSectors): # raise RegionMalformed("Offset {start}:{end} ({offset}) at index {index} pointed outside of the file".format() # start=sectorStart, end=sectorStart + sectorCount, index=index, offset=offset) # # compressedData = self._readChunk(cx, cz) # if compressedData is None: # raise RegionMalformed("Failed to read chunk data for {0}".format((cx, cz))) # # format, data = self.decompressSectors(compressedData) # chunkTag = nbt.load(buf=data) # lev = chunkTag["Level"] # xPos = lev["xPos"].value # zPos = lev["zPos"].value # overlaps = False # # for i in xrange(sectorStart, sectorStart + sectorCount): # if _freeSectors[i] is False: # overlaps = True # _freeSectors[i] = False # # # if xPos != cx or zPos != cz or overlaps: # lostAndFound[xPos, zPos] = (format, compressedData) # # if (xPos, zPos) != (cx, cz): # raise RegionMalformed("Chunk {found} was found in the slot reserved for {expected}".format(found=(xPos, zPos), expected=(cx, cz))) # else: # raise RegionMalformed("Chunk {found} (in slot {expected}) has overlapping sectors with another chunk!".format(found=(xPos, zPos), expected=(cx, cz))) # # # # except Exception, e: # logger.info("Unexpected chunk data at sector {sector} ({exc})".format(sector=sectorStart, exc=e)) # self.setOffset(cx, cz, 0) # deleted += 1 # # for cPos, (format, foundData) in lostAndFound.iteritems(): # cx, cz = cPos # if self.getOffset(cx, cz) == 0: # logger.info("Found chunk {found} and its slot is empty, recovering it".format(found=cPos)) # self._saveChunk(cx, cz, foundData[5:], format) # recovered += 1 # # logger.info("Repair complete. Removed {0} chunks, recovered {1} chunks, net {2}".format(deleted, recovered, recovered - deleted)) # def _readChunk(self, cx, cz): cx &= 0x1f cz &= 0x1f offset = self.getOffset(cx, cz) if offset == 0: return None sectorStart = offset >> 8 numSectors = offset & 0xff if numSectors == 0: return None if sectorStart + numSectors > len(self.freeSectors): return None with self.file as f: f.seek(sectorStart * self.SECTOR_BYTES) data = f.read(numSectors * self.SECTOR_BYTES) assert (len(data) > 0) logger.debug("REGION LOAD %s,%s sector %s", cx, cz, sectorStart) return data def loadChunk(self, cx, cz, world): data = self._readChunk(cx, cz) if data is None: raise ChunkNotPresent((cx, cz, self)) chunk = PocketChunk(cx, cz, data[4:], world) return chunk def saveChunk(self, chunk): cx, cz = chunk.chunkPosition cx &= 0x1f cz &= 0x1f offset = self.getOffset(cx, cz) sectorNumber = offset >> 8 sectorsAllocated = offset & 0xff data = chunk._savedData() sectorsNeeded = (len(data) + self.CHUNK_HEADER_SIZE) / self.SECTOR_BYTES + 1 if sectorsNeeded >= 256: return if sectorNumber != 0 and sectorsAllocated >= sectorsNeeded: logger.debug("REGION SAVE {0},{1} rewriting {2}b".format(cx, cz, len(data))) self.writeSector(sectorNumber, data, format) else: # we need to allocate new sectors # mark the sectors previously used for this chunk as free for i in xrange(sectorNumber, sectorNumber + sectorsAllocated): self.freeSectors[i] = True runLength = 0 try: runStart = self.freeSectors.index(True) for i in range(runStart, len(self.freeSectors)): if runLength: if self.freeSectors[i]: runLength += 1 else: runLength = 0 elif self.freeSectors[i]: runStart = i runLength = 1 if runLength >= sectorsNeeded: break except ValueError: pass # we found a free space large enough if runLength >= sectorsNeeded: logger.debug("REGION SAVE {0},{1}, reusing {2}b".format(cx, cz, len(data))) sectorNumber = runStart self.setOffset(cx, cz, sectorNumber << 8 | sectorsNeeded) self.writeSector(sectorNumber, data, format) self.freeSectors[sectorNumber:sectorNumber + sectorsNeeded] = [False] * sectorsNeeded else: # no free space large enough found -- we need to grow the # file logger.debug("REGION SAVE {0},{1}, growing by {2}b".format(cx, cz, len(data))) with self.file as f: f.seek(0, 2) filesize = f.tell() sectorNumber = len(self.freeSectors) assert sectorNumber * self.SECTOR_BYTES == filesize filesize += sectorsNeeded * self.SECTOR_BYTES f.truncate(filesize) self.freeSectors += [False] * sectorsNeeded self.setOffset(cx, cz, sectorNumber << 8 | sectorsNeeded) self.writeSector(sectorNumber, data, format) def writeSector(self, sectorNumber, data, format): with self.file as f: logger.debug("REGION: Writing sector {0}".format(sectorNumber)) f.seek(sectorNumber * self.SECTOR_BYTES) f.write(struct.pack("<I", len(data) + self.CHUNK_HEADER_SIZE)) # // chunk length f.write(data) # // chunk data # f.flush() def containsChunk(self, cx, cz): return self.getOffset(cx, cz) != 0 def getOffset(self, cx, cz): cx &= 0x1f cz &= 0x1f return self.offsets[cx + cz * 32] def setOffset(self, cx, cz, offset): cx &= 0x1f cz &= 0x1f self.offsets[cx + cz * 32] = offset with self.file as f: f.seek(0) f.write(self.offsets.tostring()) def chunkCoords(self): indexes = (i for (i, offset) in enumerate(self.offsets) if offset) coords = ((i % 32, i // 32) for i in indexes) return coords from infiniteworld import ChunkedLevelMixin from level import MCLevel, LightedChunk class PocketWorld(ChunkedLevelMixin, MCLevel): Height = 128 Length = 512 Width = 512 _gamePlatform = "old Pocket" isInfinite = True # Wrong. isInfinite actually means 'isChunked' and should be changed materials = pocketMaterials @property def allChunks(self): return list(self.chunkFile.chunkCoords()) def __init__(self, filename): if not os.path.isdir(filename): filename = os.path.dirname(filename) self.filename = filename self.dimensions = {} self.chunkFile = PocketChunksFile(os.path.join(filename, "chunks.dat")) self._loadedChunks = {} def getChunk(self, cx, cz): for p in cx, cz: if not 0 <= p <= 31: raise ChunkNotPresent((cx, cz, self)) c = self._loadedChunks.get((cx, cz)) if c is None: c = self.chunkFile.loadChunk(cx, cz, self) self._loadedChunks[cx, cz] = c return c @classmethod def _isLevel(cls, filename): clp = ("chunks.dat", "level.dat") if not os.path.isdir(filename): f = os.path.basename(filename) if f not in clp: return False filename = os.path.dirname(filename) return all([os.path.exists(os.path.join(filename, fl)) for fl in clp]) def saveInPlaceGen(self): for chunk in self._loadedChunks.itervalues(): if chunk.dirty: self.chunkFile.saveChunk(chunk) chunk.dirty = False yield def containsChunk(self, cx, cz): if cx > 31 or cz > 31 or cx < 0 or cz < 0: return False return self.chunkFile.getOffset(cx, cz) != 0 @property def chunksNeedingLighting(self): for chunk in self._loadedChunks.itervalues(): if chunk.needsLighting: yield chunk.chunkPosition class PocketChunk(LightedChunk): HeightMap = FakeChunk.HeightMap Entities = TileEntities = property(lambda self: TAG_List()) dirty = False filename = "chunks.dat" def __init__(self, cx, cz, data, world): self.chunkPosition = (cx, cz) self.world = world data = fromstring(data, dtype='uint8') self.Blocks, data = data[:32768], data[32768:] self.Data, data = data[:16384], data[16384:] self.SkyLight, data = data[:16384], data[16384:] self.BlockLight, data = data[:16384], data[16384:] self.DirtyColumns = data[:256] self.unpackChunkData() self.shapeChunkData() def unpackChunkData(self): for key in ('SkyLight', 'BlockLight', 'Data'): dataArray = getattr(self, key) dataArray.shape = (16, 16, 64) s = dataArray.shape # assert s[2] == self.world.Height / 2 # unpackedData = insert(dataArray[...,newaxis], 0, 0, 3) unpackedData = zeros((s[0], s[1], s[2] * 2), dtype='uint8') unpackedData[:, :, ::2] = dataArray unpackedData[:, :, ::2] &= 0xf unpackedData[:, :, 1::2] = dataArray unpackedData[:, :, 1::2] >>= 4 setattr(self, key, unpackedData) def shapeChunkData(self): chunkSize = 16 self.Blocks.shape = (chunkSize, chunkSize, self.world.Height) self.SkyLight.shape = (chunkSize, chunkSize, self.world.Height) self.BlockLight.shape = (chunkSize, chunkSize, self.world.Height) self.Data.shape = (chunkSize, chunkSize, self.world.Height) self.DirtyColumns.shape = chunkSize, chunkSize def _savedData(self): def packData(dataArray): assert dataArray.shape[2] == self.world.Height data = array(dataArray).reshape(16, 16, self.world.Height / 2, 2) data[..., 1] <<= 4 data[..., 1] |= data[..., 0] return array(data[:, :, :, 1]) if self.dirty: # elements of DirtyColumns are bitfields. Each bit corresponds to a # 16-block segment of the column. We set all of the bits because # we only track modifications at the chunk level. self.DirtyColumns[:] = 255 return "".join([self.Blocks.tostring(), packData(self.Data).tostring(), packData(self.SkyLight).tostring(), packData(self.BlockLight).tostring(), self.DirtyColumns.tostring(), ])
15,372
34.585648
182
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/level.py
''' Created on Jul 22, 2011 @author: Rio ''' from box import BoundingBox from collections import defaultdict from entity import Entity, TileEntity, TileTick import itertools from logging import getLogger import materials from math import floor from mclevelbase import ChunkMalformed, ChunkNotPresent import nbt from numpy import argmax, swapaxes, zeros, zeros_like import os.path import id_definitions log = getLogger(__name__) def computeChunkHeightMap(materials, blocks, HeightMap=None): """Computes the HeightMap array for a chunk, which stores the lowest y-coordinate of each column where the sunlight is still at full strength. The HeightMap array is indexed z,x contrary to the blocks array which is x,z,y. If HeightMap is passed, fills it with the result and returns it. Otherwise, returns a new array. """ lightAbsorption = materials.lightAbsorption[blocks] heights = extractHeights(lightAbsorption) heights = heights.swapaxes(0, 1) if HeightMap is None: return heights.astype('uint8') else: HeightMap[:] = heights return HeightMap def extractHeights(array): """ Given an array of bytes shaped (x, z, y), return the coordinates of the highest non-zero value in each y-column into heightMap """ # The fastest way I've found to do this is to make a boolean array with >0, # then turn it upside down with ::-1 and use argmax to get the _first_ nonzero # from each column. w, h = array.shape[:2] heightMap = zeros((w, h), 'int16') heights = argmax((array > 0)[..., ::-1], 2) heights = array.shape[2] - heights # if the entire column is air, argmax finds the first air block and the result is a top height column # top height columns won't ever have air in the top block so we can find air columns by checking for both heights[(array[..., -1] == 0) & (heights == array.shape[2])] = 0 heightMap[:] = heights return heightMap def getSlices(box, height): """ call this method to iterate through a large slice of the world by visiting each chunk and indexing its data with a subslice. this returns an iterator, which yields 3-tuples containing: + a pair of chunk coordinates (cx, cz), + a x,z,y triplet of slices that can be used to index the AnvilChunk's data arrays, + a x,y,z triplet representing the relative location of this subslice within the requested world slice. Note the different order of the coordinates between the 'slices' triplet and the 'offset' triplet. x,z,y ordering is used only to index arrays, since it reflects the order of the blocks in memory. In all other places, including an entity's 'Pos', the order is x,y,z. """ # 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 newMinY = 0 if box.miny < 0: newMinY = -box.miny miny = max(0, box.miny) maxy = min(height, box.maxy) for cx in xrange(box.mincx, box.maxcx): localMinX = 0 localMaxX = 16 if cx == box.mincx: localMinX = minxoff if cx == box.maxcx - 1: localMaxX = maxxoff newMinX = localMinX + (cx << 4) - box.minx for cz in xrange(box.mincz, box.maxcz): localMinZ = 0 localMaxZ = 16 if cz == box.mincz: localMinZ = minzoff if cz == box.maxcz - 1: localMaxZ = maxzoff newMinZ = localMinZ + (cz << 4) - box.minz slices, point = ( (slice(localMinX, localMaxX), slice(localMinZ, localMaxZ), slice(miny, maxy)), (newMinX, newMinY, newMinZ) ) yield (cx, cz), slices, point class MCLevel(object): """ MCLevel is an abstract class providing many routines to the different level types, including a common copyEntitiesFrom built on class-specific routines, and a dummy getChunk/allChunks for the finite levels. MCLevel subclasses must have Width, Length, and Height attributes. The first two are always zero for infinite levels. Subclasses must also have Blocks, and optionally Data and BlockLight. """ # ## common to Creative, Survival and Indev. these routines assume ### self has Width, Height, Length, and Blocks materials = materials.classicMaterials isInfinite = False saving = False root_tag = None Height = None Length = None Width = None players = ["Player"] dimNo = 0 parentWorld = None world = None entityClass = Entity # Game version check. Stores the info found in the 'Version::Name' tag @property def gamePlatform(self): # Should return the platform the world is from ("Java", "PE" or "Schematic") """Returns the platform the world is from ("Java", "PE", "Schematic"...)""" # I would use isinstance() here, but importing the separate level classes would cause a circular import, so this will have to do if not hasattr(self, '_gamePlatform'): type_map = { 'pymclevel.schematic.MCSchematic': 'Schematic', 'pymclevel.leveldbpocket.PocketLeveldbWorld': 'PE', 'pymclevel.infiniteworld.MCInfdevOldLevel': 'Java', } t = str(type(self)) self._gamePlatform = type_map.get(t[8:len(t) - 2], 'Unknown') return self._gamePlatform @property def gameVersionNumber(self): # Should return the version number that the world is from (eg "1.12.2"...) """Returns the version number the world was last opened in or 'Unknown'""" if self.root_tag and not hasattr(self, '_gameVersionNumber'): self._gameVersionNumber = 'Unknown' if self.gamePlatform == "PE": if 'Data' in self.root_tag and isinstance(self.root_tag['Data'], nbt.TAG_Compound): if 'lastOpenedWithVersion' in self.root_tag['Data'] and isinstance(self.root_tag['Data']['lastOpenedWithVersion'], nbt.TAG_List): self._gameVersionNumber = '.'.join([str(num.value) for num in self.root_tag['Data']['lastOpenedWithVersion']]) else: self._gameVersionNumber = self.root_tag['Data']['lastOpenedWithVersion'] elif self.gamePlatform == "Java": if 'Data' in self.root_tag and isinstance(self.root_tag['Data'], nbt.TAG_Compound): # We're opening a world. if 'Version' in self.root_tag['Data']: if 'Name' in self.root_tag['Data']['Version']: self._gameVersionNumber = self.root_tag['Data']['Version']['Name'].value elif self.root_tag.name: self._gameVersion = self.root_tag.name return self._gameVersionNumber @property def gameVersion(self): #depreciated. The output of this function is inconsistent. Use either gamePlatform or gameVersionNumber """Depreciated property. Use gamePlatform or gameVersionNumber. This returns gameVersionNumber for Java worlds and gamePlatform for all others""" log.warning('gameVersion is depreciated. Use gamePlatform or gameVersionNumber instead') if self.root_tag and not hasattr(self, '_gameVersion'): self._gameVersion = 'Unknown' if self.gamePlatform == "Java": self._gameVersion = self.gameVersionNumber else: self._gameVersion = self.gamePlatform return self._gameVersion @property def defsIds(self): if self.root_tag and not hasattr(self, '__defs_ids'): self.__defs_ids = id_definitions.get_defs_ids(self.gamePlatform, self.gameVersionNumber) return self.__defs_ids def loadDefIds(self): if self.root_tag and not hasattr(self, '__defs_ids'): self.__defs_ids = id_definitions.get_defs_ids(self.gamePlatform, self.gameVersionNumber) @classmethod def isLevel(cls, filename): """Tries to find out whether the given filename can be loaded by this class. Returns True or False. Subclasses should implement _isLevel, _isDataLevel, or _isTagLevel. """ if hasattr(cls, "_isLevel"): return cls._isLevel(filename) with file(filename) as f: data = f.read() if hasattr(cls, "_isDataLevel"): return cls._isDataLevel(data) if hasattr(cls, "_isTagLevel"): try: root_tag = nbt.load(filename, data) except: return False return cls._isTagLevel(root_tag) return False def getWorldBounds(self): return BoundingBox((0, 0, 0), self.size) @property def displayName(self): return os.path.basename(self.filename) @property def size(self): "Returns the level's dimensions as a tuple (X,Y,Z)" return self.Width, self.Height, self.Length @property def bounds(self): return BoundingBox((0, 0, 0), self.size) def close(self): pass # --- Entity Methods --- def addEntity(self, entityTag): pass def addEntities(self, entities): pass def tileEntityAt(self, x, y, z): return None def addTileEntity(self, entityTag): pass def addTileTick(self, entityTag): pass def addTileTicks(self, tileTicks): pass def getEntitiesInBox(self, box): return [] def getTileEntitiesInBox(self, box): return [] def getTileTicksInBox(self, box): return [] def removeEntitiesInBox(self, box): pass def removeTileEntitiesInBox(self, box): pass def removeTileTicksInBox(self, box): pass @property def chunkCount(self): return (self.Width + 15 >> 4) * (self.Length + 15 >> 4) @property def allChunks(self): """Returns a synthetic list of chunk positions (xPos, zPos), to fake being a chunked level format.""" return itertools.product(xrange(0, self.Width + 15 >> 4), xrange(0, self.Length + 15 >> 4)) def getChunks(self, chunks=None): """ pass a list of chunk coordinate tuples to get an iterator yielding AnvilChunks. pass nothing for an iterator of every chunk in the level. the chunks are automatically loaded.""" if chunks is None: chunks = self.allChunks return (self.getChunk(cx, cz) for (cx, cz) in chunks if self.containsChunk(cx, cz)) def _getFakeChunkEntities(self, cx, cz): """Returns Entities, TileEntities""" return nbt.TAG_List(), nbt.TAG_List() def getChunk(self, cx, cz): """Synthesize a FakeChunk object representing the chunk at the given position. Subclasses override fakeBlocksForChunk and fakeDataForChunk to fill in the chunk arrays""" f = FakeChunk() f.world = self f.chunkPosition = (cx, cz) f.Blocks = self.fakeBlocksForChunk(cx, cz) f.Data = self.fakeDataForChunk(cx, cz) whiteLight = zeros_like(f.Blocks) whiteLight[:] = 15 f.BlockLight = whiteLight f.SkyLight = whiteLight f.Entities, f.TileEntities, f.TileTicks = self._getFakeChunkEntities(cx, cz) f.root_tag = nbt.TAG_Compound() return f def getAllChunkSlices(self): slices = (slice(None), slice(None), slice(None),) box = self.bounds x, y, z = box.origin for cpos in self.allChunks: xPos, zPos = cpos try: chunk = self.getChunk(xPos, zPos) except (ChunkMalformed, ChunkNotPresent): continue yield (chunk, slices, (xPos * 16 - x, 0, zPos * 16 - z)) def _getSlices(self, box): if box == self.bounds: log.info("All chunks selected! Selecting %s chunks instead of %s", self.chunkCount, box.chunkCount) y = box.miny slices = slice(0, 16), slice(0, 16), slice(0, box.maxy) def getAllSlices(): for cPos in self.allChunks: x, z = cPos x *= 16 z *= 16 x -= box.minx z -= box.minz yield cPos, slices, (x, y, z) return getAllSlices() else: return getSlices(box, self.Height) def getChunkSlices(self, box): return ((self.getChunk(*cPos), slices, point) for cPos, slices, point in self._getSlices(box) if self.containsChunk(*cPos)) def containsPoint(self, x, y, z): return (x, y, z) in self.bounds def containsChunk(self, cx, cz): bounds = self.bounds return ((bounds.mincx <= cx < bounds.maxcx) and (bounds.mincz <= cz < bounds.maxcz)) def fakeBlocksForChunk(self, cx, cz): # return a 16x16xH block array for rendering. Alpha levels can # just return the chunk data. other levels need to reorder the # indices and return a slice of the blocks. cxOff = cx << 4 czOff = cz << 4 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) ) return b def fakeDataForChunk(self, cx, cz): # Data is emulated for flexibility cxOff = cx << 4 czOff = cz << 4 if hasattr(self, "Data"): return self.Data[cxOff:cxOff + 16, czOff:czOff + 16, 0:self.Height, ] else: return zeros(shape=(16, 16, self.Height), dtype='uint8') # --- Block accessors --- def skylightAt(self, *args): return 15 def setSkylightAt(self, *args): 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, y, z) not in self.bounds: return 0 return self.Blocks[x, z, y] def setBlockAt(self, x, y, z, blockID): if (x, y, z) not in self.bounds: return 0 self.Blocks[x, z, y] = blockID # --- Fill and Replace --- from block_fill import fillBlocks, fillBlocksIter # --- Transformations --- def rotateLeft(self): 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 pass def flipVertical(self): self.Blocks = self.Blocks[:, :, ::-1] # y=-y pass def flipNorthSouth(self): self.Blocks = self.Blocks[::-1, :, :] # x=-x pass def flipEastWest(self): self.Blocks = self.Blocks[:, ::-1, :] # z=-z pass # --- Copying --- from block_copy import copyBlocksFrom, copyBlocksFromIter def saveInPlaceGen(self): self.saveToFile(self.filename) yield def saveInPlace(self): gen = self.saveInPlaceGen() for _ in gen: pass # --- Player Methods --- def setPlayerPosition(self, pos, player="Player"): pass 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 setPlayerSpawnPosition(self, pos, player=None): pass def playerSpawnPosition(self, player=None): return self.getPlayerPosition() def setPlayerOrientation(self, yp, player="Player"): pass def getPlayerOrientation(self, player="Player"): return -45., 0. # --- Dummy Lighting Methods --- def generateLights(self, dirtyChunks=None): pass def generateLightsIter(self, dirtyChunks=None): yield 0 class EntityLevel(MCLevel): """Abstract subclass of MCLevel that adds default entity behavior""" def getEntitiesInBox(self, box): """Returns a list of references to entities in this chunk, whose positions are within box""" return [ent for ent in self.Entities if Entity.pos(ent) in box] def getTileEntitiesInBox(self, box): """Returns a list of references to tile entities in this chunk, whose positions are within box""" return [ent for ent in self.TileEntities if TileEntity.pos(ent) in box] def getTileTicksInBox(self, box): if hasattr(self, "TileTicks"): return [ent for ent in self.TileTicks if TileTick.pos(ent) in box] else: return [] def removeEntities(self, func): if not hasattr(self, "Entities"): return newEnts = [] for ent in self.Entities: if func(Entity.pos(ent)): continue newEnts.append(ent) entsRemoved = len(self.Entities) - len(newEnts) log.debug("Removed {0} entities".format(entsRemoved)) self.Entities.value[:] = newEnts return entsRemoved def removeEntitiesInBox(self, box): return self.removeEntities(lambda p: p in box) def removeTileEntities(self, func): if not hasattr(self, "TileEntities"): return newEnts = [] for ent in self.TileEntities: if func(TileEntity.pos(ent)): continue newEnts.append(ent) entsRemoved = len(self.TileEntities) - len(newEnts) log.debug("Removed {0} tile entities".format(entsRemoved)) self.TileEntities.value[:] = newEnts return entsRemoved def removeTileEntitiesInBox(self, box): return self.removeTileEntities(lambda p: p in box) def removeTileTicks(self, func): if not hasattr(self, "TileTicks"): return newEnts = [] for ent in self.TileTicks: if func(TileTick.pos(ent)): continue newEnts.append(ent) entsRemoved = len(self.TileTicks) - len(newEnts) log.debug("Removed {0} tile tickss".format(entsRemoved)) self.TileTicks.value[:] = newEnts return entsRemoved def removeTileTicksInBox(self, box): return self.removeTileTicks(lambda p: p in box) def addEntities(self, entities): for e in entities: self.addEntity(e) def addEntity(self, entityTag): assert isinstance(entityTag, nbt.TAG_Compound) self.Entities.append(entityTag) self._fakeEntities = None def tileEntityAt(self, x, y, z, print_stuff=False): entities = [] if print_stuff: print "len(self.TileEntities)", len(self.TileEntities) for entityTag in self.TileEntities: if print_stuff: print entityTag["id"].value, TileEntity.pos(entityTag), x, y, z if TileEntity.pos(entityTag) == [x, y, z]: entities.append(entityTag) if len(entities) > 1: log.info("Multiple tile entities found: {0}".format(entities)) if len(entities) == 0: return None return entities[0] def addTileEntity(self, tileEntityTag): assert isinstance(tileEntityTag, nbt.TAG_Compound) def differentPosition(a): return not ((tileEntityTag is a) or TileEntity.pos(a) == TileEntity.pos(tileEntityTag)) self.TileEntities.value[:] = filter(differentPosition, self.TileEntities) self.TileEntities.append(tileEntityTag) self._fakeEntities = None def addTileTick(self, tickTag): assert isinstance(tickTag, nbt.TAG_Compound) if hasattr(self, "TileTicks"): def differentPosition(a): return not ((tickTag is a) or TileTick.pos(a) == TileTick.pos(tickTag)) self.TileTicks.value[:] = filter(differentPosition, self.TileTicks) self.TileTicks.append(tickTag) self._fakeEntities = None def addTileTicks(self, tileTicks): for e in tileTicks: self.addTileTick(e) _fakeEntities = None def _getFakeChunkEntities(self, cx, cz): """distribute entities into sublists based on fake chunk position _fakeEntities keys are (cx, cz) and values are (Entities, TileEntities, TileTicks)""" if self._fakeEntities is None: self._fakeEntities = defaultdict(lambda: (nbt.TAG_List(), nbt.TAG_List(), nbt.TAG_List())) for i, e in enumerate((self.Entities, self.TileEntities, self.TileTicks)): for ent in e: x, y, z = [Entity, TileEntity, TileTick][i].pos(ent) ecx, ecz = map(lambda x: (int(floor(x)) >> 4), (x, z)) self._fakeEntities[ecx, ecz][i].append(ent) return self._fakeEntities[cx, cz] class ChunkBase(EntityLevel): dirty = False needsLighting = False chunkPosition = NotImplemented Blocks = Data = SkyLight = BlockLight = HeightMap = NotImplemented # override these! Width = Length = 16 @property def Height(self): return self.world.Height @property def bounds(self): cx, cz = self.chunkPosition return BoundingBox((cx << 4, 0, cz << 4), self.size) def chunkChanged(self, needsLighting=True): self.dirty = True self.needsLighting = needsLighting or self.needsLighting @property def materials(self): return self.world.materials def getChunkSlicesForBox(self, box): """ Given a BoundingBox enclosing part of the world, return a smaller box enclosing the part of this chunk intersecting the given box, and a tuple of slices that can be used to select the corresponding parts of this chunk's block and data arrays. """ bounds = self.bounds localBox = box.intersect(bounds) slices = ( slice(localBox.minx - bounds.minx, localBox.maxx - bounds.minx), slice(localBox.minz - bounds.minz, localBox.maxz - bounds.minz), slice(localBox.miny - bounds.miny, localBox.maxy - bounds.miny), ) return localBox, slices class FakeChunk(ChunkBase): @property def HeightMap(self): if hasattr(self, "_heightMap"): return self._heightMap self._heightMap = computeChunkHeightMap(self.materials, self.Blocks) return self._heightMap class LightedChunk(ChunkBase): def generateHeightMap(self): computeChunkHeightMap(self.materials, self.Blocks, self.HeightMap) def chunkChanged(self, calcLighting=True): """ You are required to call this function after you are done modifying the chunk. Pass False for calcLighting if you know your changes will not change any lights.""" self.dirty = True self.needsLighting = calcLighting or self.needsLighting self.generateHeightMap() if calcLighting: self.genFastLights() def genFastLights(self): self.SkyLight[:] = 0 if self.world.dimNo in (-1, 1): return # no light in nether or the end blocks = self.Blocks la = self.world.materials.lightAbsorption skylight = self.SkyLight heightmap = self.HeightMap for x, z in itertools.product(xrange(16), xrange(16)): skylight[x, z, heightmap[z, x]:] = 15 lv = 15 for y in reversed(range(heightmap[z, x])): lv -= (la[blocks[x, z, y]] or 1) if lv <= 0: break skylight[x, z, y] = lv
23,962
31.736339
153
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/BOParser.py
import ConfigParser from pymclevel import schematic, materials from entity import TileEntity import nbt import logging import re import os from random import randint from directories import getDataDir, getDataFile log = logging.getLogger(__name__) # Load the bo3.def file (internal BO3 block names). bo3_blocks = {} #if not os.path.exists(os.path.join(getDataDir(), 'bo3.def')): if not os.path.exists(getDataFile('bo3.def')): log.warning('The `bo3.def` file is missing in `%s`. The BO3 support will not be complete...'%getDataFile()) else: #bo3_blocks.update([(a, int(b)) for a, b in re.findall(r'^([A-Z0-9_]+)\(([0-9]*).*\)', open(os.path.join(getDataDir(), 'bo3.def')).read(), re.M)]) bo3_blocks.update([(a, int(b)) for a, b in re.findall(r'^([A-Z0-9_]+)\(([0-9]*).*\)', open(getDataFile('bo3.def')).read(), re.M)]) log.debug('BO3 block definitions loaded. %s entries found'%len(bo3_blocks.keys())) # find another way for this. # keys are block ids in uppercase, values are tuples for ranges, lists for exact states corrected_states = {'CHEST':(2,6)} class BO3: def __init__(self, filename=''): if isinstance(filename, (str, unicode)): self.delta_x, self.delta_y, self.delta_z = 0, 0, 0 self.size_x, self.size_y, self.size_z = 0, 0, 0 map_block = {} not_found = [] tileentities_list = [a.lower() for a in TileEntity.baseStructures.keys()] for k, v in materials.block_map.items(): map_block[v.replace('minecraft:', '')] = k def get_delta(x, y, z, debug=False, f_obj=None): if x < 0 and abs(x) > self.delta_x: self.delta_x = abs(x) if y < 0 and abs(y) > self.delta_y: self.delta_y = abs(y) if z < 0 and abs(z) > self.delta_z: self.delta_z = abs(z) if x + self.delta_x >= self.size_x: self.size_x = x + self.delta_x + 1 if y + self.delta_y >= self.size_y: self.size_y = y + self.delta_y + 1 if z + self.delta_z >= self.size_z: self.size_z = z + self.delta_z + 1 if debug: output_str = '; '.join(('get_delta: %s, %s %s'%(x, y, z), 'deltas: %s, %s, %s'%(self.delta_x, self.delta_y, self.delta_z), 'size: %s, %s %s'%(self.size_x, self.size_y, self.size_z))) print output_str if f_obj != None: f_obj.write(output_str) raw_data = open(filename).read() lines = re.findall(r'^Block\(.*?\)|^RandomBlock\(.*?\)', raw_data, re.M) # Doubling the schematic size calculation avoids missbuilt objects. # Rework the get_delta function? [get_delta(*b) for b in [eval(','.join(a.split('(')[1].split(')')[0].split(',', 3)[:3])) for a in lines]] [get_delta(*b) for b in [eval(','.join(a.split('(')[1].split(')')[0].split(',', 3)[:3])) for a in lines]] self.__schem = schematic.MCSchematic(shape=(self.size_x, self.size_y, self.size_z)) def get_block_data(args): x, y, z = args[:3] b = args[3] nbt_data = None if len(args) == 5 and args[4] != None: f_name = os.path.join(os.path.dirname(filename), os.path.normpath(args[4])) if os.path.exists(f_name): nbt_data = nbt.load(f_name) else: print 'Could not find %s'%args[4] print ' Canonical path: %s'%f_name x = int(x) + self.delta_x y = int(y) + self.delta_y z = int(z) + self.delta_z if b != None: b_id, b_state = (b + ':0').split(':')[:2] else: b_id, b_state = '', None if b_state: b_state = int(b_state) else: b_state = 0 return x, y, z, b_id, b_state, nbt_data def get_randomblock_data(args): x, y, z = args[:3] obj = [] bit_id = False bit_path = False bit_chance = False for arg in args[3:]: if not bit_id: obj.append(arg) bit_id = True elif arg.isdigit(): if not bit_path: obj.append(None) bit_path = True obj.append(int(arg)) bit_chance = True else: obj.append(arg) bit_path = True if bit_id and bit_path and bit_chance: chance = randint(1, 100) if chance <= obj[2]: break obj = [] bit_id, bit_path, bit_chance = False, False, False #print 'Selected random object: %s (%s, %s, %s) from %s'%(obj, x, y, z, args[3:]) # Fallback for chances < 100% if not obj: obj = [None, None] return get_block_data((x, y, z, obj[0], obj[1])) def verify_state(id, state): states = corrected_states.get(id, None) if states: if isinstance(states, tuple): if state not in range(*states): state = states[0] elif isinstance(states, list): if state not in states: state = states[0] return state for line in lines: if line.startswith('Block') or line.startswith('RandomBlock'): #print 'Parsing', line if line.startswith('Block'): x, y, z, b_id, b_state, nbt_data = get_block_data(line.replace("Block(", "").replace(")","").strip().split(",")) else: x, y, z, b_id, b_state, nbt_data = get_randomblock_data(line.replace("RandomBlock(", "").replace(")","").strip().split(",")) b_idn = map_block.get(b_id.lower(), bo3_blocks.get(b_id, None)) if b_idn: b_idn = int(b_idn) if b_id.lower() in tileentities_list: if not nbt_data: nbt_data = nbt.TAG_Compound() nbt_data.add(nbt.TAG_String(name='id', value=b_id.capitalize())) nbt_data.add(nbt.TAG_Int(name='x', value=x)) nbt_data.add(nbt.TAG_Int(name='y', value=y)) nbt_data.add(nbt.TAG_Int(name='z', value=z)) self.__schem.TileEntities.append(nbt_data) try: self.__schem.Blocks[x, z, y] = b_idn self.__schem.Data[x, z, y] = verify_state(b_id, b_state) except Exception, e: print 'Error while building BO3 data:' print e print 'size', self.size_x, self.size_y, self.size_z print line [get_delta(*b, debug=True) for b in [eval(','.join(a.split('(')[1].split(')')[0].split(',', 3)[:3])) for a in lines]] elif b_id: print 'BO3 Block not found: %s'%b_id else: log.error('Wrong type for \'filename\': got %s'%type(filename)) def getSchematic(self): return self.__schem class BO2: _parser = ConfigParser.RawConfigParser() def __init__(self, filename=''): self.__meta = {} self.__blocks = {} # [0] is lowest point, [1] is highest point, [2] is the amount to shift by self._vertical_tracker = [0,0,0] self._horizontal_tracker_1 = [0,0,0] self._horizontal_tracker_2 = [0,0,0] if filename: self._parser.read(filename) self.__version = self._parser.get('META', 'version') for item in self._parser.items("META"): self.__meta[item[0]] = item[1] for block in self._parser.items("DATA"): if int(block[0].split(",")[2]) < self._vertical_tracker[0]: self._vertical_tracker[0] = int(block[0].split(",")[2]) if int(block[0].split(",")[2]) > self._vertical_tracker[1]: self._vertical_tracker[1] = int(block[0].split(",")[2]) if int(block[0].split(",")[0]) < self._horizontal_tracker_1[0]: self._horizontal_tracker_1[0] = int(block[0].split(",")[0]) if int(block[0].split(",")[0]) > self._horizontal_tracker_1[1]: self._horizontal_tracker_1[1] = int(block[0].split(",")[0]) if int(block[0].split(",")[1]) < self._horizontal_tracker_2[0]: self._horizontal_tracker_2[0] = int(block[0].split(",")[1]) if int(block[0].split(",")[1]) > self._horizontal_tracker_2[1]: self._horizontal_tracker_2[1] = int(block[0].split(",")[1]) if self._vertical_tracker[0] < 0: self._vertical_tracker[2] = abs(self._vertical_tracker[0]) self._vertical_tracker[1] += abs(self._vertical_tracker[0]) if self._horizontal_tracker_1[0] < 0: self._horizontal_tracker_1[2] = abs(self._horizontal_tracker_1[0]) self._horizontal_tracker_1[1] += abs(self._horizontal_tracker_1[0]) if self._horizontal_tracker_2[0] < 0: self._horizontal_tracker_2[2] = abs(self._horizontal_tracker_2[0]) self._horizontal_tracker_2[1] += abs(self._horizontal_tracker_2[0]) self.__schem = schematic.MCSchematic(shape=(self._horizontal_tracker_2[1]+1, self._vertical_tracker[1]+1, self._horizontal_tracker_1[1]+1)) for block in self._parser.items("DATA"): coords = block[0].split(",") x = int(coords[1])+self._horizontal_tracker_2[2] y = int(coords[0])+self._horizontal_tracker_1[2] z = int(coords[2])+self._vertical_tracker[2] if '.' in block[1]: b, s = block[1].split('.') else: b, s = block[1], 0 self.__schem.Blocks[x,y,z] = b self.__schem.Data[x, y, z] = s def getSchematic(self): return self.__schem @property def meta(self): return self.__meta @property def blocks(self): return self.__blocks
11,236
46.214286
202
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/test_leveldb.py
# !/usr/bin/env python # # Copyright (C) 2012 Space Monkey, Inc. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # import os import sys import time import shutil import random import leveldb import argparse import tempfile import unittest class LevelDBTestCasesMixIn(object): db_class = None def setUp(self): self.db_path = tempfile.mkdtemp() def tearDown(self): shutil.rmtree(self.db_path, ignore_errors=True) def testPutGet(self): db = self.db_class(leveldb.Options(), self.db_path, create_if_missing=True) db.Put(leveldb.WriteOptions(), "key1", "val1") db.Put(leveldb.WriteOptions(), "key2", "val2", sync=True) self.assertEqual(db.Get(leveldb.ReadOptions(), "key1"), "val1") self.assertEqual(db.Get(leveldb.ReadOptions(), "key2"), "val2") self.assertEqual(db.Get(leveldb.ReadOptions(), "key1", verify_checksums=True), "val1") self.assertEqual(db.Get(leveldb.ReadOptions(), "key2", verify_checksums=True), "val2") self.assertEqual(db.Get(leveldb.ReadOptions(), "key1", fill_cache=False), "val1") self.assertEqual(db.Get(leveldb.ReadOptions(), "key2", fill_cache=False), "val2") self.assertEqual(db.Get(leveldb.ReadOptions(), "key1", verify_checksums=True, fill_cache=False), "val1") self.assertEqual(db.Get(leveldb.ReadOptions(), "key2", verify_checksums=True, fill_cache=False), "val2") self.assertEqual(db.Get(leveldb.ReadOptions(), "key1"), "val1") self.assertEqual(db.Get(leveldb.ReadOptions(), "key2"), "val2") self.assertEqual(list(db.keys()), ["key1", "key2"]) self.assertEqual(list(db.keys(prefix="key")), ["1", "2"]) self.assertEqual(list(db.keys(prefix="key1")), [""]) self.assertEqual(list(db.values()), ["val1", "val2"]) self.assertEqual(list(db.values(prefix="key")), ["val1", "val2"]) self.assertEqual(list(db.values(prefix="key1")), ["val1"]) db.close() def testDelete(self): db = self.db_class(leveldb.Options(), self.db_path, create_if_missing=True) self.assertTrue(db.Get(leveldb.ReadOptions(), "key1") is None) self.assertTrue(db.Get(leveldb.ReadOptions(), "key2") is None) self.assertTrue(db.Get(leveldb.ReadOptions(), "key3") is None) db.Put(leveldb.WriteOptions(), "key1", "val1") db.Put(leveldb.WriteOptions(), "key2", "val2") db.Put(leveldb.WriteOptions(), "key3", "val3") self.assertEqual(db.Get(leveldb.ReadOptions(), "key1"), "val1") self.assertEqual(db.Get(leveldb.ReadOptions(), "key2"), "val2") self.assertEqual(db.Get(leveldb.ReadOptions(), "key3"), "val3") db.delete("key1") db.delete("key2", sync=True) self.assertTrue(db.Get(leveldb.ReadOptions(), "key1") is None) self.assertTrue(db.Get(leveldb.ReadOptions(), "key2") is None) self.assertEqual(db.Get(leveldb.ReadOptions(), "key3"), "val3") db.close() def testRange(self): db = self.db_class(leveldb.Options(), self.db_path, create_if_missing=True) def keys(alphabet, length=5): if length == 0: yield "" return for char in alphabet: for prefix in keys(alphabet, length - 1): yield prefix + char for val, key in enumerate(keys(map(chr, xrange(ord('a'), ord('f'))))): db.Put(leveldb.WriteOptions(), key, str(val)) self.assertEquals([row.key for row in db.range("bbbb", "bbcb")], ['bbbba', 'bbbbb', 'bbbbc', 'bbbbd', 'bbbbe', 'bbbca', 'bbbcb', 'bbbcc', 'bbbcd', 'bbbce', 'bbbda', 'bbbdb', 'bbbdc', 'bbbdd', 'bbbde', 'bbbea', 'bbbeb', 'bbbec', 'bbbed', 'bbbee', 'bbcaa', 'bbcab', 'bbcac', 'bbcad', 'bbcae']) self.assertEquals([row.key for row in db.range("bbbbb", "bbcbb")], ['bbbbb', 'bbbbc', 'bbbbd', 'bbbbe', 'bbbca', 'bbbcb', 'bbbcc', 'bbbcd', 'bbbce', 'bbbda', 'bbbdb', 'bbbdc', 'bbbdd', 'bbbde', 'bbbea', 'bbbeb', 'bbbec', 'bbbed', 'bbbee', 'bbcaa', 'bbcab', 'bbcac', 'bbcad', 'bbcae', 'bbcba']) self.assertEquals([r.key for r in db.scope("dd").range("bb", "cb")], ['bba', 'bbb', 'bbc', 'bbd', 'bbe', 'bca', 'bcb', 'bcc', 'bcd', 'bce', 'bda', 'bdb', 'bdc', 'bdd', 'bde', 'bea', 'beb', 'bec', 'bed', 'bee', 'caa', 'cab', 'cac', 'cad', 'cae']) self.assertEquals([r.key for r in db.scope("dd").range("bbb", "cbb")], ['bbb', 'bbc', 'bbd', 'bbe', 'bca', 'bcb', 'bcc', 'bcd', 'bce', 'bda', 'bdb', 'bdc', 'bdd', 'bde', 'bea', 'beb', 'bec', 'bed', 'bee', 'caa', 'cab', 'cac', 'cad', 'cae', 'cba']) def testRangeOptionalEndpoints(self): db = self.db_class(leveldb.Options(), self.db_path, create_if_missing=True) db.Put(leveldb.WriteOptions(), "aa", "1") db.Put(leveldb.WriteOptions(), "bb", "2") db.Put(leveldb.WriteOptions(), "cc", "3") db.Put(leveldb.WriteOptions(), "dd", "4") db.Put(leveldb.WriteOptions(), "ee", "5") self.assertEquals([r.key for r in db.NewIterator().seek("d").range()], ["aa", "bb", "cc", "dd", "ee"]) self.assertEquals([r.key for r in db.NewIterator().seek("d").range( start_key="bb")], ["bb", "cc", "dd", "ee"]) self.assertEquals([r.key for r in db.NewIterator().seek("d").range( end_key="cc")], ["aa", "bb"]) self.assertEquals([r.key for r in db.NewIterator().seek("d").range( start_key="bb", end_key="cc")], ["bb"]) self.assertEquals([r.key for r in db.NewIterator().seek("d").range( start_key="b")], ["bb", "cc", "dd", "ee"]) self.assertEquals([r.key for r in db.NewIterator().seek("d").range( end_key="c")], ["aa", "bb"]) self.assertEquals([r.key for r in db.NewIterator().seek("d").range( start_key="b", end_key="c")], ["bb"]) self.assertEquals([r.key for r in db.NewIterator().seek("d").range( start_key="bb", start_inclusive=True)], ["bb", "cc", "dd", "ee"]) self.assertEquals([r.key for r in db.NewIterator().seek("d").range( start_key="bb", start_inclusive=False)], ["cc", "dd", "ee"]) self.assertEquals([r.key for r in db.NewIterator().seek("d").range( end_key="cc", end_inclusive=True)], ["aa", "bb", "cc"]) self.assertEquals([r.key for r in db.NewIterator().seek("d").range( end_key="cc", end_inclusive=False)], ["aa", "bb"]) self.assertEquals([r.key for r in db.NewIterator().seek("d").range( start_key="bb", end_key="cc", start_inclusive=True, end_inclusive=True)], ["bb", "cc"]) self.assertEquals([r.key for r in db.NewIterator().seek("d").range( start_key="bb", end_key="cc", start_inclusive=True, end_inclusive=False)], ["bb"]) self.assertEquals([r.key for r in db.NewIterator().seek("d").range( start_key="bb", end_key="cc", start_inclusive=False, end_inclusive=True)], ["cc"]) self.assertEquals([r.key for r in db.NewIterator().seek("d").range( start_key="bb", end_key="cc", start_inclusive=False, end_inclusive=False)], []) self.assertEquals([r.key for r in db.NewIterator().seek("d").range( start_key="b", start_inclusive=True)], ["bb", "cc", "dd", "ee"]) self.assertEquals([r.key for r in db.NewIterator().seek("d").range( start_key="b", start_inclusive=False)], ["bb", "cc", "dd", "ee"]) self.assertEquals([r.key for r in db.NewIterator().seek("d").range( end_key="c", end_inclusive=True)], ["aa", "bb"]) self.assertEquals([r.key for r in db.NewIterator().seek("d").range( end_key="c", end_inclusive=False)], ["aa", "bb"]) self.assertEquals([r.key for r in db.NewIterator().seek("d").range( start_key="b", end_key="c", start_inclusive=True, end_inclusive=True)], ["bb"]) self.assertEquals([r.key for r in db.NewIterator().seek("d").range( start_key="b", end_key="c", start_inclusive=False, end_inclusive=True)], ["bb"]) self.assertEquals([r.key for r in db.NewIterator().seek("d").range( start_key="b", end_key="c", start_inclusive=True, end_inclusive=False)], ["bb"]) self.assertEquals([r.key for r in db.NewIterator().seek("d").range( start_key="b", end_key="c", start_inclusive=False, end_inclusive=False)], ["bb"]) def testScopedDB(self, use_writebatch=False): db = self.db_class(leveldb.Options(), self.db_path, create_if_missing=True) scoped_db_1 = db.scope("prefix1_") scoped_db_2 = db.scope("prefix2_") scoped_db_2a = scoped_db_2.scope("a_") scoped_db_2b = scoped_db_2.scope("b_") scoped_db_3 = db.scope("prefix3_") w_opts = leveldb.WriteOptions() def mod(op, db, ops): if use_writebatch: batch = leveldb.WriteBatch() for args in ops: getattr(batch, op)(*args) db.write(leveldb.WriteOptions(), batch) else: for args in ops: if op != "delete": args = list(args) args.insert(0, w_opts) getattr(db, op)(*args) mod("put", db, [("1", "2"), ("prefix2_a_13", "14")]) mod("put", scoped_db_1, [("3", "4")]) mod("put", scoped_db_2, [("5", "6")]) mod("put", scoped_db_2a, [("7", "8")]) mod("put", scoped_db_2b, [("9", "10")]) mod("put", scoped_db_3, [("11", "12")]) db_data = [("1", "2"), ("prefix1_3", "4"), ("prefix2_5", "6"), ("prefix2_a_13", "14"), ("prefix2_a_7", "8"), ("prefix2_b_9", "10"), ("prefix3_11", "12")] self.assertEquals(list(db), db_data) self.assertEquals(list(scoped_db_1), [("3", "4")]) scoped_db_2_data = [("5", "6"), ("a_13", "14"), ("a_7", "8"), ("b_9", "10")] self.assertEquals(list(scoped_db_2), scoped_db_2_data) self.assertEquals(list(scoped_db_2a), [("13", "14"), ("7", "8")]) self.assertEquals(list(scoped_db_2b), [("9", "10")]) self.assertEquals(list(scoped_db_3), [("11", "12")]) for key, val in db_data: self.assertEquals(db.Get(leveldb.ReadOptions(), key), val) for key, val in scoped_db_2_data: self.assertEquals(scoped_db_2.Get(leveldb.ReadOptions(), key), val) self.assertEquals(scoped_db_1.Get(leveldb.ReadOptions(), "3"), "4") self.assertEquals(scoped_db_2a.Get(leveldb.ReadOptions(), "7"), "8") self.assertEquals(scoped_db_2b.Get(leveldb.ReadOptions(), "9"), "10") self.assertEquals(scoped_db_3.Get(leveldb.ReadOptions(), "11"), "12") self.assertEqual(scoped_db_2a.Get(leveldb.ReadOptions(), "13"), "14") mod("delete", db, [["1"], ["prefix2_a_7"]]) mod("delete", scoped_db_1, [["3"]]) mod("delete", scoped_db_2, [["5"]]) mod("delete", scoped_db_2a, [["13"]]) mod("delete", scoped_db_2b, [["9"]]) mod("delete", scoped_db_3, [["11"]]) self.assertEquals(list(db), []) self.assertEquals(list(scoped_db_1), []) self.assertEquals(list(scoped_db_2), []) self.assertEquals(list(scoped_db_2a), []) self.assertEquals(list(scoped_db_2b), []) self.assertEquals(list(scoped_db_3), []) for key, val in db_data: self.assertEquals(db.Get(leveldb.ReadOptions(), key), None) for key, val in scoped_db_2_data: self.assertEquals(scoped_db_2.Get(leveldb.ReadOptions(), key), None) self.assertEquals(scoped_db_1.Get(leveldb.ReadOptions(), "3"), None) self.assertEquals(scoped_db_2a.Get(leveldb.ReadOptions(), "7"), None) self.assertEquals(scoped_db_2b.Get(leveldb.ReadOptions(), "9"), None) self.assertEquals(scoped_db_3.Get(leveldb.ReadOptions(), "11"), None) self.assertEqual(scoped_db_2a.Get(leveldb.ReadOptions(), "13"), None) db.close() def testScopedDB_WriteBatch(self): self.testScopedDB(use_writebatch=True) def testOpaqueWriteBatch(self): db = self.db_class(leveldb.Options(), self.db_path, create_if_missing=True) scoped_db = db.scope("prefix2_") scopes = [db.scope("prefix1_"), scoped_db, scoped_db.scope("a_"), scoped_db.scope("b_"), db.scope("prefix3_")] batch = db.newBatch() for i, scope in enumerate(scopes): scope.putTo(batch, str(i), str(i)) db.write(leveldb.WriteOptions(), batch) for i, scope in enumerate(scopes): self.assertEquals(scope.Get(leveldb.ReadOptions(), str(i)), str(i)) batch.clear() for i, scope in enumerate(scopes): scope.deleteFrom(batch, str(i)) db.write(leveldb.WriteOptions(), batch) for i, scope in enumerate(scopes): self.assertEquals(scope.Get(leveldb.ReadOptions(), str(i)), None) # same effect when done through any scope batch = random.choice(scopes).newBatch() for i, scope in enumerate(scopes): scope.putTo(batch, str(i), str(2 * (i + 1))) random.choice(scopes).write(leveldb.WriteOptions(), batch) for i, scope in enumerate(scopes): self.assertEquals(scope.Get(leveldb.ReadOptions(), str(i)), str(2 * (i + 1))) batch.clear() for i, scope in enumerate(scopes): scope.deleteFrom(batch, str(i)) random.choice(scopes).write(leveldb.WriteOptions(), batch) for i, scope in enumerate(scopes): self.assertEquals(scope.Get(leveldb.ReadOptions(), str(i)), None) def testKeysWithZeroBytes(self): db = self.db_class(leveldb.Options(), self.db_path, create_if_missing=True) key_with_zero_byte = "\x01\x00\x02\x03\x04" db.Put(leveldb.WriteOptions(), key_with_zero_byte, "hey") self.assertEqual(db.Get(leveldb.ReadOptions(), key_with_zero_byte), "hey") it = db.NewIterator().SeekToFirst() self.assertTrue(it.Valid()) self.assertEqual(it.value(), "hey") self.assertEqual(it.key(), key_with_zero_byte) self.assertEqual(db.Get(leveldb.ReadOptions(), it.key()), "hey") db.close() def testValuesWithZeroBytes(self): db = self.db_class(leveldb.Options(), self.db_path, create_if_missing=True) value_with_zero_byte = "\x01\x00\x02\x03\x04" db.Put(leveldb.WriteOptions(), "hey", value_with_zero_byte) self.assertEqual(db.Get(leveldb.ReadOptions(), "hey"), value_with_zero_byte) it = db.NewIterator().SeekToFirst() self.assertTrue(it.Valid()) self.assertEqual(it.key(), "hey") self.assertEqual(it.value(), value_with_zero_byte) db.close() def testKeyRewrite(self): db = self.db_class(leveldb.Options(), self.db_path, create_if_missing=True) self.assertEqual(db.Get(leveldb.ReadOptions(), "hey"), None) db.Put(leveldb.WriteOptions(), "hey", "1") self.assertEqual(db.Get(leveldb.ReadOptions(), "hey"), "1") db.Put(leveldb.WriteOptions(), "hey", "2") self.assertEqual(db.Get(leveldb.ReadOptions(), "hey"), "2") db.Put(leveldb.WriteOptions(), "hey", "2") self.assertEqual(db.Get(leveldb.ReadOptions(), "hey"), "2") db.Put(leveldb.WriteOptions(), "hey", "3") self.assertEqual(db.Get(leveldb.ReadOptions(), "hey"), "3") def test__getsetitem__(self): db = self.db_class(leveldb.Options(), self.db_path, create_if_missing=True) db["hey"] = "1" self.assertTrue("hey" in db) self.assertEqual(db["hey"], "1") db["hey"] = "2" self.assertEqual(db["hey"], "2") db["hey"] = "2" self.assertEqual(db["hey"], "2") db["hey"] = "3" self.assertEqual(db["hey"], "3") def test__contains__(self): db = self.db_class(leveldb.Options(), self.db_path, create_if_missing=True) self.assertTrue("hey" not in db) with self.assertRaises(KeyError): db["hey"] db["hey"] = "1" self.assertTrue("hey" in db) def test__delitem__(self): db = self.db_class(leveldb.Options(), self.db_path, create_if_missing=True) self.assertTrue("hey" not in db) db["hey"] = "1" self.assertTrue("hey" in db) del db["hey"] self.assertTrue("hey" not in db) def testSnapshots(self): db = self.db_class(leveldb.Options(), self.db_path, create_if_missing=True) snapshot = db.snapshot() db["hey"] = "1" db["there"] = "2" self.assertEqual(len(list(db)), 2) self.assertEqual(len(list(snapshot)), 0) snapshot = db.snapshot() self.assertEqual(len(list(snapshot)), 2) self.assertEqual(snapshot["hey"], "1") self.assertEqual(snapshot["there"], "2") self.assertEqual(db["hey"], "1") self.assertEqual(db["there"], "2") db["hey"] = "3" db["there"] = "4" self.assertEqual(snapshot["hey"], "1") self.assertEqual(snapshot["there"], "2") self.assertEqual(db["hey"], "3") self.assertEqual(db["there"], "4") class LevelDBTestCases(LevelDBTestCasesMixIn, unittest.TestCase): db_class = staticmethod(leveldb.DB) def testInit(self): self.assertRaises(leveldb.Error, self.db_class, leveldb.Options(), self.db_path) self.db_class(leveldb.Options(), self.db_path, create_if_missing=True).close() self.db_class(leveldb.Options(), self.db_path, create_if_missing=True).close() self.db_class(leveldb.Options(), self.db_path).close() self.assertRaises(leveldb.Error, self.db_class, leveldb.Options(), self.db_path, create_if_missing=True, error_if_exists=True) def testPutSync(self, size=100): db = self.db_class(leveldb.Options(), self.db_path, create_if_missing=True) for i in xrange(size): db.Put(leveldb.WriteOptions(), str(i), str(i + 1)) start_sync_time = time.time() for i in xrange(size): db.Put(leveldb.WriteOptions(), str(i), str(i + 1), sync=True) start_unsync_time = time.time() for i in xrange(size): db.Put(leveldb.WriteOptions(), str(i), str(i + 1)) end_time = time.time() sync_time = start_unsync_time - start_sync_time unsync_time = end_time - start_unsync_time self.assertTrue(sync_time > 10 * unsync_time) db.close() def testDeleteSync(self, size=100): db = self.db_class(leveldb.Options(), self.db_path, create_if_missing=True) for i in xrange(size): db.Put(leveldb.WriteOptions(), str(i), str(i + 1)) start_sync_time = time.time() for i in xrange(size): db.delete(str(i), sync=True) end_sync_time = time.time() for i in xrange(size): db.Put(leveldb.WriteOptions(), str(i), str(i + 1)) start_unsync_time = time.time() for i in xrange(size): db.delete(str(i)) end_unsync_time = time.time() sync_time = end_sync_time - start_sync_time unsync_time = end_unsync_time - start_unsync_time self.assertTrue(sync_time > 10 * unsync_time) db.close() def testSegfaultFromIssue2(self, short_time=10): """https://code.google.com/p/leveldb-py/issues/detail?id=2""" # i assume the reporter meant opening a new db a bunch of times? paths = [] dbs = [] start_time = time.time() while time.time() - start_time < short_time: path = tempfile.mkdtemp() paths.append(path) db = self.db_class(leveldb.Options(), path, create_if_missing=True) batch = leveldb.WriteBatch() for x in xrange(10000): batch.Put(str(x), str(x)) db.write(leveldb.WriteOptions(), batch) dbs.append(db) for db in dbs: db.close() # maybe the reporter meant opening the same db over and over? start_time = time.time() path = tempfile.mkdtemp() paths.append(path) while time.time() - start_time < short_time: db = self.db_class(leveldb.Options(), path, create_if_missing=True) batch = leveldb.WriteBatch() for x in xrange(10000): batch.Put(str(x), str(x)) db.write(leveldb.WriteOptions(), batch) db.close() # or maybe the same db handle, but lots of write batches? start_time = time.time() path = tempfile.mkdtemp() paths.append(path) db = self.db_class(leveldb.Options(), path, create_if_missing=True) while time.time() - start_time < short_time: batch = leveldb.WriteBatch() for x in xrange(10000): batch.Put(str(x), str(x)) db.write(leveldb.WriteOptions(), batch) db.close() # or maybe it was lots of batch puts? start_time = time.time() path = tempfile.mkdtemp() paths.append(path) db = self.db_class(leveldb.Options(), path, create_if_missing=True) batch = leveldb.WriteBatch() x = 0 while time.time() - start_time < short_time: batch.Put(str(x), str(x)) x += 1 db.write(leveldb.WriteOptions(), batch) db.close() # if we got here, we haven't segfaulted, so, i dunno for path in paths: shutil.rmtree(path) class MemLevelDBTestCases(LevelDBTestCasesMixIn, unittest.TestCase): db_class = staticmethod(leveldb.MemoryDB) class LevelDBIteratorTestMixIn(object): db_class = None def setUp(self): self.db_path = tempfile.mkdtemp() def tearDown(self): shutil.rmtree(self.db_path) def test_iteration(self): db = self.db_class(leveldb.Options(), self.db_path, create_if_missing=True) db.Put(leveldb.WriteOptions(), 'a', 'b') db.Put(leveldb.WriteOptions(), 'c', 'd') iterator = iter(db) self.assertEqual(iterator.next(), ('a', 'b')) self.assertEqual(iterator.next(), ('c', 'd')) self.assertRaises(StopIteration, iterator.next) db.close() def test_iteration_keys_only(self): db = self.db_class(leveldb.Options(), self.db_path, create_if_missing=True) db.Put(leveldb.WriteOptions(), 'a', 'b') db.Put(leveldb.WriteOptions(), 'c', 'd') iterator = db.NewIterator(keys_only=True).SeekToFirst() self.assertEqual(iterator.next(), 'a') self.assertEqual(iterator.next(), 'c') self.assertRaises(StopIteration, iterator.next) db.close() def test_iteration_with_break(self): db = self.db_class(leveldb.Options(), self.db_path, create_if_missing=True) db.Put(leveldb.WriteOptions(), 'a', 'b') db.Put(leveldb.WriteOptions(), 'c', 'd') for key, value in db: self.assertEqual((key, value), ('a', 'b')) break db.close() def test_iteration_empty_db(self): """ Test the null condition, no entries in the database. """ db = self.db_class(leveldb.Options(), self.db_path, create_if_missing=True) for _ in db: self.fail("shouldn't happen") db.close() def test_seek(self): """ Test seeking forwards and backwards """ db = self.db_class(leveldb.Options(), self.db_path, create_if_missing=True) db.Put(leveldb.WriteOptions(), 'a', 'b') db.Put(leveldb.WriteOptions(), 'b', 'b') db.Put(leveldb.WriteOptions(), 'ca', 'a') db.Put(leveldb.WriteOptions(), 'cb', 'b') db.Put(leveldb.WriteOptions(), 'd', 'd') iterator = iter(db).seek("c") self.assertEqual(iterator.next(), ('ca', 'a')) self.assertEqual(iterator.next(), ('cb', 'b')) # seek backwards iterator.seek('a') self.assertEqual(iterator.next(), ('a', 'b')) db.close() def test_prefix(self): """ Test iterator prefixes """ batch = leveldb.WriteBatch() batch.Put('a', 'b') batch.Put('b', 'b') batch.Put('cd', 'a') batch.Put('ce', 'a') batch.Put('c', 'a') batch.Put('f', 'b') db = self.db_class(leveldb.Options(), self.db_path, create_if_missing=True) db.write(leveldb.WriteOptions(), batch) iterator = db.NewIterator(prefix="c") iterator.SeekToFirst() self.assertEqual(iterator.next(), ('', 'a')) self.assertEqual(iterator.next(), ('d', 'a')) self.assertEqual(iterator.next(), ('e', 'a')) self.assertRaises(StopIteration, iterator.next) db.close() def test_multiple_iterators(self): """ Make sure that things work with multiple iterator objects alive at one time. """ db = self.db_class(leveldb.Options(), self.db_path, create_if_missing=True) entries = [('a', 'b'), ('b', 'b')] db.Put(leveldb.WriteOptions(), *entries[0]) db.Put(leveldb.WriteOptions(), *entries[1]) iter1 = iter(db) iter2 = iter(db) self.assertEqual(iter1.next(), entries[0]) # garbage collect iter1, seek iter2 past the end of the db. Make sure # everything works. del iter1 iter2.seek('z') self.assertRaises(StopIteration, iter2.next) db.close() def test_prev(self): db = self.db_class(leveldb.Options(), self.db_path, create_if_missing=True) db.Put(leveldb.WriteOptions(), 'a', 'b') db.Put(leveldb.WriteOptions(), 'b', 'b') iterator = iter(db) entry = iterator.next() iterator.Prev() self.assertEqual(entry, iterator.next()) # it's ok to call prev when the iterator is at position 0 iterator.Prev() self.assertEqual(entry, iterator.next()) db.close() def test_seek_first_last(self): db = self.db_class(leveldb.Options(), self.db_path, create_if_missing=True) db.Put(leveldb.WriteOptions(), 'a', 'b') db.Put(leveldb.WriteOptions(), 'b', 'b') iterator = iter(db) iterator.SeekToLast() self.assertEqual(iterator.next(), ('b', 'b')) iterator.SeekToFirst() self.assertEqual(iterator.next(), ('a', 'b')) db.close() def test_scoped_seek_first(self): db = self.db_class(leveldb.Options(), os.path.join(self.db_path, "1"), create_if_missing=True) db.Put(leveldb.WriteOptions(), "ba", "1") db.Put(leveldb.WriteOptions(), "bb", "2") db.Put(leveldb.WriteOptions(), "cc", "3") db.Put(leveldb.WriteOptions(), "cd", "4") db.Put(leveldb.WriteOptions(), "de", "5") db.Put(leveldb.WriteOptions(), "df", "6") it = db.scope("a").NewIterator().SeekToFirst() self.assertFalse(it.Valid()) it = db.scope("b").NewIterator().SeekToFirst() self.assertTrue(it.Valid()) self.assertEqual(it.key(), "a") it = db.scope("c").NewIterator().SeekToFirst() self.assertTrue(it.Valid()) self.assertEqual(it.key(), "c") it = db.scope("d").NewIterator().SeekToFirst() self.assertTrue(it.Valid()) self.assertEqual(it.key(), "e") it = db.scope("e").NewIterator().SeekToFirst() self.assertFalse(it.Valid()) db.close() def test_scoped_seek_last(self): db = self.db_class(leveldb.Options(), os.path.join(self.db_path, "1"), create_if_missing=True) db.Put(leveldb.WriteOptions(), "ba", "1") db.Put(leveldb.WriteOptions(), "bb", "2") db.Put(leveldb.WriteOptions(), "cc", "3") db.Put(leveldb.WriteOptions(), "cd", "4") db.Put(leveldb.WriteOptions(), "de", "5") db.Put(leveldb.WriteOptions(), "df", "6") it = db.scope("a").NewIterator().SeekToLast() self.assertFalse(it.Valid()) it = db.scope("b").NewIterator().SeekToLast() self.assertTrue(it.Valid()) self.assertEqual(it.key(), "b") it = db.scope("c").NewIterator().SeekToLast() self.assertTrue(it.Valid()) self.assertEqual(it.key(), "d") it = db.scope("d").NewIterator().SeekToLast() self.assertTrue(it.Valid()) self.assertEqual(it.key(), "f") it = db.scope("e").NewIterator().SeekToLast() self.assertFalse(it.Valid()) db.close() db = self.db_class(leveldb.Options(), os.path.join(self.db_path, "2"), create_if_missing=True) db.Put(leveldb.WriteOptions(), "\xff\xff\xffab", "1") db.Put(leveldb.WriteOptions(), "\xff\xff\xffcd", "2") it = db.scope("\xff\xff\xff").NewIterator().SeekToLast() self.assertTrue(it.Valid()) self.assertEqual(it.key(), "cd") db.close() db = self.db_class(leveldb.Options(), os.path.join(self.db_path, "3"), create_if_missing=True) db.Put(leveldb.WriteOptions(), "\xff\xff\xfeab", "1") db.Put(leveldb.WriteOptions(), "\xff\xff\xfecd", "2") it = db.scope("\xff\xff\xff").NewIterator().SeekToLast() self.assertFalse(it.Valid()) db.close() db = self.db_class(leveldb.Options(), os.path.join(self.db_path, "4"), create_if_missing=True) db.Put(leveldb.WriteOptions(), "\xff\xff\xfeab", "1") db.Put(leveldb.WriteOptions(), "\xff\xff\xfecd", "2") it = db.scope("\xff\xff\xfe").NewIterator().SeekToLast() self.assertTrue(it.Valid()) self.assertEqual(it.key(), "cd") db.close() db = self.db_class(leveldb.Options(), os.path.join(self.db_path, "5"), create_if_missing=True) db.Put(leveldb.WriteOptions(), "\xff\xff\xfeab", "1") db.Put(leveldb.WriteOptions(), "\xff\xff\xfecd", "2") db.Put(leveldb.WriteOptions(), "\xff\xff\xffef", "1") db.Put(leveldb.WriteOptions(), "\xff\xff\xffgh", "2") it = db.scope("\xff\xff\xfe").NewIterator().SeekToLast() self.assertTrue(it.Valid()) self.assertEqual(it.key(), "cd") db.close() db = self.db_class(leveldb.Options(), os.path.join(self.db_path, "6"), create_if_missing=True) db.Put(leveldb.WriteOptions(), "\x0f\xff\xfeab", "1") db.Put(leveldb.WriteOptions(), "\x0f\xff\xfecd", "2") db.Put(leveldb.WriteOptions(), "\x0f\xff\xffef", "1") db.Put(leveldb.WriteOptions(), "\x0f\xff\xffgh", "2") it = db.scope("\x0f\xff\xfe").NewIterator().SeekToLast() self.assertTrue(it.Valid()) self.assertEqual(it.key(), "cd") db.close() db = self.db_class(leveldb.Options(), os.path.join(self.db_path, "7"), create_if_missing=True) db.Put(leveldb.WriteOptions(), "\x10\xff", "1") db.Put(leveldb.WriteOptions(), "\x11", "2") it = db.scope("\x10\xff").NewIterator().SeekToLast() self.assertTrue(it.Valid()) self.assertEqual(it.value(), "1") db.close() def test_seek_last_with_leading_zero_prefix(self): db = self.db_class(leveldb.Options(), os.path.join(self.db_path, "1"), create_if_missing=True) db.Put(leveldb.WriteOptions(), "\x00\x00\x00", "1") db.Put(leveldb.WriteOptions(), "\x00\x00\xff", "2") db.Put(leveldb.WriteOptions(), "\x00\x01\x00", "3") db.Put(leveldb.WriteOptions(), "\x01\x01\x00", "4") self.assertEqual(db.NewIterator(prefix="\x00\x00\x00").SeekToLast().value(), "1") self.assertEqual(db.NewIterator(prefix="\x00\x00").SeekToLast().value(), "2") self.assertEqual(db.NewIterator(prefix="\x00").SeekToLast().value(), "3") db.close() def test_scoped_then_iterate(self): db = self.db_class(leveldb.Options(), os.path.join(self.db_path, "1"), create_if_missing=True) for i in range(10): db.Put(leveldb.WriteOptions(), "%dfoo" % i, "bar%d" % i) it = db.NewIterator(prefix="5").SeekToFirst() self.assertTrue(it.Valid()) self.assertEqual(it.key(), "foo") self.assertEqual(it.value(), "bar5") for id_, (k, v) in enumerate(it): self.assertEqual(id_, 0) self.assertEqual(k, "foo") self.assertEqual(v, "bar5") class LevelDBIteratorTest(LevelDBIteratorTestMixIn, unittest.TestCase): db_class = staticmethod(leveldb.DB) def testApproximateSizes(self): db = self.db_class(leveldb.Options(), self.db_path, create_if_missing=True) self.assertEqual([0, 0, 0], db.approximateDiskSizes(("a", "z"), ("0", "9"), ("A", "Z"))) batch = leveldb.WriteBatch() for i in xrange(100): batch.Put("c%d" % i, os.urandom(4096)) db.write(leveldb.WriteOptions(), batch, sync=True) db.close() db = self.db_class(leveldb.Options(), self.db_path) sizes = db.approximateDiskSizes(("0", "9"), ("A", "Z"), ("a", "z")) self.assertEqual(sizes[0], 0) self.assertEqual(sizes[1], 0) self.assertTrue(sizes[2] >= 4096 * 100) for i in xrange(10): db.Put(leveldb.WriteOptions(), "3%d" % i, os.urandom(10)) db.close() db = self.db_class(leveldb.Options(), self.db_path) sizes = db.approximateDiskSizes(("A", "Z"), ("a", "z"), ("0", "9")) self.assertEqual(sizes[0], 0) self.assertTrue(sizes[1] >= 4096 * 100) self.assertTrue(sizes[2] < 4096 * 100) self.assertTrue(sizes[2] >= 10 * 10) db.close() class MemLevelDBIteratorTest(LevelDBIteratorTestMixIn, unittest.TestCase): db_class = staticmethod(leveldb.MemoryDB) def main(): parser = argparse.ArgumentParser("run tests") parser.add_argument("--runs", type=int, default=1) args = parser.parse_args() for _ in xrange(args.runs): unittest.main(argv=sys.argv[:1], exit=False) if __name__ == "__main__": main()
35,969
44.474083
94
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/items.py
from logging import getLogger import json import directories import os import shutil import types logger = getLogger(__name__) class ItemType(object): def __init__(self, id, name, maxdamage=0, damagevalue=0, stacksize=64): self.id = id self.name = name self.maxdamage = maxdamage self.damagevalue = damagevalue self.stacksize = stacksize def __repr__(self): return "ItemType({0}, '{1}')".format(self.id, self.name) def __str__(self): return "ItemType {0}: {1}".format(self.id, self.name) class Items(object): items = {} def __init__(self, filename=None): #itemsdir = os.path.join(directories.getDataDir(), "Items") itemsdir = directories.getDataFile('Items') if not os.path.exists(itemsdir): raise Exception("Couldn't find Item Files. Please reinstall MCEdit!") for file_ in os.listdir(itemsdir): if os.path.isdir(os.path.join(itemsdir, file_)): try: f = open(os.path.join(itemsdir, file_, "items.json"), 'r') itempack = json.load(f) itempacknew = {} for item in itempack: itempacknew[file_ + ":" + item] = itempack.get(item) self.items.update(itempacknew) except Exception as e: logger.debug('Error while loading items.json: %s'%e) pass try: f = open(os.path.join(itemsdir, file_, "blocks.json"), 'r') itempack = json.load(f) itempacknew = {} for item in itempack: itempacknew[file_ + ":" + item] = itempack.get(item) self.items.update(itempacknew) except Exception as e: logger.debug('Error while loading blocks.json: %s'%e) pass def findItem(self, id=0, damage=None): try: item = self.items[id] except: item = self.findItemID(id) if damage <= item["maxdamage"]: if isinstance(item["name"], (str, unicode)): return ItemType(id, item["name"], item["maxdamage"], damage, item["stacksize"]) else: if isinstance(item["name"][damage], (str, unicode)): return ItemType(id, item["name"][damage], item["maxdamage"], damage, item["stacksize"]) else: raise ItemNotFound() else: raise ItemNotFound() def findItemID(self, id): for item in self.items: itemTemp = self.items[item] if not isinstance(itemTemp, types.UnicodeType): if itemTemp["id"] == id: return self.items[item] raise ItemNotFound() class ItemNotFound(KeyError): pass items = Items()
2,951
30.404255
107
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/materials.py
from logging import getLogger from numpy import zeros, rollaxis, indices import traceback from os.path import join from collections import defaultdict from pprint import pformat import mclangres import json import os import pkg_resources import id_definitions NOTEX = (496, 496) log = getLogger(__name__) try: pkg_resources.resource_exists(__name__, 'minecraft.json') except: import sys if getattr(sys, '_MEIPASS', None): base = getattr(sys, '_MEIPASS') pkg_resources.resource_exists = lambda n,f: os.path.join(base, 'pymclevel', f) class Block(object): """ Value object representing an (id, data) pair. Provides elements of its parent material's block arrays. Blocks will have (name, ID, blockData, aka, color, brightness, opacity, blockTextures) """ def __str__(self): return "<Block {name} ({id}:{data})>".format( name=self.name, id=self.ID, data=self.blockData) def __repr__(self): return str(self) def __cmp__(self, other): if not isinstance(other, Block): return -1 key = lambda a: a and (a.ID, a.blockData) return cmp(key(self), key(other)) def __hash__(self): return hash((self.ID, self.blockData)) def __init__(self, materials, blockID, blockData=0, blockString=''): self.materials = materials self.ID = blockID self.blockData = blockData self.stringID = blockString def __getattr__(self, attr): if attr in self.__dict__: return self.__dict__[attr] if attr == "name": r = self.materials.names[self.ID] else: r = getattr(self.materials, attr)[self.ID] if attr in ("name", "aka", "color", "type", "search"): r = r[self.blockData] return r id_limit = 4096 class BlockstateAPI(object): """ An easy API to convert from numerical ID's to Blockstates and vice-versa. Each material has its own instance of this class. You can access it in a variety of ways:: from pymclevel.materials import BlockstateAPI, alphaMaterials, pocketMaterials api = BlockStateAPI.material_map[alphaMaterials] api = alphaMaterials.blockstate_api """ material_map = {} def __init__(self, mats, definition_file): self._mats = mats self.block_map = {} self.blockstates = {} for b in self._mats: if b.ID == 0: b.stringID = "air" self.block_map[b.ID] = "minecraft:" + b.stringID # When running from a bundled app on Linux (and possibly on OSX) pkg_resource can't find the needed files. if pkg_resources.resource_exists(__name__, definition_file): # We're running from source or on Windows using the executable (<<== Not sure...) with pkg_resources.resource_stream(__name__, definition_file) as def_file: self.blockstates = json.load(def_file) else: # In all other cases, retrieve the file directly from the file system. with open(os.path.join("pymclevel", definition_file)) as def_file: self.blockstates = json.load(def_file) self.material_map[self._mats] = self def idToBlockstate(self, bid, data): """ Converts from a numerical ID to a BlockState string :param bid: The ID of the block :type bid: int :param data: The data value of the block :type data: int :return: A tuple of BlockState name and it's properties :rtype: tuple """ if bid not in self.block_map: return "<Unknown>", {} name = self.block_map[bid].replace("minecraft:", "") if name not in self.blockstates["minecraft"]: return "<Unknown>", {} properties = {} for prop in self.blockstates["minecraft"][name]["properties"]: # TODO: Change this if MCEdit's mod support ever improves if prop["<data>"] == data: for field in prop.keys(): if field == "<data>": continue properties[field] = prop[field] return name, properties return name, properties def blockstateToID(self, name, properties): """ Converts from a BlockState to a numerical ID/Data pair :param name: The BlockState name :type name: str :param properties: A list of Property/Value pairs in dict form :type properties: list :return: A tuple containing the numerical ID/Data pair (<id>, <data>) :rtype: tuple """ if ":" in name: prefix, name = name.split(":") else: prefix = "minecraft" if prefix not in self.blockstates: return -1, -1 elif name not in self.blockstates[prefix]: return -1, -1 bid = self.blockstates[prefix][name]["id"] for prop in self.blockstates[prefix][name]["properties"]: correct = True for (key, value) in properties.iteritems(): if key in prop: correct = correct and (prop[key] == value) if correct: return bid, prop["<data>"] return bid, 0 @staticmethod def stringifyBlockstate(name, properties): """ Turns a Blockstate into a single string :param name: The Block's base name. IE: grass, command_block, etc. :type name: str :param properties: A list of Property/Value pairs in dict form :type properties: list :return: A complete Blockstate in string form :rtype: str """ if not name.startswith("minecraft:"): name = "minecraft:" + name # This should be changed as soon as possible result = name + "[" for (key, value) in properties.iteritems(): result += "{}={},".format(key, value) if result.endswith("["): return result[:-1] return result[:-1] + "]" @staticmethod def deStringifyBlockstate(blockstate): """ Turns a single Blockstate string into a base name, properties tuple :param blockstate: The Blockstate string :type blockstate: str :return: A tuple containing the base name and the properties for the Blockstate :rtype: tuple """ seperated = blockstate.split("[") if len(seperated) == 1: if not seperated[0].startswith("minecraft:"): seperated[0] = "minecraft:" + seperated[0] return seperated[0], {} name, props = seperated if not name.startswith("minecraft:"): name = "minecraft:" + name properties = {} props = props[:-1] props = props.split(",") for prop in props: prop = prop.split("=") properties[prop[0]] = prop[1] return name, properties class MCMaterials(object): defaultColor = (201, 119, 240, 255) defaultBrightness = 0 defaultOpacity = 15 defaultTexture = NOTEX defaultTex = [t // 16 for t in defaultTexture] def __init__(self, defaultName="Unused Block"): object.__init__(self) self.yamlDatas = [] self.defaultName = defaultName self.blockTextures = zeros((id_limit, 16, 6, 2), dtype='uint16') # Sets the array size for terrain.png self.blockTextures[:] = self.defaultTexture self.names = [[defaultName] * 16 for _ in xrange(id_limit)] self.aka = [[""] * 16 for _ in xrange(id_limit)] self.search = [[""] * 16 for _ in xrange(id_limit)] self.type = [["NORMAL"] * 16] * id_limit self.blocksByType = defaultdict(list) self.allBlocks = [] self.blocksByID = {} self.lightEmission = zeros(id_limit, dtype='uint8') self.lightEmission[:] = self.defaultBrightness self.lightAbsorption = zeros(id_limit, dtype='uint8') self.lightAbsorption[:] = self.defaultOpacity self.flatColors = zeros((id_limit, 16, 4), dtype='uint8') self.flatColors[:] = self.defaultColor self.idStr = [""] * id_limit self.id_limit = id_limit self.color = self.flatColors self.brightness = self.lightEmission self.opacity = self.lightAbsorption self.types = {} self.Air = self.addBlock(0, name="Air", texture=(0, 336), opacity=0, ) def __repr__(self): return "<MCMaterials ({0})>".format(self.name) @property def AllStairs(self): return [b for b in self.allBlocks if "Stairs" in b.name] @property def AllSlabs(self): return [b for b in self.allBlocks if "Slab" in b.name] def get(self, key, default=None): try: return self[key] except KeyError: return default def __len__(self): return len(self.allBlocks) def __iter__(self): return iter(self.allBlocks) def __getitem__(self, key): """ Let's be magic. If we get a string, return the first block whose name matches exactly. If we get a (id, data) pair or an id, return that block. for example: level.materials[0] # returns Air level.materials["Air"] # also returns Air level.materials["Powered Rail"] # returns Powered Rail level.materials["Lapis Lazuli Block"] # in Classic """ if isinstance(key, basestring): key = key.replace("minecraft:", "") key = key.lower() lowest_block = None for b in self.allBlocks: if b.name.lower() == key: return b if b.idStr.lower() == key: if b.blockData == 0: return b elif not lowest_block: lowest_block = b elif lowest_block.blockData > b.blockData: lowest_block = b if lowest_block: return lowest_block if '[' in key and self.blockstate_api: name, properties = self.blockstate_api.deStringifyBlockstate(key) return self[self.blockstate_api.blockstateToID(name, properties)] raise KeyError("No blocks named: " + key) if isinstance(key, (tuple, list)): block_id, blockData = key return self.blockWithID(block_id, blockData) return self.blockWithID(key) def blocksMatching(self, name, names=None): toReturn = [] name = name.lower() spiltNames = name.split(" ") amount = len(spiltNames) for i, v in enumerate(self.allBlocks): if names is None: nameParts = v.name.lower().split(" ") for anotherName in v.aka.lower().split(" "): nameParts.append(anotherName) for anotherName in v.search.lower().split(" "): nameParts.append(anotherName) else: nameParts = names[i].lower().split(" ") i = 0 spiltNamesUsed = [] for v2 in nameParts: Start = True j = 0 while j < len(spiltNames) and Start: if spiltNames[j] in v2 and j not in spiltNamesUsed: i += 1 spiltNamesUsed.append(j) Start = False j += 1 if i == amount: toReturn.append(v) return toReturn def blockWithID(self, block_id, data=0): if (block_id, data) in self.blocksByID: return self.blocksByID[block_id, data] else: bl = Block(self, block_id, blockData=data) return bl def setup_blockstates(self, blockstate_definition_file): self.blockstate_api = BlockstateAPI(self, blockstate_definition_file) def addJSONBlocksFromFile(self, filename): blockyaml = None try: f = pkg_resources.resource_stream(__name__, filename) except (ImportError, IOError) as e: log.debug("Cannot get resource_stream for %s %s" % (filename, e)) root = os.environ.get("PYMCLEVEL_YAML_ROOT", "pymclevel") # fall back to cwd as last resort path = join(root, filename) log.debug("Failed to read %s using pkg_resources. Trying %s instead." % (filename, path)) f = file(path) try: log.info(u"Loading block info from %s", f) blockyaml = json.load(f) except Exception as e: log.warn(u"Exception while loading block info from %s: %s", f, e) traceback.print_exc() if blockyaml: self.addJSONBlocks(blockyaml) def addJSONBlocksFromVersion(self, gamePlatform, gameVersionNumber): # Load first the versionned stuff # Fallback to the old .json file log.debug("Loading block definitions from versionned file") print "Game Version: {} : {}".format(gamePlatform, gameVersionNumber) gameVersionNumber = gameVersionNumber.replace('java ', '') blockyaml = id_definitions.ids_loader(gamePlatform, gameVersionNumber, json_dict=True) if gamePlatform == 'PE' or gamePlatform == 'old pocket': f_name = 'pocket.json' self.setup_blockstates("pe_blockstates.json") meth = build_pocket_materials elif gamePlatform == 'javalevel': # No reference to materials in javalevel.py and no related JSon file, let use the 'classic' ones? f_name = 'classic.json' meth = build_classic_materials elif gamePlatform == 'indev': f_name == 'indev.json' meth = build_indev_materials else: f_name = 'minecraft.json' self.setup_blockstates("pc_blockstates.json") meth = build_alpha_materials if blockyaml: self.addJSONBlocks(blockyaml) else: self.addJSONBlocksFromFile(f_name) meth() # build_api_material_map() def addJSONBlocks(self, blockyaml): self.yamlDatas.append(blockyaml) for block in blockyaml['blocks']: try: self.addJSONBlock(block) except Exception as e: log.warn(u"Exception while parsing block: %s", e) traceback.print_exc() log.warn(u"Block definition: \n%s", pformat(block)) def addJSONBlock(self, kw): blockID = kw['id'] # xxx unused_yaml_properties variable unused; needed for # documentation purpose of some sort? -zothar # unused_yaml_properties = \ #['explored', # # 'id', # # 'idStr', # # 'mapcolor', # # 'name', # # 'tex', # ### 'tex_data', # # 'tex_direction', # ### 'tex_direction_data', # 'tex_extra', # # 'type' # ] for val, data in kw.get('data', {0: {}}).items(): datakw = dict(kw) datakw.update(data) idStr = datakw.get('idStr', "") tex = [t * 16 for t in datakw.get('tex', self.defaultTex)] texture = [tex] * 6 texDirs = { "FORWARD": 5, "BACKWARD": 4, "LEFT": 1, "RIGHT": 0, "TOP": 2, "BOTTOM": 3, } for dirname, dirtex in datakw.get('tex_direction', {}).items(): if dirname == "SIDES": for dirname in ("LEFT", "RIGHT"): texture[texDirs[dirname]] = [t * 16 for t in dirtex] if dirname in texDirs: texture[texDirs[dirname]] = [t * 16 for t in dirtex] datakw['texture'] = texture # print datakw block = self.addBlock(blockID, val, **datakw) block.yaml = datakw self.idStr[blockID] = idStr tex_direction_data = kw.get('tex_direction_data') if tex_direction_data: texture = datakw['texture'] # X+0, X-1, Y+, Y-, Z+b, Z-f texDirMap = { "NORTH": 0, "EAST": 1, "SOUTH": 2, "WEST": 3, } def rot90cw(): rot = (5, 0, 2, 3, 4, 1) texture[:] = [texture[r] for r in rot] for data, direction in tex_direction_data.items(): for _i in xrange(texDirMap.get(direction, 0)): rot90cw() self.blockTextures[blockID][int(data)] = texture def addBlock(self, blockID, blockData=0, **kw): blockData = int(blockData) try: name = kw.pop('name', self.names[blockID][blockData]) except: print (blockID, blockData) stringName = kw.pop('idStr', '') self.lightEmission[blockID] = kw.pop('brightness', self.defaultBrightness) self.lightAbsorption[blockID] = kw.pop('opacity', self.defaultOpacity) self.aka[blockID][blockData] = kw.pop('aka', "") self.search[blockID][blockData] = kw.pop('search', "") block_type = kw.pop('type', 'NORMAL') color = kw.pop('mapcolor', self.flatColors[blockID, blockData]) self.flatColors[blockID, blockData] = (tuple(color) + (255,))[:4] texture = kw.pop('texture', None) if texture: self.blockTextures[blockID, blockData] = texture self.names[blockID][blockData] = name if blockData is 0: self.type[blockID] = [block_type] * 16 else: self.type[blockID][blockData] = block_type block = Block(self, blockID, blockData, stringName) if kw.pop('invalid', 'false') == 'false': self.allBlocks.append(block) self.blocksByType[block_type].append(block) self.blocksByID[blockID, blockData] = block return block alphaMaterials = MCMaterials(defaultName="Future Block!") alphaMaterials.name = "Alpha" classicMaterials = MCMaterials(defaultName="Not present in Classic") classicMaterials.name = "Classic" indevMaterials = MCMaterials(defaultName="Not present in Indev") indevMaterials.name = "Indev" pocketMaterials = MCMaterials() pocketMaterials.name = "Pocket" # --- Static block defs --- def build_alpha_materials(): log.info("Building Alpha materials.") alphaMaterials.Stone = alphaMaterials[1, 0] alphaMaterials.Grass = alphaMaterials[2, 0] alphaMaterials.Dirt = alphaMaterials[3, 0] alphaMaterials.Cobblestone = alphaMaterials[4, 0] alphaMaterials.WoodPlanks = alphaMaterials[5, 0] alphaMaterials.Sapling = alphaMaterials[6, 0] alphaMaterials.SpruceSapling = alphaMaterials[6, 1] alphaMaterials.BirchSapling = alphaMaterials[6, 2] alphaMaterials.Bedrock = alphaMaterials[7, 0] alphaMaterials.WaterActive = alphaMaterials[8, 0] alphaMaterials.Water = alphaMaterials[9, 0] alphaMaterials.LavaActive = alphaMaterials[10, 0] alphaMaterials.Lava = alphaMaterials[11, 0] alphaMaterials.Sand = alphaMaterials[12, 0] alphaMaterials.Gravel = alphaMaterials[13, 0] alphaMaterials.GoldOre = alphaMaterials[14, 0] alphaMaterials.IronOre = alphaMaterials[15, 0] alphaMaterials.CoalOre = alphaMaterials[16, 0] alphaMaterials.Wood = alphaMaterials[17, 0] alphaMaterials.PineWood = alphaMaterials[17, 1] alphaMaterials.BirchWood = alphaMaterials[17, 2] alphaMaterials.JungleWood = alphaMaterials[17, 3] alphaMaterials.Leaves = alphaMaterials[18, 0] alphaMaterials.PineLeaves = alphaMaterials[18, 1] alphaMaterials.BirchLeaves = alphaMaterials[18, 2] alphaMaterials.JungleLeaves = alphaMaterials[18, 3] alphaMaterials.LeavesPermanent = alphaMaterials[18, 4] alphaMaterials.PineLeavesPermanent = alphaMaterials[18, 5] alphaMaterials.BirchLeavesPermanent = alphaMaterials[18, 6] alphaMaterials.JungleLeavesPermanent = alphaMaterials[18, 7] alphaMaterials.LeavesDecaying = alphaMaterials[18, 8] alphaMaterials.PineLeavesDecaying = alphaMaterials[18, 9] alphaMaterials.BirchLeavesDecaying = alphaMaterials[18, 10] alphaMaterials.JungleLeavesDecaying = alphaMaterials[18, 11] alphaMaterials.Sponge = alphaMaterials[19, 0] alphaMaterials.Glass = alphaMaterials[20, 0] alphaMaterials.LapisLazuliOre = alphaMaterials[21, 0] alphaMaterials.LapisLazuliBlock = alphaMaterials[22, 0] alphaMaterials.Dispenser = alphaMaterials[23, 0] alphaMaterials.Sandstone = alphaMaterials[24, 0] alphaMaterials.NoteBlock = alphaMaterials[25, 0] alphaMaterials.Bed = alphaMaterials[26, 0] alphaMaterials.PoweredRail = alphaMaterials[27, 0] alphaMaterials.DetectorRail = alphaMaterials[28, 0] alphaMaterials.StickyPiston = alphaMaterials[29, 0] alphaMaterials.Web = alphaMaterials[30, 0] alphaMaterials.UnusedShrub = alphaMaterials[31, 0] alphaMaterials.TallGrass = alphaMaterials[31, 1] alphaMaterials.Shrub = alphaMaterials[31, 2] alphaMaterials.DesertShrub2 = alphaMaterials[32, 0] alphaMaterials.Piston = alphaMaterials[33, 0] alphaMaterials.PistonHead = alphaMaterials[34, 0] alphaMaterials.WhiteWool = alphaMaterials[35, 0] alphaMaterials.OrangeWool = alphaMaterials[35, 1] alphaMaterials.MagentaWool = alphaMaterials[35, 2] alphaMaterials.LightBlueWool = alphaMaterials[35, 3] alphaMaterials.YellowWool = alphaMaterials[35, 4] alphaMaterials.LightGreenWool = alphaMaterials[35, 5] alphaMaterials.PinkWool = alphaMaterials[35, 6] alphaMaterials.GrayWool = alphaMaterials[35, 7] alphaMaterials.LightGrayWool = alphaMaterials[35, 8] alphaMaterials.CyanWool = alphaMaterials[35, 9] alphaMaterials.PurpleWool = alphaMaterials[35, 10] alphaMaterials.BlueWool = alphaMaterials[35, 11] alphaMaterials.BrownWool = alphaMaterials[35, 12] alphaMaterials.DarkGreenWool = alphaMaterials[35, 13] alphaMaterials.RedWool = alphaMaterials[35, 14] alphaMaterials.BlackWool = alphaMaterials[35, 15] alphaMaterials.Block36 = alphaMaterials[36, 0] alphaMaterials.Flower = alphaMaterials[37, 0] alphaMaterials.Rose = alphaMaterials[38, 0] alphaMaterials.BrownMushroom = alphaMaterials[39, 0] alphaMaterials.RedMushroom = alphaMaterials[40, 0] alphaMaterials.BlockofGold = alphaMaterials[41, 0] alphaMaterials.BlockofIron = alphaMaterials[42, 0] alphaMaterials.DoubleStoneSlab = alphaMaterials[43, 0] alphaMaterials.DoubleSandstoneSlab = alphaMaterials[43, 1] alphaMaterials.DoubleWoodenSlab = alphaMaterials[43, 2] alphaMaterials.DoubleCobblestoneSlab = alphaMaterials[43, 3] alphaMaterials.DoubleBrickSlab = alphaMaterials[43, 4] alphaMaterials.DoubleStoneBrickSlab = alphaMaterials[43, 5] alphaMaterials.StoneSlab = alphaMaterials[44, 0] alphaMaterials.SandstoneSlab = alphaMaterials[44, 1] alphaMaterials.WoodenSlab = alphaMaterials[44, 2] alphaMaterials.CobblestoneSlab = alphaMaterials[44, 3] alphaMaterials.BrickSlab = alphaMaterials[44, 4] alphaMaterials.StoneBrickSlab = alphaMaterials[44, 5] alphaMaterials.Brick = alphaMaterials[45, 0] alphaMaterials.TNT = alphaMaterials[46, 0] alphaMaterials.Bookshelf = alphaMaterials[47, 0] alphaMaterials.MossStone = alphaMaterials[48, 0] alphaMaterials.Obsidian = alphaMaterials[49, 0] alphaMaterials.Torch = alphaMaterials[50, 0] alphaMaterials.Fire = alphaMaterials[51, 0] alphaMaterials.MonsterSpawner = alphaMaterials[52, 0] alphaMaterials.WoodenStairs = alphaMaterials[53, 0] alphaMaterials.Chest = alphaMaterials[54, 0] alphaMaterials.RedstoneWire = alphaMaterials[55, 0] alphaMaterials.DiamondOre = alphaMaterials[56, 0] alphaMaterials.BlockofDiamond = alphaMaterials[57, 0] alphaMaterials.CraftingTable = alphaMaterials[58, 0] alphaMaterials.Crops = alphaMaterials[59, 0] alphaMaterials.Farmland = alphaMaterials[60, 0] alphaMaterials.Furnace = alphaMaterials[61, 0] alphaMaterials.LitFurnace = alphaMaterials[62, 0] alphaMaterials.Sign = alphaMaterials[63, 0] alphaMaterials.WoodenDoor = alphaMaterials[64, 0] alphaMaterials.Ladder = alphaMaterials[65, 0] alphaMaterials.Rail = alphaMaterials[66, 0] alphaMaterials.StoneStairs = alphaMaterials[67, 0] alphaMaterials.WallSign = alphaMaterials[68, 0] alphaMaterials.Lever = alphaMaterials[69, 0] alphaMaterials.StoneFloorPlate = alphaMaterials[70, 0] alphaMaterials.IronDoor = alphaMaterials[71, 0] alphaMaterials.WoodFloorPlate = alphaMaterials[72, 0] alphaMaterials.RedstoneOre = alphaMaterials[73, 0] alphaMaterials.RedstoneOreGlowing = alphaMaterials[74, 0] alphaMaterials.RedstoneTorchOff = alphaMaterials[75, 0] alphaMaterials.RedstoneTorchOn = alphaMaterials[76, 0] alphaMaterials.Button = alphaMaterials[77, 0] alphaMaterials.SnowLayer = alphaMaterials[78, 0] alphaMaterials.Ice = alphaMaterials[79, 0] alphaMaterials.Snow = alphaMaterials[80, 0] alphaMaterials.Cactus = alphaMaterials[81, 0] alphaMaterials.Clay = alphaMaterials[82, 0] alphaMaterials.SugarCane = alphaMaterials[83, 0] alphaMaterials.Jukebox = alphaMaterials[84, 0] alphaMaterials.Fence = alphaMaterials[85, 0] alphaMaterials.Pumpkin = alphaMaterials[86, 0] alphaMaterials.Netherrack = alphaMaterials[87, 0] alphaMaterials.SoulSand = alphaMaterials[88, 0] alphaMaterials.Glowstone = alphaMaterials[89, 0] alphaMaterials.NetherPortal = alphaMaterials[90, 0] alphaMaterials.JackOLantern = alphaMaterials[91, 0] alphaMaterials.Cake = alphaMaterials[92, 0] alphaMaterials.RedstoneRepeaterOff = alphaMaterials[93, 0] alphaMaterials.RedstoneRepeaterOn = alphaMaterials[94, 0] alphaMaterials.StainedGlass = alphaMaterials[95, 0] alphaMaterials.Trapdoor = alphaMaterials[96, 0] alphaMaterials.HiddenSilverfishStone = alphaMaterials[97, 0] alphaMaterials.HiddenSilverfishCobblestone = alphaMaterials[97, 1] alphaMaterials.HiddenSilverfishStoneBrick = alphaMaterials[97, 2] alphaMaterials.StoneBricks = alphaMaterials[98, 0] alphaMaterials.MossyStoneBricks = alphaMaterials[98, 1] alphaMaterials.CrackedStoneBricks = alphaMaterials[98, 2] alphaMaterials.HugeBrownMushroom = alphaMaterials[99, 0] alphaMaterials.HugeRedMushroom = alphaMaterials[100, 0] alphaMaterials.IronBars = alphaMaterials[101, 0] alphaMaterials.GlassPane = alphaMaterials[102, 0] alphaMaterials.Watermelon = alphaMaterials[103, 0] alphaMaterials.PumpkinStem = alphaMaterials[104, 0] alphaMaterials.MelonStem = alphaMaterials[105, 0] alphaMaterials.Vines = alphaMaterials[106, 0] alphaMaterials.FenceGate = alphaMaterials[107, 0] alphaMaterials.BrickStairs = alphaMaterials[108, 0] alphaMaterials.StoneBrickStairs = alphaMaterials[109, 0] alphaMaterials.Mycelium = alphaMaterials[110, 0] alphaMaterials.Lilypad = alphaMaterials[111, 0] alphaMaterials.NetherBrick = alphaMaterials[112, 0] alphaMaterials.NetherBrickFence = alphaMaterials[113, 0] alphaMaterials.NetherBrickStairs = alphaMaterials[114, 0] alphaMaterials.NetherWart = alphaMaterials[115, 0] alphaMaterials.EnchantmentTable = alphaMaterials[116, 0] alphaMaterials.BrewingStand = alphaMaterials[117, 0] alphaMaterials.Cauldron = alphaMaterials[118, 0] alphaMaterials.EnderPortal = alphaMaterials[119, 0] alphaMaterials.PortalFrame = alphaMaterials[120, 0] alphaMaterials.EndStone = alphaMaterials[121, 0] alphaMaterials.DragonEgg = alphaMaterials[122, 0] alphaMaterials.RedstoneLampoff = alphaMaterials[123, 0] alphaMaterials.RedstoneLampon = alphaMaterials[124, 0] alphaMaterials.OakWoodDoubleSlab = alphaMaterials[125, 0] alphaMaterials.SpruceWoodDoubleSlab = alphaMaterials[125, 1] alphaMaterials.BirchWoodDoubleSlab = alphaMaterials[125, 2] alphaMaterials.JungleWoodDoubleSlab = alphaMaterials[125, 3] alphaMaterials.OakWoodSlab = alphaMaterials[126, 0] alphaMaterials.SpruceWoodSlab = alphaMaterials[126, 1] alphaMaterials.BirchWoodSlab = alphaMaterials[126, 2] alphaMaterials.JungleWoodSlab = alphaMaterials[126, 3] alphaMaterials.CocoaPlant = alphaMaterials[127, 0] alphaMaterials.SandstoneStairs = alphaMaterials[128, 0] alphaMaterials.EmeraldOre = alphaMaterials[129, 0] alphaMaterials.EnderChest = alphaMaterials[130, 0] alphaMaterials.TripwireHook = alphaMaterials[131, 0] alphaMaterials.Tripwire = alphaMaterials[132, 0] alphaMaterials.BlockofEmerald = alphaMaterials[133, 0] alphaMaterials.SpruceWoodStairs = alphaMaterials[134, 0] alphaMaterials.BirchWoodStairs = alphaMaterials[135, 0] alphaMaterials.JungleWoodStairs = alphaMaterials[136, 0] alphaMaterials.CommandBlock = alphaMaterials[137, 0] alphaMaterials.BeaconBlock = alphaMaterials[138, 0] alphaMaterials.CobblestoneWall = alphaMaterials[139, 0] alphaMaterials.MossyCobblestoneWall = alphaMaterials[139, 1] alphaMaterials.FlowerPot = alphaMaterials[140, 0] alphaMaterials.Carrots = alphaMaterials[141, 0] alphaMaterials.Potatoes = alphaMaterials[142, 0] alphaMaterials.WoodenButton = alphaMaterials[143, 0] alphaMaterials.MobHead = alphaMaterials[144, 0] alphaMaterials.Anvil = alphaMaterials[145, 0] alphaMaterials.TrappedChest = alphaMaterials[146, 0] alphaMaterials.WeightedPressurePlateLight = alphaMaterials[147, 0] alphaMaterials.WeightedPressurePlateHeavy = alphaMaterials[148, 0] alphaMaterials.RedstoneComparatorInactive = alphaMaterials[149, 0] alphaMaterials.RedstoneComparatorActive = alphaMaterials[150, 0] alphaMaterials.DaylightSensor = alphaMaterials[151, 0] alphaMaterials.BlockofRedstone = alphaMaterials[152, 0] alphaMaterials.NetherQuartzOre = alphaMaterials[153, 0] alphaMaterials.Hopper = alphaMaterials[154, 0] alphaMaterials.BlockofQuartz = alphaMaterials[155, 0] alphaMaterials.QuartzStairs = alphaMaterials[156, 0] alphaMaterials.ActivatorRail = alphaMaterials[157, 0] alphaMaterials.Dropper = alphaMaterials[158, 0] alphaMaterials.StainedClay = alphaMaterials[159, 0] alphaMaterials.StainedGlassPane = alphaMaterials[160, 0] alphaMaterials.AcaciaLeaves = alphaMaterials[161, 0] alphaMaterials.DarkOakLeaves = alphaMaterials[161, 1] alphaMaterials.AcaciaLeavesPermanent = alphaMaterials[161, 4] alphaMaterials.DarkOakLeavesPermanent = alphaMaterials[161, 5] alphaMaterials.AcaciaLeavesDecaying = alphaMaterials[161, 8] alphaMaterials.DarkOakLeavesDecaying = alphaMaterials[161, 9] alphaMaterials.Wood2 = alphaMaterials[162, 0] alphaMaterials.AcaciaStairs = alphaMaterials[163, 0] alphaMaterials.DarkOakStairs = alphaMaterials[164, 0] alphaMaterials.SlimeBlock = alphaMaterials[165, 0] alphaMaterials.Barrier = alphaMaterials[166, 0] alphaMaterials.IronTrapdoor = alphaMaterials[167, 0] alphaMaterials.Prismarine = alphaMaterials[168, 0] alphaMaterials.SeaLantern = alphaMaterials[169, 0] alphaMaterials.HayBlock = alphaMaterials[170, 0] alphaMaterials.Carpet = alphaMaterials[171, 0] alphaMaterials.HardenedClay = alphaMaterials[172, 0] alphaMaterials.CoalBlock = alphaMaterials[173, 0] alphaMaterials.PackedIce = alphaMaterials[174, 0] alphaMaterials.TallFlowers = alphaMaterials[175, 0] alphaMaterials.StandingBanner = alphaMaterials[176, 0] alphaMaterials.WallBanner = alphaMaterials[177, 0] alphaMaterials.DaylightSensorOn = alphaMaterials[178, 0] alphaMaterials.RedSandstone = alphaMaterials[179, 0] alphaMaterials.SmooothRedSandstone = alphaMaterials[179, 1] alphaMaterials.RedSandstoneSairs = alphaMaterials[180, 0] alphaMaterials.DoubleRedSandstoneSlab = alphaMaterials[181, 0] alphaMaterials.RedSandstoneSlab = alphaMaterials[182, 0] alphaMaterials.SpruceFenceGate = alphaMaterials[183, 0] alphaMaterials.BirchFenceGate = alphaMaterials[184, 0] alphaMaterials.JungleFenceGate = alphaMaterials[185, 0] alphaMaterials.DarkOakFenceGate = alphaMaterials[186, 0] alphaMaterials.AcaciaFenceGate = alphaMaterials[187, 0] alphaMaterials.SpruceFence = alphaMaterials[188, 0] alphaMaterials.BirchFence = alphaMaterials[189, 0] alphaMaterials.JungleFence = alphaMaterials[190, 0] alphaMaterials.DarkOakFence = alphaMaterials[191, 0] alphaMaterials.AcaciaFence = alphaMaterials[192, 0] alphaMaterials.SpruceDoor = alphaMaterials[193, 0] alphaMaterials.BirchDoor = alphaMaterials[194, 0] alphaMaterials.JungleDoor = alphaMaterials[195, 0] alphaMaterials.AcaciaDoor = alphaMaterials[196, 0] alphaMaterials.DarkOakDoor = alphaMaterials[197, 0] alphaMaterials.EndRod = alphaMaterials[198, 0] alphaMaterials.ChorusPlant = alphaMaterials[199, 0] alphaMaterials.ChorusFlowerAlive = alphaMaterials[200, 0] alphaMaterials.ChorusFlowerDead = alphaMaterials[200, 5] alphaMaterials.Purpur = alphaMaterials[201, 0] alphaMaterials.PurpurPillar = alphaMaterials[202, 0] alphaMaterials.PurpurStairs = alphaMaterials[203, 0] alphaMaterials.PurpurSlab = alphaMaterials[205, 0] alphaMaterials.EndStone = alphaMaterials[206, 0] alphaMaterials.BeetRoot = alphaMaterials[207, 0] alphaMaterials.GrassPath = alphaMaterials[208, 0] alphaMaterials.EndGateway = alphaMaterials[209, 0] alphaMaterials.CommandBlockRepeating = alphaMaterials[210, 0] alphaMaterials.CommandBlockChain = alphaMaterials[211, 0] alphaMaterials.FrostedIce = alphaMaterials[212, 0] alphaMaterials.StructureVoid = alphaMaterials[217, 0] alphaMaterials.StructureBlock = alphaMaterials[255, 0] build_api_material_map(alphaMaterials) # --- Classic static block defs --- def build_classic_materials(): log.info("Building Classic materials.") classicMaterials.Stone = classicMaterials[1] classicMaterials.Grass = classicMaterials[2] classicMaterials.Dirt = classicMaterials[3] classicMaterials.Cobblestone = classicMaterials[4] classicMaterials.WoodPlanks = classicMaterials[5] classicMaterials.Sapling = classicMaterials[6] classicMaterials.Bedrock = classicMaterials[7] classicMaterials.WaterActive = classicMaterials[8] classicMaterials.Water = classicMaterials[9] classicMaterials.LavaActive = classicMaterials[10] classicMaterials.Lava = classicMaterials[11] classicMaterials.Sand = classicMaterials[12] classicMaterials.Gravel = classicMaterials[13] classicMaterials.GoldOre = classicMaterials[14] classicMaterials.IronOre = classicMaterials[15] classicMaterials.CoalOre = classicMaterials[16] classicMaterials.Wood = classicMaterials[17] classicMaterials.Leaves = classicMaterials[18] classicMaterials.Sponge = classicMaterials[19] classicMaterials.Glass = classicMaterials[20] classicMaterials.RedWool = classicMaterials[21] classicMaterials.OrangeWool = classicMaterials[22] classicMaterials.YellowWool = classicMaterials[23] classicMaterials.LimeWool = classicMaterials[24] classicMaterials.GreenWool = classicMaterials[25] classicMaterials.AquaWool = classicMaterials[26] classicMaterials.CyanWool = classicMaterials[27] classicMaterials.BlueWool = classicMaterials[28] classicMaterials.PurpleWool = classicMaterials[29] classicMaterials.IndigoWool = classicMaterials[30] classicMaterials.VioletWool = classicMaterials[31] classicMaterials.MagentaWool = classicMaterials[32] classicMaterials.PinkWool = classicMaterials[33] classicMaterials.BlackWool = classicMaterials[34] classicMaterials.GrayWool = classicMaterials[35] classicMaterials.WhiteWool = classicMaterials[36] classicMaterials.Flower = classicMaterials[37] classicMaterials.Rose = classicMaterials[38] classicMaterials.BrownMushroom = classicMaterials[39] classicMaterials.RedMushroom = classicMaterials[40] classicMaterials.BlockofGold = classicMaterials[41] classicMaterials.BlockofIron = classicMaterials[42] classicMaterials.DoubleStoneSlab = classicMaterials[43] classicMaterials.StoneSlab = classicMaterials[44] classicMaterials.Brick = classicMaterials[45] classicMaterials.TNT = classicMaterials[46] classicMaterials.Bookshelf = classicMaterials[47] classicMaterials.MossStone = classicMaterials[48] classicMaterials.Obsidian = classicMaterials[49] build_api_material_map(classicMaterials) # --- Indev static block defs --- def build_indev_materials(): log.info("Building Indev materials.") indevMaterials.Stone = indevMaterials[1] indevMaterials.Grass = indevMaterials[2] indevMaterials.Dirt = indevMaterials[3] indevMaterials.Cobblestone = indevMaterials[4] indevMaterials.WoodPlanks = indevMaterials[5] indevMaterials.Sapling = indevMaterials[6] indevMaterials.Bedrock = indevMaterials[7] indevMaterials.WaterActive = indevMaterials[8] indevMaterials.Water = indevMaterials[9] indevMaterials.LavaActive = indevMaterials[10] indevMaterials.Lava = indevMaterials[11] indevMaterials.Sand = indevMaterials[12] indevMaterials.Gravel = indevMaterials[13] indevMaterials.GoldOre = indevMaterials[14] indevMaterials.IronOre = indevMaterials[15] indevMaterials.CoalOre = indevMaterials[16] indevMaterials.Wood = indevMaterials[17] indevMaterials.Leaves = indevMaterials[18] indevMaterials.Sponge = indevMaterials[19] indevMaterials.Glass = indevMaterials[20] indevMaterials.RedWool = indevMaterials[21] indevMaterials.OrangeWool = indevMaterials[22] indevMaterials.YellowWool = indevMaterials[23] indevMaterials.LimeWool = indevMaterials[24] indevMaterials.GreenWool = indevMaterials[25] indevMaterials.AquaWool = indevMaterials[26] indevMaterials.CyanWool = indevMaterials[27] indevMaterials.BlueWool = indevMaterials[28] indevMaterials.PurpleWool = indevMaterials[29] indevMaterials.IndigoWool = indevMaterials[30] indevMaterials.VioletWool = indevMaterials[31] indevMaterials.MagentaWool = indevMaterials[32] indevMaterials.PinkWool = indevMaterials[33] indevMaterials.BlackWool = indevMaterials[34] indevMaterials.GrayWool = indevMaterials[35] indevMaterials.WhiteWool = indevMaterials[36] indevMaterials.Flower = indevMaterials[37] indevMaterials.Rose = indevMaterials[38] indevMaterials.BrownMushroom = indevMaterials[39] indevMaterials.RedMushroom = indevMaterials[40] indevMaterials.BlockofGold = indevMaterials[41] indevMaterials.BlockofIron = indevMaterials[42] indevMaterials.DoubleStoneSlab = indevMaterials[43] indevMaterials.StoneSlab = indevMaterials[44] indevMaterials.Brick = indevMaterials[45] indevMaterials.TNT = indevMaterials[46] indevMaterials.Bookshelf = indevMaterials[47] indevMaterials.MossStone = indevMaterials[48] indevMaterials.Obsidian = indevMaterials[49] indevMaterials.Torch = indevMaterials[50, 0] indevMaterials.Fire = indevMaterials[51, 0] indevMaterials.InfiniteWater = indevMaterials[52, 0] indevMaterials.InfiniteLava = indevMaterials[53, 0] indevMaterials.Chest = indevMaterials[54, 0] indevMaterials.Cog = indevMaterials[55, 0] indevMaterials.DiamondOre = indevMaterials[56, 0] indevMaterials.BlockofDiamond = indevMaterials[57, 0] indevMaterials.CraftingTable = indevMaterials[58, 0] indevMaterials.Crops = indevMaterials[59, 0] indevMaterials.Farmland = indevMaterials[60, 0] indevMaterials.Furnace = indevMaterials[61, 0] indevMaterials.LitFurnace = indevMaterials[62, 0] build_api_material_map(indevMaterials) # --- Pocket static block defs --- def build_pocket_materials(): log.info("Building Pocket materials.") pocketMaterials.Air = pocketMaterials[0, 0] pocketMaterials.Stone = pocketMaterials[1, 0] pocketMaterials.Grass = pocketMaterials[2, 0] pocketMaterials.Dirt = pocketMaterials[3, 0] pocketMaterials.Cobblestone = pocketMaterials[4, 0] pocketMaterials.WoodPlanks = pocketMaterials[5, 0] pocketMaterials.Sapling = pocketMaterials[6, 0] pocketMaterials.SpruceSapling = pocketMaterials[6, 1] pocketMaterials.BirchSapling = pocketMaterials[6, 2] pocketMaterials.Bedrock = pocketMaterials[7, 0] pocketMaterials.Wateractive = pocketMaterials[8, 0] pocketMaterials.Water = pocketMaterials[9, 0] pocketMaterials.Lavaactive = pocketMaterials[10, 0] pocketMaterials.Lava = pocketMaterials[11, 0] pocketMaterials.Sand = pocketMaterials[12, 0] pocketMaterials.Gravel = pocketMaterials[13, 0] pocketMaterials.GoldOre = pocketMaterials[14, 0] pocketMaterials.IronOre = pocketMaterials[15, 0] pocketMaterials.CoalOre = pocketMaterials[16, 0] pocketMaterials.Wood = pocketMaterials[17, 0] pocketMaterials.PineWood = pocketMaterials[17, 1] pocketMaterials.BirchWood = pocketMaterials[17, 2] pocketMaterials.JungleWood = pocketMaterials[17, 3] pocketMaterials.Leaves = pocketMaterials[18, 0] pocketMaterials.PineLeaves = pocketMaterials[18, 1] pocketMaterials.BirchLeaves = pocketMaterials[18, 2] pocketMaterials.JungleLeaves = pocketMaterials[18, 3] pocketMaterials.Sponge = pocketMaterials[19, 0] pocketMaterials.Glass = pocketMaterials[20, 0] pocketMaterials.LapisLazuliOre = pocketMaterials[21, 0] pocketMaterials.LapisLazuliBlock = pocketMaterials[22, 0] pocketMaterials.Sandstone = pocketMaterials[24, 0] pocketMaterials.NoteBlock = pocketMaterials[25, 0] pocketMaterials.Bed = pocketMaterials[26, 0] pocketMaterials.PoweredRail = pocketMaterials[27, 0] pocketMaterials.DetectorRail = pocketMaterials[28, 0] pocketMaterials.Web = pocketMaterials[30, 0] pocketMaterials.UnusedShrub = pocketMaterials[31, 0] pocketMaterials.TallGrass = pocketMaterials[31, 1] pocketMaterials.Shrub = pocketMaterials[31, 2] pocketMaterials.WhiteWool = pocketMaterials[35, 0] pocketMaterials.OrangeWool = pocketMaterials[35, 1] pocketMaterials.MagentaWool = pocketMaterials[35, 2] pocketMaterials.LightBlueWool = pocketMaterials[35, 3] pocketMaterials.YellowWool = pocketMaterials[35, 4] pocketMaterials.LightGreenWool = pocketMaterials[35, 5] pocketMaterials.PinkWool = pocketMaterials[35, 6] pocketMaterials.GrayWool = pocketMaterials[35, 7] pocketMaterials.LightGrayWool = pocketMaterials[35, 8] pocketMaterials.CyanWool = pocketMaterials[35, 9] pocketMaterials.PurpleWool = pocketMaterials[35, 10] pocketMaterials.BlueWool = pocketMaterials[35, 11] pocketMaterials.BrownWool = pocketMaterials[35, 12] pocketMaterials.DarkGreenWool = pocketMaterials[35, 13] pocketMaterials.RedWool = pocketMaterials[35, 14] pocketMaterials.BlackWool = pocketMaterials[35, 15] pocketMaterials.Flower = pocketMaterials[37, 0] pocketMaterials.Rose = pocketMaterials[38, 0] pocketMaterials.BrownMushroom = pocketMaterials[39, 0] pocketMaterials.RedMushroom = pocketMaterials[40, 0] pocketMaterials.BlockofGold = pocketMaterials[41, 0] pocketMaterials.BlockofIron = pocketMaterials[42, 0] pocketMaterials.DoubleStoneSlab = pocketMaterials[43, 0] pocketMaterials.DoubleSandstoneSlab = pocketMaterials[43, 1] pocketMaterials.DoubleWoodenSlab = pocketMaterials[43, 2] pocketMaterials.DoubleCobblestoneSlab = pocketMaterials[43, 3] pocketMaterials.DoubleBrickSlab = pocketMaterials[43, 4] pocketMaterials.StoneSlab = pocketMaterials[44, 0] pocketMaterials.SandstoneSlab = pocketMaterials[44, 1] pocketMaterials.WoodenSlab = pocketMaterials[44, 2] pocketMaterials.CobblestoneSlab = pocketMaterials[44, 3] pocketMaterials.BrickSlab = pocketMaterials[44, 4] pocketMaterials.Brick = pocketMaterials[45, 0] pocketMaterials.TNT = pocketMaterials[46, 0] pocketMaterials.Bookshelf = pocketMaterials[47, 0] pocketMaterials.MossStone = pocketMaterials[48, 0] pocketMaterials.Obsidian = pocketMaterials[49, 0] pocketMaterials.Torch = pocketMaterials[50, 0] pocketMaterials.Fire = pocketMaterials[51, 0] pocketMaterials.MonsterSpawner = pocketMaterials[52, 0] pocketMaterials.WoodenStairs = pocketMaterials[53, 0] pocketMaterials.Chest = pocketMaterials[54, 0] pocketMaterials.RedstoneWire = pocketMaterials[55, 0] pocketMaterials.DiamondOre = pocketMaterials[56, 0] pocketMaterials.BlockofDiamond = pocketMaterials[57, 0] pocketMaterials.CraftingTable = pocketMaterials[58, 0] pocketMaterials.Crops = pocketMaterials[59, 0] pocketMaterials.Farmland = pocketMaterials[60, 0] pocketMaterials.Furnace = pocketMaterials[61, 0] pocketMaterials.LitFurnace = pocketMaterials[62, 0] pocketMaterials.Sign = pocketMaterials[63, 0] pocketMaterials.WoodenDoor = pocketMaterials[64, 0] pocketMaterials.Ladder = pocketMaterials[65, 0] pocketMaterials.Rail = pocketMaterials[66, 0] pocketMaterials.StoneStairs = pocketMaterials[67, 0] pocketMaterials.WallSign = pocketMaterials[68, 0] pocketMaterials.Lever = pocketMaterials[69, 0] pocketMaterials.StoneFloorPlate = pocketMaterials[70, 0] pocketMaterials.IronDoor = pocketMaterials[71, 0] pocketMaterials.WoodFloorPlate = pocketMaterials[72, 0] pocketMaterials.RedstoneOre = pocketMaterials[73, 0] pocketMaterials.RedstoneOreGlowing = pocketMaterials[74, 0] pocketMaterials.RedstoneTorchOff = pocketMaterials[75, 0] pocketMaterials.RedstoneTorchOn = pocketMaterials[76, 0] pocketMaterials.Button = pocketMaterials[77, 0] pocketMaterials.SnowLayer = pocketMaterials[78, 0] pocketMaterials.Ice = pocketMaterials[79, 0] pocketMaterials.Snow = pocketMaterials[80, 0] pocketMaterials.Cactus = pocketMaterials[81, 0] pocketMaterials.Clay = pocketMaterials[82, 0] pocketMaterials.SugarCane = pocketMaterials[83, 0] pocketMaterials.Fence = pocketMaterials[85, 0] pocketMaterials.Pumpkin = pocketMaterials[86, 0] pocketMaterials.Netherrack = pocketMaterials[87, 0] pocketMaterials.SoulSand = pocketMaterials[88, 0] pocketMaterials.Glowstone = pocketMaterials[89, 0] pocketMaterials.NetherPortal = pocketMaterials[90, 0] pocketMaterials.JackOLantern = pocketMaterials[91, 0] pocketMaterials.Cake = pocketMaterials[92, 0] pocketMaterials.InvisibleBedrock = pocketMaterials[95, 0] pocketMaterials.Trapdoor = pocketMaterials[96, 0] pocketMaterials.MonsterEgg = pocketMaterials[97, 0] pocketMaterials.StoneBricks = pocketMaterials[98, 0] pocketMaterials.BrownMushroom = pocketMaterials[99, 0] pocketMaterials.RedMushroom = pocketMaterials[100, 0] pocketMaterials.IronBars = pocketMaterials[101, 0] pocketMaterials.GlassPane = pocketMaterials[102, 0] pocketMaterials.Watermelon = pocketMaterials[103, 0] pocketMaterials.PumpkinStem = pocketMaterials[104, 0] pocketMaterials.MelonStem = pocketMaterials[105, 0] pocketMaterials.Vines = pocketMaterials[106, 0] pocketMaterials.FenceGate = pocketMaterials[107, 0] pocketMaterials.BrickStairs = pocketMaterials[108, 0] pocketMaterials.StoneBrickStairs = pocketMaterials[109, 0] pocketMaterials.Mycelium = pocketMaterials[110, 0] pocketMaterials.Lilypad = pocketMaterials[111, 0] pocketMaterials.NetherBrick = pocketMaterials[112, 0] pocketMaterials.NetherBrickFence = pocketMaterials[113, 0] pocketMaterials.NetherBrickStairs = pocketMaterials[114, 0] pocketMaterials.NetherWart = pocketMaterials[115, 0] pocketMaterials.EnchantmentTable = pocketMaterials[116, 0] pocketMaterials.BrewingStand = pocketMaterials[117, 0] pocketMaterials.EndPortalFrame = pocketMaterials[120, 0] pocketMaterials.EndStone = pocketMaterials[121, 0] pocketMaterials.RedstoneLampoff = pocketMaterials[122, 0] pocketMaterials.RedstoneLampon = pocketMaterials[123, 0] pocketMaterials.ActivatorRail = pocketMaterials[126, 0] pocketMaterials.Cocoa = pocketMaterials[127, 0] pocketMaterials.SandstoneStairs = pocketMaterials[128, 0] pocketMaterials.EmeraldOre = pocketMaterials[129, 0] pocketMaterials.TripwireHook = pocketMaterials[131, 0] pocketMaterials.Tripwire = pocketMaterials[132, 0] pocketMaterials.BlockOfEmerald = pocketMaterials[133, 0] pocketMaterials.SpruceWoodStairs = pocketMaterials[134, 0] pocketMaterials.BirchWoodStairs = pocketMaterials[135, 0] pocketMaterials.JungleWoodStairs = pocketMaterials[136, 0] pocketMaterials.CommandBlock = pocketMaterials[137, 0] pocketMaterials.CobblestoneWall = pocketMaterials[139, 0] pocketMaterials.FlowerPot = pocketMaterials[140, 0] pocketMaterials.Carrots = pocketMaterials[141, 0] pocketMaterials.Potato = pocketMaterials[142, 0] pocketMaterials.WoodenButton = pocketMaterials[143, 0] pocketMaterials.MobHead = pocketMaterials[144, 0] pocketMaterials.Anvil = pocketMaterials[145, 0] pocketMaterials.TrappedChest = pocketMaterials[146, 0] pocketMaterials.WeightedPressurePlateLight = pocketMaterials[147, 0] pocketMaterials.WeightedPressurePlateHeavy = pocketMaterials[148, 0] pocketMaterials.DaylightSensor = pocketMaterials[151, 0] pocketMaterials.BlockOfRedstone = pocketMaterials[152, 0] pocketMaterials.NetherQuartzOre = pocketMaterials[153, 0] pocketMaterials.BlockOfQuartz = pocketMaterials[155, 0] pocketMaterials.DoubleWoodenSlab = pocketMaterials[157, 0] pocketMaterials.WoodenSlab = pocketMaterials[158, 0] pocketMaterials.StainedClay = pocketMaterials[159, 0] pocketMaterials.AcaciaLeaves = pocketMaterials[161, 0] pocketMaterials.AcaciaWood = pocketMaterials[162, 0] pocketMaterials.AcaciaWoodStairs = pocketMaterials[163, 0] pocketMaterials.DarkOakWoodStairs = pocketMaterials[164, 0] pocketMaterials.IronTrapdoor = pocketMaterials[167, 0] pocketMaterials.HayBale = pocketMaterials[170, 0] pocketMaterials.Carpet = pocketMaterials[171, 0] pocketMaterials.HardenedClay = pocketMaterials[172, 0] pocketMaterials.BlockOfCoal = pocketMaterials[173, 0] pocketMaterials.PackedIce = pocketMaterials[174, 0] # Is 'Sunflower' used? pocketMaterials.Sunflower = pocketMaterials[175, 0] pocketMaterials.TallFlowers = pocketMaterials[175, 0] pocketMaterials.DaylightSensorOn = pocketMaterials[178, 0] pocketMaterials.SpruceFenceGate = pocketMaterials[183, 0] pocketMaterials.BirchFenceGate = pocketMaterials[184, 0] pocketMaterials.JungleFenceGate = pocketMaterials[185, 0] pocketMaterials.DarkOakFenceGate = pocketMaterials[186, 0] pocketMaterials.AcaciaFenceGate = pocketMaterials[187, 0] pocketMaterials.CommandBlockRepeating = pocketMaterials[188, 0] pocketMaterials.CommandBlockChain = pocketMaterials[189, 0] pocketMaterials.GrassPath = pocketMaterials[198, 0] pocketMaterials.ItemFrame = pocketMaterials[199, 0] pocketMaterials.Podzol = pocketMaterials[243, 0] pocketMaterials.Beetroot = pocketMaterials[244, 0] pocketMaterials.StoneCutter = pocketMaterials[245, 0] pocketMaterials.GlowingObsidian = pocketMaterials[246, 0] pocketMaterials.NetherReactor = pocketMaterials[247, 0] pocketMaterials.NetherReactorUsed = pocketMaterials[247, 1] pocketMaterials.UpdateGameBlock1 = pocketMaterials[248, 0] pocketMaterials.UpdateGameBlock2 = pocketMaterials[249, 0] pocketMaterials.StructureBlock = pocketMaterials[252, 0] pocketMaterials.info_reserved6 = pocketMaterials[255, 0] build_api_material_map(pocketMaterials) def printStaticDefs(name, file_name=None): # printStaticDefs('alphaMaterials') # file_name: file to write the output to mats = eval(name) msg = "MCEdit static definitions for '%s'\n\n"%name mats_ids = [] for b in sorted(mats.allBlocks): msg += "{name}.{0} = {name}[{1},{2}]\n".format( b.name.replace(" ", "").replace("(", "").replace(")", ""), b.ID, b.blockData, name=name, ) if b.ID not in mats_ids: mats_ids.append(b.ID) print msg if file_name: msg += "\nNumber of materials: %s\n%s" % (len(mats_ids), mats_ids) id_min = min(mats_ids) id_max = max(mats_ids) msg += "\n\nLowest ID: %s\nHighest ID: %s\n" % (id_min, id_max) missing_ids = [] for i in xrange(id_min, id_max + 1): if i not in mats_ids: missing_ids.append(i) if missing_ids: msg += "\nIDs not in the list:\n%s\n(%s IDs)\n" % (missing_ids, len(missing_ids)) open(file_name, 'w').write(msg) print "Written to '%s'" % file_name _indices = rollaxis(indices((id_limit, 16)), 0, 3) def _filterTable(filters, unavailable, default=(0, 0)): # a filter table is a id_limit table of (ID, data) pairs. table = zeros((id_limit, 16, 2), dtype='uint8') table[:] = _indices for u in unavailable: try: if u[1] == 0: u = u[0] except TypeError: pass table[u] = default for f, t in filters: try: if f[1] == 0: f = f[0] except TypeError: pass table[f] = t return table nullConversion = lambda b, d: (b, d) def filterConversion(table): def convert(blocks, data): if data is None: data = 0 t = table[blocks, data] return t[..., 0], t[..., 1] return convert def guessFilterTable(matsFrom, matsTo): """ Returns a pair (filters, unavailable) filters is a list of (from, to) pairs; from and to are (ID, data) pairs unavailable is a list of (ID, data) pairs in matsFrom not found in matsTo. Searches the 'name' and 'aka' fields to find matches. """ filters = [] unavailable = [] toByName = dict(((b.name, b) for b in sorted(matsTo.allBlocks, reverse=True))) for fromBlock in matsFrom.allBlocks: block = toByName.get(fromBlock.name) if block is None: for b in matsTo.allBlocks: if b.name.startswith(fromBlock.name): block = b break if block is None: for b in matsTo.allBlocks: if fromBlock.name in b.name: block = b break if block is None: for b in matsTo.allBlocks: if fromBlock.name in b.aka or fromBlock.name in b.search: block = b break if block is None: if "Indigo Wool" == fromBlock.name: block = toByName.get("Purple Wool") elif "Violet Wool" == fromBlock.name: block = toByName.get("Purple Wool") if block: if block != fromBlock: filters.append(((fromBlock.ID, fromBlock.blockData), (block.ID, block.blockData))) else: unavailable.append((fromBlock.ID, fromBlock.blockData)) return filters, unavailable allMaterials = (alphaMaterials, classicMaterials, pocketMaterials, indevMaterials) _conversionFuncs = {} def conversionFunc(destMats, sourceMats): if destMats is sourceMats: return nullConversion func = _conversionFuncs.get((destMats, sourceMats)) if func: return func filters, unavailable = guessFilterTable(sourceMats, destMats) log.debug("") log.debug("%s %s %s", sourceMats.name, "=>", destMats.name) for a, b in [(sourceMats.blockWithID(*a), destMats.blockWithID(*b)) for a, b in filters]: log.debug("{0:20}: \"{1}\"".format('"' + a.name + '"', b.name)) log.debug("") log.debug("Missing blocks: %s", [sourceMats.blockWithID(*a).name for a in unavailable]) table = _filterTable(filters, unavailable, (35, 0)) func = filterConversion(table) _conversionFuncs[(destMats, sourceMats)] = func return func def convertBlocks(destMats, sourceMats, blocks, blockData): if sourceMats == destMats: return blocks, blockData return conversionFunc(destMats, sourceMats)(blocks, blockData) namedMaterials = dict((i.name, i) for i in allMaterials) def build_api_material_map(mats=alphaMaterials): _mats = BlockstateAPI.material_map.get(mats) if not _mats: raise RuntimeError("BlockstateAPI.material_map[%s] not ready."%mats) global block_map block_map = _mats.block_map blockstates = _mats.blockstates global idToBlockState idToBlockstate = _mats.idToBlockstate global blockstateToID blockstateToID = _mats.blockstateToID global stringifyBlockstate stringifyBlockstate = _mats.stringifyBlockstate global deStringifyBlockstate deStringifyBlockstate = _mats.deStringifyBlockstate for mat in allMaterials: if mat not in BlockstateAPI.material_map: continue for block in mat.allBlocks: if block == mat.Air: continue setattr(block, "Blockstate", BlockstateAPI.material_map[mat].idToBlockstate(block.ID, block.blockData)) # alphaMaterials has to be 'preloaded' for now... alphaMaterials.addJSONBlocksFromVersion('Unknown','Unknown') __all__ = "indevMaterials, pocketMaterials, alphaMaterials, classicMaterials, namedMaterials, MCMaterials, BlockstateAPI".split(", ") if '--dump-mats' in os.sys.argv: os.sys.argv.remove('--dump-mats') alphaMaterials.addJSONBlocksFromFile("minecraft.json") alphaMaterials.setup_blockstates("pc_blockstates.json") classicMaterials.addJSONBlocksFromFile("classic.json") indevMaterials.addJSONBlocksFromFile("indev.json") pocketMaterials.addJSONBlocksFromFile("pocket.json") pocketMaterials.setup_blockstates("pe_blockstates.json") for n in ("indevMaterials", "pocketMaterials", "alphaMaterials", "classicMaterials"): printStaticDefs(n, "%s.mats" % n.split('M')[0]) if '--find-blockstates' in os.sys.argv: alphaMaterials.addJSONBlocksFromFile("minecraft.json") alphaMaterials.setup_blockstates("pc_blockstates.json") pocketMaterials.addJSONBlocksFromFile("pocket.json") pocketMaterials.setup_blockstates("pe_blockstates.json") pe_blockstates = {'minecraft': {}} passed = [] failed = [] for block in pocketMaterials: ID = block.ID DATA = block.blockData pc_block = alphaMaterials.get((ID, DATA)) if pc_block and pc_block.stringID == block.stringID: passed.append(block) else: failed.append(block) print '{} failed block check'.format(len(failed)) for block in failed: print '!{}!'.format(block) for block in passed: if block.stringID not in pe_blockstates["minecraft"]: pe_blockstates["minecraft"][block.stringID] = {} pe_blockstates["minecraft"][block.stringID]["id"] = block.ID pe_blockstates["minecraft"][block.stringID]["properties"] = [] blockstate = idToBlockstate(block.ID, block.blockData) state = {"<data>": block.blockData} for (key, value) in blockstate[1].iteritems(): state[key] = value pe_blockstates["minecraft"][block.stringID]['properties'].append(state)
59,779
41.976276
133
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/mclevel.py
# -*- coding: utf-8 -*- """ MCLevel interfaces Sample usage: import mclevel # Call mclevel.fromFile to identify and open any of these four file formats: # # Classic levels - gzipped serialized java objects. Returns an instance of MCJavalevel # Indev levels - gzipped NBT data in a single file. Returns an MCIndevLevel # Schematics - gzipped NBT data in a single file. Returns an MCSchematic. # MCSchematics have the special method rotateLeft which will reorient torches, stairs, and other tiles appropriately. # Alpha levels - world folder structure containing level.dat and chunk folders. Single or Multiplayer. # Can accept a path to the world folder or a path to the level.dat. Returns an MCInfdevOldLevel # Load a Classic level. level = mclevel.fromFile("server_level.dat"); # fromFile identified the file type and returned a MCJavaLevel. MCJavaLevel doesn't actually know any java. It guessed the # location of the Blocks array by starting at the end of the file and moving backwards until it only finds valid blocks. # It also doesn't know the dimensions of the level. This is why you have to tell them to MCEdit via the filename. # This works here too: If the file were 512 wide, 512 long, and 128 high, I'd have to name it "server_level_512_512_128.dat" # # This is one area for improvement. # Classic and Indev levels have all of their blocks in one place. blocks = level.Blocks # Sand to glass. blocks[blocks == level.materials.Sand.ID] = level.materials.Glass.ID # Save the file with another name. This only works for non-Alpha levels. level.saveToFile("server_level_glassy.dat"); # Load an Alpha world # Loading an Alpha world immediately scans the folder for chunk files. This takes longer for large worlds. ourworld = mclevel.fromFile("C:\\Minecraft\\OurWorld"); # Convenience method to load a numbered world from the saves folder. world1 = mclevel.loadWorldNumber(1); # Find out which chunks are present. Doing this will scan the chunk folders the # first time it is used. If you already know where you want to be, skip to # world1.getChunk(xPos, zPos) chunkPositions = list(world1.allChunks) # allChunks returns an iterator that yields a (xPos, zPos) tuple for each chunk xPos, zPos = chunkPositions[0]; # retrieve an AnvilChunk object. this object will load and decompress # the chunk as needed, and remember whether it needs to be saved or relighted chunk = world1.getChunk(xPos, zPos) ### Access the data arrays of the chunk like so: # Take note that the array is indexed x, z, y. The last index corresponds to # height or altitude. blockType = chunk.Blocks[0,0,64] chunk.Blocks[0,0,64] = 1 # Access the chunk's Entities and TileEntities as arrays of TAG_Compound as # they appear in the save format. # Entities usually have Pos, Health, and id # TileEntities usually have tileX, tileY, tileZ, and id # For more information, google "Chunk File Format" for entity in chunk.Entities: if entity["id"].value == "Spider": entity["Health"].value = 50 # Accessing one byte at a time from the Blocks array is very slow in Python. # To get around this, we have methods to access multiple bytes at once. # The first technique is slicing. You can use slicing to restrict your access # to certain depth levels, or to extract a column or a larger section from the # array. Standard python slice notation is used. # Set the top half of the array to 0. The : says to use the entire array along # that dimension. The syntax []= indicates we are overwriting part of the array chunk.Blocks[:,:,64:] = 0 # Using [] without = creates a 'view' on part of the array. This is not a # copy, it is a reference to a portion of the original array. midBlocks = chunk.Blocks[:,:,32:64] # Here's a gotcha: You can't just write 'midBlocks = 0' since it will replace # the 'midBlocks' reference itself instead of accessing the array. Instead, do # this to access and overwrite the array using []= syntax. midBlocks[:] = 0 # The second is masking. Using a comparison operator ( <, >, ==, etc ) # against the Blocks array will return a 'mask' that we can use to specify # positions in the array. # Create the mask from the result of the equality test. fireBlocks = ( chunk.Blocks==world.materials.Fire.ID ) # Access Blocks using the mask to set elements. The syntax is the same as # using []= with slices chunk.Blocks[fireBlocks] = world.materials.Leaves.ID # You can also combine mask arrays using logical operations (&, |, ^) and use # the mask to access any other array of the same shape. # Here we turn all trees into birch trees. # Extract a mask from the Blocks array to find the locations of tree trunks. # Or | it with another mask to find the locations of leaves. # Use the combined mask to access the Data array and set those locations to birch # Note that the Data, BlockLight, and SkyLight arrays have been # unpacked from 4-bit arrays to numpy uint8 arrays. This makes them much easier # to work with. treeBlocks = ( chunk.Blocks == world.materials.Wood.ID ) treeBlocks |= ( chunk.Blocks == world.materials.Leaves.ID ) chunk.Data[treeBlocks] = 2 # birch # The chunk doesn't know you've changed any of that data. Call chunkChanged() # to let it know. This will mark the chunk for lighting calculation, # recompression, and writing to disk. It will also immediately recalculate the # chunk's HeightMap and fill the SkyLight only with light falling straight down. # These are relatively fast and were added here to aid MCEdit. chunk.chunkChanged(); # To recalculate all of the dirty lights in the world, call generateLights world.generateLights(); # Move the player and his spawn world.setPlayerPosition( (0, 67, 0) ) # add 3 to make sure his head isn't in the ground. world.setPlayerSpawnPosition( (0, 64, 0) ) # Save the level.dat and any chunks that have been marked for writing to disk # This also compresses any chunks marked for recompression. world.saveInPlace(); # Advanced use: # The getChunkSlices method returns an iterator that returns slices of chunks within the specified range. # the slices are returned as tuples of (chunk, slices, point) # chunk: The AnvilChunk object we're interested in. # slices: A 3-tuple of slice objects that can be used to index chunk's data arrays # point: A 3-tuple of floats representing the relative position of this subslice within the larger slice. # # Take caution: # the point tuple is ordered (x,y,z) in accordance with the tuples used to initialize a bounding box # however, the slices tuple is ordered (x,z,y) for easy indexing into the arrays. # Here is an old version of MCInfdevOldLevel.fillBlocks in its entirety: def fillBlocks(self, box, blockType, blockData = 0): chunkIterator = self.getChunkSlices(box) for (chunk, slices, point) in chunkIterator: chunk.Blocks[slices] = blockType chunk.Data[slices] = blockData chunk.chunkChanged(); Copyright 2010 David Rio Vierra """ from indev import MCIndevLevel from infiniteworld import MCInfdevOldLevel from javalevel import MCJavaLevel from logging import getLogger import logging from directories import minecraftSaveFileDir import nbt from numpy import fromstring import os from pocket import PocketWorld from leveldbpocket import PocketLeveldbWorld from pymclevel import leveldbpocket from schematic import INVEditChest, MCSchematic, ZipSchematic import sys import traceback log = getLogger(__name__) class LoadingError(RuntimeError): pass def fromFile(filename, loadInfinite=True, readonly=False): ''' The preferred method for loading Minecraft levels of any type. pass False to loadInfinite if you'd rather not load infdev levels. ''' log.info(u"Identifying " + filename) if not filename: raise IOError("File not found: " + filename) if not os.path.exists(filename): raise IOError("File not found: " + filename) if ZipSchematic._isLevel(filename): log.info("Zipfile found, attempting zipped infinite level") lev = ZipSchematic(filename) log.info("Detected zipped Infdev level") return lev if PocketWorld._isLevel(filename): return PocketWorld(filename) if MCInfdevOldLevel._isLevel(filename): log.info(u"Detected Infdev level.dat") if loadInfinite: return MCInfdevOldLevel(filename=filename, readonly=readonly) else: raise ValueError("Asked to load {0} which is an infinite level, loadInfinite was False".format( os.path.basename(filename))) if PocketLeveldbWorld._isLevel(filename): if leveldbpocket.leveldb_available: return PocketLeveldbWorld(filename) else: logging.exception("Pocket support has failed") if os.path.isdir(filename): logging.exception("World load failed, trying to open a directory instead of a file") f = file(filename, 'rb') rawdata = f.read() f.close() if len(rawdata) < 4: raise ValueError("{0} is too small! ({1}) ".format(filename, len(rawdata))) data = fromstring(rawdata, dtype='uint8') if not data.any(): raise ValueError("{0} contains only zeroes. This file is damaged beyond repair.") if MCJavaLevel._isDataLevel(data): log.info(u"Detected Java-style level") lev = MCJavaLevel(filename, data) lev.compressed = False return lev # ungzdata = None compressed = True unzippedData = None try: unzippedData = nbt.gunzip(rawdata) except Exception as e: log.info(u"Exception during Gzip operation, assuming {0} uncompressed: {1!r}".format(filename, e)) if unzippedData is None: compressed = False unzippedData = rawdata #data = data = unzippedData if MCJavaLevel._isDataLevel(data): log.info(u"Detected compressed Java-style level") lev = MCJavaLevel(filename, data) lev.compressed = compressed return lev try: root_tag = nbt.load(buf=data) except Exception as e: log.info(u"Error during NBT load: {0!r}".format(e)) log.info(traceback.format_exc()) log.info(u"Fallback: Detected compressed flat block array, yzx ordered ") try: lev = MCJavaLevel(filename, data) lev.compressed = compressed return lev except Exception as e2: raise LoadingError(("Multiple errors encountered", e, e2), sys.exc_info()[2]) else: if MCIndevLevel._isTagLevel(root_tag): log.info(u"Detected Indev .mclevel") return MCIndevLevel(root_tag, filename) if MCSchematic._isTagLevel(root_tag): log.info(u"Detected Schematic.") return MCSchematic(filename=filename) if INVEditChest._isTagLevel(root_tag): log.info(u"Detected INVEdit inventory file") return INVEditChest(root_tag=root_tag, filename=filename) raise IOError("Cannot detect file type.") def loadWorld(name): filename = os.path.join(minecraftSaveFileDir, name) return fromFile(filename) def loadWorldNumber(i): # deprecated filename = u"{0}{1}{2}{3}{1}".format(minecraftSaveFileDir, os.sep, u"World", i) return fromFile(filename)
11,260
35.800654
125
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/block_fill.py
import logging import materials log = logging.getLogger(__name__) import numpy from mclevelbase import exhaust import blockrotation from box import BoundingBox from entity import TileEntity def blockReplaceTable(blocksToReplace): blocktable = numpy.zeros((materials.id_limit, 16), dtype='bool') for b in blocksToReplace: blocktable[b.ID, b.blockData] = True return blocktable def fillBlocks(level, box, blockInfo, blocksToReplace=(), noData=False): return exhaust(level.fillBlocksIter(box, blockInfo, blocksToReplace, noData=noData)) def fillBlocksIter(level, box, blockInfo, blocksToReplace=(), noData=False): if box is None: chunkIterator = level.getAllChunkSlices() box = level.bounds else: chunkIterator = level.getChunkSlices(box) log.info("Replacing {0} with {1}".format(blocksToReplace, blockInfo)) changesLighting = True blocktable = None if len(blocksToReplace): blocktable = blockReplaceTable(blocksToReplace) newAbsorption = level.materials.lightAbsorption[blockInfo.ID] oldAbsorptions = [level.materials.lightAbsorption[b.ID] for b in blocksToReplace] changesLighting = False for a in oldAbsorptions: if a != newAbsorption: changesLighting = True newEmission = level.materials.lightEmission[blockInfo.ID] oldEmissions = [level.materials.lightEmission[b.ID] for b in blocksToReplace] for a in oldEmissions: if a != newEmission: changesLighting = True tileEntity = None if blockInfo.stringID in TileEntity.stringNames.keys(): if level.gamePlatform == "Java": split_ver = level.gameVersionNumber.split('.') else: split_ver = level.gamePlatform.split('.') if 'Unknown' not in split_ver and "PE" not in split_ver and int(split_ver[0]) >= 1 and int(split_ver[1]) >= 11: tileEntity = "minecraft:{}".format(blockInfo.stringID) else: tileEntity = TileEntity.stringNames[blockInfo.stringID] blocksIdToReplace = [block.ID for block in blocksToReplace] blocksList = [] append = blocksList.append defsIds = level.defsIds if tileEntity and box is not None: for (boxX, boxY, boxZ) in box.positions: if blocktable is None or level.blockAt(boxX, boxY, boxZ) in blocksIdToReplace: tileEntityObject = TileEntity.Create(tileEntity, defsIds=defsIds) TileEntity.setpos(tileEntityObject, (boxX, boxY, boxZ)) append(tileEntityObject) i = 0 skipped = 0 replaced = 0 for (chunk, slices, point) in chunkIterator: i += 1 if i % 100 == 0: log.info(u"Chunk {0}...".format(i)) yield i, box.chunkCount blocks = chunk.Blocks[slices] data = chunk.Data[slices] mask = slice(None) needsLighting = changesLighting if blocktable is not None: mask = blocktable[blocks, data] blockCount = mask.sum() replaced += blockCount # don't waste time relighting and copying if the mask is empty if blockCount: blocks[:][mask] = blockInfo.ID if not noData: data[mask] = blockInfo.blockData else: skipped += 1 needsLighting = False def include(tileEntity): p = TileEntity.pos(tileEntity) x, y, z = map(lambda a, b, c: (a - b) - c, p, point, box.origin) return not ((p in box) and mask[x, z, y]) chunk.TileEntities[:] = filter(include, chunk.TileEntities) else: blocks[:] = blockInfo.ID if not noData: data[:] = blockInfo.blockData chunk.removeTileEntitiesInBox(box) chunkBounds = chunk.bounds smallBoxSize = (1, 1, 1) tileEntitiesToEdit = [t for t in blocksList if chunkBounds.intersect(BoundingBox(TileEntity.pos(t), smallBoxSize)).volume > 0] for tileEntityObject in tileEntitiesToEdit: chunk.addTileEntity(tileEntityObject) blocksList.remove(tileEntityObject) chunk.chunkChanged(needsLighting) if len(blocksToReplace): log.info(u"Replace: Skipped {0} chunks, replaced {1} blocks".format(skipped, replaced))
4,437
32.877863
134
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/run_regression_test.py
# !/usr/bin/env python import tempfile import sys import subprocess import shutil import os import hashlib import contextlib import gzip import fnmatch import tarfile import zipfile def generate_file_list(directory): for dirpath, dirnames, filenames in os.walk(directory): for filename in filenames: yield os.path.join(dirpath, filename) def sha1_file(name, checksum=None): CHUNKSIZE = 1024 if checksum is None: checksum = hashlib.sha1() if fnmatch.fnmatch(name, "*.dat"): opener = gzip.open else: opener = open with contextlib.closing(opener(name, 'rb')) as data: chunk = data.read(CHUNKSIZE) while len(chunk) == CHUNKSIZE: checksum.update(chunk) chunk = data.read(CHUNKSIZE) else: checksum.update(chunk) return checksum def calculate_result(directory): checksum = hashlib.sha1() for filename in sorted(generate_file_list(directory)): if filename.endswith("session.lock"): continue sha1_file(filename, checksum) return checksum.hexdigest() @contextlib.contextmanager def temporary_directory(prefix='regr'): name = tempfile.mkdtemp(prefix) try: yield name finally: shutil.rmtree(name) @contextlib.contextmanager def directory_clone(src): with temporary_directory('regr') as name: subdir = os.path.join(name, "subdir") shutil.copytree(src, subdir) yield subdir def launch_subprocess(directory, arguments, env=None): #my python breaks with an empty environ, i think it wants PATH #if sys.platform == "win32": if env is None: env = {} newenv = {} newenv.update(os.environ) newenv.update(env) proc = subprocess.Popen((["python.exe"] if sys.platform == "win32" else []) + [ "./mce.py", directory] + arguments, stdin=subprocess.PIPE, stdout=subprocess.PIPE, env=newenv) return proc class RegressionError(Exception): pass def do_test(test_data, result_check, arguments=()): """Run a regression test on the given world. result_check - sha1 of the recursive tree generated arguments - arguments to give to mce.py on execution """ result_check = result_check.lower() env = { 'MCE_RANDOM_SEED': '42', 'MCE_LAST_PLAYED': '42', } if 'MCE_PROFILE' in os.environ: env['MCE_PROFILE'] = os.environ['MCE_PROFILE'] with directory_clone(test_data) as directory: proc = launch_subprocess(directory, arguments, env) proc.stdin.close() proc.wait() if proc.returncode: raise RegressionError("Program execution failed!") checksum = calculate_result(directory).lower() if checksum != result_check.lower(): raise RegressionError("Checksum mismatch: {0!r} != {1!r}".format(checksum, result_check)) print "[OK] (sha1sum of result is {0!r}, as expected)".format(result_check) def do_test_match_output(test_data, result_check, arguments=()): result_check = result_check.lower() env = { 'MCE_RANDOM_SEED': '42', 'MCE_LAST_PLAYED': '42' } with directory_clone(test_data) as directory: proc = launch_subprocess(directory, arguments, env) proc.stdin.close() output = proc.stdout.read() proc.wait() if proc.returncode: raise RegressionError("Program execution failed!") print "Output\n{0}".format(output) checksum = hashlib.sha1() checksum.update(output) checksum = checksum.hexdigest() if checksum != result_check.lower(): raise RegressionError("Checksum mismatch: {0!r} != {1!r}".format(checksum, result_check)) print "[OK] (sha1sum of result is {0!r}, as expected)".format(result_check) alpha_tests = [ (do_test, 'baseline', '2bf250ec4e5dd8bfd73b3ccd0a5ff749569763cf', []), (do_test, 'degrief', '2b7eecd5e660f20415413707b4576b1234debfcb', ['degrief']), (do_test_match_output, 'analyze', '9cb4aec2ed7a895c3a5d20d6e29e26459e00bd53', ['analyze']), (do_test, 'relight', 'f3b3445b0abca1fe2b183bc48b24fb734dfca781', ['relight']), (do_test, 'replace', '4e816038f9851817b0d75df948d058143708d2ec', ['replace', 'Water (active)', 'with', 'Lava (active)']), (do_test, 'fill', '94566d069edece4ff0cc52ef2d8f877fbe9720ab', ['fill', 'Water (active)']), (do_test, 'heightmap', '71c20e7d7e335cb64b3eb0e9f6f4c9abaa09b070', ['heightmap', 'regression_test/mars.png']), ] import optparse parser = optparse.OptionParser() parser.add_option("--profile", help="Perform profiling on regression tests", action="store_true") def main(argv): options, args = parser.parse_args(argv) if len(args) <= 1: do_these_regressions = ['*'] else: do_these_regressions = args[1:] with directory_clone("testfiles/AnvilWorld") as directory: test_data = directory passes = [] fails = [] for func, name, sha, args in alpha_tests: 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 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)) print fails[-1] else: passes.append("Regression {0!r} complete.".format(name)) print passes[-1] print "{0} tests passed.".format(len(passes)) for line in fails: print line if __name__ == '__main__': sys.exit(main(sys.argv))
5,917
28.59
114
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/player.py
import nbt import player_cache class Player: def __init__(self, playerNBTFile): self.nbtFile = playerNBTFile self.nbtFileName = playerNBTFile.split("\\")[-1] self.root_tag = nbt.load(playerNBTFile) # Properties setup self._uuid = self.nbtFileName.split(".")[0] playerName = player_cache.getPlayerNameFromUUID(self._uuid) if playerName != self._uuid: self._name = playerName else: self._name = None self._gametype = self.root_tag["playerGameType"].value self._pos = [self.root_tag["Pos"][0].value, self.root_tag["Pos"][1].value, self.root_tag["Pos"][2].value] self._rot = [self.root_tag["Rotation"][0].value, self.root_tag["Rotation"][1].value] self._health = self.root_tag["Health"].value self._healf = self.root_tag["HealF"].value self._xp_level = self.root_tag["XpLevel"].value self._inventory = self.root_tag["Inventory"].value @property def name(self): return self._name @property def gametype(self): return self._gametype @property def uuid(self): return self._uuid @property def pos(self): return self._pos @property def rot(self): return self._rot @property def health(self): return self._health @property def healf(self): return self._healf @property def XP_Level(self): return self._xp_level @property def inventory(self): return self._inventory def save(self): raise NotImplementedError("Player Data cannot be saved right now")
1,695
23.941176
113
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/setup_leveldb.py
#!/usr/bin/python2.7 # # setup_leveldb.py # # Compiles and installs Minecraft Pocket Edtition binary support. # __author__ = "D.C.-G. 2017" __version__ = "0.4.0" import sys import os import platform import fnmatch import re if sys.platform != "linux2": print "This script can't run on other platforms than Linux ones..." sys.exit(1) bin_deps = ('gcc', 'g++', 'unzip', 'wget|curl') wget_curl = None wget_cmd = "wget -q --no-check-certificate -O" curl_cmd = "curl -LskS -o" leveldb_mojang_sources_url = "https://codeload.github.com/Mojang/leveldb-mcpe/zip/" leveldb_mojang_commit = "5722a489c0fabf70f7bb36f70adc2ac70ff90377" # leveldb_other_sources_url = "https://codeload.github.com/jocopa3/leveldb-mcpe/zip/" # leveldb_other_commit = "56bdd1f38dde7074426d85eab01a5c1c0b5b1cfe" leveldb_other_sources_url = "https://codeload.github.com/LaChal/leveldb-mcpe/zip/" leveldb_other_commit = "9191f0499cd6d71e4e08c513f3a331a1ffe24332" zlib_sources_url = "https://codeload.github.com/madler/zlib/zip/" zlib_commit = "4a090adef8c773087ec8916ad3c2236ef560df27" zlib_ideal_version = "1.2.8" zlib_minimum_version = "1.2.8" zlib_supported_versions = (zlib_minimum_version, zlib_ideal_version, "1.2.10") silent = False def check_bins(bins): print 'Searching for the needed binaries %s...' % repr(bins).replace("'", '') missing_bin = False for name in bins: names = [] if '|' in name: names = name.split('|') if names: found = False for n in names: if not os.system('which %s > /dev/null' % n): found = True break else: print "Could not find %s." % n if found: g_keys = globals().keys() g_name = name.replace('|', '_') print "g_name", g_name, g_name in g_keys if g_name in g_keys: globals()[g_name] = globals()['%s_cmd' % n] else: print '*** WARNING: None of these binaries were found on your system: %s.'%', '.join(names) else: if os.system('which %s > /dev/null' % name): print '*** WARNING: %s not found.' % name missing_bin = True if missing_bin: if not silent: a = raw_input('The binary dependencies are not satisfied. The build may fail.\nContinue [y/N]?') else: a = 'n' if a and a in 'yY': pass else: sys.exit(1) else: print 'All the needed binaries were found.' # Picked from another project to find the lib and adapted to the need ARCH = {'32bit': '32', '64bit': '64'}[platform.architecture()[0]] default_paths = ['/lib', '/lib32', '/lib64', '/usr/lib', '/usr/lib32','/usr/lib64', '/usr/local/lib', os.path.expanduser('~/.local/lib'), '.'] # Gather the libraries paths. def get_lib_paths(file_name): paths = [] if os.path.isfile(file_name): lines = [a.strip() for a in open(file_name).readlines()] for i, line in enumerate(lines): if not line.startswith('#') and line.strip(): if line.startswith('include'): line = line.split(' ', 1)[1] if '*' in line: pat = r"%s" % line.split(os.path.sep)[-1].replace('.', '\.').replace('*', '.*') d = os.path.split(line)[0] if os.path.isdir(d): for n in os.listdir(d): r = re.findall(pat, n) if r: paths += [a for a in get_lib_paths(os.path.join(d, n)) if a not in paths] else: paths += [a for a in get_lib_paths(line) if not a in paths] elif not line in paths and os.path.isdir(line): paths.append(line) return paths def find_lib(lib_name, input_file='/etc/ld.so.conf'): paths = default_paths + get_lib_paths(input_file) arch_paths = [] other_paths = [] while paths: path = paths.pop(0) if ARCH in path: arch_paths.insert(0, path) elif path.endswith('/lib'): arch_paths.append(path) else: other_paths.append(path) paths = arch_paths + other_paths found = None r = None ver = None name = lib_name hash_list = name.split('.') hash_list.reverse() idx = hash_list.index('so') i = 0 while i <= idx and not found: for path in paths: print "Scanning %s for %s" % (path, name) if os.path.exists(path): for path, dirnames, filenames in os.walk(path): if name in filenames: found = os.path.join(path, name) break if found: break i += 1 name = name.rsplit('.', 1)[0] cur_dir = os.getcwd() os.chdir(path) if found: base_path = os.path.split(found)[0] while os.path.islink(found): found = os.readlink(found) if not found.startswith("/"): found = os.path.abspath(os.path.join(base_path, found)) # Verify the architecture of the library inp, outp = os.popen2('file %s | grep "ELF %s"' % (found, ARCH)) r = bool(outp.read()) inp.close() outp.close() # If the architecture could not be check with library internal data, rely on the folder name. if os.path.split(found)[0] in arch_paths: r = True v = found.rsplit('.so.', 1) if len(v) == 2: ver = v[1] os.chdir(cur_dir) return found, r, ver def get_sources(name, url): print "Downloading sources for %s" % name print "URL: %s" % url os.system("%s %s.zip %s" % (wget_curl, name, url)) print "Unpacking %s" % name os.system("unzip -q %s.zip" % name) os.system("mv $(ls -d1 */ | egrep '{n}-') {n}".format(n=name)) print "Cleaning archive." os.remove("%s.zip" % name) def build_zlib(): print "Building zlib..." return os.WEXITSTATUS(os.system("./configure; make")) # Bad and dirty, but working untill Mojang implement this (or like): code injection # directly into the sources before compilation. # As an alternative to this, you may prefer to run this script with the '--alt-leveldb' # CLI option, since the other repository don't need this code injection. before = 0 after = 1 c_inject = { "c.h": { # The hook to look for code injection. "hook": """ extern void leveldb_options_set_compression(leveldb_options_t*, int); """, # The data to be injected. "data": """ extern void leveldb_options_set_compressor(leveldb_options_t*, int, int); """, # Where to inject the data: after the "hook" or before it. "where": after }, "c.cc": { "hook": """ void leveldb_options_set_compression(leveldb_options_t* opt, int t) { """, "data": """ void leveldb_options_set_compressor(leveldb_options_t* opt, int i, int t) { switch(t) { case 0: opt->rep.compressors[i] = nullptr; break; #ifdef SNAPPY case leveldb_snappy_compression: opt->rep.compressors[i] = new leveldb::SnappyCompressor(); break; #endif case leveldb_zlib_compression: opt->rep.compressors[i] = new leveldb::ZlibCompressor(); break; case leveldb_zlib_raw_compression: opt->rep.compressors[i] = new leveldb::ZlibCompressorRaw(); break; } } """, "where": before } } def build_leveldb(zlib): print "Building leveldb..." # Inject the needed code into the sources. for root, d_names, f_names in os.walk("."): for f_name in fnmatch.filter(f_names, "c.[ch]*"): if f_name in c_inject.keys(): hook = c_inject[f_name]["hook"] data = c_inject[f_name]["data"] where = c_inject[f_name]["where"] with open(os.path.join(root, f_name), "r+") as fd: f_data = fd.read() if data not in f_data: if where == before: c_data = "\n".join((data, hook)) else: c_data = "\n".join((hook, data)) fd.seek(0) fd.write(f_data.replace(hook, c_data)) if zlib: with open("Makefile", "r+") as f: # If '-lz' is specified, we *may* need to specify the full library path. Just force it to be sure. data = f.read().replace("LIBS += $(PLATFORM_LIBS) -lz", "LIBS += $(PLATFORM_LIBS) %s" % zlib) # All the same if a path is specified, we need the one we found here. (SuSE don't have a /lib/x64_86-linux-gnu directory.) data = data.replace("LIBS += $(PLATFORM_LIBS) /lib/x86_64-linux-gnu/libz.so.1.2.8", "LIBS += $(PLATFORM_LIBS) %s" % zlib) f.seek(0) f.write(data) cpath = os.environ.get("CPATH") if cpath: os.environ["CPATH"] = ":".join(("./zlib", cpath)) else: os.environ["CPATH"] = "./zlib" return os.WEXITSTATUS(os.system("make")) def request_zlib_build(): print " Enter 'b' to build zlib v%s only for leveldb." % zlib_ideal_version print " Enter 'a' to quit now and install zlib yourself." print " Enter 'c' to continue." a = "" if not silent: while a.lower() not in "abc": a = raw_input("Build zlib [b], abort [a] or continue [c]? ") else: a = "a" if a == "b": return True elif a == "a": sys.exit(1) elif a == "c": return None def main(): print "=" * 72 print "Building Linux Minecraft Pocket Edition for MCEdit..." print "-----------------------------------------------------" global leveldb_commit global zlib_commit global zlib_sources_url global silent global zlib_ideal_version force_zlib = False leveldb_source_url = leveldb_mojang_sources_url leveldb_commit = leveldb_mojang_commit cur_dir = os.getcwd() if "--force-zlib" in sys.argv: force_zlib = True sys.argv.remove("--force-zlib") if "--alt-leveldb" in sys.argv: leveldb_source_url = leveldb_other_sources_url leveldb_commit = leveldb_other_commit for arg, var in (("--leveldb-source-url", "leveldb_source_url"), ("--leveldb-commit", "leveldb_commit"), ("--zlib-source-url", "zlib_source_url"), ("--zlib-commit", "zlib_commit")): if arg in sys.argv: globals()[var] = sys.argv[sys.argv.index(arg) + 1] leveldb_source_url += leveldb_commit zlib_sources_url += zlib_commit if "--silent" in sys.argv: silent = True if "--debug-cenv" in sys.argv: print 'CPATH:', os.environ.get('CPATH', 'empty!') print 'PATH:', os.environ.get('PATH', 'empty!') print 'LD_LIBRARY_PATH', os.environ.get('LD_LIBRARY_PATH', 'empty!') print 'LIBRARY_PATH', os.environ.get('LIBRARY_PATH', 'empty!') check_bins(bin_deps) # Get the sources here. get_sources("leveldb", leveldb_source_url) os.chdir("leveldb") get_sources("zlib", zlib_sources_url) os.chdir(cur_dir) zlib = (None, None, None) # Check zlib if not force_zlib: print "Checking zlib." zlib = find_lib("libz.so.%s" % zlib_ideal_version) print zlib if zlib == (None, None, None): zlib = None print "*** WARNING: zlib not found!" print " It is recommended you install zlib v%s on your system or" % zlib_ideal_version print " let this script install it only for leveldb." force_zlib = request_zlib_build() else: if zlib[2] == None: print "*** WARNING: zlib has been found, but the exact version could not be" print " determined." print " It is recommended you install zlib v%s on your system or" % zlib_ideal_version print " let this script install it only for leveldb." force_zlib = request_zlib_build() elif zlib[2] not in zlib_supported_versions: print "*** WARNING: zlib was found, but its version is %s." % zlib[2] print " You can try to build with this version, but it may fail," print " or the generated libraries may not work..." force_zlib = request_zlib_build() if zlib[1] == False: print "*** WARNING: zlib has been found on your system, but not for the" print " current architecture." print " You apparently run on a %s, and the found zlib is %s" % (ARCH, zlib[0]) print " Building the Pocket Edition support may fail. If not," print " the support may not work." print " You can continue, but it is recommended to install zlib." force_zlib = request_zlib_build() if force_zlib is None: print "Build continues with zlib v%s" % zlib[2] else: print "Found compliant zlib v%s." % zlib[2] zlib = zlib[0] if force_zlib: os.chdir("leveldb/zlib") r = build_zlib() if r: print "Zlib build failed." return r os.chdir(cur_dir) os.rename("leveldb/zlib/libz.so.1.2.10", "./libz.so.1.2.10") os.rename("leveldb/zlib/libz.so.1", "./libz.so.1") os.rename("leveldb/zlib/libz.so", "./libz.so") for root, d_names, f_names in os.walk("leveldb"): for f_name in fnmatch.filter(f_names, "libz.so*"): os.rename(os.path.join(root, f_name), os.path.join(".", f_name)) # Tweak the leveldb makefile to force the linker to use the built zlib with open("leveldb/Makefile", "r+") as f: data = f.read() data = data.replace("PLATFORM_SHARED_LDFLAGS", "PSL") data = data.replace("LDFLAGS += $(PLATFORM_LDFLAGS)", "LDFLAGS += $(PLATFORM_LDFLAGS)\nPSL = -L{d} -lz -Wl,-R{d} $(PLATFORM_SHARED_LDFLAGS)".format(d=cur_dir)) data = data.replace("LIBS += $(PLATFORM_LIBS) -lz", "LIBS += -L{d} -lz -Wl,-R{d} $(PLATFORM_LIBS)".format(d=cur_dir)) f.seek(0) f.write(data) zlib = None os.chdir("leveldb") r = build_leveldb(zlib) if r: print "PE support build failed." return r os.chdir(cur_dir) for root, d_names, f_names in os.walk("leveldb"): for f_name in fnmatch.filter(f_names, "libleveldb.so*"): os.rename(os.path.join(root, f_name), os.path.join(".", f_name)) print "Setup script ended." if __name__ == "__main__": sys.exit(main())
15,212
36.014599
137
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/infiniteworld.py
''' Created on Jul 22, 2011 @author: Rio ''' import collections from datetime import datetime import itertools from logging import getLogger from math import floor import os import random import shutil import struct import time import traceback import weakref import zlib import sys from box import BoundingBox from entity import Entity, TileEntity, TileTick from faces import FaceXDecreasing, FaceXIncreasing, FaceZDecreasing, FaceZIncreasing from level import LightedChunk, EntityLevel, computeChunkHeightMap, MCLevel, ChunkBase from materials import alphaMaterials from mclevelbase import ChunkMalformed, ChunkNotPresent, ChunkAccessDenied,ChunkConcurrentException,exhaust, PlayerNotFound import nbt from numpy import array, clip, maximum, zeros, asarray, unpackbits, arange from regionfile import MCRegionFile import logging from uuid import UUID import id_definitions log = getLogger(__name__) DIM_NETHER = -1 DIM_END = 1 __all__ = ["ZeroChunk", "AnvilChunk", "ChunkedLevelMixin", "MCInfdevOldLevel", "MCAlphaDimension"] _zeros = {} class SessionLockLost(IOError): pass def ZeroChunk(height=512): z = _zeros.get(height) if z is None: z = _zeros[height] = _ZeroChunk(height) return z class _ZeroChunk(ChunkBase): " a placebo for neighboring-chunk routines " def __init__(self, height=512): zeroChunk = zeros((16, 16, height), 'uint8') whiteLight = zeroChunk + 15 self.Blocks = zeroChunk self.BlockLight = whiteLight self.SkyLight = whiteLight self.Data = zeroChunk def unpackNibbleArray(dataArray): s = dataArray.shape unpackedData = zeros((s[0], s[1], s[2] * 2), dtype='uint8') unpackedData[:, :, ::2] = dataArray unpackedData[:, :, ::2] &= 0xf unpackedData[:, :, 1::2] = dataArray unpackedData[:, :, 1::2] >>= 4 return unpackedData def packNibbleArray(unpackedData): packedData = array(unpackedData.reshape(16, 16, unpackedData.shape[2] / 2, 2)) packedData[..., 1] <<= 4 packedData[..., 1] |= packedData[..., 0] return array(packedData[:, :, :, 1]) def sanitizeBlocks(chunk): # change grass to dirt where needed so Minecraft doesn't flip out and die grass = chunk.Blocks == chunk.materials.Grass.ID grass |= chunk.Blocks == chunk.materials.Dirt.ID badgrass = grass[:, :, 1:] & grass[:, :, :-1] chunk.Blocks[:, :, :-1][badgrass] = chunk.materials.Dirt.ID # remove any thin snow layers immediately above other thin snow layers. # minecraft doesn't flip out, but it's almost never intended if hasattr(chunk.materials, "SnowLayer"): snowlayer = chunk.Blocks == chunk.materials.SnowLayer.ID badsnow = snowlayer[:, :, 1:] & snowlayer[:, :, :-1] chunk.Blocks[:, :, 1:][badsnow] = chunk.materials.Air.ID class AnvilChunkData(object): """ This is the chunk data backing an AnvilChunk. Chunk data is retained by the MCInfdevOldLevel until its AnvilChunk is no longer used, then it is either cached in memory, discarded, or written to disk according to resource limits. AnvilChunks are stored in a WeakValueDictionary so we can find out when they are no longer used by clients. The AnvilChunkData for an unused chunk may safely be discarded or written out to disk. The client should probably not keep references to a whole lot of chunks or else it will run out of memory. """ def __init__(self, world, chunkPosition, root_tag=None, create=False): self.chunkPosition = chunkPosition self.world = world self.root_tag = root_tag self.dirty = False self.Blocks = zeros((16, 16, world.Height), 'uint16') self.Data = zeros((16, 16, world.Height), 'uint8') self.BlockLight = zeros((16, 16, world.Height), 'uint8') self.SkyLight = zeros((16, 16, world.Height), 'uint8') self.SkyLight[:] = 15 if create: self._create() else: self._load(root_tag) levelTag = self.root_tag["Level"] if "Biomes" not in levelTag: levelTag["Biomes"] = nbt.TAG_Byte_Array(zeros((16, 16), 'uint8')) levelTag["Biomes"].value[:] = -1 def _create(self): (cx, cz) = self.chunkPosition chunkTag = nbt.TAG_Compound() chunkTag.name = "" levelTag = nbt.TAG_Compound() chunkTag["Level"] = levelTag levelTag["HeightMap"] = nbt.TAG_Int_Array(zeros((16, 16), 'uint32').newbyteorder()) levelTag["TerrainPopulated"] = nbt.TAG_Byte(1) levelTag["xPos"] = nbt.TAG_Int(cx) levelTag["zPos"] = nbt.TAG_Int(cz) levelTag["LastUpdate"] = nbt.TAG_Long(0) levelTag["Entities"] = nbt.TAG_List() levelTag["TileEntities"] = nbt.TAG_List() levelTag["TileTicks"] = nbt.TAG_List() self.root_tag = chunkTag self.dirty = True def _get_blocks_and_data_from_blockstates(self, section): long_array = section["BlockStates"].value bits_amount = len(long_array) / 64 binary_blocks = unpackbits(long_array[::-1].astype(">i8").view("uint8")).reshape(-1, bits_amount) blocks_before_palette = binary_blocks.dot(2**arange(binary_blocks.shape[1]-1, -1, -1))[::-1] blocks = asarray(section["Palette"].value, dtype="object")[blocks_before_palette] raise NotImplementedError("1.13 version not supported yet") def _load(self, root_tag): self.root_tag = root_tag for sec in self.root_tag["Level"].pop("Sections", []): y = sec["Y"].value * 16 values_to_get = ["SkyLight", "BlockLight"] if "Blocks" in sec and "Data" in sec: values_to_get.extend(["Blocks", "Data"]) else: Blocks, Data = self._get_blocks_and_data_from_blockstates(sec) self.Blocks[..., y:y + 16], self.Data[..., y:y + 16] = Blocks, Data for name in values_to_get: arr = getattr(self, name) secarray = sec[name].value if name == "Blocks": secarray.shape = (16, 16, 16) else: secarray.shape = (16, 16, 8) secarray = unpackNibbleArray(secarray) arr[..., y:y + 16] = secarray.swapaxes(0, 2) tag = sec.get("Add") if tag is not None: tag.value.shape = (16, 16, 8) add = unpackNibbleArray(tag.value) self.Blocks[..., y:y + 16] |= (array(add, 'uint16') << 8).swapaxes(0, 2) def savedTagData(self): """ does not recalculate any data or light """ log.debug(u"Saving chunk: {0}".format(self)) sanitizeBlocks(self) sections = nbt.TAG_List() append = sections.append for y in xrange(0, self.world.Height, 16): section = nbt.TAG_Compound() Blocks = self.Blocks[..., y:y + 16].swapaxes(0, 2) Data = self.Data[..., y:y + 16].swapaxes(0, 2) BlockLight = self.BlockLight[..., y:y + 16].swapaxes(0, 2) SkyLight = self.SkyLight[..., y:y + 16].swapaxes(0, 2) if (not Blocks.any() and not BlockLight.any() and (SkyLight == 15).all()): continue Data = packNibbleArray(Data) BlockLight = packNibbleArray(BlockLight) SkyLight = packNibbleArray(SkyLight) add = Blocks >> 8 if add.any(): section["Add"] = nbt.TAG_Byte_Array(packNibbleArray(add).astype('uint8')) section['Blocks'] = nbt.TAG_Byte_Array(array(Blocks, 'uint8')) section['Data'] = nbt.TAG_Byte_Array(array(Data)) section['BlockLight'] = nbt.TAG_Byte_Array(array(BlockLight)) section['SkyLight'] = nbt.TAG_Byte_Array(array(SkyLight)) section["Y"] = nbt.TAG_Byte(y / 16) append(section) self.root_tag["Level"]["Sections"] = sections data = self.root_tag.save(compressed=False) del self.root_tag["Level"]["Sections"] log.debug(u"Saved chunk {0}".format(self)) return data @property def materials(self): return self.world.materials class AnvilChunk(LightedChunk): """ This is a 16x16xH chunk in an (infinite) world. The properties Blocks, Data, SkyLight, BlockLight, and Heightmap are ndarrays containing the respective blocks in the chunk file. Each array is indexed [x,z,y]. The Data, Skylight, and BlockLight arrays are automatically unpacked from nibble arrays into byte arrays for better handling. """ def __init__(self, chunkData): self.world = chunkData.world self.chunkPosition = chunkData.chunkPosition self.chunkData = chunkData def savedTagData(self): return self.chunkData.savedTagData() def __str__(self): return u"AnvilChunk, coords:{0}, world: {1}, D:{2}, L:{3}".format(self.chunkPosition, self.world.displayName, self.dirty, self.needsLighting) @property def needsLighting(self): return self.chunkPosition in self.world.chunksNeedingLighting @needsLighting.setter def needsLighting(self, value): if value: self.world.chunksNeedingLighting.add(self.chunkPosition) else: self.world.chunksNeedingLighting.discard(self.chunkPosition) def generateHeightMap(self): computeChunkHeightMap(self.materials, self.Blocks, self.HeightMap) def addEntity(self, entityTag): def doubleize(name): # This is needed for compatibility with Indev levels. Those levels use TAG_Float for entity motion and pos if name in entityTag: m = entityTag[name] entityTag[name] = nbt.TAG_List([nbt.TAG_Double(i.value) for i in m]) doubleize("Motion") doubleize("Position") self.dirty = True return super(AnvilChunk, self).addEntity(entityTag) def removeEntitiesInBox(self, box): self.dirty = True return super(AnvilChunk, self).removeEntitiesInBox(box) def removeTileEntitiesInBox(self, box): self.dirty = True return super(AnvilChunk, self).removeTileEntitiesInBox(box) def addTileTick(self, tickTag): self.dirty = True return super(AnvilChunk, self).addTileTick(tickTag) def removeTileTicksInBox(self, box): self.dirty = True return super(AnvilChunk, self).removeTileTicksInBox(box) # --- AnvilChunkData accessors --- @property def root_tag(self): return self.chunkData.root_tag @property def dirty(self): return self.chunkData.dirty @dirty.setter def dirty(self, val): self.chunkData.dirty = val # --- Chunk attributes --- @property def materials(self): return self.world.materials @property def Blocks(self): return self.chunkData.Blocks @Blocks.setter def Blocks(self, value): self.chunkData.Blocks = value @property def Data(self): return self.chunkData.Data @property def SkyLight(self): return self.chunkData.SkyLight @property def BlockLight(self): return self.chunkData.BlockLight @property def Biomes(self): return self.root_tag["Level"]["Biomes"].value.reshape((16, 16)) @property def HeightMap(self): return self.root_tag["Level"]["HeightMap"].value.reshape((16, 16)) @property def Entities(self): return self.root_tag["Level"]["Entities"] @property def TileEntities(self): return self.root_tag["Level"]["TileEntities"] @property def TileTicks(self): if "TileTicks" in self.root_tag["Level"]: return self.root_tag["Level"]["TileTicks"] else: self.root_tag["Level"]["TileTicks"] = nbt.TAG_List() return self.root_tag["Level"]["TileTicks"] @property def TerrainPopulated(self): return self.root_tag["Level"]["TerrainPopulated"].value @TerrainPopulated.setter def TerrainPopulated(self, val): """True or False. If False, the game will populate the chunk with ores and vegetation on next load""" self.root_tag["Level"]["TerrainPopulated"].value = val self.dirty = True base36alphabet = "0123456789abcdefghijklmnopqrstuvwxyz" def decbase36(s): return int(s, 36) def base36(n): global base36alphabet n = int(n) if 0 == n: return '0' neg = "" if n < 0: neg = "-" n = -n work = [] while n: n, digit = divmod(n, 36) work.append(base36alphabet[digit]) return neg + ''.join(reversed(work)) def deflate(data): # zobj = zlib.compressobj(6,zlib.DEFLATED,-zlib.MAX_WBITS,zlib.DEF_MEM_LEVEL,0) # zdata = zobj.compress(data) # zdata += zobj.flush() # return zdata return zlib.compress(data) def inflate(data): return zlib.decompress(data) class ChunkedLevelMixin(MCLevel): def blockLightAt(self, x, y, z): ''' Gets the light value of the block at the specified X, Y, Z coordinates :param x: The X block coordinate :type x: int :param y: The Y block coordinate :type y: int :param z: The Z block coordinate :type z: int :return: The light value or 0 if the Y coordinate is above the maximum height limit or below 0 :rtype: int ''' if y < 0 or y >= self.Height: return 0 zc = z >> 4 xc = x >> 4 xInChunk = x & 0xf zInChunk = z & 0xf ch = self.getChunk(xc, zc) return ch.BlockLight[xInChunk, zInChunk, y] def setBlockLightAt(self, x, y, z, newLight): ''' Sets the light value of the block at the specified X, Y, Z coordinates :param x: The X block coordinate :type x: int :param y: The Y block coordinate :type y: int :param z: The Z block coordinate :type z: int :param newLight: The desired light value :type newLight: int :return: Returns 0 if the Y coordinate is above the maximum height limit or below 0. Doesn't return anything otherwise :rtype: int ''' if y < 0 or y >= self.Height: return 0 zc = z >> 4 xc = x >> 4 xInChunk = x & 0xf zInChunk = z & 0xf ch = self.getChunk(xc, zc) ch.BlockLight[xInChunk, zInChunk, y] = newLight ch.chunkChanged(False) def blockDataAt(self, x, y, z): ''' Gets the data value of the block at the specified X, Y, Z coordinates :param x: The X block coordinate :type x: int :param y: The Y block coordinate :type y: int :param z: The Z block coordinate :type z: int :return: The data value of the block or 0 if the Y coordinate is above the maximum height limit or below 0 :rtype: int ''' if y < 0 or y >= self.Height: return 0 zc = z >> 4 xc = x >> 4 xInChunk = x & 0xf zInChunk = z & 0xf try: ch = self.getChunk(xc, zc) except ChunkNotPresent: return 0 return ch.Data[xInChunk, zInChunk, y] def setBlockDataAt(self, x, y, z, newdata): ''' Sets the data value of the block at the specified X, Y, Z coordinates :param x: The X block coordinate :type x: int :param y: The Y block coordinate :type y: int :param z: The Z block coordinate :type z: int :param newdata: The desired data value :type newData: int :return: Returns 0 if the Y coordinate is above the maximum height limit or below 0 or the chunk doesn't exist. Doesn't return anything otherwise :rtype: int ''' if y < 0 or y >= self.Height: return 0 zc = z >> 4 xc = x >> 4 xInChunk = x & 0xf zInChunk = z & 0xf try: ch = self.getChunk(xc, zc) except ChunkNotPresent: return 0 ch.Data[xInChunk, zInChunk, y] = newdata ch.dirty = True ch.needsLighting = True def blockAt(self, x, y, z): """returns 0 for blocks outside the loadable chunks. automatically loads chunks.""" if y < 0 or y >= self.Height: return 0 zc = z >> 4 xc = x >> 4 xInChunk = x & 0xf zInChunk = z & 0xf try: ch = self.getChunk(xc, zc) except ChunkNotPresent: return 0 if y >= ch.Height: return 0 return ch.Blocks[xInChunk, zInChunk, y] def setBlockAt(self, x, y, z, blockID): """returns 0 for blocks outside the loadable chunks. automatically loads chunks.""" if y < 0 or y >= self.Height: return 0 zc = z >> 4 xc = x >> 4 xInChunk = x & 0xf zInChunk = z & 0xf try: ch = self.getChunk(xc, zc) except ChunkNotPresent: return 0 ch.Blocks[xInChunk, zInChunk, y] = blockID ch.dirty = True ch.needsLighting = True def skylightAt(self, x, y, z): if y < 0 or y >= self.Height: return 0 zc = z >> 4 xc = x >> 4 xInChunk = x & 0xf zInChunk = z & 0xf ch = self.getChunk(xc, zc) return ch.SkyLight[xInChunk, zInChunk, y] def setSkylightAt(self, x, y, z, lightValue): if y < 0 or y >= self.Height: return 0 zc = z >> 4 xc = x >> 4 xInChunk = x & 0xf zInChunk = z & 0xf ch = self.getChunk(xc, zc) skyLight = ch.SkyLight oldValue = skyLight[xInChunk, zInChunk, y] ch.chunkChanged(False) if oldValue < lightValue: skyLight[xInChunk, zInChunk, y] = lightValue return oldValue < lightValue createChunk = NotImplemented def generateLights(self, dirtyChunkPositions=None): return exhaust(self.generateLightsIter(dirtyChunkPositions)) def generateLightsIter(self, dirtyChunkPositions=None): """ dirtyChunks may be an iterable yielding (xPos,zPos) tuples if none, generate lights for all chunks that need lighting """ startTime = datetime.now() if dirtyChunkPositions is None: dirtyChunkPositions = self.chunksNeedingLighting else: dirtyChunkPositions = (c for c in dirtyChunkPositions if self.containsChunk(*c)) dirtyChunkPositions = sorted(dirtyChunkPositions) maxLightingChunks = getattr(self, 'loadedChunkLimit', 400) log.info(u"Asked to light {0} chunks".format(len(dirtyChunkPositions))) chunkLists = [dirtyChunkPositions] def reverseChunkPosition((cx, cz)): return cz, cx def splitChunkLists(chunkLists): newChunkLists = [] append = newChunkLists.append for l in chunkLists: # list is already sorted on x position, so this splits into left and right smallX = l[:len(l) / 2] bigX = l[len(l) / 2:] # sort halves on z position smallX = sorted(smallX, key=reverseChunkPosition) bigX = sorted(bigX, key=reverseChunkPosition) # add quarters to list append(smallX[:len(smallX) / 2]) append(smallX[len(smallX) / 2:]) append(bigX[:len(bigX) / 2]) append(bigX[len(bigX) / 2:]) return newChunkLists while len(chunkLists[0]) > maxLightingChunks: chunkLists = splitChunkLists(chunkLists) if len(chunkLists) > 1: log.info(u"Using {0} batches to conserve memory.".format(len(chunkLists))) # batchSize = min(len(a) for a in chunkLists) estimatedTotals = [len(a) * 32 for a in chunkLists] workDone = 0 for i, dc in enumerate(chunkLists): log.info(u"Batch {0}/{1}".format(i, len(chunkLists))) dc = sorted(dc) workTotal = sum(estimatedTotals) t = 0 for c, t, p in self._generateLightsIter(dc): yield c + workDone, t + workTotal - estimatedTotals[i], p estimatedTotals[i] = t workDone += t timeDelta = datetime.now() - startTime if len(dirtyChunkPositions): log.info(u"Completed in {0}, {1} per chunk".format(timeDelta, dirtyChunkPositions and timeDelta / len( dirtyChunkPositions) or 0)) return def _generateLightsIter(self, dirtyChunkPositions): la = array(self.materials.lightAbsorption) clip(la, 1, 15, la) dirtyChunks = set(self.getChunk(*cPos) for cPos in dirtyChunkPositions) workDone = 0 workTotal = len(dirtyChunks) * 29 progressInfo = (u"Lighting {0} chunks".format(len(dirtyChunks))) log.info(progressInfo) for i, chunk in enumerate(dirtyChunks): chunk.chunkChanged() yield i, workTotal, progressInfo assert chunk.dirty and chunk.needsLighting workDone += len(dirtyChunks) workTotal = len(dirtyChunks) for ch in list(dirtyChunks): # relight all blocks in neighboring chunks in case their light source disappeared. cx, cz = ch.chunkPosition for dx, dz in itertools.product((-1, 0, 1), (-1, 0, 1)): try: ch = self.getChunk(cx + dx, cz + dz) except (ChunkNotPresent, ChunkMalformed): continue dirtyChunks.add(ch) ch.dirty = True dirtyChunks = sorted(dirtyChunks, key=lambda x: x.chunkPosition) workTotal += len(dirtyChunks) * 28 for i, chunk in enumerate(dirtyChunks): chunk.BlockLight[:] = self.materials.lightEmission[chunk.Blocks] chunk.dirty = True zeroChunk = ZeroChunk(self.Height) zeroChunk.BlockLight[:] = 0 zeroChunk.SkyLight[:] = 0 startingDirtyChunks = dirtyChunks oldLeftEdge = zeros((1, 16, self.Height), 'uint8') oldBottomEdge = zeros((16, 1, self.Height), 'uint8') oldChunk = zeros((16, 16, self.Height), 'uint8') if self.dimNo in (-1, 1): lights = ("BlockLight",) else: lights = ("BlockLight", "SkyLight") log.info(u"Dispersing light...") def clipLight(light): # light arrays are all uint8 by default, so when results go negative # they become large instead. reinterpret as signed int using view() # and then clip to range light.view('int8').clip(0, 15, light) for j, light in enumerate(lights): zerochunkLight = getattr(zeroChunk, light) newDirtyChunks = list(startingDirtyChunks) work = 0 for i in xrange(14): if len(newDirtyChunks) == 0: workTotal -= len(startingDirtyChunks) * (14 - i) break progressInfo = u"{0} Pass {1}: {2} chunks".format(light, i, len(newDirtyChunks)) log.info(progressInfo) # propagate light! # for each of the six cardinal directions, figure a new light value for # adjoining blocks by reducing this chunk's light by light absorption and fall off. # compare this new light value against the old light value and update with the maximum. # # we calculate all chunks one step before moving to the next step, to ensure all gaps at chunk edges are filled. # we do an extra cycle because lights sent across edges may lag by one cycle. # # xxx this can be optimized by finding the highest and lowest blocks # that changed after one pass, and only calculating changes for that # vertical slice on the next pass. newDirtyChunks would have to be a # list of (cPos, miny, maxy) tuples or a cPos : (miny, maxy) dict newDirtyChunks = set(newDirtyChunks) newDirtyChunks.discard(zeroChunk) dirtyChunks = sorted(newDirtyChunks, key=lambda x: x.chunkPosition) newDirtyChunks = list() append = newDirtyChunks.append for chunk in dirtyChunks: (cx, cz) = chunk.chunkPosition neighboringChunks = {} for dir, dx, dz in ((FaceXDecreasing, -1, 0), (FaceXIncreasing, 1, 0), (FaceZDecreasing, 0, -1), (FaceZIncreasing, 0, 1)): try: neighboringChunks[dir] = self.getChunk(cx + dx, cz + dz) except (ChunkNotPresent, ChunkMalformed): neighboringChunks[dir] = zeroChunk neighboringChunks[dir].dirty = True chunkLa = la[chunk.Blocks] chunkLight = getattr(chunk, light) oldChunk[:] = chunkLight[:] ### Spread light toward -X nc = neighboringChunks[FaceXDecreasing] ncLight = getattr(nc, light) oldLeftEdge[:] = ncLight[15:16, :, 0:self.Height] # save the old left edge # left edge newlight = (chunkLight[0:1, :, :self.Height] - la[nc.Blocks[15:16, :, 0:self.Height]]) clipLight(newlight) maximum(ncLight[15:16, :, 0:self.Height], newlight, ncLight[15:16, :, 0:self.Height]) # chunk body newlight = (chunkLight[1:16, :, 0:self.Height] - chunkLa[0:15, :, 0:self.Height]) clipLight(newlight) maximum(chunkLight[0:15, :, 0:self.Height], newlight, chunkLight[0:15, :, 0:self.Height]) # right edge nc = neighboringChunks[FaceXIncreasing] ncLight = getattr(nc, light) newlight = ncLight[0:1, :, :self.Height] - chunkLa[15:16, :, 0:self.Height] clipLight(newlight) maximum(chunkLight[15:16, :, 0:self.Height], newlight, chunkLight[15:16, :, 0:self.Height]) ### Spread light toward +X # right edge nc = neighboringChunks[FaceXIncreasing] ncLight = getattr(nc, light) newlight = (chunkLight[15:16, :, 0:self.Height] - la[nc.Blocks[0:1, :, 0:self.Height]]) clipLight(newlight) maximum(ncLight[0:1, :, 0:self.Height], newlight, ncLight[0:1, :, 0:self.Height]) # chunk body newlight = (chunkLight[0:15, :, 0:self.Height] - chunkLa[1:16, :, 0:self.Height]) clipLight(newlight) maximum(chunkLight[1:16, :, 0:self.Height], newlight, chunkLight[1:16, :, 0:self.Height]) # left edge nc = neighboringChunks[FaceXDecreasing] ncLight = getattr(nc, light) newlight = ncLight[15:16, :, :self.Height] - chunkLa[0:1, :, 0:self.Height] clipLight(newlight) maximum(chunkLight[0:1, :, 0:self.Height], newlight, chunkLight[0:1, :, 0:self.Height]) zerochunkLight[:] = 0 # zero the zero chunk after each direction # so the lights it absorbed don't affect the next pass # check if the left edge changed and dirty or compress the chunk appropriately if (oldLeftEdge != ncLight[15:16, :, :self.Height]).any(): # chunk is dirty append(nc) ### Spread light toward -Z # bottom edge nc = neighboringChunks[FaceZDecreasing] ncLight = getattr(nc, light) oldBottomEdge[:] = ncLight[:, 15:16, :self.Height] # save the old bottom edge newlight = (chunkLight[:, 0:1, :self.Height] - la[nc.Blocks[:, 15:16, :self.Height]]) clipLight(newlight) maximum(ncLight[:, 15:16, :self.Height], newlight, ncLight[:, 15:16, :self.Height]) # chunk body newlight = (chunkLight[:, 1:16, :self.Height] - chunkLa[:, 0:15, :self.Height]) clipLight(newlight) maximum(chunkLight[:, 0:15, :self.Height], newlight, chunkLight[:, 0:15, :self.Height]) # top edge nc = neighboringChunks[FaceZIncreasing] ncLight = getattr(nc, light) newlight = ncLight[:, 0:1, :self.Height] - chunkLa[:, 15:16, 0:self.Height] clipLight(newlight) maximum(chunkLight[:, 15:16, 0:self.Height], newlight, chunkLight[:, 15:16, 0:self.Height]) ### Spread light toward +Z # top edge nc = neighboringChunks[FaceZIncreasing] ncLight = getattr(nc, light) newlight = (chunkLight[:, 15:16, :self.Height] - la[nc.Blocks[:, 0:1, :self.Height]]) clipLight(newlight) maximum(ncLight[:, 0:1, :self.Height], newlight, ncLight[:, 0:1, :self.Height]) # chunk body newlight = (chunkLight[:, 0:15, :self.Height] - chunkLa[:, 1:16, :self.Height]) clipLight(newlight) maximum(chunkLight[:, 1:16, :self.Height], newlight, chunkLight[:, 1:16, :self.Height]) # bottom edge nc = neighboringChunks[FaceZDecreasing] ncLight = getattr(nc, light) newlight = ncLight[:, 15:16, :self.Height] - chunkLa[:, 0:1, 0:self.Height] clipLight(newlight) maximum(chunkLight[:, 0:1, 0:self.Height], newlight, chunkLight[:, 0:1, 0:self.Height]) zerochunkLight[:] = 0 if (oldBottomEdge != ncLight[:, 15:16, :self.Height]).any(): append(nc) newlight = (chunkLight[:, :, 0:self.Height - 1] - chunkLa[:, :, 1:self.Height]) clipLight(newlight) maximum(chunkLight[:, :, 1:self.Height], newlight, chunkLight[:, :, 1:self.Height]) newlight = (chunkLight[:, :, 1:self.Height] - chunkLa[:, :, 0:self.Height - 1]) clipLight(newlight) maximum(chunkLight[:, :, 0:self.Height - 1], newlight, chunkLight[:, :, 0:self.Height - 1]) if (oldChunk != chunkLight).any(): append(chunk) work += 1 yield workDone + work, workTotal, progressInfo workDone += work workTotal -= len(startingDirtyChunks) workTotal += work work = 0 for ch in startingDirtyChunks: ch.needsLighting = False def TagProperty(tagName, tagType, default_or_func=None): def getter(self): if tagName not in self.root_tag["Data"]: if hasattr(default_or_func, "__call__"): default = default_or_func(self) else: default = default_or_func self.root_tag["Data"][tagName] = tagType(default) return self.root_tag["Data"][tagName].value def setter(self, val): self.root_tag["Data"][tagName] = tagType(value=val) return property(getter, setter) class AnvilWorldFolder(object): def __init__(self, filename): if not os.path.exists(filename): os.mkdir(filename) elif not os.path.isdir(filename): raise IOError("AnvilWorldFolder: Not a folder: %s" % filename) self.filename = filename self.regionFiles = {} # --- File paths --- def getFilePath(self, path): path = path.replace("/", os.path.sep) return os.path.join(self.filename, path) def getFolderPath(self, path, checksExists=True, generation=False): if checksExists and not os.path.exists(self.filename) and "##MCEDIT.TEMP##" in path and not generation: raise IOError("The file does not exist") path = self.getFilePath(path) if not os.path.exists(path) and "players" not in path: os.makedirs(path) return path # --- Region files --- def getRegionFilename(self, rx, rz): return os.path.join(self.getFolderPath("region", False), "r.%s.%s.%s" % (rx, rz, "mca")) def getRegionFile(self, rx, rz): regionFile = self.regionFiles.get((rx, rz)) if regionFile: return regionFile regionFile = MCRegionFile(self.getRegionFilename(rx, rz), (rx, rz)) self.regionFiles[rx, rz] = regionFile return regionFile def getRegionForChunk(self, cx, cz): rx = cx >> 5 rz = cz >> 5 return self.getRegionFile(rx, rz) def closeRegions(self): for rf in self.regionFiles.values(): rf.close() self.regionFiles = {} # --- Chunks and chunk listing --- @staticmethod def tryLoadRegionFile(filepath): filename = os.path.basename(filepath) bits = filename.split('.') if len(bits) < 4 or bits[0] != 'r' or bits[3] != "mca": return None try: rx, rz = map(int, bits[1:3]) except ValueError: return None return MCRegionFile(filepath, (rx, rz)) def findRegionFiles(self): regionDir = self.getFolderPath("region", generation=True) regionFiles = os.listdir(regionDir) for filename in regionFiles: yield os.path.join(regionDir, filename) def listChunks(self): chunks = set() for filepath in self.findRegionFiles(): regionFile = self.tryLoadRegionFile(filepath) if regionFile is None: continue if regionFile.offsets.any(): rx, rz = regionFile.regionCoords self.regionFiles[rx, rz] = regionFile for index, offset in enumerate(regionFile.offsets): if offset: cx = index & 0x1f cz = index >> 5 cx += rx << 5 cz += rz << 5 chunks.add((cx, cz)) else: log.info(u"Removing empty region file {0}".format(filepath)) regionFile.close() os.unlink(regionFile.path) return chunks def containsChunk(self, cx, cz): rx = cx >> 5 rz = cz >> 5 if not os.path.exists(self.getRegionFilename(rx, rz)): return False return self.getRegionForChunk(cx, cz).containsChunk(cx, cz) def deleteChunk(self, cx, cz): r = cx >> 5, cz >> 5 rf = self.getRegionFile(*r) if rf: rf.setOffset(cx & 0x1f, cz & 0x1f, 0) if (rf.offsets == 0).all(): rf.close() os.unlink(rf.path) del self.regionFiles[r] def readChunk(self, cx, cz): if not self.containsChunk(cx, cz): raise ChunkNotPresent((cx, cz)) return self.getRegionForChunk(cx, cz).readChunk(cx, cz) def saveChunk(self, cx, cz, data): regionFile = self.getRegionForChunk(cx, cz) regionFile.saveChunk(cx, cz, data) def copyChunkFrom(self, worldFolder, cx, cz): fromRF = worldFolder.getRegionForChunk(cx, cz) rf = self.getRegionForChunk(cx, cz) rf.copyChunkFrom(fromRF, cx, cz) class MCInfdevOldLevel(ChunkedLevelMixin, EntityLevel): ''' A class that handles the data that is stored in a Minecraft Java level. This class is the type of the 'level' parameter that is passed to a filter's :func:`perform` function ''' playersFolder = None def __init__(self, filename=None, create=False, random_seed=None, last_played=None, readonly=False, dat_name='level'): """ Load an Alpha level from the given filename. It can point to either a level.dat or a folder containing one. If create is True, it will also create the world using the random_seed and last_played arguments. If they are none, a random 64-bit seed will be selected for RandomSeed and long(time.time() * 1000) will be used for LastPlayed. If you try to create an existing world, its level.dat will be replaced. """ self.dat_name = dat_name self.Length = 0 self.Width = 0 self.Height = 256 self.playerTagCache = {} self.players = [] assert not (create and readonly) self.lockAcquireFuncs = [] self.lockLoseFuncs = [] self.initTime = -1 if os.path.basename(filename) in ("%s.dat" % dat_name, "%s.dat_old" % dat_name): filename = os.path.dirname(filename) if not os.path.exists(filename): if not create: raise IOError('File not found') os.mkdir(filename) if not os.path.isdir(filename): raise IOError('File is not a Minecraft Alpha world') self.worldFolder = AnvilWorldFolder(filename) self.filename = self.worldFolder.getFilePath("%s.dat" % dat_name) self.readonly = readonly if not readonly: self.acquireSessionLock() workFolderPath = self.worldFolder.getFolderPath("##MCEDIT.TEMP##") workFolderPath2 = self.worldFolder.getFolderPath("##MCEDIT.TEMP2##") if os.path.exists(workFolderPath): # xxxxxxx Opening a world a second time deletes the first world's work folder and crashes when the first # world tries to read a modified chunk from the work folder. This mainly happens when importing a world # into itself after modifying it. shutil.rmtree(workFolderPath, True) if os.path.exists(workFolderPath2): shutil.rmtree(workFolderPath2, True) self.unsavedWorkFolder = AnvilWorldFolder(workFolderPath) self.fileEditsFolder = AnvilWorldFolder(workFolderPath2) self.editFileNumber = 1 # maps (cx, cz) pairs to AnvilChunk self._loadedChunks = weakref.WeakValueDictionary() # maps (cx, cz) pairs to AnvilChunkData self._loadedChunkData = {} self.recentChunks = collections.deque(maxlen=20) self.chunksNeedingLighting = set() self._allChunks = None self.dimensions = {} self.loadLevelDat(create, random_seed, last_played) if dat_name == 'level': assert self.version == self.VERSION_ANVIL, "Pre-Anvil world formats are not supported (for now)" if not readonly: if os.path.exists(self.worldFolder.getFolderPath("players")) and os.listdir( self.worldFolder.getFolderPath("players")) != []: self.playersFolder = self.worldFolder.getFolderPath("players") self.oldPlayerFolderFormat = True if os.path.exists(self.worldFolder.getFolderPath("playerdata")): self.playersFolder = self.worldFolder.getFolderPath("playerdata") self.oldPlayerFolderFormat = False self.players = [x[:-4] for x in os.listdir(self.playersFolder) if x.endswith(".dat")] for player in self.players: try: UUID(player, version=4) except ValueError: try: print "{0} does not seem to be in a valid UUID format".format(player) except UnicodeEncode: try: print u"{0} does not seem to be in a valid UUID format".format(player) except UnicodeError: print "{0} does not seem to be in a valid UUID format".format(repr(player)) self.players.remove(player) if "Player" in self.root_tag["Data"]: self.players.append("Player") self.preloadDimensions() # --- Load, save, create --- def _create(self, filename, random_seed, last_played): # create a new level root_tag = nbt.TAG_Compound() root_tag["Data"] = nbt.TAG_Compound() root_tag["Data"]["SpawnX"] = nbt.TAG_Int(0) root_tag["Data"]["SpawnY"] = nbt.TAG_Int(2) root_tag["Data"]["SpawnZ"] = nbt.TAG_Int(0) if last_played is None: last_played = long(time.time() * 1000) if random_seed is None: random_seed = long(random.random() * 0xffffffffffffffffL) - 0x8000000000000000L self.root_tag = root_tag root_tag["Data"]['version'] = nbt.TAG_Int(self.VERSION_ANVIL) self.LastPlayed = long(last_played) self.RandomSeed = long(random_seed) self.SizeOnDisk = 0 self.Time = 1 self.DayTime = 1 self.LevelName = os.path.basename(self.worldFolder.filename) # ## if singleplayer: self.createPlayer("Player") def acquireSessionLock(self): lock_file = self.worldFolder.getFilePath("session.lock") self.initTime = int(time.time() * 1000) with file(lock_file, "wb") as f: f.write(struct.pack(">q", self.initTime)) f.flush() os.fsync(f.fileno()) for function in self.lockAcquireFuncs: function() def setSessionLockCallback(self, acquire_func, lose_func): self.lockAcquireFuncs.append(acquire_func) self.lockLoseFuncs.append(lose_func) def checkSessionLock(self): if self.readonly: raise SessionLockLost("World is opened read only.") lockfile = self.worldFolder.getFilePath("session.lock") try: (lock, ) = struct.unpack(">q", file(lockfile, "rb").read()) except struct.error: lock = -1 if lock != self.initTime: for func in self.lockLoseFuncs: func() raise SessionLockLost("Session lock lost. This world is being accessed from another location.") def loadLevelDat(self, create=False, random_seed=None, last_played=None): dat_name = self.dat_name if create: self._create(self.filename, random_seed, last_played) self.saveInPlace() else: try: self.root_tag = nbt.load(self.filename) # Load the resource for the game version if self.gamePlatform != 'Unknown': # Force the definitions to be loaded by calling the attribute. self.loadDefIds() # except Exception as e: filename_old = self.worldFolder.getFilePath("%s.dat_old"%dat_name) log.info("Error loading {1}.dat, trying {1}.dat_old ({0})".format(e, dat_name)) try: self.root_tag = nbt.load(filename_old) log.info("%s.dat restored from backup."%dat_name) self.saveInPlace() except Exception as e: traceback.print_exc() print repr(e) log.info("Error loading %s.dat_old. Initializing with defaults."%dat_name) self._create(self.filename, random_seed, last_played) if self.root_tag.get('Data', nbt.TAG_Compound()).get('Version', nbt.TAG_Compound()).get('Id', nbt.TAG_Int(-1)).value > 1451: raise NotImplementedError("Java 1.13 format worlds are not supported at this time") def saveInPlaceGen(self): if self.readonly: raise IOError("World is opened read only. (%s)"%self.filename) self.saving = True self.checkSessionLock() for level in self.dimensions.itervalues(): for _ in MCInfdevOldLevel.saveInPlaceGen(level): yield dirtyChunkCount = 0 for chunk in self._loadedChunkData.itervalues(): cx, cz = chunk.chunkPosition if chunk.dirty: data = chunk.savedTagData() dirtyChunkCount += 1 self.worldFolder.saveChunk(cx, cz, data) chunk.dirty = False yield for cx, cz in self.unsavedWorkFolder.listChunks(): if (cx, cz) not in self._loadedChunkData: data = self.unsavedWorkFolder.readChunk(cx, cz) self.worldFolder.saveChunk(cx, cz, data) dirtyChunkCount += 1 yield self.unsavedWorkFolder.closeRegions() shutil.rmtree(self.unsavedWorkFolder.filename, True) if not os.path.exists(self.unsavedWorkFolder.filename): os.mkdir(self.unsavedWorkFolder.filename) for path, tag in self.playerTagCache.iteritems(): tag.save(path) if self.playersFolder is not None: for file_ in os.listdir(self.playersFolder): if file_.endswith(".dat") and file_[:-4] not in self.players: os.remove(os.path.join(self.playersFolder, file_)) self.playerTagCache.clear() self.root_tag.save(self.filename) self.saving = False log.info(u"Saved {0} chunks (dim {1})".format(dirtyChunkCount, self.dimNo)) def unload(self): """ Unload all chunks and close all open filehandles. """ if self.saving: raise ChunkAccessDenied self.worldFolder.closeRegions() if not self.readonly: self.unsavedWorkFolder.closeRegions() self._allChunks = None self.recentChunks.clear() self._loadedChunks.clear() self._loadedChunkData.clear() def close(self): """ Unload all chunks and close all open filehandles. Discard any unsaved data. """ self.unload() try: self.checkSessionLock() shutil.rmtree(self.unsavedWorkFolder.filename, True) shutil.rmtree(self.fileEditsFolder.filename, True) except SessionLockLost: pass # --- Resource limits --- loadedChunkLimit = 400 # --- Constants --- GAMETYPE_SURVIVAL = 0 GAMETYPE_CREATIVE = 1 VERSION_MCR = 19132 VERSION_ANVIL = 19133 # --- Instance variables --- materials = alphaMaterials isInfinite = True parentWorld = None dimNo = 0 Height = 256 _bounds = None # --- NBT Tag variables --- SizeOnDisk = TagProperty('SizeOnDisk', nbt.TAG_Long, 0) RandomSeed = TagProperty('RandomSeed', nbt.TAG_Long, 0) Time = TagProperty('Time', nbt.TAG_Long, 0) # Age of the world in ticks. 20 ticks per second; 24000 ticks per day. DayTime = TagProperty('DayTime', nbt.TAG_Long, 0) LastPlayed = TagProperty('LastPlayed', nbt.TAG_Long, lambda self: long(time.time() * 1000)) LevelName = TagProperty('LevelName', nbt.TAG_String, lambda self: self.displayName) GeneratorName = TagProperty('generatorName', nbt.TAG_String, 'default') MapFeatures = TagProperty('MapFeatures', nbt.TAG_Byte, 1) GameType = TagProperty('GameType', nbt.TAG_Int, 0) # 0 for survival, 1 for creative version = TagProperty('version', nbt.TAG_Int, VERSION_ANVIL) # --- World info --- def __str__(self): return "MCInfdevOldLevel(\"%s\")" % os.path.basename(self.worldFolder.filename) @property def displayName(self): # shortname = os.path.basename(self.filename) # if shortname == "level.dat": shortname = os.path.basename(os.path.dirname(self.filename)) return shortname def init_scoreboard(self): ''' Creates a scoreboard for the world :return: A scoreboard :rtype: pymclevel.nbt.TAG_Compound() ''' if os.path.exists(self.worldFolder.getFolderPath("data")): if os.path.exists(self.worldFolder.getFolderPath("data")+"/scoreboard.dat"): return nbt.load(self.worldFolder.getFolderPath("data")+"/scoreboard.dat") else: root_tag = nbt.TAG_Compound() root_tag["data"] = nbt.TAG_Compound() root_tag["data"]["Objectives"] = nbt.TAG_List() root_tag["data"]["PlayerScores"] = nbt.TAG_List() root_tag["data"]["Teams"] = nbt.TAG_List() root_tag["data"]["DisplaySlots"] = nbt.TAG_List() self.save_scoreboard(root_tag) return root_tag else: self.worldFolder.getFolderPath("data") root_tag = nbt.TAG_Compound() root_tag["data"] = nbt.TAG_Compound() root_tag["data"]["Objectives"] = nbt.TAG_List() root_tag["data"]["PlayerScores"] = nbt.TAG_List() root_tag["data"]["Teams"] = nbt.TAG_List() root_tag["data"]["DisplaySlots"] = nbt.TAG_List() self.save_scoreboard(root_tag) return root_tag def save_scoreboard(self, score): ''' Saves the provided scoreboard :param score: The scoreboard :type score: pymclevel.nbt.TAG_Compound() ''' score.save(self.worldFolder.getFolderPath("data")+"/scoreboard.dat") def init_player_data(self): dat_name = self.dat_name player_data = {} if self.oldPlayerFolderFormat: for p in self.players: if p != "Player": player_data_file = os.path.join(self.worldFolder.getFolderPath("players"), p+".dat") player_data[p] = nbt.load(player_data_file) else: data = nbt.load(self.worldFolder.getFilePath("%s.dat"%dat_name)) player_data[p] = data["Data"]["Player"] else: for p in self.players: if p != "Player": player_data_file = os.path.join(self.worldFolder.getFolderPath("playerdata"), p+".dat") player_data[p] = nbt.load(player_data_file) else: data = nbt.load(self.worldFolder.getFilePath("%s.dat"%dat_name)) player_data[p] = data["Data"]["Player"] #player_data = [] #for p in [x for x in os.listdir(self.playersFolder) if x.endswith(".dat")]: #player_data.append(player.Player(self.playersFolder+"\\"+p)) return player_data def save_player_data(self, player_data): if self.oldPlayerFolderFormat: for p in player_data.keys(): if p != "Player": player_data[p].save(os.path.join(self.worldFolder.getFolderPath("players"), p+".dat")) else: for p in player_data.keys(): if p != "Player": player_data[p].save(os.path.join(self.worldFolder.getFolderPath("playerdata"), p+".dat")) @property def bounds(self): if self._bounds is None: self._bounds = self.getWorldBounds() return self._bounds def getWorldBounds(self): if self.chunkCount == 0: return BoundingBox((0, 0, 0), (0, 0, 0)) allChunks = array(list(self.allChunks)) mincx = (allChunks[:, 0]).min() maxcx = (allChunks[:, 0]).max() mincz = (allChunks[:, 1]).min() maxcz = (allChunks[:, 1]).max() origin = (mincx << 4, 0, mincz << 4) size = ((maxcx - mincx + 1) << 4, self.Height, (maxcz - mincz + 1) << 4) return BoundingBox(origin, size) @property def size(self): return self.bounds.size # --- Format detection --- @classmethod def _isLevel(cls, filename): if os.path.exists(os.path.join(filename, "chunks.dat")) or os.path.exists(os.path.join(filename, "db")): return False # exclude Pocket Edition folders if not os.path.isdir(filename): f = os.path.basename(filename) if f not in ("level.dat", "level.dat_old"): return False filename = os.path.dirname(filename) files = os.listdir(filename) if "db" in files: return False if "level.dat" in files or "level.dat_old" in files: return True return False # --- Dimensions --- def preloadDimensions(self): worldDirs = os.listdir(self.worldFolder.filename) for dirname in worldDirs: if dirname.startswith("DIM"): try: dimNo = int(dirname[3:]) log.info("Found dimension {0}".format(dirname)) dim = MCAlphaDimension(self, dimNo) self.dimensions[dimNo] = dim except Exception as e: log.error(u"Error loading dimension {0}: {1}".format(dirname, e)) def getDimension(self, dimNo): if self.dimNo != 0: return self.parentWorld.getDimension(dimNo) if dimNo in self.dimensions: return self.dimensions[dimNo] dim = MCAlphaDimension(self, dimNo, create=True) self.dimensions[dimNo] = dim return dim # --- Region I/O --- def preloadChunkPositions(self): log.info(u"Scanning for regions...") self._allChunks = self.worldFolder.listChunks() if not self.readonly: self._allChunks.update(self.unsavedWorkFolder.listChunks()) self._allChunks.update(self._loadedChunkData.iterkeys()) def getRegionForChunk(self, cx, cz): return self.worldFolder.getRegionForChunk(cx, cz) # --- Chunk I/O --- def dirhash(self, n): return self.dirhashes[n % 64] def _dirhash(self): n = self n %= 64 s = u"" if n >= 36: s += u"1" n -= 36 s += u"0123456789abcdefghijklmnopqrstuvwxyz"[n] return s dirhashes = [_dirhash(n) for n in xrange(64)] def _oldChunkFilename(self, cx, cz): return self.worldFolder.getFilePath( "%s/%s/c.%s.%s.dat" % (self.dirhash(cx), self.dirhash(cz), base36(cx), base36(cz))) def extractChunksInBox(self, box, parentFolder): for cx, cz in box.chunkPositions: if self.containsChunk(cx, cz): self.extractChunk(cx, cz, parentFolder) def extractChunk(self, cx, cz, parentFolder): if not os.path.exists(parentFolder): os.mkdir(parentFolder) chunkFilename = self._oldChunkFilename(cx, cz) outputFile = os.path.join(parentFolder, os.path.basename(chunkFilename)) chunk = self.getChunk(cx, cz) chunk.root_tag.save(outputFile) @property def chunkCount(self): """Returns the number of chunks in the level. May initiate a costly chunk scan.""" if self._allChunks is None: self.preloadChunkPositions() return len(self._allChunks) @property def allChunks(self): """Iterates over (xPos, zPos) tuples, one for each chunk in the level. May initiate a costly chunk scan.""" if self._allChunks is None: self.preloadChunkPositions() return self._allChunks.__iter__() def copyChunkFrom(self, world, cx, cz): """ Copy a chunk from world into the same chunk position in self. """ assert isinstance(world, MCInfdevOldLevel) if self.readonly: raise IOError("World is opened read only.") if world.saving | self.saving: raise ChunkAccessDenied self.checkSessionLock() destChunk = self._loadedChunks.get((cx, cz)) sourceChunk = world._loadedChunks.get((cx, cz)) if sourceChunk: if destChunk: log.debug("Both chunks loaded. Using block copy.") # Both chunks loaded. Use block copy. self.copyBlocksFrom(world, destChunk.bounds, destChunk.bounds.origin) return else: log.debug("Source chunk loaded. Saving into work folder.") # Only source chunk loaded. Discard destination chunk and save source chunk in its place. self._loadedChunkData.pop((cx, cz), None) self.unsavedWorkFolder.saveChunk(cx, cz, sourceChunk.savedTagData()) return else: if destChunk: log.debug("Destination chunk loaded. Using block copy.") # Only destination chunk loaded. Use block copy. self.copyBlocksFrom(world, destChunk.bounds, destChunk.bounds.origin) else: log.debug("No chunk loaded. Using world folder.copyChunkFrom") # Neither chunk loaded. Copy via world folders. self._loadedChunkData.pop((cx, cz), None) # If the source chunk is dirty, write it to the work folder. chunkData = world._loadedChunkData.pop((cx, cz), None) if chunkData and chunkData.dirty: data = chunkData.savedTagData() world.unsavedWorkFolder.saveChunk(cx, cz, data) if world.unsavedWorkFolder.containsChunk(cx, cz): sourceFolder = world.unsavedWorkFolder else: sourceFolder = world.worldFolder self.unsavedWorkFolder.copyChunkFrom(sourceFolder, cx, cz) def _getChunkBytes(self, cx, cz): if not self.readonly and self.unsavedWorkFolder.containsChunk(cx, cz): return self.unsavedWorkFolder.readChunk(cx, cz) else: return self.worldFolder.readChunk(cx, cz) def _getChunkData(self, cx, cz): chunkData = self._loadedChunkData.get((cx, cz)) if chunkData is not None: return chunkData if self.saving: raise ChunkAccessDenied try: data = self._getChunkBytes(cx, cz) root_tag = nbt.load(buf=data) chunkData = AnvilChunkData(self, (cx, cz), root_tag) except (MemoryError, ChunkNotPresent): raise except Exception as e: raise ChunkMalformed("Chunk {0} had an error: {1!r}".format((cx, cz), e), sys.exc_info()[2]) if not self.readonly and self.unsavedWorkFolder.containsChunk(cx, cz): chunkData.dirty = True self._storeLoadedChunkData(chunkData) return chunkData def _storeLoadedChunkData(self, chunkData): if len(self._loadedChunkData) > self.loadedChunkLimit: # Try to find a chunk to unload. The chunk must not be in _loadedChunks, which contains only chunks that # are in use by another object. If the chunk is dirty, save it to the temporary folder. if not self.readonly: self.checkSessionLock() for (ocx, ocz), oldChunkData in self._loadedChunkData.items(): if (ocx, ocz) not in self._loadedChunks: if oldChunkData.dirty and not self.readonly: data = oldChunkData.savedTagData() self.unsavedWorkFolder.saveChunk(ocx, ocz, data) del self._loadedChunkData[ocx, ocz] break self._loadedChunkData[chunkData.chunkPosition] = chunkData def getChunk(self, cx, cz): ''' Read the chunk from disk, load it, and then return it :param cx: The X coordinate of the Chunk :type cx: int :param cz: The Z coordinate of the Chunk :type cz: int :rtype: pymclevel.infiniteworld.AnvilChunk ''' chunk = self._loadedChunks.get((cx, cz)) if chunk is not None: return chunk chunkData = self._getChunkData(cx, cz) chunk = AnvilChunk(chunkData) self._loadedChunks[cx, cz] = chunk self.recentChunks.append(chunk) return chunk def markDirtyChunk(self, cx, cz): self.getChunk(cx, cz).chunkChanged() def markDirtyBox(self, box): for cx, cz in box.chunkPositions: self.markDirtyChunk(cx, cz) def listDirtyChunks(self): for cPos, chunkData in self._loadedChunkData.iteritems(): if chunkData.dirty: yield cPos # --- HeightMaps --- def heightMapAt(self, x, z): zc = z >> 4 xc = x >> 4 xInChunk = x & 0xf zInChunk = z & 0xf ch = self.getChunk(xc, zc) heightMap = ch.HeightMap return heightMap[zInChunk, xInChunk] # HeightMap indices are backwards # --- Biome manipulation --- def biomeAt(self, x, z): ''' Gets the biome of the block at the specified coordinates. Since biomes are for the entire column at the coordinate, the Y coordinate wouldn't change the result :param x: The X block coordinate :type x: int :param z: The Z block coordinate :type z: int :rtype: int ''' biomes = self.getChunk(int(x/16),int(z/16)).root_tag["Level"]["Biomes"].value xChunk = int(x/16) * 16 zChunk = int(z/16) * 16 return int(biomes[(z - zChunk) * 16 + (x - xChunk)]) def setBiomeAt(self, x, z, biomeID): ''' Sets the biome data for the Y column at the specified X and Z coordinates :param x: The X block coordinate :type x: int :param z: The Z block coordinate :type z: int :param biomeID: The wanted biome ID :type biomeID: int ''' biomes = self.getChunk(int(x/16), int(z/16)).root_tag["Level"]["Biomes"].value xChunk = int(x/16) * 16 zChunk = int(z/16) * 16 biomes[(z - zChunk) * 16 + (x - xChunk)] = biomeID # --- Entities and TileEntities --- def addEntity(self, entityTag): ''' Adds an Entity to the level and sets its position to the values of the 'Pos' tag :param entityTag: The NBT data of the Entity :type entityTag: pymclevel.nbt.TAG_Compound ''' assert isinstance(entityTag, nbt.TAG_Compound) x, y, z = map(lambda x: int(floor(x)), Entity.pos(entityTag)) try: chunk = self.getChunk(x >> 4, z >> 4) except (ChunkNotPresent, ChunkMalformed): return None # raise Error, can't find a chunk? chunk.addEntity(entityTag) chunk.dirty = True def tileEntityAt(self, x, y, z): ''' Gets the TileEntity at the specified X, Y, and Z block coordinates :param x: The X block coordinate :type x: int :param y: The Y block coordinate :type y: int :param z: The Z block coordinate :type z: int :rtype: pymclevel.nbt.TAG_Compound ''' chunk = self.getChunk(x >> 4, z >> 4) return chunk.tileEntityAt(x, y, z) def addTileEntity(self, tileEntityTag): ''' Adds an TileEntity to the level and sets its position to the values of the X, Y, and Z tags :param tileEntityTag: The NBT data of the TileEntity :type tileEntityTag: pymclevel.nbt.TAG_Compound ''' assert isinstance(tileEntityTag, nbt.TAG_Compound) if 'x' not in tileEntityTag: return x, y, z = TileEntity.pos(tileEntityTag) try: chunk = self.getChunk(x >> 4, z >> 4) except (ChunkNotPresent, ChunkMalformed): return # raise Error, can't find a chunk? chunk.addTileEntity(tileEntityTag) chunk.dirty = True def addTileTick(self, tickTag): ''' Adds an TileTick to the level and sets its position to the values of the X, Y, and Z tags :param tickTag: The NBT data of the TileTick :type tickTag: pymclevel.nbt.TAG_Compound ''' assert isinstance(tickTag, nbt.TAG_Compound) if 'x' not in tickTag: return x, y, z = TileTick.pos(tickTag) try: chunk = self.getChunk(x >> 4,z >> 4) except(ChunkNotPresent, ChunkMalformed): return chunk.addTileTick(tickTag) chunk.dirty = True def getEntitiesInBox(self, box): ''' Get all of the Entities in the specified box :param box: The box to search for Entities in :type box: pymclevel.box.BoundingBox :return: A list of all the Entity tags in the box :rtype: list ''' entities = [] for chunk, slices, point in self.getChunkSlices(box): entities += chunk.getEntitiesInBox(box) return entities def getTileEntitiesInBox(self, box): ''' Get all of the TileEntities in the specified box :param box: The box to search for TileEntities in :type box: pymclevel.box.BoundingBox :return: A list of all the TileEntity tags in the box :rtype: list ''' tileEntites = [] for chunk, slices, point in self.getChunkSlices(box): tileEntites += chunk.getTileEntitiesInBox(box) return tileEntites def getTileTicksInBox(self, box): ''' Get all of the TileTicks in the specified box :param box: The box to search for TileTicks in :type box: pymclevel.box.BoundingBox :return: A list of all the TileTick tags in the box :rtype: list ''' tileticks = [] for chunk, slices, point in self.getChunkSlices(box): tileticks += chunk.getTileTicksInBox(box) return tileticks def removeEntitiesInBox(self, box): ''' Removes all of the Entities in the specified box :param box: The box to remove all Entities from :type box: pymclevel.box.BoundingBox :return: The number of Entities removed :rtype: int ''' count = 0 for chunk, slices, point in self.getChunkSlices(box): count += chunk.removeEntitiesInBox(box) log.info("Removed {0} entities".format(count)) return count def removeTileEntitiesInBox(self, box): ''' Removes all of the TileEntities in the specified box :param box: The box to remove all TileEntities from :type box: pymclevel.box.BoundingBox :return: The number of TileEntities removed :rtype: int ''' count = 0 for chunk, slices, point in self.getChunkSlices(box): count += chunk.removeTileEntitiesInBox(box) log.info("Removed {0} tile entities".format(count)) return count def removeTileTicksInBox(self, box): ''' Removes all of the TileTicks in the specified box :param box: The box to remove all TileTicks from :type box: pymclevel.box.BoundingBox :return: The number of TileTicks removed :rtype: int ''' count = 0 for chunk, slices, point in self.getChunkSlices(box): count += chunk.removeTileTicksInBox(box) log.info("Removed {0} tile ticks".format(count)) return count # --- Chunk manipulation --- def containsChunk(self, cx, cz): ''' Checks if the specified chunk exists/has been generated :param cx: The X coordinate of the chunk :type cx: int :param cz: The Z coordinate of the chunk :type cz: int :return: True if the chunk exists/has been generated, False otherwise :rtype: bool ''' if self._allChunks is not None: return (cx, cz) in self._allChunks if (cx, cz) in self._loadedChunkData: return True return self.worldFolder.containsChunk(cx, cz) def containsPoint(self, x, y, z): ''' Checks if the specified X, Y, Z coordinate has been generated :param x: The X coordinate :type x: int :param y: The Y coordinate :type y: int :param z: The Z coordinate :type z: int :return: True if the point exists/has been generated, False otherwise :rtype: bool ''' if y < 0 or y > self.Height: return False return self.containsChunk(x >> 4, z >> 4) def createChunk(self, cx, cz): ''' Creates a chunk at the specified chunk coordinates if it doesn't exist already :param cx: The X coordinate of the chunk :type cx: int :param cz: The Z coordinate of the chunk :type cz: int :raises ValueError: Raise when a chunk is already present/generated at the specified X and Z coordinates ''' if self.containsChunk(cx, cz): raise ValueError("{0}:Chunk {1} already present!".format(self, (cx, cz))) if self._allChunks is not None: self._allChunks.add((cx, cz)) self._storeLoadedChunkData(AnvilChunkData(self, (cx, cz), create=True)) self._bounds = None def createChunks(self, chunks): ''' Creates multiple chunks specified by a list of chunk X and Z coordinate tuples :param chunks: A list of chunk X and Z coordinates in tuple form [(cx, cz), (cx, cz)...] :type chunks: list :return: A list of the chunk coordinates that were created, doesn't include coordinates of ones already present :rtype: list ''' i = 0 ret = [] append = ret.append for cx, cz in chunks: i += 1 if not self.containsChunk(cx, cz): append((cx, cz)) self.createChunk(cx, cz) assert self.containsChunk(cx, cz), "Just created {0} but it didn't take".format((cx, cz)) if i % 100 == 0: log.info(u"Chunk {0}...".format(i)) log.info("Created {0} chunks.".format(len(ret))) return ret def createChunksInBox(self, box): ''' Creates all chunks that would be present in the box :param box: The box to generate chunks in :type box: pymclevel.box.BoundingBox :return: A list of the chunk coordinates that were created, doesn't include coordinates of ones already present :rtype: list ''' log.info(u"Creating {0} chunks in {1}".format((box.maxcx - box.mincx) * (box.maxcz - box.mincz), ((box.mincx, box.mincz), (box.maxcx, box.maxcz)))) return self.createChunks(box.chunkPositions) def deleteChunk(self, cx, cz): ''' Deletes the chunk at the specified chunk coordinates :param cx: The X coordinate of the chunk :type cx: int :param cz: The Z coordinate of the chunk :type cz: int ''' self.worldFolder.deleteChunk(cx, cz) if self._allChunks is not None: self._allChunks.discard((cx, cz)) self._bounds = None def deleteChunksInBox(self, box): ''' Deletes all of the chunks in the specified box :param box: The box of chunks to remove :type box: pymclevel.box.BoundingBox :return: A list of the chunk coordinates of the chunks that were deleted :rtype: list ''' log.info(u"Deleting {0} chunks in {1}".format((box.maxcx - box.mincx) * (box.maxcz - box.mincz), ((box.mincx, box.mincz), (box.maxcx, box.maxcz)))) i = 0 ret = [] append = ret.append for cx, cz in itertools.product(xrange(box.mincx, box.maxcx), xrange(box.mincz, box.maxcz)): i += 1 if self.containsChunk(cx, cz): self.deleteChunk(cx, cz) append((cx, cz)) assert not self.containsChunk(cx, cz), "Just deleted {0} but it didn't take".format((cx, cz)) if i % 100 == 0: log.info(u"Chunk {0}...".format(i)) return ret # --- Player and spawn manipulation --- def playerSpawnPosition(self, player=None): """ xxx if player is None then it gets the default spawn position for the world if player hasn't used a bed then it gets the default spawn position """ dataTag = self.root_tag["Data"] if player is None: playerSpawnTag = dataTag else: playerSpawnTag = self.getPlayerTag(player) return [playerSpawnTag.get(i, dataTag[i]).value for i in ("SpawnX", "SpawnY", "SpawnZ")] def setPlayerSpawnPosition(self, pos, player=None): """ xxx if player is None then it sets the default spawn position for the world """ if player is None: playerSpawnTag = self.root_tag["Data"] else: playerSpawnTag = self.getPlayerTag(player) for name, val in zip(("SpawnX", "SpawnY", "SpawnZ"), pos): playerSpawnTag[name] = nbt.TAG_Int(val) def getPlayerPath(self, player, dim=0): ''' Gets the file path to the player file :param player: The UUID of the player :type player: str :param dim: The dimension that the player resides in :type dim: int :return: The file path to the player data file :rtype: str ''' assert player != "Player" if dim != 0: return os.path.join(os.path.dirname(self.level.filename), "DIM%s" % dim, "playerdata", "%s.dat" % player) else: return os.path.join(self.playersFolder, "%s.dat" % player) def getPlayerTag(self, player="Player"): ''' Gets the NBT data for the specified player :param player: The UUID of the player :type player: str :return: The NBT data for the player :rtype: pymclevel.nbt.TAG_Compound ''' if player == "Player": if player in self.root_tag["Data"]: # single-player world return self.root_tag["Data"]["Player"] raise PlayerNotFound(player) else: playerFilePath = self.getPlayerPath(player) playerTag = self.playerTagCache.get(playerFilePath) if playerTag is None: if os.path.exists(playerFilePath): playerTag = nbt.load(playerFilePath) self.playerTagCache[playerFilePath] = playerTag else: raise PlayerNotFound(player) return playerTag def getPlayerDimension(self, player="Player"): ''' Gets the dimension that the specified player is currently in :param player: The UUID of the player :type player: str :return: The dimension the player is currently in :rtype: int ''' playerTag = self.getPlayerTag(player) if "Dimension" not in playerTag: return 0 return playerTag["Dimension"].value def setPlayerDimension(self, d, player="Player"): ''' Sets the player's current dimension :param d: The desired dimension (0 for Overworld, -1 for Nether, 1 for The End) :type d: int :param player: The UUID of the player :type player: str ''' playerTag = self.getPlayerTag(player) if "Dimension" not in playerTag: playerTag["Dimension"] = nbt.TAG_Int(0) playerTag["Dimension"].value = d def setPlayerPosition(self, (x, y, z), player="Player"): ''' Sets the specified player's position :param x: The desired X coordinate :type x: float :param y: The desired Y coordinate :type y: float :param z: The desired Z coordinate :type z: float :param player: The UUID of the player :type player: str ''' posList = nbt.TAG_List([nbt.TAG_Double(p) for p in (x, y - 1.75, z)]) playerTag = self.getPlayerTag(player) playerTag["Pos"] = posList def getPlayerPosition(self, player="Player"): ''' Gets the position for the specified player :param player: The UUID of the player :type player: str :return: The X, Y, Z coordinates of the player :rtype: tuple ''' playerTag = self.getPlayerTag(player) posList = playerTag["Pos"] x, y, z = map(lambda x: x.value, posList) return x, y + 1.75, z def setPlayerOrientation(self, yp, player="Player"): ''' Sets the specified player's orientation :param yp: The desired Yaw and Pitch :type yp: tuple or list :param player: The UUID of the player :type player: str ''' self.getPlayerTag(player)["Rotation"] = nbt.TAG_List([nbt.TAG_Float(p) for p in yp]) def getPlayerOrientation(self, player="Player"): ''' Gets the orientation of the specified player :param player: The UUID of the player :type player: str :return: The orientation of the player in the format: (yaw, pitch) :rtype: numpy.array ''' yp = map(lambda x: x.value, self.getPlayerTag(player)["Rotation"]) y, p = yp if p == 0: p = 0.000000001 if p == 180.0: p -= 0.000000001 yp = y, p return array(yp) def setPlayerAbilities(self, gametype, player="Player"): playerTag = self.getPlayerTag(player) # Check for the Abilities tag. It will be missing in worlds from before # Beta 1.9 Prerelease 5. if 'abilities' not in playerTag: playerTag['abilities'] = nbt.TAG_Compound() # Assumes creative (1) is the only mode with these abilities set, # which is true for now. Future game modes may not hold this to be # true, however. if gametype == 1: playerTag['abilities']['instabuild'] = nbt.TAG_Byte(1) playerTag['abilities']['mayfly'] = nbt.TAG_Byte(1) playerTag['abilities']['invulnerable'] = nbt.TAG_Byte(1) else: playerTag['abilities']['flying'] = nbt.TAG_Byte(0) playerTag['abilities']['instabuild'] = nbt.TAG_Byte(0) playerTag['abilities']['mayfly'] = nbt.TAG_Byte(0) playerTag['abilities']['invulnerable'] = nbt.TAG_Byte(0) def setPlayerGameType(self, gametype, player="Player"): ''' Sets the specified player's gametype/gamemode :param gametype: The desired Gametype/Gamemode number :type gametype: int :param player: The UUID of the player :type player: str ''' playerTag = self.getPlayerTag(player) # This annoyingly works differently between single- and multi-player. if player == "Player": self.GameType = gametype self.setPlayerAbilities(gametype, player) else: playerTag['playerGameType'] = nbt.TAG_Int(gametype) self.setPlayerAbilities(gametype, player) def getPlayerGameType(self, player="Player"): ''' Gets the Gamemode of the specified player :param player: The UUID of the player :type player: str :return: The Gamemode number :rtype: int ''' if player == "Player": return self.GameType else: playerTag = self.getPlayerTag(player) return playerTag["playerGameType"].value def createPlayer(self, playerName): ''' ~Deprecated~ Creates a player with default values :param playerName: The name of the player :type playerName: str ''' if playerName == "Player": playerTag = self.root_tag["Data"].setdefault(playerName, nbt.TAG_Compound()) else: playerTag = nbt.TAG_Compound() playerTag['Air'] = nbt.TAG_Short(300) playerTag['AttackTime'] = nbt.TAG_Short(0) playerTag['DeathTime'] = nbt.TAG_Short(0) playerTag['Fire'] = nbt.TAG_Short(-20) playerTag['Health'] = nbt.TAG_Short(20) playerTag['HurtTime'] = nbt.TAG_Short(0) playerTag['Score'] = nbt.TAG_Int(0) playerTag['FallDistance'] = nbt.TAG_Float(0) playerTag['OnGround'] = nbt.TAG_Byte(0) playerTag["Inventory"] = nbt.TAG_List() playerTag['Motion'] = nbt.TAG_List([nbt.TAG_Double(0) for i in xrange(3)]) playerTag['Pos'] = nbt.TAG_List([nbt.TAG_Double([0.5, 2.8, 0.5][i]) for i in xrange(3)]) playerTag['Rotation'] = nbt.TAG_List([nbt.TAG_Float(0), nbt.TAG_Float(0)]) if playerName != "Player": self.playerTagCache[self.getPlayerPath(playerName)] = playerTag class MCAlphaDimension(MCInfdevOldLevel): def __init__(self, parentWorld, dimNo, create=False): filename = parentWorld.worldFolder.getFolderPath("DIM" + str(int(dimNo))) self.parentWorld = parentWorld MCInfdevOldLevel.__init__(self, filename, create) self.dimNo = dimNo self.filename = parentWorld.filename self.players = self.parentWorld.players self.playersFolder = self.parentWorld.playersFolder self.playerTagCache = self.parentWorld.playerTagCache @property def root_tag(self): return self.parentWorld.root_tag def __str__(self): return u"MCAlphaDimension({0}, {1})".format(self.parentWorld, self.dimNo) def loadLevelDat(self, create=False, random_seed=None, last_played=None): pass def preloadDimensions(self): pass def _create(self, *args, **kw): pass def acquireSessionLock(self): pass def checkSessionLock(self): self.parentWorld.checkSessionLock() dimensionNames = {-1: "Nether", 1: "The End"} @property def displayName(self): return u"{0} ({1})".format(self.parentWorld.displayName, self.dimensionNames.get(self.dimNo, "Dimension %d" % self.dimNo)) def saveInPlace(self, saveSelf=False): """saving the dimension will save the parent world, which will save any other dimensions that need saving. the intent is that all of them can stay loaded at once for fast switching """ if saveSelf: MCInfdevOldLevel.saveInPlace(self) else: self.parentWorld.saveInPlace()
83,854
33.954148
153
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/javalevel.py
''' Created on Jul 22, 2011 @author: Rio ''' __all__ = ["MCJavaLevel"] from cStringIO import StringIO import gzip from level import MCLevel from logging import getLogger from numpy import fromstring import os import re log = getLogger(__name__) class MCJavaLevel(MCLevel): _gamePlatform = 'javalevel' def setBlockDataAt(self, *args): pass def blockDataAt(self, *args): return 0 @property def Height(self): return self.Blocks.shape[2] @property def Length(self): return self.Blocks.shape[1] @property def Width(self): return self.Blocks.shape[0] @staticmethod def guessSize(data): Width = 64 Length = 64 Height = 64 if data.shape[0] <= (32 * 32 * 64) * 2: log.warn(u"Can't guess the size of a {0} byte level".format(data.shape[0])) raise IOError("MCJavaLevel attempted for smaller than 64 blocks cubed") if data.shape[0] > (64 * 64 * 64) * 2: Width = 128 Length = 128 Height = 64 if data.shape[0] > (128 * 128 * 64) * 2: Width = 256 Length = 256 Height = 64 if data.shape[0] > (256 * 256 * 64) * 2: # could also be 256*256*256 Width = 512 Length = 512 Height = 64 if data.shape[0] > 512 * 512 * 64 * 2: # just to load shadowmarch castle Width = 512 Length = 512 Height = 256 return Width, Length, Height @classmethod def _isDataLevel(cls, data): return (data[0] == 0x27 and data[1] == 0x1B and data[2] == 0xb7 and data[3] == 0x88) def __init__(self, filename, data): self.filename = filename if isinstance(data, basestring): data = fromstring(data, dtype='uint8') self.filedata = data # try to take x,z,y from the filename r = re.findall("\d+", os.path.basename(filename)) if r and len(r) >= 3: (w, l, h) = map(int, r[-3:]) if w * l * h > data.shape[0]: log.info("Not enough blocks for size " + str((w, l, h))) w, l, h = self.guessSize(data) else: w, l, h = self.guessSize(data) log.info(u"MCJavaLevel created for potential level of size " + str((w, l, h))) blockCount = h * l * w if blockCount > data.shape[0]: raise ValueError( "Level file does not contain enough blocks! (size {s}) Try putting the size into the filename, e.g. server_level_{w}_{l}_{h}.dat".format( w=w, l=l, h=h, s=data.shape)) blockOffset = data.shape[0] - blockCount blocks = data[blockOffset:blockOffset + blockCount] maxBlockType = 64 # maximum allowed in classic while max(blocks[-4096:]) > maxBlockType: # guess the block array by starting at the end of the file # and sliding the blockCount-sized window back until it # looks like every block has a valid blockNumber blockOffset -= 1 blocks = data[blockOffset:blockOffset + blockCount] if blockOffset <= -data.shape[0]: raise IOError("Can't find a valid array of blocks <= #%d" % maxBlockType) self.Blocks = blocks self.blockOffset = blockOffset blocks.shape = (w, l, h) blocks.strides = (1, w, w * l) def saveInPlaceGen(self): s = StringIO() g = gzip.GzipFile(fileobj=s, mode='wb') g.write(self.filedata.tostring()) g.flush() g.close() try: os.rename(self.filename, self.filename + ".old") except Exception: pass try: with open(self.filename, 'wb') as f: f.write(s.getvalue()) except Exception, e: log.info(u"Error while saving java level in place: {0}".format(e)) try: os.remove(self.filename) except: pass os.rename(self.filename + ".old", self.filename) try: os.remove(self.filename + ".old") except Exception: pass yield class MCSharpLevel(MCLevel): """ int magic = convert(data.readShort()) logger.trace("Magic number: {}", magic) if (magic != 1874) throw new IOException("Only version 1 MCSharp levels supported (magic number was "+magic+")") int width = convert(data.readShort()) int height = convert(data.readShort()) int depth = convert(data.readShort()) logger.trace("Width: {}", width) logger.trace("Depth: {}", depth) logger.trace("Height: {}", height) int spawnX = convert(data.readShort()) int spawnY = convert(data.readShort()) int spawnZ = convert(data.readShort()) int spawnRotation = data.readUnsignedByte() int spawnPitch = data.readUnsignedByte() int visitRanks = data.readUnsignedByte() int buildRanks = data.readUnsignedByte() byte[][][] blocks = new byte[width][height][depth] int i = 0 BlockManager manager = BlockManager.getBlockManager() for(int z = 0;z<depth;z++) { for(int y = 0;y<height;y++) { byte[] row = new byte[height] data.readFully(row) for(int x = 0;x<width;x++) { blocks[x][y][z] = translateBlock(row[x]) } } } lvl.setBlocks(blocks, new byte[width][height][depth], width, height, depth) lvl.setSpawnPosition(new Position(spawnX, spawnY, spawnZ)) lvl.setSpawnRotation(new Rotation(spawnRotation, spawnPitch)) lvl.setEnvironment(new Environment()) return lvl }"""
5,903
29.590674
153
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/block_copy.py
from datetime import datetime import logging log = logging.getLogger(__name__) import numpy from box import BoundingBox from mclevelbase import exhaust import materials from entity import Entity, TileEntity from copy import deepcopy def convertBlocks(destLevel, sourceLevel, blocks, blockData): return materials.convertBlocks(destLevel.materials, sourceLevel.materials, blocks, blockData) def sourceMaskFunc(blocksToCopy): if blocksToCopy is not None: typemask = numpy.zeros(materials.id_limit, dtype='bool') typemask[blocksToCopy] = 1 def maskedSourceMask(sourceBlocks): return typemask[sourceBlocks] return maskedSourceMask def unmaskedSourceMask(_sourceBlocks): return slice(None, None) return unmaskedSourceMask def adjustCopyParameters(destLevel, sourceLevel, sourceBox, destinationPoint): log.debug(u"Asked to copy {} blocks \n\tfrom {} in {}\n\tto {} in {}".format( sourceBox.volume, sourceBox, sourceLevel, destinationPoint, destLevel)) if destLevel.Width == 0: return sourceBox, destinationPoint destBox = BoundingBox(destinationPoint, sourceBox.size) actualDestBox = destBox.intersect(destLevel.bounds) actualSourceBox = BoundingBox(sourceBox.origin + actualDestBox.origin - destBox.origin, destBox.size) actualDestPoint = actualDestBox.origin return actualSourceBox, actualDestPoint def copyBlocksFromIter(destLevel, sourceLevel, sourceBox, destinationPoint, blocksToCopy=None, entities=True, create=False, biomes=False, tileTicks=True, staticCommands=False, moveSpawnerPos=False, regenerateUUID=False, first=False, cancelCommandBlockOffset=False): """ copy blocks between two infinite levels by looping through the destination's chunks. make a sub-box of the source level for each chunk and copy block and entities in the sub box to the dest chunk.""" (lx, ly, lz) = sourceBox.size sourceBox, destinationPoint = adjustCopyParameters(destLevel, sourceLevel, sourceBox, destinationPoint) # needs work xxx log.info(u"Copying {0} blocks from {1} to {2}".format(ly * lz * lx, sourceBox, destinationPoint)) startTime = datetime.now() destBox = BoundingBox(destinationPoint, sourceBox.size) chunkCount = destBox.chunkCount i = 0 e = 0 t = 0 tt = 0 sourceMask = sourceMaskFunc(blocksToCopy) copyOffset = [d - s for s, d in zip(sourceBox.origin, destinationPoint)] # Visit each chunk in the destination area. # Get the region of the source area corresponding to that chunk # Visit each chunk of the region of the source area # Get the slices of the destination chunk # Get the slices of the source chunk # Copy blocks and data for destCpos in destBox.chunkPositions: cx, cz = destCpos destChunkBox = BoundingBox((cx << 4, 0, cz << 4), (16, destLevel.Height, 16)).intersect(destBox) destChunkBoxInSourceLevel = BoundingBox([d - o for o, d in zip(copyOffset, destChunkBox.origin)], destChunkBox.size) if not destLevel.containsChunk(*destCpos): if create and any(sourceLevel.containsChunk(*c) for c in destChunkBoxInSourceLevel.chunkPositions): # Only create chunks in the destination level if the source level has chunks covering them. destLevel.createChunk(*destCpos) else: continue destChunk = destLevel.getChunk(*destCpos) i += 1 yield (i, chunkCount) if i % 100 == 0: log.info("Chunk {0}...".format(i)) for srcCpos in destChunkBoxInSourceLevel.chunkPositions: if not sourceLevel.containsChunk(*srcCpos): continue sourceChunk = sourceLevel.getChunk(*srcCpos) sourceChunkBox, sourceSlices = sourceChunk.getChunkSlicesForBox(destChunkBoxInSourceLevel) if sourceChunkBox.volume == 0: continue sourceChunkBoxInDestLevel = BoundingBox([d + o for o, d in zip(copyOffset, sourceChunkBox.origin)], sourceChunkBox.size) _, destSlices = destChunk.getChunkSlicesForBox(sourceChunkBoxInDestLevel) sourceBlocks = sourceChunk.Blocks[sourceSlices] sourceData = sourceChunk.Data[sourceSlices] mask = sourceMask(sourceBlocks) convertedSourceBlocks, convertedSourceData = convertBlocks(destLevel, sourceLevel, sourceBlocks, sourceData) destChunk.Blocks[destSlices][mask] = convertedSourceBlocks[mask] if convertedSourceData is not None: destChunk.Data[destSlices][mask] = convertedSourceData[mask] def copy(p): return p in sourceChunkBoxInDestLevel and (blocksToCopy is None or mask[ int(p[0] - sourceChunkBoxInDestLevel.minx), int(p[2] - sourceChunkBoxInDestLevel.minz), int(p[1] - sourceChunkBoxInDestLevel.miny), ]) if entities: destChunk.removeEntities(copy) ents = sourceChunk.getEntitiesInBox(destChunkBoxInSourceLevel) e += len(ents) for entityTag in ents: eTag = Entity.copyWithOffset(entityTag, copyOffset, regenerateUUID) destLevel.addEntity(eTag) destChunk.removeTileEntities(copy) tileEntities = sourceChunk.getTileEntitiesInBox(destChunkBoxInSourceLevel) t += len(tileEntities) for tileEntityTag in tileEntities: eTag = TileEntity.copyWithOffset(tileEntityTag, copyOffset, staticCommands, moveSpawnerPos, first, cancelCommandBlockOffset) destLevel.addTileEntity(eTag) destChunk.removeTileTicks(copy) tileTicksList = sourceChunk.getTileTicksInBox(destChunkBoxInSourceLevel) tt += len(tileTicksList) for tileTick in tileTicksList: eTag = deepcopy(tileTick) eTag['x'].value = tileTick['x'].value + copyOffset[0] eTag['y'].value = tileTick['y'].value + copyOffset[1] eTag['z'].value = tileTick['z'].value + copyOffset[2] destLevel.addTileTick(eTag) if biomes and hasattr(destChunk, 'Biomes') and hasattr(sourceChunk, 'Biomes'): destChunk.Biomes[destSlices[:2]] = sourceChunk.Biomes[sourceSlices[:2]] destChunk.chunkChanged() log.info("Duration: {0}".format(datetime.now() - startTime)) log.info("Copied {0} entities and {1} tile entities and {2} tile ticks".format(e, t, tt)) def copyBlocksFrom(destLevel, sourceLevel, sourceBox, destinationPoint, blocksToCopy=None, entities=True, create=False, biomes=False, tileTicks=True, staticCommands=False, moveSpawnerPos=False, first=False, cancelCommandBlockOffset=False): return exhaust( copyBlocksFromIter(destLevel, sourceLevel, sourceBox, destinationPoint, blocksToCopy, entities, create, biomes, tileTicks,staticCommands, moveSpawnerPos,first, cancelCommandBlockOffset))
7,258
39.780899
194
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/minecraft_server.py
import atexit import itertools import logging import os from os.path import dirname, join, basename import random from pymclevel import PocketLeveldbWorld import re import shutil import subprocess import sys import tempfile import time import urllib import json import urllib2 import infiniteworld from directories import getCacheDir from mclevelbase import exhaust, ChunkNotPresent log = logging.getLogger(__name__) __author__ = 'Rio' # Thank you, Stackoverflow # http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python def which(program): def is_exe(f): return os.path.exists(f) and os.access(f, os.X_OK) fpath, _fname = os.path.split(program) if fpath: if is_exe(program): return program else: if sys.platform == "win32": if "SYSTEMROOT" in os.environ: root = os.environ["SYSTEMROOT"] exe_file = os.path.join(root, program) if is_exe(exe_file): return exe_file if "PATH" in os.environ: for path in os.environ["PATH"].split(os.pathsep): exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None convert = lambda text: int(text) if text.isdigit() else text alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)] def getVersions(doSnapshot): JAR_VERSION_URL_TEMPLATE = "https://s3.amazonaws.com/Minecraft.Download/versions/{}/minecraft_server.{}.jar" versionSite = urllib2.urlopen("http://s3.amazonaws.com/Minecraft.Download/versions/versions.json") versionSiteResponse = versionSite.read() versionJSON = json.loads(versionSiteResponse) if doSnapshot: version = versionJSON["latest"]["snapshot"] else: version = versionJSON["latest"]["release"] print "Version: " + version URL = JAR_VERSION_URL_TEMPLATE.format(version, version) return URL def sort_nicely(l): """ Sort the given list in the way that humans expect. """ l.sort(key=alphanum_key) class ServerJarStorage(object): _cacheDir = os.path.join(getCacheDir(), u"ServerJarStorage") def __init__(self, cacheDir=None): if not os.path.exists(self._cacheDir): os.makedirs(self._cacheDir) readme = os.path.join(self._cacheDir, "README.TXT") if not os.path.exists(readme): with open(readme, "w") as f: f.write(""" About this folder: This folder is used by MCEdit and pymclevel to store different versions of the Minecraft Server to use for terrain generation. It should have one or more subfolders, one for each version of the server. Each subfolder must hold at least one file named minecraft_server.jar, and the subfolder's name should have the server's version plus the names of any installed mods. There may already be a subfolder here (for example, "Release 1.7.10") if you have used the Chunk Create feature in MCEdit to create chunks using the server. Version numbers can be automatically detected. If you place one or more minecraft_server.jar files in this folder, they will be placed automatically into well-named subfolders the next time you run MCEdit. If a file's name begins with "minecraft_server" and ends with ".jar", it will be detected in this way. """) self.reloadVersions() def reloadVersions(self): cacheDirList = os.listdir(self._cacheDir) self.versions = list( reversed(sorted([v for v in cacheDirList if os.path.exists(self.jarfileForVersion(v))], key=alphanum_key))) if MCServerChunkGenerator.java_exe: for f in cacheDirList: p = os.path.join(self._cacheDir, f) if f.startswith("minecraft_server") and f.endswith(".jar") and os.path.isfile(p): print "Unclassified minecraft_server.jar found in cache dir. Discovering version number..." self.cacheNewVersion(p) os.remove(p) print "Minecraft_Server.jar storage initialized." print u"Each server is stored in a subdirectory of {0} named with the server's version number".format( self._cacheDir) print "Cached servers: ", self.versions def downloadCurrentServer(self, getSnapshot): self.snapshot = getSnapshot print "Downloading the latest Minecraft Server..." try: (filename, headers) = urllib.urlretrieve(getVersions(getSnapshot)) except Exception as e: print "Error downloading server: {0!r}".format(e) return self.cacheNewVersion(filename, allowDuplicate=False) def cacheNewVersion(self, filename, allowDuplicate=True): """ Finds the version number from the server jar at filename and copies it into the proper subfolder of the server jar cache folder""" version = MCServerChunkGenerator._serverVersionFromJarFile(filename) print "Found version ", version versionDir = os.path.join(self._cacheDir, version) i = 1 newVersionDir = versionDir while os.path.exists(newVersionDir): if not allowDuplicate: return newVersionDir = versionDir + " (" + str(i) + ")" i += 1 os.mkdir(newVersionDir) shutil.copy2(filename, os.path.join(newVersionDir, "minecraft_server.jar")) if version not in self.versions: self.versions.append(version) def jarfileForVersion(self, v): return os.path.join(self._cacheDir, v, "minecraft_server.jar").encode(sys.getfilesystemencoding()) def checksumForVersion(self, v): jf = self.jarfileForVersion(v) with open(jf, "rb") as f: import hashlib return hashlib.md5(f.read()).hexdigest() broken_versions = ["Beta 1.9 Prerelease {0}".format(i) for i in (1, 2, 3)] @property def latestVersion(self): if len(self.versions) == 0: return None return max((v for v in self.versions if v not in self.broken_versions), key=alphanum_key) def getJarfile(self, version=None): if len(self.versions) == 0: print "No servers found in cache." self.downloadCurrentServer(False) version = version or self.latestVersion if version not in self.versions: return None return self.jarfileForVersion(version) class JavaNotFound(RuntimeError): pass class VersionNotFound(RuntimeError): pass def readProperties(filename): if not os.path.exists(filename): return {} with open(filename) as f: properties = dict((line.split("=", 2) for line in (l.strip() for l in f) if not line.startswith("#"))) return properties def saveProperties(filename, properties): with open(filename, "w") as f: for k, v in properties.iteritems(): f.write("{0}={1}\n".format(k, v)) def findJava(): # Here we implement the Java executable on the CLI. # This is because several version of Java may be installed on the system, and the one # needed fir the server may not be in the path... log.info("Looking for Java") if "--java" in sys.argv: idx = sys.argv.index("--java") java_exe_path = sys.argv.pop(idx + 1) sys.argv.pop(idx) log.info("CLI switch '--java' found: %s" % java_exe_path) else: if sys.platform == "win32": java_exe_path = "java.exe" else: java_exe_path = "java" if sys.platform == "win32": java_exe = which(java_exe_path) if java_exe is None: KEY_NAME = "HKLM\SOFTWARE\JavaSoft\Java Runtime Environment" try: p = subprocess.Popen(["REG", "QUERY", KEY_NAME, "/v", "CurrentVersion"], stdout=subprocess.PIPE, universal_newlines=True) o, e = p.communicate() lines = o.split("\n") for l in lines: l = l.strip() if l.startswith("CurrentVersion"): words = l.split(None, 2) version = words[-1] p = subprocess.Popen(["REG", "QUERY", KEY_NAME + "\\" + version, "/v", "JavaHome"], stdout=subprocess.PIPE, universal_newlines=True) o, e = p.communicate() lines = o.split("\n") for l in lines: l = l.strip() if l.startswith("JavaHome"): w = l.split(None, 2) javaHome = w[-1] java_exe = os.path.join(javaHome, "bin", "java.exe") print "RegQuery: java.exe found at ", java_exe break except Exception as e: print "Error while locating java.exe using the Registry: ", repr(e) else: java_exe = which(java_exe_path) return java_exe class MCServerChunkGenerator(object): """Generates chunks using minecraft_server.jar. Uses a ServerJarStorage to store different versions of minecraft_server.jar in an application support folder. from pymclevel import * Example usage: gen = MCServerChunkGenerator() # with no arguments, use the newest # server version in the cache, or download # the newest one automatically level = loadWorldNamed("MyWorld") gen.generateChunkInLevel(level, 12, 24) Using an older version: gen = MCServerChunkGenerator("Beta 1.6.5") """ defaultJarStorage = None java_exe = findJava() jarStorage = None _tempWorldCache = {} processes = [] def __init__(self, version=None, jarfile=None, jarStorage=None): self.jarStorage = jarStorage or self.getDefaultJarStorage() if self.java_exe is None: raise JavaNotFound( "Could not find java. Please check that java is installed correctly. (Could not find java in your PATH environment variable.)") if jarfile is None: jarfile = self.jarStorage.getJarfile(version) if jarfile is None: raise VersionNotFound( "Could not find minecraft_server.jar for version {0}. Please make sure that a minecraft_server.jar is placed under {1} in a subfolder named after the server's version number.".format( version or "(latest)", self.jarStorage._cacheDir)) self.serverJarFile = jarfile self.serverVersion = version or self._serverVersion() atexit.register(MCServerChunkGenerator.terminateProcesses) @classmethod def getDefaultJarStorage(cls): if cls.defaultJarStorage is None: cls.defaultJarStorage = ServerJarStorage() return cls.defaultJarStorage @classmethod def clearWorldCache(cls): cls._tempWorldCache = {} for tempDir in os.listdir(cls.worldCacheDir): t = os.path.join(cls.worldCacheDir, tempDir) if os.path.isdir(t): shutil.rmtree(t) def createReadme(self): readme = os.path.join(self.worldCacheDir, "README.TXT") if not os.path.exists(readme): with open(readme, "w") as f: f.write(""" About this folder: This folder is used by MCEdit and pymclevel to cache levels during terrain generation. Feel free to delete it for any reason. """) worldCacheDir = os.path.join(tempfile.gettempdir(), "pymclevel_MCServerChunkGenerator") def tempWorldForLevel(self, level): # tempDir = tempfile.mkdtemp("mclevel_servergen") tempDir = os.path.join(self.worldCacheDir, self.jarStorage.checksumForVersion(self.serverVersion), str(level.RandomSeed)) propsFile = os.path.join(tempDir, "server.properties") properties = readProperties(propsFile) tempWorld = self._tempWorldCache.get((self.serverVersion, level.RandomSeed)) if tempWorld is None: if not os.path.exists(tempDir): os.makedirs(tempDir) self.createReadme() worldName = "world" worldName = properties.setdefault("level-name", worldName) tempWorldDir = os.path.join(tempDir, worldName) tempWorld = infiniteworld.MCInfdevOldLevel(tempWorldDir, create=True, random_seed=level.RandomSeed) tempWorld.close() tempWorldRO = infiniteworld.MCInfdevOldLevel(tempWorldDir, readonly=True) self._tempWorldCache[self.serverVersion, level.RandomSeed] = tempWorldRO if level.dimNo == 0: properties["allow-nether"] = "false" else: tempWorld = tempWorld.getDimension(level.dimNo) properties["allow-nether"] = "true" properties["server-port"] = int(32767 + random.random() * 32700) saveProperties(propsFile, properties) return tempWorld, tempDir def generateAtPosition(self, tempWorld, tempDir, cx, cz): return exhaust(self.generateAtPositionIter(tempWorld, tempDir, cx, cz)) @staticmethod def addEULA(tempDir): eulaLines = [ "#By changing the setting below to TRUE you are indicating your agreement to our EULA (https://account.mojang.com/documents/minecraft_eula).\n", "#Wed Jul 23 21:10:11 EDT 2014\n", "eula=true\n"] with open(tempDir + "/" + "eula.txt", "w") as f: f.writelines(eulaLines) def generateAtPositionIter(self, tempWorld, tempDir, cx, cz, simulate=False): tempWorldRW = infiniteworld.MCInfdevOldLevel(tempWorld.filename) tempWorldRW.setPlayerSpawnPosition((cx * 16, 64, cz * 16)) tempWorldRW.saveInPlace() tempWorldRW.close() del tempWorldRW tempWorld.unload() self.addEULA(tempDir) startTime = time.time() proc = self.runServer(tempDir) while proc.poll() is None: line = proc.stdout.readline().strip() yield line # Forge and FML change stderr output, causing MCServerChunkGenerator to wait endlessly. # # Vanilla: # 2012-11-13 11:29:19 [INFO] Done (9.962s)! # # Forge/FML: # 2012-11-13 11:47:13 [INFO] [Minecraft] Done (8.020s)! if "INFO" in line and "Done" in line: if simulate: duration = time.time() - startTime simSeconds = max(8, int(duration) + 1) for i in xrange(simSeconds): # process tile ticks yield "%2d/%2d: Simulating the world for a little bit..." % (i, simSeconds) time.sleep(1) proc.stdin.write("stop\n") proc.wait() break if "FAILED TO BIND" in line: proc.kill() proc.wait() raise RuntimeError("Server failed to bind to port!") stdout, _ = proc.communicate() if "Could not reserve enough space" in stdout and not MCServerChunkGenerator.lowMemory: MCServerChunkGenerator.lowMemory = True for i in self.generateAtPositionIter(tempWorld, tempDir, cx, cz): yield i (tempWorld.parentWorld or tempWorld).loadLevelDat() # reload version number def copyChunkAtPosition(self, tempWorld, level, cx, cz): if level.containsChunk(cx, cz): return try: tempChunkBytes = tempWorld._getChunkBytes(cx, cz) except ChunkNotPresent as e: raise ChunkNotPresent("While generating a world in {0} using server {1} ({2!r})".format(tempWorld, self.serverJarFile, e), sys.exc_info()[ 2]) if isinstance(level, PocketLeveldbWorld): level.saveGeneratedChunk(cx, cz, tempChunkBytes) else: level.worldFolder.saveChunk(cx, cz, tempChunkBytes) level._allChunks = None def generateChunkInLevel(self, level, cx, cz): assert isinstance(level, infiniteworld.MCInfdevOldLevel) tempWorld, tempDir = self.tempWorldForLevel(level) self.generateAtPosition(tempWorld, tempDir, cx, cz) self.copyChunkAtPosition(tempWorld, level, cx, cz) minRadius = 12 maxRadius = 20 def createLevel(self, level, box, simulate=False, **kw): return exhaust(self.createLevelIter(level, box, simulate, **kw)) def createLevelIter(self, level, box, simulate=False, worldType="DEFAULT", **kw): if isinstance(level, basestring): filename = level level = infiniteworld.MCInfdevOldLevel(filename, create=True, **kw) assert isinstance(level, infiniteworld.MCInfdevOldLevel) minRadius = self.minRadius genPositions = list(itertools.product( xrange(box.mincx, box.maxcx, minRadius * 2), xrange(box.mincz, box.maxcz, minRadius * 2))) for i, (cx, cz) in enumerate(genPositions): log.info("Generating at %s" % ((cx, cz),)) parentDir = dirname(os.path.abspath(level.worldFolder.filename)) propsFile = join(parentDir, "server.properties") props = readProperties(join(dirname(self.serverJarFile), "server.properties")) props["level-name"] = basename(level.worldFolder.filename) props["server-port"] = int(32767 + random.random() * 32700) props["level-type"] = worldType saveProperties(propsFile, props) for p in self.generateAtPositionIter(level, parentDir, cx, cz, simulate): yield i, len(genPositions), p level.close() def generateChunksInLevel(self, level, chunks): return exhaust(self.generateChunksInLevelIter(level, chunks)) def generateChunksInLevelIter_old(self, level, chunks, simulate=False): tempWorld, tempDir = self.tempWorldForLevel(level) startLength = len(chunks) minRadius = self.minRadius maxRadius = self.maxRadius chunks = set(chunks) while len(chunks): length = len(chunks) centercx, centercz = chunks.pop() chunks.add((centercx, centercz)) # assume the generator always generates at least an 11x11 chunk square. centercx += minRadius centercz += minRadius # boxedChunks = [cPos for cPos in chunks if inBox(cPos)] print "Generating {0} chunks out of {1} starting from {2}".format("XXX", len(chunks), (centercx, centercz)) yield startLength - len(chunks), startLength # chunks = [c for c in chunks if not inBox(c)] for p in self.generateAtPositionIter(tempWorld, tempDir, centercx, centercz, simulate): yield startLength - len(chunks), startLength, p i = 0 for cx, cz in itertools.product( xrange(centercx - maxRadius, centercx + maxRadius), xrange(centercz - maxRadius, centercz + maxRadius)): if level.containsChunk(cx, cz): chunks.discard((cx, cz)) elif ((cx, cz) in chunks and all(tempWorld.containsChunk(ncx, ncz) for ncx, ncz in itertools.product(xrange(cx - 1, cx + 2), xrange(cz - 1, cz + 2))) ): self.copyChunkAtPosition(tempWorld, level, cx, cz) i += 1 chunks.discard((cx, cz)) yield startLength - len(chunks), startLength if length == len(chunks): print "No chunks were generated. Aborting." break level.saveInPlace() def generateChunksInLevelIter_new(self, level, chunks, simulate=False): # This chunk generator version can create an arbitrary amount of chunks. # It has been remarked that 'holes' appear in large zones (saw 'holes' when generated 250 and 350 chunks). # This version may also be faster than the 'old' one. tempWorld, tempDir = self.tempWorldForLevel(level) startLength = len(chunks) minRadius = self.minRadius maxRadius = self.maxRadius chunks = set(chunks) uncreated_chunks = [] i = 0 boxedChunks = [cPos for cPos in chunks if chunks] while len(chunks): length = len(chunks) centercx, centercz = chunks.pop() chunks.add((centercx, centercz)) print "Generated {0} chunks out of {1} starting from {2}".format(startLength - len(chunks), startLength, (centercx, centercz)) yield startLength - len(chunks), startLength, "Generating..." for p in self.generateAtPositionIter(tempWorld, tempDir, centercx, centercz, simulate): yield startLength - len(chunks), startLength, p yield i, startLength, "Adding chunks to world..." for cx, cz in itertools.product( xrange(centercx - maxRadius, centercx + maxRadius), xrange(centercz - maxRadius, centercz + maxRadius)): if level.containsChunk(cx, cz): chunks.discard((cx, cz)) if (cx, cz) in uncreated_chunks: uncreated_chunks.remove((cx, cz)) elif ((cx, cz) in chunks and tempWorld.containsChunk(cx, cz)): try: self.copyChunkAtPosition(tempWorld, level, cx, cz) i += 1 chunks.discard((cx, cz)) if (cx, cz) in uncreated_chunks: uncreated_chunks.remove((cx, cz)) except: uncreated_chunks.append((cx, cz)) else: if (cx, cz) in boxedChunks and (cx, cz) not in uncreated_chunks: log.info("adding (%s, %s) to uncreated_chunks"%(cx, cz)) uncreated_chunks.append((cx, cz)) yield i, startLength, "Generating..." msg = "" if len(chunks) == startLength: msg = "No chunks were generated. Aborting." elif uncreated_chunks: msg = "Some chunks were not generated. Reselect them and retry." if msg: log.warning(msg) # print "len(uncreated_chunks)", len(uncreated_chunks) level.saveInPlace() # if __builtins__.get('mcenf_generateChunksInLevelIter', False): # log.info("Using new MCServerChunkGenerator.generateChunksInLevelIter") # generateChunksInLevelIter = generateChunksInLevelIter_new # else: # generateChunksInLevelIter = generateChunksInLevelIter_old generateChunksInLevelIter = generateChunksInLevelIter_new def runServer(self, startingDir): if isinstance(startingDir, unicode): startingDir = startingDir.encode(sys.getfilesystemencoding()) return self._runServer(startingDir, self.serverJarFile) lowMemory = False @classmethod def _runServer(cls, startingDir, jarfile): log.info("Starting server %s in %s", jarfile, startingDir) if cls.lowMemory: memflags = [] else: memflags = ["-Xmx1024M", "-Xms1024M", ] proc = subprocess.Popen([cls.java_exe, "-Djava.awt.headless=true"] + memflags + ["-jar", jarfile], executable=cls.java_exe, cwd=startingDir, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, ) cls.processes.append(proc) return proc @classmethod def terminateProcesses(cls): for process in cls.processes: if process.poll() is None: try: process.terminate() except: pass def _serverVersion(self): return self._serverVersionFromJarFile(self.serverJarFile) @classmethod def _serverVersionFromJarFile(cls, jarfile): tempdir = tempfile.mkdtemp("mclevel_servergen") proc = cls._runServer(tempdir, jarfile) version = "Unknown" # out, err = proc.communicate() # for line in err.split("\n"): while proc.poll() is None: line = proc.stdout.readline() if "Preparing start region" in line: break if "Starting minecraft server version" in line: version = line.split("Starting minecraft server version")[1].strip() break if proc.returncode is None: try: proc.kill() except WindowsError: pass # access denied, process already terminated proc.wait() shutil.rmtree(tempdir) if ";)" in version: version = version.replace(";)", "") # Damnit, Jeb! # Versions like "0.2.1" are alphas, and versions like "1.0.0" without "Beta" are releases if version[0] == "0": version = "Alpha " + version elif 'w' in version or 'pre' in version: version = "Snapshot " + version else: try: if int(version[0]) > 0: version = "Release " + version except ValueError: pass return version
26,166
36.542324
199
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/__init__.py
# Versioned data relative objects MCEDIT_DEFS = {} MCEDIT_IDS = {} # Maps the numeric and name ids to entries in MCEDIT_DEFS from box import BoundingBox, FloatBox from entity import Entity, TileEntity from faces import faceDirections, FaceXDecreasing, FaceXIncreasing, FaceYDecreasing, FaceYIncreasing, FaceZDecreasing, \ FaceZIncreasing, MaxDirections from indev import MCIndevLevel from infiniteworld import ChunkedLevelMixin, AnvilChunk, MCAlphaDimension, MCInfdevOldLevel, ZeroChunk import items from javalevel import MCJavaLevel from level import ChunkBase, computeChunkHeightMap, EntityLevel, FakeChunk, LightedChunk, MCLevel from materials import alphaMaterials, classicMaterials, indevMaterials, MCMaterials, namedMaterials, pocketMaterials from mclevelbase import ChunkNotPresent, PlayerNotFound from leveldbpocket import PocketLeveldbWorld from directories import minecraftSaveFileDir, getMinecraftProfileDirectory, getSelectedProfile from mclevel import fromFile, loadWorld, loadWorldNumber from nbt import load, gunzip, TAG_Byte, TAG_Byte_Array, TAG_Compound, TAG_Double, TAG_Float, TAG_Int, TAG_Int_Array, \ TAG_List, TAG_Long, TAG_Short, TAG_String import pocket from schematic import INVEditChest, MCSchematic, ZipSchematic saveFileDir = minecraftSaveFileDir
1,284
50.4
120
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/id_definitions_2.py
import os import json from logging import getLogger import collections #from pymclevel import MCEDIT_DEFS, MCEDIT_IDS #import pymclevel import re #import id_definitions log = getLogger(__name__) def get_deps(base_version, file_name): deps = [base_version] print "Base: {}".format(base_version) fp = open(os.path.join('mcver', base_version, file_name)) data = json.loads(fp.read()) fp.close() if "load" in data: deps.extend(get_deps(data["load"], file_name)) return deps def update(orig_dict, new_dict): for key, val in new_dict.iteritems(): if isinstance(val, collections.Mapping): tmp = update(orig_dict.get(key, { }), val) orig_dict[key] = tmp elif isinstance(val, list): orig_dict[key] = (orig_dict.get(key, []) + val) else: orig_dict[key] = new_dict[key] return orig_dict def aggregate(base_version, file_name): deps = get_deps(base_version, file_name) deps.reverse() print deps aggregate_data = {} for dep in deps: fp = open(os.path.join('mcver', dep, file_name)) data = json.loads(fp.read()) fp.close() update(aggregate_data, data) print aggregate_data with open("out.json", 'wb') as out: json.dump(aggregate_data, out) #print get_deps("1.12", "entities.json") aggregate("1.12", "entities.json")
1,394
25.826923
61
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/blockrotation.py
import materials from materials import alphaMaterials from numpy import arange, zeros # #!# Needed for the bad hack done with 'blocktable'... import collections import re class __Rotation: def __init__(self): for i, blocktype in enumerate(self.blocktypes): self.blocktypes[i] = eval(blocktype) def genericRoll(cls): rotation = arange(16, dtype='uint8') if hasattr(cls, "Up") and hasattr(cls, "Down"): rotation[cls.Up] = cls.North rotation[cls.Down] = cls.South rotation[cls.South] = cls.Up rotation[cls.North] = cls.Down return rotation def genericVerticalFlip(cls): rotation = arange(16, dtype='uint8') if hasattr(cls, "Up") and hasattr(cls, "Down"): rotation[cls.Up] = cls.Down rotation[cls.Down] = cls.Up if hasattr(cls, "TopNorth") and hasattr(cls, "TopWest") and hasattr(cls, "TopSouth") and hasattr(cls, "TopEast"): rotation[cls.North] = cls.TopNorth rotation[cls.West] = cls.TopWest rotation[cls.South] = cls.TopSouth rotation[cls.East] = cls.TopEast rotation[cls.TopNorth] = cls.North rotation[cls.TopWest] = cls.West rotation[cls.TopSouth] = cls.South rotation[cls.TopEast] = cls.East return rotation def genericRotation(cls): rotation = arange(16, dtype='uint8') rotation[cls.North] = cls.West rotation[cls.West] = cls.South rotation[cls.South] = cls.East rotation[cls.East] = cls.North if hasattr(cls, "TopNorth") and hasattr(cls, "TopWest") and hasattr(cls, "TopSouth") and hasattr(cls, "TopEast"): rotation[cls.TopNorth] = cls.TopWest rotation[cls.TopWest] = cls.TopSouth rotation[cls.TopSouth] = cls.TopEast rotation[cls.TopEast] = cls.TopNorth return rotation def genericEastWestFlip(cls): rotation = arange(16, dtype='uint8') rotation[cls.West] = cls.East rotation[cls.East] = cls.West if hasattr(cls, "TopWest") and hasattr(cls, "TopEast"): rotation[cls.TopWest] = cls.TopEast rotation[cls.TopEast] = cls.TopWest return rotation def genericNorthSouthFlip(cls): rotation = arange(16, dtype='uint8') rotation[cls.South] = cls.North rotation[cls.North] = cls.South if hasattr(cls, "TopNorth") and hasattr(cls, "TopSouth"): rotation[cls.TopSouth] = cls.TopNorth rotation[cls.TopNorth] = cls.TopSouth return rotation rotationClasses = [] def genericFlipRotation(cls): cls.rotateLeft = genericRotation(cls) cls.roll = genericRoll(cls) cls.flipVertical = genericVerticalFlip(cls) cls.flipEastWest = genericEastWestFlip(cls) cls.flipNorthSouth = genericNorthSouthFlip(cls) rotationClasses.append(cls) return cls # Note, directions are based on the old north. North in here is East ingame. class Torch(__Rotation): blocktypes = [ 'alphaMaterials.Torch.ID', 'alphaMaterials.RedstoneTorchOn.ID', 'alphaMaterials.RedstoneTorchOff.ID', ] South = 1 North = 2 West = 3 East = 4 # on the bottom Up = 5 genericFlipRotation(Torch) Torch.roll = arange(16, dtype='uint8') Torch.roll[Torch.Up] = Torch.North Torch.roll[Torch.South] = Torch.Up class Ladder(__Rotation): blocktypes = ['alphaMaterials.Ladder.ID'] East = 2 West = 3 North = 4 South = 5 genericFlipRotation(Ladder) class Stair(__Rotation): blocktypes = ['list(set([b.ID for b in alphaMaterials.AllStairs]))'] South = 0 North = 1 West = 2 East = 3 TopSouth = 4 TopNorth = 5 TopWest = 6 TopEast = 7 genericFlipRotation(Stair) Stair.roll = arange(16, dtype='uint8') Stair.roll[Stair.East] = Stair.East Stair.roll[Stair.West] = Stair.West Stair.roll[Stair.TopEast] = Stair.TopEast Stair.roll[Stair.TopWest] = Stair.TopWest Stair.roll[Stair.North] = Stair.South Stair.roll[Stair.South] = Stair.TopSouth Stair.roll[Stair.TopSouth] = Stair.TopNorth Stair.roll[Stair.TopNorth] = Stair.North # data value 0-8 bottom and 9-15 Top class HalfSlab(__Rotation): blocktypes = ['list(set([b.ID for b in alphaMaterials.AllSlabs]))'] HalfSlab.flipVertical = arange(16, dtype='uint8') for i in xrange(8): HalfSlab.flipVertical[i] = i + 8 HalfSlab.flipVertical[i + 8] = i rotationClasses.append(HalfSlab) class WallSign(__Rotation): blocktypes = ['alphaMaterials.WallSign.ID', 'alphaMaterials.WallBanner.ID'] East = 2 West = 3 North = 4 South = 5 genericFlipRotation(WallSign) class FurnaceDispenserChest(__Rotation): blocktypes = [ 'alphaMaterials.Furnace.ID', 'alphaMaterials.LitFurnace.ID', 'alphaMaterials.Chest.ID', 'alphaMaterials.EnderChest.ID', 'alphaMaterials.TrappedChest.ID' ] East = 2 West = 3 North = 4 South = 5 genericFlipRotation(FurnaceDispenserChest) class Pumpkin(__Rotation): blocktypes = [ 'alphaMaterials.Pumpkin.ID', 'alphaMaterials.JackOLantern.ID', ] East = 0 South = 1 West = 2 North = 3 genericFlipRotation(Pumpkin) class Rail(__Rotation): blocktypes = ['alphaMaterials.Rail.ID'] EastWest = 0 NorthSouth = 1 South = 2 North = 3 East = 4 West = 5 Northeast = 6 Southeast = 7 Southwest = 8 Northwest = 9 def generic8wayRotation(cls): cls.rotateLeft = genericRotation(cls) cls.rotateLeft[cls.Northeast] = cls.Northwest cls.rotateLeft[cls.Southeast] = cls.Northeast cls.rotateLeft[cls.Southwest] = cls.Southeast cls.rotateLeft[cls.Northwest] = cls.Southwest cls.flipEastWest = genericEastWestFlip(cls) cls.flipEastWest[cls.Northeast] = cls.Northwest cls.flipEastWest[cls.Northwest] = cls.Northeast cls.flipEastWest[cls.Southwest] = cls.Southeast cls.flipEastWest[cls.Southeast] = cls.Southwest cls.flipNorthSouth = genericNorthSouthFlip(cls) cls.flipNorthSouth[cls.Northeast] = cls.Southeast cls.flipNorthSouth[cls.Southeast] = cls.Northeast cls.flipNorthSouth[cls.Southwest] = cls.Northwest cls.flipNorthSouth[cls.Northwest] = cls.Southwest rotationClasses.append(cls) generic8wayRotation(Rail) Rail.rotateLeft[Rail.NorthSouth] = Rail.EastWest Rail.rotateLeft[Rail.EastWest] = Rail.NorthSouth Rail.roll = arange(16, dtype='uint8') Rail.roll[Rail.North] = Rail.South def applyBit(apply): def _applyBit(class_or_array): if hasattr(class_or_array, "rotateLeft"): for a in (class_or_array.flipEastWest, class_or_array.flipNorthSouth, class_or_array.rotateLeft): apply(a) if hasattr(class_or_array, "flipVertical"): apply(class_or_array.flipVertical) if hasattr(class_or_array, "roll"): apply(class_or_array.roll) else: array = class_or_array apply(array) return _applyBit @applyBit def applyBit8(array): array[8:16] = array[0:8] | 0x8 @applyBit def applyBit4(array): array[4:8] = array[0:4] | 0x4 array[12:16] = array[8:12] | 0x4 @applyBit def applyBits48(array): array[4:8] = array[0:4] | 0x4 array[8:16] = array[0:8] | 0x8 applyThrownBit = applyBit8 class PoweredDetectorRail(Rail): blocktypes = ['alphaMaterials.PoweredRail.ID', 'alphaMaterials.DetectorRail.ID', 'alphaMaterials.ActivatorRail.ID'] PoweredDetectorRail.rotateLeft = genericRotation(PoweredDetectorRail) PoweredDetectorRail.rotateLeft[PoweredDetectorRail.NorthSouth] = PoweredDetectorRail.EastWest PoweredDetectorRail.rotateLeft[PoweredDetectorRail.EastWest] = PoweredDetectorRail.NorthSouth PoweredDetectorRail.flipEastWest = genericEastWestFlip(PoweredDetectorRail) PoweredDetectorRail.flipNorthSouth = genericNorthSouthFlip(PoweredDetectorRail) applyThrownBit(PoweredDetectorRail) rotationClasses.append(PoweredDetectorRail) class Lever(__Rotation): blocktypes = ['alphaMaterials.Lever.ID'] ThrownBit = 0x8 # DownSouth indicates floor lever pointing South in off state DownSouth = 0 South = 1 North = 2 West = 3 East = 4 UpSouth = 5 UpWest = 6 DownWest = 7 Lever.rotateLeft = genericRotation(Lever) Lever.rotateLeft[Lever.UpSouth] = Lever.UpWest Lever.rotateLeft[Lever.UpWest] = Lever.UpSouth Lever.rotateLeft[Lever.DownSouth] = Lever.DownWest Lever.rotateLeft[Lever.DownWest] = Lever.DownSouth Lever.flipEastWest = genericEastWestFlip(Lever) Lever.flipNorthSouth = genericNorthSouthFlip(Lever) Lever.flipVertical = arange(16, dtype='uint8') Lever.flipVertical[Lever.UpSouth] = Lever.DownSouth Lever.flipVertical[Lever.DownSouth] = Lever.UpSouth Lever.flipVertical[Lever.UpWest] = Lever.DownWest Lever.flipVertical[Lever.DownWest] = Lever.UpWest Lever.roll = arange(16, dtype='uint8') Lever.roll[Lever.North] = Lever.DownSouth Lever.roll[Lever.South] = Lever.UpSouth Lever.roll[Lever.DownSouth] = Lever.South Lever.roll[Lever.DownWest] = Lever.South Lever.roll[Lever.UpSouth] = Lever.North Lever.roll[Lever.UpWest] = Lever.North applyThrownBit(Lever) rotationClasses.append(Lever) @genericFlipRotation class Button(__Rotation): blocktypes = ['alphaMaterials.Button.ID', 'alphaMaterials.WoodenButton.ID'] PressedBit = 0x8 Down = 0 South = 1 North = 2 West = 3 East = 4 Up = 5 applyThrownBit(Button) class SignPost(__Rotation): blocktypes = ['alphaMaterials.Sign.ID', 'alphaMaterials.MobHead.ID', 'alphaMaterials.StandingBanner.ID'] South = 0 SouthSouthWest = 1 SouthWest = 2 SouthWestWest = 3 West = 4 NorthWestWest = 5 NorthWest = 6 NorthNorthWest = 7 North = 8 NorthNorthEast = 9 NorthEast = 10 NorthEastEast = 11 East = 12 SouthEastEast = 13 SouthEast = 14 SouthSouthEast = 15 #rotate by increasing clockwise rotateLeft = arange(16, dtype='uint8') rotateLeft -= 4 rotateLeft &= 0xf SignPost.flipNorthSouth = arange(16, dtype='uint8') SignPost.flipNorthSouth[SignPost.East] = SignPost.West SignPost.flipNorthSouth[SignPost.West] = SignPost.East SignPost.flipNorthSouth[SignPost.SouthWestWest] = SignPost.SouthEastEast SignPost.flipNorthSouth[SignPost.SouthEastEast] = SignPost.SouthWestWest SignPost.flipNorthSouth[SignPost.SouthWest] = SignPost.SouthEast SignPost.flipNorthSouth[SignPost.SouthEast] = SignPost.SouthWest SignPost.flipNorthSouth[SignPost.SouthSouthWest] = SignPost.SouthSouthEast SignPost.flipNorthSouth[SignPost.SouthSouthEast] = SignPost.SouthSouthWest SignPost.flipNorthSouth[SignPost.NorthEastEast] = SignPost.NorthWestWest SignPost.flipNorthSouth[SignPost.NorthWestWest] = SignPost.NorthEastEast SignPost.flipNorthSouth[SignPost.NorthEast] = SignPost.NorthWest SignPost.flipNorthSouth[SignPost.NorthWest] = SignPost.NorthEast SignPost.flipNorthSouth[SignPost.NorthNorthEast] = SignPost.NorthNorthWest SignPost.flipNorthSouth[SignPost.NorthNorthWest] = SignPost.NorthNorthEast SignPost.flipEastWest = arange(16, dtype='uint8') SignPost.flipEastWest[SignPost.North] = SignPost.South SignPost.flipEastWest[SignPost.South] = SignPost.North SignPost.flipEastWest[SignPost.SouthSouthEast] = SignPost.NorthNorthEast SignPost.flipEastWest[SignPost.NorthNorthEast] = SignPost.SouthSouthEast SignPost.flipEastWest[SignPost.NorthEast] = SignPost.SouthEast SignPost.flipEastWest[SignPost.SouthEast] = SignPost.NorthEast SignPost.flipEastWest[SignPost.SouthEastEast] = SignPost.NorthEastEast SignPost.flipEastWest[SignPost.NorthEastEast] = SignPost.SouthEastEast SignPost.flipEastWest[SignPost.NorthNorthWest] = SignPost.SouthSouthWest SignPost.flipEastWest[SignPost.SouthSouthWest] = SignPost.NorthNorthWest SignPost.flipEastWest[SignPost.NorthWest] = SignPost.SouthWest SignPost.flipEastWest[SignPost.SouthWest] = SignPost.NorthWest SignPost.flipEastWest[SignPost.NorthWestWest] = SignPost.SouthWestWest SignPost.flipEastWest[SignPost.SouthWestWest] = SignPost.NorthWestWest rotationClasses.append(SignPost) class Bed(__Rotation): blocktypes = ['alphaMaterials.Bed.ID'] West = 0 North = 1 East = 2 South = 3 genericFlipRotation(Bed) applyBit8(Bed) applyBit4(Bed) class EndPortal(__Rotation): blocktypes = ['alphaMaterials.PortalFrame.ID'] West = 0 North = 1 East = 2 South = 3 genericFlipRotation(EndPortal) applyBit4(EndPortal) class Door(__Rotation): blocktypes = [ 'alphaMaterials.IronDoor.ID', 'alphaMaterials.WoodenDoor.ID', 'alphaMaterials.SpruceDoor.ID', 'alphaMaterials.BirchDoor.ID', 'alphaMaterials.JungleDoor.ID', 'alphaMaterials.AcaciaDoor.ID', 'alphaMaterials.DarkOakDoor.ID', 'alphaMaterials.WoodenDoor.ID', ] South = 0 West = 1 North = 2 East = 3 SouthOpen = 4 WestOpen = 5 NorthOpen = 6 EastOpen = 7 Left = 8 Right = 9 rotateLeft = arange(16, dtype='uint8') Door.rotateLeft[Door.South] = Door.West Door.rotateLeft[Door.West] = Door.North Door.rotateLeft[Door.North] = Door.East Door.rotateLeft[Door.East] = Door.South Door.rotateLeft[Door.SouthOpen] = Door.WestOpen Door.rotateLeft[Door.WestOpen] = Door.NorthOpen Door.rotateLeft[Door.NorthOpen] = Door.EastOpen Door.rotateLeft[Door.EastOpen] = Door.SouthOpen # applyBit4(Door.rotateLeft) Door.flipEastWest = arange(16, dtype='uint8') Door.flipEastWest[Door.Left] = Door.Right Door.flipEastWest[Door.Right] = Door.Left Door.flipEastWest[Door.East] = Door.West Door.flipEastWest[Door.West] = Door.East Door.flipEastWest[Door.EastOpen] = Door.WestOpen Door.flipEastWest[Door.WestOpen] = Door.EastOpen Door.flipNorthSouth = arange(16, dtype='uint8') Door.flipNorthSouth[Door.Left] = Door.Right Door.flipNorthSouth[Door.Right] = Door.Left Door.flipNorthSouth[Door.North] = Door.South Door.flipNorthSouth[Door.South] = Door.North Door.flipNorthSouth[Door.NorthOpen] = Door.SouthOpen Door.flipNorthSouth[Door.SouthOpen] = Door.NorthOpen rotationClasses.append(Door) class Log(__Rotation): blocktypes = [ 'alphaMaterials.Wood.ID', 'alphaMaterials.Wood2.ID', ] Type1Up = 0 Type2Up = 1 Type3Up = 2 Type4Up = 3 Type1NorthSouth = 4 Type2NorthSouth = 5 Type3NorthSouth = 6 Type4NorthSouth = 7 Type1EastWest = 8 Type2EastWest = 9 Type3EastWest = 10 Type4EastWest = 11 Log.rotateLeft = arange(16, dtype='uint8') Log.rotateLeft[Log.Type1NorthSouth] = Log.Type1EastWest Log.rotateLeft[Log.Type1EastWest] = Log.Type1NorthSouth Log.rotateLeft[Log.Type2NorthSouth] = Log.Type2EastWest Log.rotateLeft[Log.Type2EastWest] = Log.Type2NorthSouth Log.rotateLeft[Log.Type3NorthSouth] = Log.Type3EastWest Log.rotateLeft[Log.Type3EastWest] = Log.Type3NorthSouth Log.rotateLeft[Log.Type4NorthSouth] = Log.Type4EastWest Log.rotateLeft[Log.Type4EastWest] = Log.Type4NorthSouth Log.roll = arange(16, dtype='uint8') Log.roll[Log.Type1NorthSouth] = Log.Type1Up Log.roll[Log.Type2NorthSouth] = Log.Type2Up Log.roll[Log.Type3NorthSouth] = Log.Type3Up Log.roll[Log.Type4NorthSouth] = Log.Type4Up Log.roll[Log.Type1Up] = Log.Type1NorthSouth Log.roll[Log.Type2Up] = Log.Type2NorthSouth Log.roll[Log.Type3Up] = Log.Type3NorthSouth Log.roll[Log.Type4Up] = Log.Type4NorthSouth rotationClasses.append(Log) class RedstoneRepeater(__Rotation): blocktypes = [ 'alphaMaterials.RedstoneRepeaterOff.ID', 'alphaMaterials.RedstoneRepeaterOn.ID' ] East = 0 South = 1 West = 2 North = 3 genericFlipRotation(RedstoneRepeater) # high bits of the repeater indicate repeater delay, and should be preserved applyBits48(RedstoneRepeater) class Trapdoor(__Rotation): blocktypes = ['alphaMaterials.Trapdoor.ID', 'alphaMaterials.IronTrapdoor.ID'] West = 0 East = 1 South = 2 North = 3 TopWest = 4 TopEast = 5 TopSouth = 6 TopNorth = 7 genericFlipRotation(Trapdoor) applyOpenedBit = applyBit8 applyOpenedBit(Trapdoor) class PistonBody(__Rotation): blocktypes = ['alphaMaterials.StickyPiston.ID', 'alphaMaterials.Piston.ID'] Down = 0 Up = 1 East = 2 West = 3 North = 4 South = 5 genericRoll(PistonBody) genericFlipRotation(PistonBody) applyPistonBit = applyBit8 applyPistonBit(PistonBody) class PistonHead(PistonBody): blocktypes = ['alphaMaterials.PistonHead.ID'] rotationClasses.append(PistonHead) # Mushroom types: # Value Description Textures # 0 Fleshy piece Pores on all sides # 1 Corner piece Cap texture on top, directions 1 (cloud direction) and 2 (sunrise) # 2 Side piece Cap texture on top and direction 2 (sunrise) # 3 Corner piece Cap texture on top, directions 2 (sunrise) and 3 (cloud origin) # 4 Side piece Cap texture on top and direction 1 (cloud direction) # 5 Top piece Cap texture on top # 6 Side piece Cap texture on top and direction 3 (cloud origin) # 7 Corner piece Cap texture on top, directions 0 (sunset) and 1 (cloud direction) # 8 Side piece Cap texture on top and direction 0 (sunset) # 9 Corner piece Cap texture on top, directions 3 (cloud origin) and 0 (sunset) # 10 Stem piece Stem texture on all four sides, pores on top and bottom class HugeMushroom(__Rotation): blocktypes = ['alphaMaterials.HugeRedMushroom.ID', 'alphaMaterials.HugeBrownMushroom.ID'] Northeast = 1 East = 2 Southeast = 3 South = 6 Southwest = 9 West = 8 Northwest = 7 North = 4 generic8wayRotation(HugeMushroom) HugeMushroom.roll = arange(16, dtype='uint8') HugeMushroom.roll[HugeMushroom.Southeast] = HugeMushroom.Northeast HugeMushroom.roll[HugeMushroom.South] = HugeMushroom.North HugeMushroom.roll[HugeMushroom.Southwest] = HugeMushroom.Northwest class Vines(__Rotation): blocktypes = ['alphaMaterials.Vines.ID'] WestBit = 1 NorthBit = 2 EastBit = 4 SouthBit = 8 rotateLeft = arange(16, dtype='uint8') flipEastWest = arange(16, dtype='uint8') flipNorthSouth = arange(16, dtype='uint8') # Hmm... Since each bit is a direction, we can rotate by shifting! Vines.rotateLeft = 0xf & ((Vines.rotateLeft >> 1) | (Vines.rotateLeft << 3)) # Wherever each bit is set, clear it and set the opposite bit EastWestBits = (Vines.EastBit | Vines.WestBit) Vines.flipEastWest[(Vines.flipEastWest & EastWestBits) > 0] ^= EastWestBits NorthSouthBits = (Vines.NorthBit | Vines.SouthBit) Vines.flipNorthSouth[(Vines.flipNorthSouth & NorthSouthBits) > 0] ^= NorthSouthBits rotationClasses.append(Vines) class Anvil(__Rotation): blocktypes = ['alphaMaterials.Anvil.ID'] East = 0 South = 1 West = 2 North = 3 genericFlipRotation(Anvil) applyAnvilBit = applyBit8 applyAnvilBit(Anvil) @genericFlipRotation class Hay(__Rotation): blocktypes = ['alphaMaterials.HayBlock.ID'] Up = 0 Down = 0 East = 8 West = 8 North = 4 South = 4 @genericFlipRotation class QuartzPillar(__Rotation): blocktypes = ['alphaMaterials.BlockofQuartz.ID'] Up = 2 Down = 2 East = 4 West = 4 North = 3 South = 3 @genericFlipRotation class PurpurPillar(__Rotation): blocktypes = ['alphaMaterials.PurpurPillar.ID'] Up = 0 Down = 0 East = 8 West = 8 North = 4 South = 4 @genericFlipRotation class NetherPortal(__Rotation): blocktypes = ['alphaMaterials.NetherPortal.ID'] East = 1 West = 1 North = 2 South = 2 class FenceGate(__Rotation): blocktypes = ['materials.alphaMaterials.FenceGate.ID', 'materials.alphaMaterials.SpruceFenceGate.ID', 'materials.alphaMaterials.BirchFenceGate.ID', 'materials.alphaMaterials.JungleFenceGate.ID', 'materials.alphaMaterials.DarkOakFenceGate.ID', 'materials.alphaMaterials.AcaciaFenceGate.ID'] South = 1 West = 2 North = 3 East = 0 genericFlipRotation(FenceGate) applyFenceGateBits = applyBits48 applyFenceGateBits(FenceGate) @genericFlipRotation class EnderPortal(__Rotation): blocktypes = ['alphaMaterials.EnderPortal.ID'] South = 0 West = 1 North = 2 East = 3 @genericFlipRotation class CocoaPlant(__Rotation): blocktypes = ['alphaMaterials.CocoaPlant.ID'] North = 0 East = 1 South = 2 West = 3 applyBits48(CocoaPlant) # growth state @genericFlipRotation class TripwireHook(__Rotation): blocktypes = ['alphaMaterials.TripwireHook.ID'] South = 1 West = 2 North = 3 East = 0 applyBits48(TripwireHook) @genericFlipRotation class MobHead(__Rotation): blocktypes = ['alphaMaterials.MobHead.ID'] East = 2 West = 3 North = 4 South = 5 @genericFlipRotation class Hopper(__Rotation): blocktypes = ['alphaMaterials.Hopper.ID'] Down = 0 East = 2 West = 3 North = 4 South = 5 applyBit8(Hopper) Hopper.roll = arange(16, dtype='uint8') Hopper.roll[Hopper.Down] = Hopper.South Hopper.roll[Hopper.North] = Hopper.Down @genericFlipRotation class DropperCommandblock(__Rotation): blocktypes = [ 'alphaMaterials.Dropper.ID', 'alphaMaterials.Dispenser.ID', 'alphaMaterials.CommandBlock.ID', 'alphaMaterials.CommandBlockRepeating.ID', 'alphaMaterials.CommandBlockChain.ID' ] Down = 0 Up = 1 East = 2 West = 3 North = 4 South = 5 applyBit8(DropperCommandblock) @genericFlipRotation class RedstoneComparator(__Rotation): blocktypes = ['alphaMaterials.RedstoneComparatorInactive.ID', 'alphaMaterials.RedstoneComparatorActive.ID'] East = 0 South = 1 West = 2 North = 3 applyBits48(RedstoneComparator) @genericFlipRotation class EndRod(__Rotation): blocktypes = ['alphaMaterials.EndRod.ID'] Down = 0 Up = 1 East = 2 West = 3 North = 4 South = 5 def _get_attribute(obj, attr): # Helper function used to get arbitrary attribute from an arbitrary object. if hasattr(obj, attr): return getattr(obj, attr) else: raise AttributeError("Object {0} does not have attribute '{1}".format(obj, attr)) def masterRotationTable(attrname): # compute a materials.id_limitx16 table mapping each possible blocktype/data combination to # the resulting data when the block is rotated table = zeros((materials.id_limit, 16), dtype='uint8') table[:] = arange(16, dtype='uint8') for cls in rotationClasses: if hasattr(cls, attrname): blocktable = getattr(cls, attrname) for blocktype in cls.blocktypes: # Very bad stuff here... try: table[eval(blocktype)] = blocktable except (NameError, ValueError) as e: try: table[eval(blocktype)] = blocktable except (NameError, SyntaxError): raise_malformed = False res = re.findall(r"^([a-zA-Z_][,a-zA-Z0-9._]*)[ ]+for[ ]+([(a-zA-Z_][, a-zA-Z0-9_.)]*)[ ]+in[ ]+([a-zA-Z_][,a-zA-Z0-9._]*)$", blocktype) if res and len(res[0]) == 3: # No function call is made in 'bolcktype', so we don't need to check for them. # Only 'stuff for stuff in other_stuff' is used. # 'res[0]' is split in 3 elements: left part of 'for', inner part between 'for'and 'in', and right part of 'in' # Let define 'left' is the left part of 'for', 'right' is the inner part between 'for'and 'in', and 'iter_obj' the right part of 'in'. # If the 'left' and 'right' are the same, check 'iter_obj' for nested attributes (like in 'a for a in b.c.d') # If 'left' and 'right' aren't the same, check if 'left' is using calls to attributes (like in 'a.b for a in c') # If yes, check the 'iter_obj for nested attributes. # To not write repeated code, let use variables to store the status of each of the three elements. left, right, iter_obj = res[0] left_valid = False right_valid = False iter_obj_valid = False # Test 'right' first, since calling attribute on this element in 'for' loops is invalid in Python. if '.' in right: SyntaxError("Malformed string: %s. Calling attributes on the right of 'for' is invalid." % blocktype) # Test 'iter_obj'. _iter_obj, _o_str = iter_obj.split('.', 1) if _iter_obj in globals().keys(): iter_obj = globals()[_iter_obj] while '.' in _o_str: _iter_obj, _ostr = _ostr.split('.') iter_obj = getattr(iter_obj, _iter_obj) # Test 'left'. left_name, left_attrs = left.split('.') if left_name != right: SyntaxError("Malformed string: '%s'" % blocktype) # All checks passed, we can proceed the loop. if left_attrs: [table[eval('a.%s' % left_attrs)] for a in iter_obj] # print table else: table[blocktype] = [a for a in iter_obj] else: raise_malformed = True if raise_malformed: raise SyntaxError("Malformed string: %s" % blocktype) return table def rotationTypeTable(): table = {} for cls in rotationClasses: for b in cls.blocktypes: table[b] = cls return table class BlockRotation: def __init__(self): self.rotateLeft = masterRotationTable("rotateLeft") self.flipEastWest = masterRotationTable("flipEastWest") self.flipNorthSouth = masterRotationTable("flipNorthSouth") self.flipVertical = masterRotationTable("flipVertical") self.roll = masterRotationTable("roll") self.typeTable = rotationTypeTable() def SameRotationType(blocktype1, blocktype2): # use different default values for typeTable.get() to make it return false when neither blocktype is present return BlockRotation().typeTable.get(blocktype1.ID) == BlockRotation().typeTable.get(blocktype2.ID, BlockRotation()) def FlipVertical(blocks, data): data[:] = BlockRotation().flipVertical[blocks, data] def FlipNorthSouth(blocks, data): data[:] = BlockRotation().flipNorthSouth[blocks, data] def FlipEastWest(blocks, data): data[:] = BlockRotation().flipEastWest[blocks, data] def RotateLeft(blocks, data): data[:] = BlockRotation().rotateLeft[blocks, data] def Roll(blocks, data): data[:] = BlockRotation().roll[blocks, data]
27,196
27.038144
162
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/leveldb.py
# !/usr/bin/env python # # Copyright (C) 2012 Space Monkey, Inc. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # """ LevelDB Python interface via C-Types. http://code.google.com/p/leveldb-py/ Missing still (but in progress): * custom comparators, filter policies, caches This interface requires nothing more than the leveldb shared object with the C api being installed. Now requires LevelDB 1.6 or newer. For most usages, you are likely to only be interested in the "DB" and maybe the "WriteBatch" classes for construction. The other classes are helper classes that you may end up using as part of those two root classes. * DBInterface - This class wraps a LevelDB. Created by either the DB or MemoryDB constructors * Iterator - this class is created by calls to DBInterface::iterator. Supports range requests, seeking, prefix searching, etc * WriteBatch - this class is a standalone object. You can perform writes and deletes on it, but nothing happens to your database until you write the writebatch to the database with DB::write """ __author__ = "JT Olds" __email__ = "[email protected]" import bisect import ctypes import ctypes.util import weakref import threading from collections import namedtuple import os import sys import platform import directories # Let have some logging stuff. import logging log = logging.getLogger(__name__) # Here we want to load the file corresponding to the current paltform. # So, let check for that :) try: plat = sys.platform if plat == 'linux2': # This library shall not be installed system wide, let take it from the directory where this module is if # we're running from source, or from the same directory alongside the Linux bundle file. if getattr(sys, 'frozen', False): searched = [] p = os.path.dirname(os.path.abspath(__file__)) # When running from a bundle the .so shall be in '<program install directory>/<last part of p> # Let's try to find it without taking care of the name of the bundle file. b_dir, so_dir = os.path.split(p) b_dir = os.path.split(b_dir)[0] pth = None while pth is None and b_dir != '/': _p = os.path.join(b_dir, so_dir) if os.path.exists(os.path.join(_p, 'libleveldb.so')): pth = _p else: searched.append(_p) b_dir = os.path.split(b_dir)[0] if pth is None: raise IOError("File 'libleveldb.so' not found in any of these places:\n%s" % '\n'.join(searched)) else: log.info("Found 'libleveldb.so' in %s"%pth) else: pth = os.path.dirname(os.path.abspath(__file__)) _ldb = ctypes.CDLL(os.path.join(pth, 'libleveldb.so')) elif plat == 'darwin': # since on OSX the program is bundled in a .app archive, shall we use the same (or approching) thecnique as for Linux? _ldb = ctypes.CDLL(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'libleveldb.dylib')) elif plat == 'win32': if getattr(sys, '_MEIPASS', False): import win32api win32api.SetDllDirectory(sys._MEIPASS) DLL_NAME = 'LevelDB-MCPE-32bit.dll' if platform.architecture()[0] == '64bit' or sys.maxsize > 2**32: DLL_NAME = 'LevelDB-MCPE-64bit.dll' #_ldb = ctypes.CDLL(os.path.join(os.path.dirname(os.path.abspath(__file__)), "LevelDB-MCPE.dll")) _ldb = ctypes.CDLL(str(directories.getDataFile('pymclevel', DLL_NAME))) log.debug("Binary support v%s.%s for PE 1+ world succesfully loaded." % (_ldb.leveldb_major_version(), _ldb.leveldb_minor_version())) except Exception as e: # What shall we do if the library is not found? # If the library is not loaded, the _ldb object does not exists, and every call to it will crash MCEdit... # We may import this module using try/except statement. log.error("The binary support for PE 1+ worlds could not be loaded:") log.error(e) raise e _ldb.leveldb_filterpolicy_create_bloom.argtypes = [ctypes.c_int] _ldb.leveldb_filterpolicy_create_bloom.restype = ctypes.c_void_p _ldb.leveldb_filterpolicy_destroy.argtypes = [ctypes.c_void_p] _ldb.leveldb_filterpolicy_destroy.restype = None _ldb.leveldb_cache_create_lru.argtypes = [ctypes.c_size_t] _ldb.leveldb_cache_create_lru.restype = ctypes.c_void_p _ldb.leveldb_cache_destroy.argtypes = [ctypes.c_void_p] _ldb.leveldb_cache_destroy.restype = None _ldb.leveldb_options_create.argtypes = [] _ldb.leveldb_options_create.restype = ctypes.c_void_p _ldb.leveldb_options_set_filter_policy.argtypes = [ctypes.c_void_p, ctypes.c_void_p] _ldb.leveldb_options_set_filter_policy.restype = None _ldb.leveldb_options_set_create_if_missing.argtypes = [ctypes.c_void_p, ctypes.c_ubyte] _ldb.leveldb_options_set_create_if_missing.restype = None _ldb.leveldb_options_set_error_if_exists.argtypes = [ctypes.c_void_p, ctypes.c_ubyte] _ldb.leveldb_options_set_error_if_exists.restype = None _ldb.leveldb_options_set_paranoid_checks.argtypes = [ctypes.c_void_p, ctypes.c_ubyte] _ldb.leveldb_options_set_paranoid_checks.restype = None _ldb.leveldb_options_set_write_buffer_size.argtypes = [ctypes.c_void_p, ctypes.c_size_t] _ldb.leveldb_options_set_write_buffer_size.restype = None _ldb.leveldb_options_set_max_open_files.argtypes = [ctypes.c_void_p, ctypes.c_int] _ldb.leveldb_options_set_max_open_files.restype = None _ldb.leveldb_options_set_cache.argtypes = [ctypes.c_void_p, ctypes.c_void_p] _ldb.leveldb_options_set_cache.restype = None _ldb.leveldb_options_set_block_size.argtypes = [ctypes.c_void_p, ctypes.c_size_t] _ldb.leveldb_options_set_block_size.restype = None _ldb.leveldb_options_destroy.argtypes = [ctypes.c_void_p] _ldb.leveldb_options_destroy.restype = None _ldb.leveldb_options_set_compression.argtypes = [ctypes.c_void_p, ctypes.c_int] _ldb.leveldb_options_set_compression.restype = None try: # options obj, index, compressor obj, error checker pointer _ldb.leveldb_options_set_compressor.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int] _ldb.leveldb_options_set_compressor.restype = None except Exception as exc: log.debug("ERROR: leveldb::Options.compressors interface could not be accessed:") log.debug("%s" % exc) _ldb.leveldb_open.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_void_p] _ldb.leveldb_open.restype = ctypes.c_void_p _ldb.leveldb_close.argtypes = [ctypes.c_void_p] _ldb.leveldb_close.restype = None _ldb.leveldb_put.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_void_p] _ldb.leveldb_put.restype = None _ldb.leveldb_delete.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_void_p] _ldb.leveldb_delete.restype = None _ldb.leveldb_write.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p] _ldb.leveldb_write.restype = None _ldb.leveldb_get.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_void_p, ctypes.c_void_p] _ldb.leveldb_get.restype = ctypes.POINTER(ctypes.c_char) _ldb.leveldb_writeoptions_create.argtypes = [] _ldb.leveldb_writeoptions_create.restype = ctypes.c_void_p _ldb.leveldb_writeoptions_destroy.argtypes = [ctypes.c_void_p] _ldb.leveldb_writeoptions_destroy.restype = None _ldb.leveldb_writeoptions_set_sync.argtypes = [ctypes.c_void_p, ctypes.c_ubyte] _ldb.leveldb_writeoptions_set_sync.restype = None _ldb.leveldb_readoptions_create.argtypes = [] _ldb.leveldb_readoptions_create.restype = ctypes.c_void_p _ldb.leveldb_readoptions_destroy.argtypes = [ctypes.c_void_p] _ldb.leveldb_readoptions_destroy.restype = None _ldb.leveldb_readoptions_set_verify_checksums.argtypes = [ctypes.c_void_p, ctypes.c_ubyte] _ldb.leveldb_readoptions_set_verify_checksums.restype = None _ldb.leveldb_readoptions_set_fill_cache.argtypes = [ctypes.c_void_p, ctypes.c_ubyte] _ldb.leveldb_readoptions_set_fill_cache.restype = None _ldb.leveldb_readoptions_set_snapshot.argtypes = [ctypes.c_void_p, ctypes.c_void_p] _ldb.leveldb_readoptions_set_snapshot.restype = None _ldb.leveldb_create_iterator.argtypes = [ctypes.c_void_p, ctypes.c_void_p] _ldb.leveldb_create_iterator.restype = ctypes.c_void_p _ldb.leveldb_iter_destroy.argtypes = [ctypes.c_void_p] _ldb.leveldb_iter_destroy.restype = None _ldb.leveldb_iter_valid.argtypes = [ctypes.c_void_p] _ldb.leveldb_iter_valid.restype = ctypes.c_bool _ldb.leveldb_iter_key.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_size_t)] _ldb.leveldb_iter_key.restype = ctypes.c_void_p _ldb.leveldb_iter_value.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_size_t)] _ldb.leveldb_iter_value.restype = ctypes.c_void_p _ldb.leveldb_iter_next.argtypes = [ctypes.c_void_p] _ldb.leveldb_iter_next.restype = None _ldb.leveldb_iter_prev.argtypes = [ctypes.c_void_p] _ldb.leveldb_iter_prev.restype = None _ldb.leveldb_iter_seek_to_first.argtypes = [ctypes.c_void_p] _ldb.leveldb_iter_seek_to_first.restype = None _ldb.leveldb_iter_seek_to_last.argtypes = [ctypes.c_void_p] _ldb.leveldb_iter_seek_to_last.restype = None _ldb.leveldb_iter_seek.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t] _ldb.leveldb_iter_seek.restype = None _ldb.leveldb_iter_get_error.argtypes = [ctypes.c_void_p, ctypes.c_void_p] _ldb.leveldb_iter_get_error.restype = None _ldb.leveldb_writebatch_create.argtypes = [] _ldb.leveldb_writebatch_create.restype = ctypes.c_void_p _ldb.leveldb_writebatch_destroy.argtypes = [ctypes.c_void_p] _ldb.leveldb_writebatch_destroy.restype = None _ldb.leveldb_writebatch_clear.argtypes = [ctypes.c_void_p] _ldb.leveldb_writebatch_clear.restype = None _ldb.leveldb_writebatch_put.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_void_p, ctypes.c_size_t] _ldb.leveldb_writebatch_put.restype = None _ldb.leveldb_writebatch_delete.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t] _ldb.leveldb_writebatch_delete.restype = None _ldb.leveldb_approximate_sizes.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p] _ldb.leveldb_approximate_sizes.restype = None _ldb.leveldb_compact_range.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_void_p, ctypes.c_size_t] _ldb.leveldb_compact_range.restype = None _ldb.leveldb_create_snapshot.argtypes = [ctypes.c_void_p] _ldb.leveldb_create_snapshot.restype = ctypes.c_void_p _ldb.leveldb_release_snapshot.argtypes = [ctypes.c_void_p, ctypes.c_void_p] _ldb.leveldb_release_snapshot.restype = None _ldb.leveldb_free.argtypes = [ctypes.c_void_p] _ldb.leveldb_free.restype = None Row = namedtuple('Row', 'key value') def Options(): pass def WriteOptions(): pass def ReadOptions(): pass class Error(Exception): pass class ZipCompressionError(Exception): pass class Iterator(object): """This class is created by calling __iter__ or iterator on a DB interface """ __slots__ = ["_prefix", "_impl", "_keys_only"] def __init__(self, impl, keys_only=False, prefix=None): self._impl = impl self._prefix = prefix self._keys_only = keys_only def status(self): pass Status = status def Valid(self): """Returns whether the iterator is valid or not @rtype: bool """ valid = self._impl.Valid() if not valid or self._prefix is None: return valid key = self._impl.key() return key[:len(self._prefix)] == self._prefix def SeekToFirst(self): """ Jump to first key in database @return: self @rtype: Iter """ if self._prefix is not None: self._impl.seek(self._prefix) else: self._impl.SeekToFirst() return self def SeekToLast(self): """ Jump to last key in database @return: self @rtype: Iter """ # if we have no prefix or the last possible prefix of this length, just # seek to the last key in the db. if self._prefix is None or self._prefix == "\xff" * len(self._prefix): self._impl.SeekToLast() return self # we have a prefix. see if there's anything after our prefix. # there's probably a much better way to calculate the Next prefix. hex_prefix = self._prefix.encode('hex') Next_prefix = hex(long(hex_prefix, 16) + 1)[2:].rstrip("L") Next_prefix = Next_prefix.rjust(len(hex_prefix), "0") Next_prefix = Next_prefix.decode("hex").rstrip("\x00") self._impl.seek(Next_prefix) if self._impl.Valid(): # there is something after our prefix. we're on it, so step back self._impl.Prev() else: # there is nothing after our prefix, just seek to the last key self._impl.SeekToLast() return self def seek(self, key): """Move the iterator to key. This may be called after StopIteration, allowing you to reuse an iterator safely. @param key: Where to position the iterator. @type key: str @return: self @rtype: Iter """ if self._prefix is not None: key = self._prefix + key self._impl.seek(key) return self Seek = seek def key(self): """Returns the iterator's current key. You should be sure the iterator is currently valid first by calling valid() @rtype: string """ key = self._impl.key() if self._prefix is not None: return key[len(self._prefix):] return key Key = key def value(self): """Returns the iterator's current value. You should be sure the iterator is currently valid first by calling valid() @rtype: string """ return self._impl.val() Value = value def __iter__(self): return self def Next(self): """Advances the iterator one step. Also returns the current value prior to moving the iterator @rtype: Row (namedtuple of key, value) if keys_only=False, otherwise string (the key) @raise StopIteration: if called on an iterator that is not valid """ if not self.Valid(): raise StopIteration() if self._keys_only: rv = self.key() else: rv = Row(self.key(), self.value()) self._impl.Next() return rv next = Next def Prev(self): """Backs the iterator up one step. Also returns the current value prior to moving the iterator. @rtype: Row (namedtuple of key, value) if keys_only=False, otherwise string (the key) @raise StopIteration: if called on an iterator that is not valid """ if not self.Valid(): raise StopIteration() if self._keys_only: rv = self.key() else: rv = Row(self.key(), self.value()) self._impl.Prev() return rv def stepForward(self): """Same as Next but does not return any data or check for validity""" self._impl.Next() StepForward = stepForward def stepBackward(self): """Same as Prev but does not return any data or check for validity""" self._impl.Prev() StepBackward = stepBackward def range(self, start_key=None, end_key=None, start_inclusive=True, end_inclusive=False): """A generator for some range of rows""" if start_key is not None: self.seek(start_key) if not start_inclusive and self.key() == start_key: self._impl.Next() else: self.SeekToFirst() for row in self: if end_key is not None and (row.key > end_key or ( not end_inclusive and row.key == end_key)): break yield row Range = range def keys(self): while self.Valid(): yield self.key() self.stepForward() Keys = keys def values(self): while self.Valid(): yield self.value() self.stepForward() Values = values def close(self): self._impl.close() Close = close class _OpaqueWriteBatch(object): """This is an opaque write batch that must be written to using the putTo and deleteFrom methods on DBInterface. """ def __init__(self): self._puts = {} self._deletes = set() self._private = True def clear(self): self._puts = {} self._deletes = set() Clear = clear class WriteBatch(_OpaqueWriteBatch): """This class is created stand-alone, but then written to some existing DBInterface """ def __init__(self): _OpaqueWriteBatch.__init__(self) self._private = False def put(self, key, val): self._deletes.discard(key) self._puts[key] = val Put = put def delete(self, key): self._puts.pop(key, None) self._deletes.add(key) Delete = delete class DBInterface(object): """This class is created through a few different means: Initially, it can be created using either the DB() or MemoryDB() module-level methods. In almost every case, you want the DB() method. You can then get new DBInterfaces from an existing DBInterface by calling snapshot or scope. """ __slots__ = ["_impl", "_prefix", "_allow_close", "_default_sync", "_default_verify_checksums", "_default_fill_cache"] def __init__(self, impl, prefix=None, allow_close=False, default_sync=False, default_verify_checksums=False, default_fill_cache=True): self._impl = impl self._prefix = prefix self._allow_close = allow_close self._default_sync = default_sync self._default_verify_checksums = default_verify_checksums self._default_fill_cache = default_fill_cache def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): self.close() def close(self): if self._allow_close: self._impl.close() Close = close @staticmethod def newBatch(): return _OpaqueWriteBatch() NewBatch = newBatch def put(self, options, key, val, sync=None): if sync is None: sync = self._default_sync if self._prefix is not None: key = self._prefix + key self._impl.put(options, key, val, sync=sync) Put = put # pylint: disable=W0212 def putTo(self, batch, key, val): if not batch._private: raise ValueError("batch not from DBInterface.newBatch") if self._prefix is not None: key = self._prefix + key batch._deletes.discard(key) batch._puts[key] = val PutTo = putTo def delete(self, key, sync=None): if sync is None: sync = self._default_sync if self._prefix is not None: key = self._prefix + key self._impl.delete(key, sync=sync) Delete = delete # pylint: disable=W0212 def deleteFrom(self, batch, key): if not batch._private: raise ValueError("batch not from DBInterface.newBatch") if self._prefix is not None: key = self._prefix + key batch._puts.pop(key, None) batch._deletes.add(key) DeleteFrom = deleteFrom def Get(self, options, key, verify_checksums=None, fill_cache=None): if verify_checksums is None: verify_checksums = self._default_verify_checksums if fill_cache is None: fill_cache = self._default_fill_cache if self._prefix is not None: key = self._prefix + key return self._impl.Get(None, key, verify_checksums=verify_checksums, fill_cache=fill_cache) # pylint: disable=W0212 def write(self, options, batch, sync=None): if sync is None: sync = self._default_sync if self._prefix is not None and not batch._private: unscoped_batch = _OpaqueWriteBatch() for key, value in batch._puts.iteritems(): unscoped_batch._puts[self._prefix + key] = value for key in batch._deletes: unscoped_batch._deletes.add(self._prefix + key) batch = unscoped_batch return self._impl.write(options, batch, sync=sync) Write = write def NewIterator(self, options=None, verify_checksums=None, fill_cache=None, prefix=None, keys_only=False): if verify_checksums is None: verify_checksums = self._default_verify_checksums if fill_cache is None: fill_cache = self._default_fill_cache if self._prefix is not None: if prefix is None: prefix = self._prefix else: prefix = self._prefix + prefix return Iterator( self._impl.NewIterator(verify_checksums=verify_checksums, fill_cache=fill_cache), keys_only=keys_only, prefix=prefix) def snapshot(self, default_sync=None, default_verify_checksums=None, default_fill_cache=None): if default_sync is None: default_sync = self._default_sync if default_verify_checksums is None: default_verify_checksums = self._default_verify_checksums if default_fill_cache is None: default_fill_cache = self._default_fill_cache return DBInterface(self._impl.snapshot(), prefix=self._prefix, allow_close=False, default_sync=default_sync, default_verify_checksums=default_verify_checksums, default_fill_cache=default_fill_cache) Snapshot = snapshot def __iter__(self): return self.NewIterator().SeekToFirst() def __getitem__(self, k): v = self.Get(None, k) if v is None: raise KeyError(k) return v def __setitem__(self, k, v): self.put(None, k, v) def __delitem__(self, k): self.delete(k) def __contains__(self, key): return self.has(key) def has(self, key, verify_checksums=None, fill_cache=None): return self.Get(None, key, verify_checksums=verify_checksums, fill_cache=fill_cache) is not None Has = has def scope(self, prefix, default_sync=None, default_verify_checksums=None, default_fill_cache=None): if default_sync is None: default_sync = self._default_sync if default_verify_checksums is None: default_verify_checksums = self._default_verify_checksums if default_fill_cache is None: default_fill_cache = self._default_fill_cache if self._prefix is not None: prefix = self._prefix + prefix return DBInterface(self._impl, prefix=prefix, allow_close=False, default_sync=default_sync, default_verify_checksums=default_verify_checksums, default_fill_cache=default_fill_cache) Scope = scope def range(self, start_key=None, end_key=None, start_inclusive=True, end_inclusive=False, verify_checksums=None, fill_cache=None): if verify_checksums is None: verify_checksums = self._default_verify_checksums if fill_cache is None: fill_cache = self._default_fill_cache return self.NewIterator(verify_checksums=verify_checksums, fill_cache=fill_cache).range(start_key=start_key, end_key=end_key, start_inclusive=start_inclusive, end_inclusive=end_inclusive) Range = range def keys(self, verify_checksums=None, fill_cache=None, prefix=None): if verify_checksums is None: verify_checksums = self._default_verify_checksums if fill_cache is None: fill_cache = self._default_fill_cache return self.NewIterator(verify_checksums=verify_checksums, fill_cache=fill_cache, prefix=prefix).SeekToFirst().keys() Keys = keys def values(self, verify_checksums=None, fill_cache=None, prefix=None): if verify_checksums is None: verify_checksums = self._default_verify_checksums if fill_cache is None: fill_cache = self._default_fill_cache return self.NewIterator(verify_checksums=verify_checksums, fill_cache=fill_cache, prefix=prefix).SeekToFirst().values() Values = values def approximateDiskSizes(self, *ranges): return self._impl.approximateDiskSizes(*ranges) ApproximateDiskSizes = approximateDiskSizes def compactRange(self, start_key, end_key): return self._impl.compactRange(start_key, end_key) CompactRange = compactRange def MemoryDB(*_args, **kwargs): """This is primarily for unit testing. If you are doing anything serious, you definitely are more interested in the standard DB class. Arguments are ignored. TODO: if the LevelDB C api ever allows for other environments, actually use LevelDB code for this, instead of reimplementing it all in Python. """ assert kwargs.get("create_if_missing", True) return DBInterface(_MemoryDBImpl(), allow_close=True) class _IteratorMemImpl(object): __slots__ = ["_data", "_idx"] def __init__(self, memdb_data): self._data = memdb_data self._idx = -1 def Valid(self): return 0 <= self._idx < len(self._data) def key(self): return self._data[self._idx][0] Key = key def val(self): return self._data[self._idx][1] Val = val def seek(self, key): self._idx = bisect.bisect_left(self._data, (key, "")) Seek = seek def SeekToFirst(self): self._idx = 0 def SeekToLast(self): self._idx = len(self._data) - 1 def Prev(self): self._idx -= 1 def Next(self): self._idx += 1 def close(self): self._data = [] self._idx = -1 Close = close class _MemoryDBImpl(object): __slots__ = ["_data", "_lock", "_is_snapshot"] def __init__(self, data=None, is_snapshot=False): if data is None: self._data = [] else: self._data = data self._lock = threading.RLock() self._is_snapshot = is_snapshot def close(self): with self._lock: self._data = [] Close = close def put(self, options, key, val, **_kwargs): if self._is_snapshot: raise TypeError("cannot put on leveldb snapshot") assert isinstance(key, str) assert isinstance(val, str) with self._lock: idx = bisect.bisect_left(self._data, (key, "")) if 0 <= idx < len(self._data) and self._data[idx][0] == key: self._data[idx] = (key, val) else: self._data.insert(idx, (key, val)) Put = put def delete(self, key, **_kwargs): if self._is_snapshot: raise TypeError("cannot delete on leveldb snapshot") with self._lock: idx = bisect.bisect_left(self._data, (key, "")) if 0 <= idx < len(self._data) and self._data[idx][0] == key: del self._data[idx] Delete = delete def Get(self, options, key, **_kwargs): with self._lock: idx = bisect.bisect_left(self._data, (key, "")) if 0 <= idx < len(self._data) and self._data[idx][0] == key: return self._data[idx][1] return None # pylint: disable=W0212 def write(self, options, batch, **_kwargs): if self._is_snapshot: raise TypeError("cannot write on leveldb snapshot") with self._lock: for key, val in batch._puts.iteritems(): self.put(options, key, val) for key in batch._deletes: self.delete(key) Write = write def NewIterator(self, **_kwargs): # WARNING: huge performance hit. # leveldb iterators are actually lightweight snapshots of the data. in # real leveldb, an iterator won't change its idea of the full database # even if puts or deletes happen while the iterator is in use. to # simulate this, there isn't anything simple we can do for now besides # just copy the whole thing. with self._lock: return _IteratorMemImpl(self._data[:]) def approximateDiskSizes(self, *ranges): if self._is_snapshot: raise TypeError("cannot calculate disk sizes on leveldb snapshot") return [0] * len(ranges) ApproximateDiskSizes = approximateDiskSizes def compactRange(self, start_key, end_key): pass CompactRange = compactRange def snapshot(self): if self._is_snapshot: return self with self._lock: return _MemoryDBImpl(data=self._data[:], is_snapshot=True) Snapshot = snapshot class _PointerRef(object): __slots__ = ["ref", "_close", "_referrers", "__weakref__"] def __init__(self, ref, close_cb): self.ref = ref self._close = close_cb self._referrers = weakref.WeakValueDictionary() def addReferrer(self, referrer): self._referrers[id(referrer)] = referrer AddReferrer = addReferrer def close(self): ref, self.ref = self.ref, None close, self._close = self._close, None referrers = self._referrers self._referrers = weakref.WeakValueDictionary() for referrer in referrers.valuerefs(): referrer = referrer() if referrer is not None: referrer.close() if ref is not None and close is not None: close(ref) Close = close __del__ = close def _checkError(error): if bool(error): message = ctypes.string_at(error) _ldb.leveldb_free(ctypes.cast(error, ctypes.c_void_p)) _err = Error if 'corrupted compressed block contents' in message: _err = ZipCompressionError raise _err(message) class _IteratorDbImpl(object): __slots__ = ["_ref"] def __init__(self, iterator_ref): self._ref = iterator_ref def Valid(self): return _ldb.leveldb_iter_valid(self._ref.ref) def key(self): length = ctypes.c_size_t(0) val_p = _ldb.leveldb_iter_key(self._ref.ref, ctypes.byref(length)) assert bool(val_p) return ctypes.string_at(val_p, length.value) Key = key def val(self): length = ctypes.c_size_t(0) val_p = _ldb.leveldb_iter_value(self._ref.ref, ctypes.byref(length)) assert bool(val_p) return ctypes.string_at(val_p, length.value) Val = val def seek(self, key): _ldb.leveldb_iter_seek(self._ref.ref, key, len(key)) self._checkError() Seek = seek def SeekToFirst(self): _ldb.leveldb_iter_seek_to_first(self._ref.ref) self._checkError() def SeekToLast(self): _ldb.leveldb_iter_seek_to_last(self._ref.ref) self._checkError() def Prev(self): _ldb.leveldb_iter_prev(self._ref.ref) self._checkError() def Next(self): _ldb.leveldb_iter_next(self._ref.ref) self._checkError() def _checkError(self): error = ctypes.POINTER(ctypes.c_char)() _ldb.leveldb_iter_get_error(self._ref.ref, ctypes.byref(error)) _checkError(error) def close(self): self._ref.close() Close = close def DB(options_, path, bloom_filter_size=10, create_if_missing=False, error_if_exists=False, paranoid_checks=False, write_buffer_size=(4 * 1024 * 1024), max_open_files=1000, block_cache_size=(8 * 1024 * 1024), block_size=163840, default_sync=False, default_verify_checksums=False, default_fill_cache=True, compressors=(2,)): """This is the expected way to open a database. Returns a DBInterface. """ filter_policy = _PointerRef( _ldb.leveldb_filterpolicy_create_bloom(bloom_filter_size), _ldb.leveldb_filterpolicy_destroy) cache = _PointerRef( _ldb.leveldb_cache_create_lru(block_cache_size), _ldb.leveldb_cache_destroy) global options options = _ldb.leveldb_options_create() # Handling the dual compression in PE 1.2+ # Since the code on Mojang's side is not compatible with this for now, # let fallback to the prior behaviour calling leveldb_options_set_compression # with first element in 'compressors'. if hasattr(_ldb, 'leveldb_options_set_compressor'): log.debug("Found 'leveldb_options_set_compressors' in _ldb") if isinstance(compressors, int): # Old behaviour, only one compressor _ldb.leveldb_options_set_compression(options, compressors) elif isinstance(compressors, (list, tuple)): # Here we need more than one compressors for i, compr in enumerate(compressors): if isinstance(compr, int): _ldb.leveldb_options_set_compressor(options, i, compr) else: raise TypeError("Wrong type for compressor #%s: int wanted, %s found (%s)." % (i, type(compr), compr)) else: _ldb.leveldb_options_set_compression(options, compressors[0]) _ldb.leveldb_options_set_filter_policy( options, filter_policy.ref) _ldb.leveldb_options_set_create_if_missing(options, create_if_missing) _ldb.leveldb_options_set_error_if_exists(options, error_if_exists) _ldb.leveldb_options_set_paranoid_checks(options, paranoid_checks) _ldb.leveldb_options_set_write_buffer_size(options, write_buffer_size) _ldb.leveldb_options_set_max_open_files(options, max_open_files) _ldb.leveldb_options_set_cache(options, cache.ref) _ldb.leveldb_options_set_block_size(options, block_size) error = ctypes.POINTER(ctypes.c_char)() db = _ldb.leveldb_open(options, path, ctypes.byref(error)) _ldb.leveldb_options_destroy(options) _checkError(error) db = _PointerRef(db, _ldb.leveldb_close) filter_policy.addReferrer(db) cache.addReferrer(db) return DBInterface(_LevelDBImpl(db, other_objects=(filter_policy, cache)), allow_close=True, default_sync=default_sync, default_verify_checksums=default_verify_checksums, default_fill_cache=default_fill_cache) class _LevelDBImpl(object): __slots__ = ["_objs", "_db", "_snapshot"] def __init__(self, db_ref, snapshot_ref=None, other_objects=()): self._objs = other_objects self._db = db_ref self._snapshot = snapshot_ref def close(self): db, self._db = self._db, None objs, self._objs = self._objs, () if db is not None: db.close() for obj in objs: obj.close() Close = close def put(self, options, key, val, sync=False): if self._snapshot is not None: raise TypeError("cannot put on leveldb snapshot") error = ctypes.POINTER(ctypes.c_char)() options = _ldb.leveldb_writeoptions_create() _ldb.leveldb_writeoptions_set_sync(options, sync) _ldb.leveldb_put(self._db.ref, options, key, len(key), val, len(val), ctypes.byref(error)) _ldb.leveldb_writeoptions_destroy(options) _checkError(error) Put = put def delete(self, key, sync=False): if self._snapshot is not None: raise TypeError("cannot delete on leveldb snapshot") error = ctypes.POINTER(ctypes.c_char)() options = _ldb.leveldb_writeoptions_create() _ldb.leveldb_writeoptions_set_sync(options, sync) _ldb.leveldb_delete(self._db.ref, options, key, len(key), ctypes.byref(error)) _ldb.leveldb_writeoptions_destroy(options) _checkError(error) Delete = delete def Get(self, options, key, verify_checksums=False, fill_cache=True): error = ctypes.POINTER(ctypes.c_char)() options = _ldb.leveldb_readoptions_create() _ldb.leveldb_readoptions_set_verify_checksums(options, verify_checksums) _ldb.leveldb_readoptions_set_fill_cache(options, fill_cache) if self._snapshot is not None: _ldb.leveldb_readoptions_set_snapshot(options, self._snapshot.ref) size = ctypes.c_size_t(0) val_p = _ldb.leveldb_get(self._db.ref, options, key, len(key), ctypes.byref(size), ctypes.byref(error)) if bool(val_p): val = ctypes.string_at(val_p, size.value) _ldb.leveldb_free(ctypes.cast(val_p, ctypes.c_void_p)) else: val = None _ldb.leveldb_readoptions_destroy(options) _checkError(error) return val # pylint: disable=W0212 def write(self, options, batch, sync=False): if self._snapshot is not None: raise TypeError("cannot delete on leveldb snapshot") real_batch = _ldb.leveldb_writebatch_create() for key, val in batch._puts.iteritems(): _ldb.leveldb_writebatch_put(real_batch, key, len(key), val, len(val)) for key in batch._deletes: _ldb.leveldb_writebatch_delete(real_batch, key, len(key)) error = ctypes.POINTER(ctypes.c_char)() options = _ldb.leveldb_writeoptions_create() _ldb.leveldb_writeoptions_set_sync(options, sync) _ldb.leveldb_write(self._db.ref, options, real_batch, ctypes.byref(error)) _ldb.leveldb_writeoptions_destroy(options) _ldb.leveldb_writebatch_destroy(real_batch) _checkError(error) Write = write def NewIterator(self, options=None, verify_checksums=False, fill_cache=True): options = _ldb.leveldb_readoptions_create() if self._snapshot is not None: _ldb.leveldb_readoptions_set_snapshot(options, self._snapshot.ref) _ldb.leveldb_readoptions_set_verify_checksums( options, verify_checksums) _ldb.leveldb_readoptions_set_fill_cache(options, fill_cache) it_ref = _PointerRef( _ldb.leveldb_create_iterator(self._db.ref, options), _ldb.leveldb_iter_destroy) _ldb.leveldb_readoptions_destroy(options) self._db.addReferrer(it_ref) return _IteratorDbImpl(it_ref) def approximateDiskSizes(self, *ranges): if self._snapshot is not None: raise TypeError("cannot calculate disk sizes on leveldb snapshot") assert len(ranges) > 0 key_type = ctypes.c_void_p * len(ranges) len_type = ctypes.c_size_t * len(ranges) start_keys, start_lens = key_type(), len_type() end_keys, end_lens = key_type(), len_type() sizes = (ctypes.c_uint64 * len(ranges))() for i, range_ in enumerate(ranges): assert isinstance(range_, tuple) and len(range_) == 2 assert isinstance(range_[0], str) and isinstance(range_[1], str) start_keys[i] = ctypes.cast(range_[0], ctypes.c_void_p) end_keys[i] = ctypes.cast(range_[1], ctypes.c_void_p) start_lens[i], end_lens[i] = len(range_[0]), len(range_[1]) _ldb.leveldb_approximate_sizes(self._db.ref, len(ranges), start_keys, start_lens, end_keys, end_lens, sizes) return list(sizes) ApproximateDiskSizes = approximateDiskSizes def compactRange(self, start_key, end_key): assert isinstance(start_key, str) and isinstance(end_key, str) _ldb.leveldb_compact_range(self._db.ref, start_key, len(start_key), end_key, len(end_key)) CompactRange = compactRange def snapshot(self): snapshot_ref = _PointerRef( _ldb.leveldb_create_snapshot(self._db.ref), lambda ref: _ldb.leveldb_release_snapshot(self._db.ref, ref)) self._db.addReferrer(snapshot_ref) return _LevelDBImpl(self._db, snapshot_ref=snapshot_ref, other_objects=self._objs) Snapshot = snapshot log.debug("MCEdit-Unified internal PE 1+ support initialized.")
43,146
35.076087
137
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/entity.py
''' Created on Jul 23, 2011 @author: Rio ''' from math import isnan import random import nbt from copy import deepcopy __all__ = ["Entity", "TileEntity", "TileTick"] UNKNOWN_ENTITY_MASK = 1000 class TileEntity(object): baseStructures = { "Furnace": ( ("BurnTime", nbt.TAG_Short), ("CookTime", nbt.TAG_Short), ("Items", nbt.TAG_List), ), "Sign": ( ("Text1", nbt.TAG_String), ("Text2", nbt.TAG_String), ("Text3", nbt.TAG_String), ("Text4", nbt.TAG_String), ), "MobSpawner": ( ("EntityId", nbt.TAG_String), ("SpawnData", nbt.TAG_Compound), ), "Chest": ( ("Items", nbt.TAG_List), ), "Music": ( ("note", nbt.TAG_Byte), ), "Trap": ( ("Items", nbt.TAG_List), ), "RecordPlayer": ( ("Record", nbt.TAG_Int), ), "Piston": ( ("blockId", nbt.TAG_Int), ("blockData", nbt.TAG_Int), ("facing", nbt.TAG_Int), ("progress", nbt.TAG_Float), ("extending", nbt.TAG_Byte), ), "Cauldron": ( ("Items", nbt.TAG_List), ("BrewTime", nbt.TAG_Int), ), "Control": ( ("Command", nbt.TAG_String), ("CustomName", nbt.TAG_String), ("TrackOutput", nbt.TAG_Byte), ("SuccessCount", nbt.TAG_Int) ), "FlowerPot": ( ("Item", nbt.TAG_String), ("Data", nbt.TAG_Int), ), "Bed": ( ("color", nbt.TAG_Int), ), "EnchantTable": ( ("CustomName", nbt.TAG_String), ), "Dropper": ( ("Items", nbt.TAG_List), ), "Dispenser": ( ("Items", nbt.TAG_List), ), "Hopper": ( ("Items", nbt.TAG_List), ), "MobHead": { ("SkullType", nbt.TAG_Byte), ("Rot", nbt.TAG_Byte), ("Owner", nbt.TAG_Compound), } } otherNames = { "Furnace": "Furnace", "Sign": "Sign", "Monster Spawner": "MobSpawner", "Chest": "Chest", "Bed": "Bed", "Note Block": "Music", "Trapped Chest": "Chest", "Jukebox": "RecordPlayer", "Piston": "Piston", "Cauldron": "Cauldron", "Command Block": "Control", "FlowerPot": "FlowerPot", "EnchantTable": "EnchantTable", "Dropper": "Dropper", "Dispenser": "Dispenser", "Hopper": "Hopper", "MobHead": "Skull", } stringNames = { "furnace": "Furnace", "lit_furnace": "Furnace", "standing_sign": "Sign", "wall_sign": "Sign", "mob_spawner": "MobSpawner", "chest": "Chest", "bed": "Bed", "ender_chest": "Chest", "noteblock": "Music", "trapped_chest": "Chest", "jukebox": "RecordPlayer", "sticky_piston": "Piston", "piston": "Piston", "cauldron": "Cauldron", "command_block": "Control", "repeating_command_block": "Control", "chain_command_block": "Control", "flower_pot": "FlowerPot", "enchanting_table": "EnchantTable", "dropper": "Dropper", "dispenser": "Dispenser", "hopper": "Hopper", "skull": "MobHead", } knownIDs = baseStructures.keys() maxItems = { "Furnace": 3, "Chest": 27, "Trap": 9, "Cauldron": 4, "Dropper": 9, "Hopper": 5, "Dispenser": 9, } slotNames = { "Furnace": { 0: "Raw", 1: "Fuel", 2: "Product" }, "Cauldron": { 0: "Potion", 1: "Potion", 2: "Potion", 3: "Reagent", } } @classmethod def Create(cls, tileEntityID, pos=(0, 0, 0), defsIds=None, **kw): tileEntityTag = nbt.TAG_Compound() # If defsIds is None, lets use the current MCEDIT_DEFS and MCEDIT_IDS objects. if not defsIds: from pymclevel import MCEDIT_DEFS else: MCEDIT_DEFS = defsIds.mcedit_defs _id = MCEDIT_DEFS.get(tileEntityID, tileEntityID) tileEntityTag["id"] = nbt.TAG_String(_id) base = cls.baseStructures.get(tileEntityID, None) if base: for (name, tag) in base: tileEntityTag[name] = tag() if tileEntityID == "Control": if name == "CustomName": tileEntityTag[name] = nbt.TAG_String("@") elif name == "SuccessCount": tileEntityTag[name] = nbt.TAG_Int(0) elif tileEntityID == "MobSpawner": entity = kw.get("entity") if name == "EntityId": tileEntityTag[name] = nbt.TAG_String(MCEDIT_DEFS.get("Pig", "Pig")) if name == "SpawnData": spawn_id = nbt.TAG_String(MCEDIT_DEFS.get("Pig", "Pig"), "id") tileEntityTag["SpawnData"] = tag() if entity: for k, v in entity.iteritems(): tileEntityTag["SpawnData"][k] = deepcopy(v) else: tileEntityTag["SpawnData"].add(spawn_id) elif tileEntityID == "Bed": if name == "color": tileEntityTag[name] = nbt.TAG_Int(14) cls.setpos(tileEntityTag, pos) return tileEntityTag @classmethod def pos(cls, tag): return [tag[a].value for a in 'xyz'] @classmethod def setpos(cls, tag, pos): for a, p in zip('xyz', pos): tag[a] = nbt.TAG_Int(p) @classmethod def copyWithOffset(cls, tileEntity, copyOffset, staticCommands, moveSpawnerPos, first, cancelCommandBlockOffset=False, defsIds=None): # You'll need to use this function twice # The first time with first equals to True # The second time with first equals to False # If defsIds is None, lets use the current MCEDIT_DEFS and MCEDIT_IDS objects. if not defsIds: from pymclevel import MCEDIT_IDS else: MCEDIT_IDS = defsIds.mcedit_ids eTag = deepcopy(tileEntity) eTag['x'] = nbt.TAG_Int(tileEntity['x'].value + copyOffset[0]) eTag['y'] = nbt.TAG_Int(tileEntity['y'].value + copyOffset[1]) eTag['z'] = nbt.TAG_Int(tileEntity['z'].value + copyOffset[2]) def num(x): try: return int(x) except ValueError: return float(x) def coordX(x, argument): if first: x = str(num(x)) + '!' + str(num(x) + copyOffset[0]) elif argument and x.find("!") >= 0: x = x[x.index("!") + 1:] x = str(num(x) + copyOffset[0]) elif not argument and x.find("!") >= 0: x = x[:x.index("!")] return x def coordY(y, argument): if first: y = str(num(y)) + '!' + str(num(y) + copyOffset[1]) elif argument and y.find("!") >= 0: y = y[y.index("!") + 1:] y = str(num(y) + copyOffset[1]) elif not argument and y.find("!") >= 0: y = y[:y.index("!")] return y def coordZ(z, argument): if first: z = str(num(z)) + '!' + str(num(z) + copyOffset[2]) elif argument and z.find("!") >= 0: z = z[z.index("!") + 1:] z = str(num(z) + copyOffset[2]) elif not argument and z.find("!") >= 0: z = z[:z.index("!")] return z def coords(x, y, z, argument): if x[0] != "~": x = coordX(x, argument) if y[0] != "~": y = coordY(y, argument) if z[0] != "~": z = coordZ(z, argument) return x, y, z if eTag['id'].value == 'MobSpawner' or MCEDIT_IDS.get(eTag['id'].value) == 'DEF_BLOCKS_MOB_SPAWNER': mobs = [] if 'SpawnData' in eTag: mob = eTag['SpawnData'] if mob: mobs.append(mob) if 'SpawnPotentials' in eTag: potentials = eTag['SpawnPotentials'] for p in potentials: if 'properties' in p: mobs.extend(p["Properties"]) elif 'Entity' in p: mobs.extend(p["Entity"]) for mob in mobs: # Why do we get a unicode object as tag 'mob'? if "Pos" in mob and mob != "Pos": if first: pos = Entity.pos(mob) x, y, z = [str(part) for part in pos] x, y, z = coords(x, y, z, moveSpawnerPos) mob['Temp1'] = nbt.TAG_String(x) mob['Temp2'] = nbt.TAG_String(y) mob['Temp3'] = nbt.TAG_String(z) elif 'Temp1' in mob and 'Temp2' in mob and 'Temp3' in mob: x = mob['Temp1'] y = mob['Temp2'] z = mob['Temp3'] del mob['Temp1'] del mob['Temp2'] del mob['Temp3'] parts = [] for part in (x, y, z): part = str(part) part = part[13:len(part) - 2] parts.append(part) x, y, z = parts pos = [float(p) for p in coords(x, y, z, moveSpawnerPos)] Entity.setpos(mob, pos) if (eTag['id'].value == "Control" or MCEDIT_IDS.get(eTag['id'].value) == 'DEF_BLOCKS_COMMAND_BLOCK') and not cancelCommandBlockOffset: command = eTag['Command'].value oldCommand = command def selectorCoords(selector): old_selector = selector try: char_num = 0 new_selector = "" dont_copy = 0 if len(selector) > 4: if '0' <= selector[3] <= '9': new_selector = selector[:3] end_char_x = selector.find(',', 4, len(selector) - 1) if end_char_x == -1: end_char_x = len(selector) - 1 x = selector[3:end_char_x] x = coordX(x, staticCommands) new_selector += x + ',' end_char_y = selector.find(',', end_char_x + 1, len(selector) - 1) if end_char_y == -1: end_char_y = len(selector) - 1 y = selector[end_char_x + 1:end_char_y] y = coordY(y, staticCommands) new_selector += y + ',' end_char_z = selector.find(',', end_char_y + 1, len(selector) - 1) if end_char_z == -1: end_char_z = len(selector) - 1 z = selector[end_char_y + 1:end_char_z] z = coordZ(z, staticCommands) new_selector += z + ',' + selector[end_char_z + 1:] else: for char in selector: if dont_copy != 0: dont_copy -= 1 else: if (char != 'x' and char != 'y' and char != 'z') or letter: new_selector += char if char == '[' or char == ',': letter = False else: letter = True elif char == 'x' and not letter: new_selector += selector[char_num:char_num + 2] char_x = char_num + 2 end_char_x = selector.find(',', char_num + 3, len(selector) - 1) if end_char_x == -1: end_char_x = len(selector) - 1 x = selector[char_x:end_char_x] dont_copy = len(x) + 1 x = coordX(x, staticCommands) new_selector += x elif char == 'y' and not letter: new_selector += selector[char_num:char_num + 2] char_y = char_num + 2 end_char_y = selector.find(',', char_num + 3, len(selector) - 1) if end_char_y == -1: end_char_y = len(selector) - 1 y = selector[char_y:end_char_y] dont_copy = len(y) + 1 y = coordY(y, staticCommands) new_selector += y elif char == 'z' and not letter: new_selector += selector[char_num:char_num + 2] char_z = char_num + 2 end_char_z = selector.find(',', char_num + 3, len(selector) - 1) if end_char_z == -1: end_char_z = len(selector) - 1 z = selector[char_z:end_char_z] dont_copy = len(z) + 1 z = coordZ(z, staticCommands) new_selector += z char_num += 1 else: new_selector = old_selector except: new_selector = old_selector finally: return new_selector try: execute = False Slash = False if command[0] == "/": command = command[1:] Slash = True # Adjust command coordinates. words = command.split(' ') i = 0 for word in words: if word[0] == '@': words[i] = selectorCoords(word) i += 1 if command.startswith('execute'): stillExecuting = True execute = True saving_command = "" while stillExecuting: if Slash: saving_command += '/' x, y, z = words[2:5] words[2:5] = coords(x, y, z, staticCommands) if words[5] == 'detect': x, y, z = words[6:9] words[6:9] = coords(x, y, z, staticCommands) saving_command += ' '.join(words[:9]) words = words[9:] else: saving_command += ' '.join(words[:5]) words = words[5:] command = ' '.join(words) saving_command += ' ' Slash = False if command[0] == "/": command = command[1:] Slash = True words = command.split(' ') if not command.startswith('execute'): stillExecuting = False if (command.startswith('tp') and len(words) == 5) or command.startswith( 'particle') or command.startswith('replaceitem block') or ( command.startswith('spawnpoint') and len(words) == 5) or command.startswith('stats block') or ( command.startswith('summon') and len(words) >= 5): x, y, z = words[2:5] words[2:5] = coords(x, y, z, staticCommands) elif command.startswith('blockdata') or command.startswith('setblock') or ( command.startswith('setworldspawn') and len(words) == 4): x, y, z = words[1:4] words[1:4] = coords(x, y, z, staticCommands) elif command.startswith('playsound') and len(words) >= 6: x, y, z = words[3:6] words[3:6] = coords(x, y, z, staticCommands) elif command.startswith('clone'): x1, y1, z1, x2, y2, z2, x, y, z = words[1:10] x1, y1, z1 = coords(x1, y1, z1, staticCommands) x2, y2, z2 = coords(x2, y2, z2, staticCommands) x, y, z = coords(x, y, z, staticCommands) words[1:10] = x1, y1, z1, x2, y2, z2, x, y, z elif command.startswith('fill'): x1, y1, z1, x2, y2, z2 = words[1:7] x1, y1, z1 = coords(x1, y1, z1, staticCommands) x2, y2, z2 = coords(x2, y2, z2, staticCommands) words[1:7] = x1, y1, z1, x2, y2, z2 elif command.startswith('spreadplayers'): x, z = words[1:3] if x[0] != "~": x = coordX(x, staticCommands) if z[0] != "~": z = coordZ(z, staticCommands) words[1:3] = x, z elif command.startswith('worldborder center') and len(words) == 4: x, z = words[2:4] if x[0] != "~": x = coordX(x, staticCommands) if z[0] != "~": z = coordZ(z, staticCommands) words[2:4] = x, z if Slash: command = '/' else: command = "" command += ' '.join(words) if execute: command = saving_command + command eTag['Command'].value = command except: eTag['Command'].value = oldCommand return eTag class Entity(object): entityList = { "Item": 1, "XPOrb": 2, "LeashKnot": 8, "Painting": 9, "Arrow": 10, "Snowball": 11, "Fireball": 12, "SmallFireball": 13, "ThrownEnderpearl": 14, "EyeOfEnderSignal": 15, "ThrownPotion": 16, "ThrownExpBottle": 17, "ItemFrame": 18, "WitherSkull": 19, "PrimedTnt": 20, "FallingSand": 21, "FireworksRocketEntity": 22, "ArmorStand": 30, "MinecartCommandBlock": 40, "Boat": 41, "MinecartRideable": 42, "MinecartChest": 43, "MinecartFurnace": 44, "MinecartTNT": 45, "MinecartHopper": 46, "MinecartSpawner": 47, "Mob": 48, "Monster": 49, "Creeper": 50, "Skeleton": 51, "Spider": 52, "Giant": 53, "Zombie": 54, "Slime": 55, "Ghast": 56, "PigZombie": 57, "Enderman": 58, "CaveSpider": 59, "Silverfish": 60, "Blaze": 61, "LavaSlime": 62, "EnderDragon": 63, "WitherBoss": 64, "Bat": 65, "Witch": 66, "Endermite": 67, "Guardian": 68, "Pig": 90, "Sheep": 91, "Cow": 92, "Chicken": 93, "Squid": 94, "Wolf": 95, "MushroomCow": 96, "SnowMan": 97, "Ozelot": 98, "VillagerGolem": 99, "EntityHorse": 100, "Rabbit": 101, "Villager": 120, "EnderCrystal": 200} monsters = ["Creeper", "Skeleton", "Spider", "CaveSpider", "Giant", "Zombie", "Slime", "PigZombie", "Ghast", "Pig", "Sheep", "Cow", "Chicken", "Squid", "Wolf", "Monster", "Enderman", "Silverfish", "Blaze", "Villager", "LavaSlime", "WitherBoss", "Witch", "Endermite", "Guardian", "Rabbit", "Bat", "MushroomCow", "SnowMan", "Ozelot", "VillagerGolem", "EntityHorse" ] projectiles = ["Arrow", "Snowball", "Egg", "Fireball", "SmallFireball", "ThrownEnderpearl", "EyeOfEnderSignal", "ThrownPotion", "ThrownExpBottle", "WitherSkull", "FireworksRocketEntity" ] items = ["Item", "XPOrb", "Painting", "EnderCrystal", "ItemFrame", "WitherSkull", ] vehicles = ["MinecartRidable", "MinecartChest", "MinecartFurnace", "MinecartTNT" "MinecartHopper" "MinecartSpawner" "MinecartCommandBlock" "Boat", ] tiles = ["PrimedTnt", "FallingSand"] maxItems = { "MinecartChest": 27, "MinecartHopper": 5, "EntityHorse": 15 } @classmethod def Create(cls, entityID, **kw): entityTag = nbt.TAG_Compound() entityTag["id"] = nbt.TAG_String(entityID) Entity.setpos(entityTag, (0, 0, 0)) return entityTag @classmethod def pos(cls, tag): if "Pos" not in tag: raise InvalidEntity(tag) else: values = [a.value for a in tag["Pos"]] if isnan(values[0]) and 'xTile' in tag: values[0] = tag['xTile'].value if isnan(values[1]) and 'yTile' in tag: values[1] = tag['yTile'].value if isnan(values[2]) and 'zTile' in tag: values[2] = tag['zTile'].value return values @classmethod def setpos(cls, tag, pos): tag["Pos"] = nbt.TAG_List([nbt.TAG_Double(p) for p in pos]) @classmethod def copyWithOffset(cls, entity, copyOffset, regenerateUUID=False): eTag = deepcopy(entity) # Need to check the content of the copy to regenerate the possible sub entities UUIDs. # A simple fix for the 1.9+ minecarts is proposed. positionTags = map(lambda p, co: type(p)((p.value + co)), eTag["Pos"], copyOffset) eTag["Pos"] = nbt.TAG_List(positionTags) # Also match the 'minecraft:XXX' names # if eTag["id"].value in ("Painting", "ItemFrame", u'minecraft:painting', u'minecraft:item_frame'): # print "#" * 40 # print eTag # eTag["TileX"].value += copyOffset[0] # eTag["TileY"].value += copyOffset[1] # eTag["TileZ"].value += copyOffset[2] # Trying more agnostic way if eTag.get('TileX') and eTag.get('TileY') and eTag.get('TileZ'): eTag["TileX"].value += copyOffset[0] eTag["TileY"].value += copyOffset[1] eTag["TileZ"].value += copyOffset[2] if "Riding" in eTag: eTag["Riding"] = Entity.copyWithOffset(eTag["Riding"], copyOffset) # # Fix for 1.9+ minecarts if "Passengers" in eTag: passengers = nbt.TAG_List() for passenger in eTag["Passengers"]: passengers.append(Entity.copyWithOffset(passenger, copyOffset, regenerateUUID)) eTag["Passengers"] = passengers # # if regenerateUUID: # Courtesy of SethBling eTag["UUIDMost"] = nbt.TAG_Long((random.getrandbits(47) << 16) | (1 << 12) | random.getrandbits(12)) eTag["UUIDLeast"] = nbt.TAG_Long(-((7 << 60) | random.getrandbits(60))) return eTag @classmethod def getId(cls, v): return cls.entityList.get(v, 'No ID') class PocketEntity(Entity): unknown_entity_top = UNKNOWN_ENTITY_MASK + 0 entityList = {"Chicken": 10, "Cow": 11, "Pig": 12, "Sheep": 13, "Wolf": 14, "Villager": 15, "Mooshroom": 16, "Squid": 17, "Rabbit": 18, "Bat": 19, "Iron Golem": 20, "Snow Golem": 21, "Ocelot": 22, "Horse": 23, "Donkey": 24, "Mule": 25, "SkeletonHorse": 26, "ZombieHorse": 27, "PolarBear": 28, "Zombie": 32, "Creeper": 33, "Skeleton": 34, "Spider": 35, "Zombie Pigman": 36, "Slime": 37, "Enderman": 38, "Silverfish": 39, "Cave Spider": 40, "Ghast": 41, "Magma Cube": 42, "Blaze": 43, "Zombie Villager": 44, "Witch": 45, "StraySkeleton": 46, "Hust": 47, "WitherSkeleton": 48, "Guardian": 49, "ElderGuardian": 50, "WitherBoss": 52, "EnderDragon": 53, "Shulker": 54, "Endermite": 55, "Player": 63, "Item": 64, "PrimedTnt": 65, "FallingSand": 66, "ThrownExpBottle": 68, "XPOrb": 69, "EyeOfEnderSignal": 70, "EnderCrystal": 71, "ShulkerBullet": 76, "Fishing Rod Bobber": 77, "DragonFireball": 79, "Arrow": 80, "Snowball": 81, "Egg": 82, "Painting": 83, "MinecartRideable": 84, "Fireball": 85, "ThrownPotion": 86, "ThrownEnderpearl": 87, "LeashKnot": 88, "WitherSkull": 89, "Boat": 90, "Lightning": 93, "Blaze Fireball": 94, "AreaEffectCloud": 95, "Minecart with Hopper": 96, "Minecart with TNT": 97, "Minecart with Chest": 98, "LingeringPotion": 101} @classmethod def getNumId(cls, v): """Retruns the numeric ID of an entity, or a generated one if the entity is not known. The generated one is generated like this: 'UNKNOWN_ENTITY_MASK + X', where 'X' is a number. The first unknown entity will have the numerical ID 1001, the second one 1002, and so on. :v: the entity string ID to search for.""" id = cls.getId(v) if type(id) != int and v not in cls.entityList.keys(): id = cls.unknown_entity_top + 1 cls.entityList[v] = cls.entityList['Entity %s'%id] = id cls.unknown_entity_top += 1 return id class TileTick(object): @classmethod def pos(cls, tag): return [tag[a].value for a in 'xyz'] class InvalidEntity(ValueError): pass class InvalidTileEntiy(ValueError): pass
28,748
35.026316
142
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/schematic.py
""" Created on Jul 22, 2011 @author: Rio """ import atexit from contextlib import closing import os import shutil import zipfile from logging import getLogger import blockrotation from box import BoundingBox import infiniteworld from level import MCLevel, EntityLevel from materials import alphaMaterials, MCMaterials, namedMaterials from mclevelbase import exhaust import nbt from numpy import array, swapaxes, uint8, zeros, resize, ndenumerate from release import TAG as RELEASE_TAG import math import copy log = getLogger(__name__) __all__ = ['MCSchematic', 'INVEditChest', 'StructureNBT'] DEBUG = True class MCSchematic(EntityLevel): materials = alphaMaterials def __init__(self, shape=None, root_tag=None, filename=None, mats='Alpha'): """ shape is (x,y,z) for a new level's shape. if none, takes root_tag as a TAG_Compound for an existing schematic file. if none, tries to read the tag from filename. if none, results are undefined. materials can be a MCMaterials instance, or one of "Classic", "Alpha", "Pocket" to indicate allowable blocks. The default is Alpha. block coordinate order in the file is y,z,x to use the same code as classic/indev levels. in hindsight, this was a completely arbitrary decision. the Entities and TileEntities are nbt.TAG_List objects containing TAG_Compounds. this makes it easy to copy entities without knowing about their insides. rotateLeft swaps the axes of the different arrays. because of this, the Width, Height, and Length reflect the current dimensions of the schematic rather than the ones specified in the NBT structure. I'm not sure what happens when I try to re-save a rotated schematic. """ if DEBUG: log.debug(u"Creating schematic.") if filename: if DEBUG: log.debug(u"Using %s"%filename) self.filename = filename if None is root_tag and os.path.exists(filename): root_tag = nbt.load(filename) if DEBUG: log.debug(u"%s loaded."%filename) else: self.filename = None if mats in namedMaterials: if DEBUG: log.debug(u"Using named materials.") self.materials = namedMaterials[mats] else: assert (isinstance(mats, MCMaterials)) self.materials = mats if root_tag: self.root_tag = root_tag if DEBUG: log.debug(u"Processing materials.") if "Materials" in root_tag: self.materials = namedMaterials[self.Materials] else: root_tag["Materials"] = nbt.TAG_String(self.materials.name) if DEBUG: log.debug(u"Processing size.") w = self.root_tag["Width"].value l = self.root_tag["Length"].value h = self.root_tag["Height"].value if DEBUG: log.debug(u"Reshaping blocks.") self._Blocks = self.root_tag["Blocks"].value.astype('uint16').reshape(h, l, w) # _Blocks is y, z, x del self.root_tag["Blocks"] if "AddBlocks" in self.root_tag: if DEBUG: log.debug(u"Processing AddBlocks.") # Use WorldEdit's "AddBlocks" array to load and store the 4 high bits of a block ID. # Unlike Minecraft's NibbleArrays, this array stores the first block's bits in the # 4 high bits of the first byte. size = (h * l * w) # If odd, add one to the size to make sure the adjacent slices line up. add = zeros(size + (size & 1), 'uint16') # Fill the even bytes with data add[::2] = resize(self.root_tag["AddBlocks"].value, add[::2].shape) # Copy the low 4 bits to the odd bytes add[1::2] = add[::2] & 0xf # Shift the even bytes down add[::2] >>= 4 # Shift every byte up before merging it with Blocks add <<= 8 self._Blocks |= add[:size].reshape(h, l, w) del self.root_tag["AddBlocks"] self.root_tag["Data"].value = self.root_tag["Data"].value.reshape(h, l, w) if "Biomes" in self.root_tag: if DEBUG: log.debug(u"Processing Biomes.") self.root_tag["Biomes"].value.shape = (l, w) else: if DEBUG: log.debug(u"No root tag found, creating a blank schematic.") assert shape is not None root_tag = nbt.TAG_Compound(name="Schematic") root_tag["Height"] = nbt.TAG_Short(shape[1]) root_tag["Length"] = nbt.TAG_Short(shape[2]) root_tag["Width"] = nbt.TAG_Short(shape[0]) root_tag["Entities"] = nbt.TAG_List() root_tag["TileEntities"] = nbt.TAG_List() root_tag["TileTicks"] = nbt.TAG_List() root_tag["Materials"] = nbt.TAG_String(self.materials.name) self._Blocks = zeros((shape[1], shape[2], shape[0]), 'uint16') root_tag["Data"] = nbt.TAG_Byte_Array(zeros((shape[1], shape[2], shape[0]), uint8)) root_tag["Biomes"] = nbt.TAG_Byte_Array(zeros((shape[2], shape[0]), uint8)) self.root_tag = root_tag self.root_tag["Data"].value &= 0xF # discard high bits def saveToFile(self, filename=None): """ save to file named filename, or use self.filename. XXX NOT THREAD SAFE AT ALL. """ if filename is None: filename = self.filename if filename is None: raise IOError, u"Attempted to save an unnamed schematic in place" self.Materials = self.materials.name self.root_tag["Blocks"] = nbt.TAG_Byte_Array(self._Blocks.astype('uint8')) add = self._Blocks >> 8 if add.any(): # WorldEdit AddBlocks compatibility. # The first 4-bit value is stored in the high bits of the first byte. # Increase odd size by one to align slices. packed_add = zeros(add.size + (add.size & 1), 'uint8') packed_add[:add.size] = add.ravel() # Shift even bytes to the left packed_add[::2] <<= 4 # Merge odd bytes into even bytes packed_add[::2] |= packed_add[1::2] # Save only the even bytes, now that they contain the odd bytes in their lower bits. packed_add = packed_add[0::2] self.root_tag["AddBlocks"] = nbt.TAG_Byte_Array(packed_add) with open(filename, 'wb') as chunkfh: self.root_tag.save(chunkfh) del self.root_tag["Blocks"] self.root_tag.pop("AddBlocks", None) def __str__(self): return u"MCSchematic(shape={0}, materials={2}, filename=\"{1}\")".format(self.size, self.filename or u"", self.Materials) # these refer to the blocks array instead of the file's height because rotation swaps the axes # this will have an impact later on when editing schematics instead of just importing/exporting @property def Length(self): return self.Blocks.shape[1] @property def Width(self): return self.Blocks.shape[0] @property def Height(self): return self.Blocks.shape[2] @property def Blocks(self): return swapaxes(self._Blocks, 0, 2) @property def Data(self): return swapaxes(self.root_tag["Data"].value, 0, 2) @property def Entities(self): return self.root_tag["Entities"] @property def TileEntities(self): return self.root_tag["TileEntities"] @property def TileTicks(self): if "TileTicks" in self.root_tag: return self.root_tag["TileTicks"] else: self.root_tag["TileTicks"] = nbt.TAG_List() return self.root_tag["TileTicks"] @property def Materials(self): return self.root_tag["Materials"].value @Materials.setter def Materials(self, val): if "Materials" not in self.root_tag: self.root_tag["Materials"] = nbt.TAG_String() self.root_tag["Materials"].value = val @property def Biomes(self): return swapaxes(self.root_tag["Biomes"].value, 0, 1) @classmethod def _isTagLevel(cls, root_tag): return "Schematic" == root_tag.name def _update_shape(self): root_tag = self.root_tag shape = self.Blocks.shape root_tag["Height"] = nbt.TAG_Short(shape[2]) root_tag["Length"] = nbt.TAG_Short(shape[1]) root_tag["Width"] = nbt.TAG_Short(shape[0]) def rotateLeftBlocks(self): """ rotateLeft the blocks direction without there location """ blockrotation.RotateLeft(self.Blocks, self.Data) def rotateLeft(self): self._fakeEntities = None self._Blocks = swapaxes(self._Blocks, 1, 2)[:, ::-1, :] # x=z; z=-x if "Biomes" in self.root_tag: self.root_tag["Biomes"].value = swapaxes(self.root_tag["Biomes"].value, 0, 1)[::-1, :] self.root_tag["Data"].value = swapaxes(self.root_tag["Data"].value, 1, 2)[:, ::-1, :] # x=z; z=-x self._update_shape() blockrotation.RotateLeft(self.Blocks, self.Data) log.info(u"Relocating entities...") mcedit_ids_get = self.defsIds.mcedit_ids.get for entity in self.Entities: for p in "Pos", "Motion": if p == "Pos": zBase = self.Length else: zBase = 0.0 if p in entity: newX = entity[p][2].value newZ = zBase - entity[p][0].value entity[p][0].value = newX entity[p][2].value = newZ entity["Rotation"][0].value -= 90.0 if entity["id"].value in ("Painting", "ItemFrame") or mcedit_ids_get(entity["id"].value) in ('DEFS_ENTITIES_PAINTING', 'DEFS_ENTITIES_ITEM_FRAME'): x, z = entity["TileX"].value, entity["TileZ"].value newx = z newz = self.Length - x - 1 entity["TileX"].value, entity["TileZ"].value = newx, newz facing = entity.get("Facing", entity.get("Direction")) if facing is None: dirFacing = entity.get("Dir") if dirFacing is not None: if dirFacing.value == 0: dirFacing.value = 2 elif dirFacing.value == 2: dirFacing.value = 0 facing = dirFacing else: raise Exception("None of tags Facing/Direction/Dir found in entity %s during rotating - %r" % (entity["id"].value, entity)) facing.value = (facing.value - 1) % 4 for tileEntity in self.TileEntities: if 'x' not in tileEntity: continue newX = tileEntity["z"].value newZ = self.Length - tileEntity["x"].value - 1 tileEntity["x"].value = newX tileEntity["z"].value = newZ if "TileTicks" in self.root_tag: for tileTick in self.TileTicks: newX = tileTick["z"].value newZ = tileTick["x"].value tileTick["x"].value = newX tileTick["z"].value = newZ def rollBlocks(self): """ rolls the blocks direction without the block location """ blockrotation.Roll(self.Blocks, self.Data) def roll(self): " xxx rotate stuff - destroys biomes" self.root_tag.pop('Biomes', None) self._fakeEntities = None self._Blocks = swapaxes(self._Blocks, 2, 0)[:, :, ::-1] # x=y; y=-x self.root_tag["Data"].value = swapaxes(self.root_tag["Data"].value, 2, 0)[:, :, ::-1] self._update_shape() blockrotation.Roll(self.Blocks, self.Data) log.info(u"N/S Roll: Relocating entities...") mcedit_ids_get = self.defsIds.mcedit_ids.get for i, entity in enumerate(self.Entities): newX = self.Width - entity["Pos"][1].value newY = entity["Pos"][0].value entity["Pos"][0].value = newX entity["Pos"][1].value = newY if "Motion" in entity: newX = entity["Motion"][1].value newY = -entity["Motion"][0].value entity["Motion"][0].value = newX entity["Motion"][1].value = newY # I think this is right # Although rotation isn't that important as most entities can't rotate and mobs # don't serialize rotation. newX = entity["Rotation"][1].value newY = -entity["Rotation"][0].value entity["Rotation"][0].value = newX entity["Rotation"][1].value = newY if entity["id"].value in ("Painting", "ItemFrame") or mcedit_ids_get(entity["id"].value) in ('DEFS_ENTITIES_PAINTING', 'DEFS_ENTITIES_ITEM_FRAME'): newX = self.Width - entity["TileY"].value - 1 newY = entity["TileX"].value entity["TileX"].value = newX entity["TileY"].value = newY for tileEntity in self.TileEntities: newX = self.Width - tileEntity["y"].value - 1 newY = tileEntity["x"].value tileEntity["x"].value = newX tileEntity["y"].value = newY if hasattr(self, "TileTicks"): for tileTick in self.TileTicks: newX = self.Width - tileTick["y"].value - 1 newY = tileTick["x"].value tileTick["x"].value = newX tileTick["y"].value = newY def flipVerticalBlocks(self): blockrotation.FlipVertical(self.Blocks, self.Data) def flipVertical(self): " xxx delete stuff " self._fakeEntities = None blockrotation.FlipVertical(self.Blocks, self.Data) self._Blocks = self._Blocks[::-1, :, :] # y=-y self.root_tag["Data"].value = self.root_tag["Data"].value[::-1, :, :] log.info(u"N/S Flip: Relocating entities...") mcedit_ids_get = self.defsIds.mcedit_ids.get for entity in self.Entities: ent_id_val = entity["id"].value entity["Pos"][1].value = self.Height - entity["Pos"][1].value if "Motion" in entity: entity["Motion"][1].value = -entity["Motion"][1].value entity["Rotation"][1].value = -entity["Rotation"][1].value if ent_id_val in ("Painting", "ItemFrame") or mcedit_ids_get(ent_id_val) in ('DEFS_ENTITIES_PAINTING', 'DEFS_ENTITIES_ITEM_FRAME'): entity["TileY"].value = self.Height - entity["TileY"].value - 1 for tileEntity in self.TileEntities: tileEntity["y"].value = self.Height - tileEntity["y"].value - 1 if "TileTicks" in self.root_tag: for tileTick in self.TileTicks: tileTick["y"].value = self.Height - tileTick["y"].value - 1 # Width of paintings paintingMap = {'Kebab': 1, 'Aztec': 1, 'Alban': 1, 'Aztec2': 1, 'Bomb': 1, 'Plant': 1, 'Wasteland': 1, 'Wanderer': 1, 'Graham': 1, 'Pool': 2, 'Courbet': 2, 'Sunset': 2, 'Sea': 2, 'Creebet': 2, 'Match': 2, 'Stage': 2, 'Void': 2, 'SkullAndRoses': 2, 'Wither': 2, 'Fighters': 4, 'Skeleton': 4, 'DonkeyKong': 4, 'Pointer': 4, 'Pigscene': 4, 'BurningSkull': 4} def flipNorthSouthBlocks(self): blockrotation.FlipNorthSouth(self.Blocks, self.Data) def flipNorthSouth(self): if "Biomes" in self.root_tag: self.root_tag["Biomes"].value = self.root_tag["Biomes"].value[::-1, :] self._fakeEntities = None blockrotation.FlipNorthSouth(self.Blocks, self.Data) self._Blocks = self._Blocks[:, :, ::-1] # x=-x self.root_tag["Data"].value = self.root_tag["Data"].value[:, :, ::-1] northSouthPaintingMap = [0, 3, 2, 1] log.info(u"N/S Flip: Relocating entities...") mcedit_ids_get = self.defsIds.mcedit_ids.get for entity in self.Entities: try: entity["Pos"][0].value = self.Width - entity["Pos"][0].value except: pass try: entity["Motion"][0].value = -entity["Motion"][0].value except: pass try: entity["Rotation"][0].value *= -1.0 except: pass # Special logic for old width painting as TileX/TileZ favours -x/-z try: ent_id_val = entity["id"].value mce_ent_id_val = mcedit_ids_get(ent_id_val) if ent_id_val in ("Painting", "ItemFrame") or mce_ent_id_val in ('DEFS_ENTITIES_PAINTING', 'DEFS_ENTITIES_ITEM_FRAME'): facing = entity.get("Facing", entity.get("Direction")) if facing is None: dirFacing = entity.get("Dir") if dirFacing is not None: if dirFacing.value == 0: dirFacing.value = 2 elif dirFacing.value == 2: dirFacing.value = 0 facing = dirFacing else: raise Exception("None of tags Facing/Direction/Dir found in entity %s during flipping - %r" % (ent_id_val, entity)) if ent_id_val == "Painting" or mce_ent_id_val == 'DEFS_ENTITIES_PAINTING': if facing.value == 2: entity["TileX"].value = self.Width - entity["TileX"].value - self.paintingMap[entity["Motive"].value] % 2 elif facing.value == 0: entity["TileX"].value = self.Width - entity["TileX"].value - 2 + self.paintingMap[entity["Motive"].value] % 2 else: entity["TileX"].value = self.Width - entity["TileX"].value - 1 if facing.value == 3: entity["TileZ"].value = entity["TileZ"].value - 1 + self.paintingMap[entity["Motive"].value] % 2 elif facing.value == 1: entity["TileZ"].value = entity["TileZ"].value + 1 - self.paintingMap[entity["Motive"].value] % 2 facing.value = northSouthPaintingMap[facing.value] elif ent_id_val == "ItemFrame" or mce_ent_id_val == 'DEFS_ENTITIES_ITEM_FRAME': entity["TileX"].value = self.Width - entity["TileX"].value - 1 facing.value = northSouthPaintingMap[facing.value] except: pass for tileEntity in self.TileEntities: if 'x' not in tileEntity: continue tileEntity["x"].value = self.Width - tileEntity["x"].value - 1 if "TileTicks" in self.root_tag: for tileTick in self.TileTicks: tileTick["x"].value = self.Width - tileTick["x"].value - 1 def flipEastWestBlocks(self): blockrotation.FlipEastWest(self.Blocks, self.Data) def flipEastWest(self): if "Biomes" in self.root_tag: self.root_tag["Biomes"].value = self.root_tag["Biomes"].value[:, ::-1] self._fakeEntities = None blockrotation.FlipEastWest(self.Blocks, self.Data) self._Blocks = self._Blocks[:, ::-1, :] # z=-z self.root_tag["Data"].value = self.root_tag["Data"].value[:, ::-1, :] eastWestPaintingMap = [2, 1, 0, 3] log.info(u"E/W Flip: Relocating entities...") mcedit_ids_get = self.defsIds.mcedit_ids.get for entity in self.Entities: try: entity["Pos"][2].value = self.Length - entity["Pos"][2].value except: pass try: entity["Motion"][2].value = -entity["Motion"][2].value except: pass try: entity["Rotation"][0].value = entity["Rotation"][0].value * -1.0 + 180 except: pass # Special logic for old width painting as TileX/TileZ favours -x/-z try: ent_id_val = entity["id"].value mce_ent_id_val = mcedit_ids_get(ent_id_val) if ent_id_val in ("Painting", "ItemFrame") or mce_ent_id_val in ('DEFS_ENTITIES_PAINTING', 'DEFS_ENTITIES_ITEM_FRAME'): facing = entity.get("Facing", entity.get("Direction")) if facing is None: dirFacing = entity.get("Dir") if dirFacing is not None: if dirFacing.value == 0: dirFacing.value = 2 elif dirFacing.value == 2: dirFacing.value = 0 facing = dirFacing else: raise Exception("None of tags Facing/Direction/Dir found in entity %s during flipping - %r" % (entity["id"].value, entity)) if ent_id_val == "Painting" or mce_ent_id_val == 'DEFS_ENTITIES_PAINTING': if facing.value == 1: entity["TileZ"].value = self.Length - entity["TileZ"].value - 2 + self.paintingMap[entity["Motive"].value] % 2 elif facing.value == 3: entity["TileZ"].value = self.Length - entity["TileZ"].value - self.paintingMap[entity["Motive"].value] % 2 else: entity["TileZ"].value = self.Length - entity["TileZ"].value - 1 if facing.value == 0: entity["TileX"].value = entity["TileX"].value + 1 - self.paintingMap[entity["Motive"].value] % 2 elif facing.value == 2: entity["TileX"].value = entity["TileX"].value - 1 + self.paintingMap[entity["Motive"].value] % 2 facing.value = eastWestPaintingMap[facing.value] elif ent_id_val == "ItemFrame" or mce_ent_id_val == 'DEFS_ENTITIES_ITEM_FRAME': entity["TileZ"].value = self.Length - entity["TileZ"].value - 1 facing.value = eastWestPaintingMap[facing.value] except: pass for tileEntity in self.TileEntities: tileEntity["z"].value = self.Length - tileEntity["z"].value - 1 if "TileTicks" in self.root_tag: for tileTick in self.TileTicks: tileTick["z"].value = self.Length - tileTick["z"].value - 1 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] @classmethod def chestWithItemID(cls, itemID, count=64, damage=0): """ Creates a chest with a stack of 'itemID' in each slot. Optionally specify the count of items in each stack. Pass a negative value for damage to create unnaturally sturdy tools. """ root_tag = nbt.TAG_Compound() invTag = nbt.TAG_List() root_tag["Inventory"] = invTag for slot in xrange(9, 36): itemTag = nbt.TAG_Compound() itemTag["Slot"] = nbt.TAG_Byte(slot) itemTag["Count"] = nbt.TAG_Byte(count) itemTag["id"] = nbt.TAG_Short(itemID) itemTag["Damage"] = nbt.TAG_Short(damage) invTag.append(itemTag) chest = INVEditChest(root_tag, "") return chest def getChunk(self, cx, cz): chunk = super(MCSchematic, self).getChunk(cx, cz) if "Biomes" in self.root_tag: x = cx << 4 z = cz << 4 chunk.Biomes = self.Biomes[x:x + 16, z:z + 16] return chunk class INVEditChest(MCSchematic): Width = 1 Height = 1 Length = 1 Data = array([[[0]]], 'uint8') Entities = nbt.TAG_List() Materials = alphaMaterials @classmethod def _isTagLevel(cls, root_tag): return "Inventory" in root_tag def __init__(self, root_tag, filename): self.Blocks = array([[[alphaMaterials.Chest.ID]]], 'uint8') if filename: self.filename = filename if None is root_tag: try: root_tag = nbt.load(filename) except IOError as e: log.info(u"Failed to load file {0}".format(e)) raise else: assert root_tag, "Must have either root_tag or filename" self.filename = None for item in list(root_tag["Inventory"]): slot = item["Slot"].value if slot < 9 or slot >= 36: root_tag["Inventory"].remove(item) else: item["Slot"].value -= 9 # adjust for different chest slot indexes self.root_tag = root_tag @property def TileEntities(self): chestTag = nbt.TAG_Compound() chest_id = "Chest" if self.gamePlatform == "Java": split_ver = self.gameVersionNumber.split('.') else: split_ver = self.gamePlatform.split('.') if int(split_ver[0]) >= 1 and int(split_ver[1]) >= 11: chest_id = "minecraft:chest" chestTag["id"] = nbt.TAG_String(chest_id) chestTag["Items"] = nbt.TAG_List(self.root_tag["Inventory"]) chestTag["x"] = nbt.TAG_Int(0) chestTag["y"] = nbt.TAG_Int(0) chestTag["z"] = nbt.TAG_Int(0) return nbt.TAG_List([chestTag], name="TileEntities") class ZipSchematic(infiniteworld.MCInfdevOldLevel): def __init__(self, filename, create=False): self.zipfilename = filename tempdir = tempfile.mktemp("schematic") if create is False: zf = zipfile.ZipFile(filename, allowZip64=True) zf.extractall(tempdir) zf.close() if os.path.exists(os.path.join(tempdir, '##MCEDIT.TEMP##', 'region')): shutil.move(os.path.join(tempdir, '##MCEDIT.TEMP##', 'region'), os.path.join(tempdir, 'region')) super(ZipSchematic, self).__init__(tempdir, create, dat_name='schematic') atexit.register(shutil.rmtree, self.worldFolder.filename, True) try: schematicDat = nbt.load(self.worldFolder.getFilePath("schematic.dat")) self.Width = schematicDat['Width'].value self.Height = schematicDat['Height'].value self.Length = schematicDat['Length'].value if "Materials" in schematicDat: self.materials = namedMaterials[schematicDat["Materials"].value] except Exception as e: print "Exception reading schematic.dat, skipping: {0!r}".format(e) self.Width = 0 self.Length = 0 def __del__(self): shutil.rmtree(self.worldFolder.filename, True) def saveInPlaceGen(self): self.saveToFile(self.zipfilename) yield def saveToFile(self, filename): schematicDat = nbt.TAG_Compound() schematicDat.name = "Mega Schematic" schematicDat["Width"] = nbt.TAG_Int(self.size[0]) schematicDat["Height"] = nbt.TAG_Int(self.size[1]) schematicDat["Length"] = nbt.TAG_Int(self.size[2]) schematicDat["Materials"] = nbt.TAG_String(self.materials.name) schematicDat.save(self.worldFolder.getFilePath("schematic.dat")) basedir = self.worldFolder.filename assert os.path.isdir(basedir) with closing(zipfile.ZipFile(filename, "w", zipfile.ZIP_STORED, allowZip64=True)) as z: for root, dirs, files in os.walk(basedir): # NOTE: ignore empty directories for fn in files: absfn = os.path.join(root, fn) shutil.move(absfn, absfn.replace("##MCEDIT.TEMP##" + os.sep, "")) absfn = absfn.replace("##MCEDIT.TEMP##" + os.sep, "") zfn = absfn[len(basedir) + len(os.sep):] # XXX: relative path z.write(absfn, zfn) def getWorldBounds(self): return BoundingBox((0, 0, 0), (self.Width, self.Height, self.Length)) @classmethod def _isLevel(cls, filename): return zipfile.is_zipfile(filename) class StructureNBT(object): SUPPORTED_VERSIONS = [1, ] def __init__(self, filename=None, root_tag=None, size=None, mats=alphaMaterials): self._author = None self._blocks = None self._palette = None self._entities = [] self._tile_entities = None self._size = None self._version = None self._mat = mats self.blockstate = mats.blockstate_api if filename: root_tag = nbt.load(filename) if root_tag: self._root_tag = root_tag self._size = (self._root_tag["size"][0].value, self._root_tag["size"][1].value, self._root_tag["size"][2].value) self._author = self._root_tag.get("author", nbt.TAG_String()).value self._version = self._root_tag.get("DataVersion", nbt.TAG_Int(1)).value self._palette = self.__toPythonPrimitive(self._root_tag["palette"]) self._blocks = zeros(self.Size, dtype=tuple) self._blocks.fill((0, 0)) self._entities = [] self._tile_entities = zeros(self.Size, dtype=nbt.TAG_Compound) self._tile_entities.fill({}) for block in self._root_tag["blocks"]: x, y, z = [p.value for p in block["pos"].value] self._blocks[x, y, z] = self.blockstate.blockstateToID(*self.get_state(block["state"].value)) if "nbt" in block: compound = nbt.TAG_Compound() compound.update(block["nbt"]) self._tile_entities[x, y, z] = compound for e in self._root_tag["entities"]: entity = e["nbt"] entity["Pos"] = e["pos"] self._entities.append(entity) elif size: self._root_tag = nbt.TAG_Compound() self._size = size self._blocks = zeros(self.Size, dtype=tuple) self._blocks.fill((0, 0)) self._entities = [] self._tile_entities = zeros(self.Size, dtype=nbt.TAG_Compound) self._tile_entities.fill({}) def toSchematic(self): schem = MCSchematic(shape=self.Size, mats=self._mat) for (x, y, z), value in ndenumerate(self._blocks): b_id, b_data = value schem.Blocks[x, z, y] = b_id schem.Data[x, z, y] = b_data for (x, y, z), value in ndenumerate(self._tile_entities): if not value: continue tag = value tag["x"] = nbt.TAG_Int(x) tag["y"] = nbt.TAG_Int(y) tag["z"] = nbt.TAG_Int(z) schem.addTileEntity(tag) entity_list = nbt.TAG_List() for e in self._entities: entity_list.append(e) schem.root_tag["Entities"] = entity_list return schem @classmethod def fromSchematic(cls, schematic): structure = cls(size=(schematic.Width, schematic.Height, schematic.Length), mats=namedMaterials[getattr(schematic, "Materials", 'Alpha')]) schematic = copy.copy(schematic) for (x, z, y), b_id in ndenumerate(schematic.Blocks): data = schematic.Data[x, z, y] structure._blocks[x, y, z] = (b_id, data) for te in schematic.TileEntities: x, y, z = te["x"].value, te["y"].value, te["z"].value del te["x"] del te["y"] del te["z"] structure._tile_entities[x, y, z] = te for e in schematic.Entities: structure._entities.append(e) return structure def __toPythonPrimitive(self, _nbt): if isinstance(_nbt, nbt.TAG_Compound): d = {} for key in _nbt.keys(): if isinstance(_nbt[key], nbt.TAG_Compound): d[key] = self.__toPythonPrimitive(_nbt[key]) elif isinstance(_nbt[key], nbt.TAG_List): l = [] for value in _nbt[key]: if isinstance(value, nbt.TAG_Compound): l.append(self.__toPythonPrimitive(value)) else: l.append(value.value) d[key] = l else: d[key] = _nbt[key].value return d elif isinstance(_nbt, nbt.TAG_List): l = [] for tag in _nbt: if isinstance(tag, nbt.TAG_Compound): l.append(self.__toPythonPrimitive(tag)) elif isinstance(tag, nbt.TAG_List): l.append(self.__toPythonPrimitive(tag)) else: l.append(tag.value) return l def __convertPaletteToDict(self): palette = [] for state in self._root_tag["palette"]: block = {"Name": state["Name"].value} if "Properties" in state: block["Properties"] = {} for (key, value) in state["Properties"].iteritems(): block["Properties"][key] = value.value palette.append(block) return palette def get_state(self, index): if index > (len(self._palette) - 1): raise IndexError() return self._palette[index]["Name"], self._palette[index].get("Properties", {}) def get_palette_index(self, name, properties=None): # TODO: Switch to string comparison of properties, instead of dict comparison for i in xrange(len(self._palette)): if self._palette[i]["Name"] == name: if properties and "Properties" in self._palette[i]: for (key, value) in properties.iteritems(): if not self._palette[i]["Properties"].get(key, None) == value: continue return i else: return i return -1 def _find_air(self): for i in xrange(len(self._palette)): if self._palette[i]["Name"] == "minecraft:air": return i return -1 def save(self, filename=""): structure_tag = nbt.TAG_Compound() blocks_tag = nbt.TAG_List() palette_tag = nbt.TAG_List() entities_tag = nbt.TAG_List() palette = [] if not self._author: self._author = "MCEdit-Unified v{}".format(RELEASE_TAG) structure_tag["author"] = nbt.TAG_String(self._author) if self._version: structure_tag["DataVersion"] = nbt.TAG_Int(self.DataVersion) else: structure_tag["DataVersion"] = nbt.TAG_Int(self.SUPPORTED_VERSIONS[-1]) structure_tag["size"] = nbt.TAG_List( [ nbt.TAG_Int(self.Size[0]), nbt.TAG_Int(self.Size[1]), nbt.TAG_Int(self.Size[2]) ] ) blockstate_api = self.blockstate.material_map.get(self._mat, self.blockstate.material_map[alphaMaterials]) for z in xrange(self._blocks.shape[2]): # For some reason, ndenumerate() didn't work, but this does for x in xrange(self._blocks.shape[0]): for y in xrange(self._blocks.shape[1]): value = self._blocks[x, y, z] name, properties = blockstate_api.idToBlockstate(*value) blockstate = blockstate_api.stringifyBlockstate(name, properties) #if blockstate not in index_table: # index_table[blockstate] = len(index_table) #index = index_table[blockstate] if blockstate not in palette: palette.append(blockstate) index = palette.index(blockstate) block = nbt.TAG_Compound() block["state"] = nbt.TAG_Int(index) block["pos"] = nbt.TAG_List( [ nbt.TAG_Int(x), nbt.TAG_Int(y), nbt.TAG_Int(z) ] ) if self._tile_entities[x, y, z]: block["nbt"] = self._tile_entities[x, y, z] blocks_tag.append(block) structure_tag["blocks"] = blocks_tag for blockstate in palette: name, properties = blockstate_api.deStringifyBlockstate(blockstate) state = nbt.TAG_Compound() state["Name"] = nbt.TAG_String(name) if properties: props = nbt.TAG_Compound() for (key, value) in properties.iteritems(): props[key] = nbt.TAG_String(value) state["Properties"] = props palette_tag.insert(palette.index(blockstate), state) structure_tag["palette"] = palette_tag for e in self._entities: entity = nbt.TAG_Compound() pos = e["Pos"] entity["pos"] = pos entity["nbt"] = e blockPos = nbt.TAG_List() for coord in pos: blockPos.append(nbt.TAG_Int(math.floor(coord.value))) entity["blockPos"] = blockPos entities_tag.append(entity) structure_tag["entities"] = entities_tag structure_tag.save(filename) @property def Author(self): return self._author @property def Size(self): return self._size @property def Blocks(self): return self._blocks @property def Entities(self): return self._entities @property def Palette(self): return self._palette @property def DataVersion(self): return self._version def adjustExtractionParameters(self, box): x, y, z = box.origin w, h, l = box.size destX = destY = destZ = 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 h <= 0: return if self.Width: if x < 0: w += x destX -= x x = 0 if x >= self.Width: return if x + w >= self.Width: w = self.Width - x if w <= 0: return if z < 0: l += z destZ -= z z = 0 if z >= self.Length: return if z + l >= self.Length: l = self.Length - z if l <= 0: return box = BoundingBox((x, y, z), (w, h, l)) return box, (destX, destY, destZ) def extractSchematicFrom(sourceLevel, box, entities=True, cancelCommandBlockOffset=False): return exhaust(extractSchematicFromIter(sourceLevel, box, entities, cancelCommandBlockOffset)) def extractSchematicFromIter(sourceLevel, box, entities=True, cancelCommandBlockOffset=False): p = sourceLevel.adjustExtractionParameters(box) if p is None: yield None return newbox, destPoint = p tempSchematic = MCSchematic(shape=box.size, mats=sourceLevel.materials) for i in tempSchematic.copyBlocksFromIter(sourceLevel, newbox, destPoint, entities=entities, biomes=True, first=True, cancelCommandBlockOffset=cancelCommandBlockOffset): yield i yield tempSchematic MCLevel.extractSchematic = extractSchematicFrom MCLevel.extractSchematicIter = extractSchematicFromIter MCLevel.adjustExtractionParameters = adjustExtractionParameters import tempfile def extractZipSchematicFrom(sourceLevel, box, zipfilename=None, entities=True): return exhaust(extractZipSchematicFromIter(sourceLevel, box, zipfilename, entities)) def extractZipSchematicFromIter(sourceLevel, box, zipfilename=None, entities=True, cancelCommandBlockOffset=False): # converts classic blocks to alpha # probably should only apply to alpha levels if zipfilename is None: zipfilename = tempfile.mktemp("zipschematic.zip") atexit.register(shutil.rmtree, zipfilename, True) p = sourceLevel.adjustExtractionParameters(box) if p is None: return sourceBox, destPoint = p destPoint = (0, 0, 0) tempSchematic = ZipSchematic(zipfilename, create=True) tempSchematic.materials = sourceLevel.materials for i in tempSchematic.copyBlocksFromIter(sourceLevel, sourceBox, destPoint, entities=entities, create=True, biomes=True, first=True, cancelCommandBlockOffset=cancelCommandBlockOffset): yield i tempSchematic.Width, tempSchematic.Height, tempSchematic.Length = sourceBox.size tempSchematic.saveInPlace() # lights not needed for this format - crashes minecraft though yield tempSchematic MCLevel.extractZipSchematic = extractZipSchematicFrom MCLevel.extractZipSchematicIter = extractZipSchematicFromIter def extractAnySchematic(level, box): return exhaust(level.extractAnySchematicIter(box)) def extractAnySchematicIter(level, box): if box.chunkCount < infiniteworld.MCInfdevOldLevel.loadedChunkLimit: for i in level.extractSchematicIter(box): yield i else: for i in level.extractZipSchematicIter(box): yield i MCLevel.extractAnySchematic = extractAnySchematic MCLevel.extractAnySchematicIter = extractAnySchematicIter
43,343
36.92126
173
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/test/schematic_test.py
import itertools import os import unittest from pymclevel import mclevel from templevel import TempLevel, mktemp from pymclevel.schematic import MCSchematic from pymclevel.box import BoundingBox __author__ = 'Rio' class TestSchematics(unittest.TestCase): def setUp(self): # self.alphaLevel = TempLevel("Dojo_64_64_128.dat") self.indevLevel = TempLevel("hell.mclevel") self.anvilLevel = TempLevel("AnvilWorld") def testCreate(self): # log.info("Schematic from indev") size = (64, 64, 64) temp = mktemp("testcreate.schematic") schematic = MCSchematic(shape=size, filename=temp, mats='Classic') level = self.indevLevel.level schematic.copyBlocksFrom(level, BoundingBox((0, 0, 0), (64, 64, 64,)), (0, 0, 0)) assert ((schematic.Blocks[0:64, 0:64, 0:64] == level.Blocks[0:64, 0:64, 0:64]).all()) schematic.copyBlocksFrom(level, BoundingBox((0, 0, 0), (64, 64, 64,)), (-32, -32, -32)) assert ((schematic.Blocks[0:32, 0:32, 0:32] == level.Blocks[32:64, 32:64, 32:64]).all()) schematic.saveInPlace() schem = mclevel.fromFile("schematics/CreativeInABox.schematic") tempSchematic = MCSchematic(shape=(1, 1, 3)) tempSchematic.copyBlocksFrom(schem, BoundingBox((0, 0, 0), (1, 1, 3)), (0, 0, 0)) level = self.anvilLevel.level for cx, cz in itertools.product(xrange(0, 4), xrange(0, 4)): try: level.createChunk(cx, cz) except ValueError: pass schematic.copyBlocksFrom(level, BoundingBox((0, 0, 0), (64, 64, 64,)), (0, 0, 0)) schematic.close() os.remove(temp) def testRotate(self): level = self.anvilLevel.level schematic = level.extractSchematic(BoundingBox((0, 0, 0), (21, 11, 8))) schematic.rotateLeft() level.copyBlocksFrom(schematic, schematic.bounds, level.bounds.origin, biomes=True, create=True) schematic.flipEastWest() level.copyBlocksFrom(schematic, schematic.bounds, level.bounds.origin, biomes=True, create=True) schematic.flipVertical() level.copyBlocksFrom(schematic, schematic.bounds, level.bounds.origin, biomes=True, create=True) def testZipSchematic(self): level = self.anvilLevel.level x, y, z = level.bounds.origin x += level.bounds.size[0] / 2 & ~15 z += level.bounds.size[2] / 2 & ~15 box = BoundingBox((x, y, z), (64, 64, 64,)) zs = level.extractZipSchematic(box) assert (box.chunkCount == zs.chunkCount) zs.close() os.remove(zs.filename) def testINVEditChests(self): invFile = mclevel.fromFile("schematics/Chests/TinkerersBox.inv") assert invFile.Blocks.any() assert not invFile.Data.any() assert len(invFile.Entities) == 0 assert len(invFile.TileEntities) == 1 # raise SystemExit
2,936
35.259259
104
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/test/nbt_test.py
from cStringIO import StringIO import os from os.path import join import time import unittest import numpy from pymclevel import nbt from templevel import TempLevel __author__ = 'Rio' class TestNBT(): @staticmethod def testLoad(): "Load an indev level." level = nbt.load("testfiles/hell.mclevel") # The root tag must have a name, and so must any tag within a TAG_Compound print level.name # Use the [] operator to look up subtags of a TAG_Compound. print level["Environment"]["SurroundingGroundHeight"].value # Numeric, string, and bytearray types have a value that can be accessed and changed. print level["Map"]["Blocks"].value return level @staticmethod def testLoadUncompressed(): root_tag = nbt.load("testfiles/uncompressed.nbt") @staticmethod def testLoadNBTExplorer(): root_tag = nbt.load("testfiles/modified_by_nbtexplorer.dat") @staticmethod def testCreate(): "Create an indev level." # The root of an NBT file is always a TAG_Compound. level = nbt.TAG_Compound(name="MinecraftLevel") # Subtags of a TAG_Compound are automatically named when you use the [] operator. level["About"] = nbt.TAG_Compound() level["About"]["Author"] = nbt.TAG_String("codewarrior") level["About"]["CreatedOn"] = nbt.TAG_Long(time.time()) level["Environment"] = nbt.TAG_Compound() level["Environment"]["SkyBrightness"] = nbt.TAG_Byte(16) level["Environment"]["SurroundingWaterHeight"] = nbt.TAG_Short(32) level["Environment"]["FogColor"] = nbt.TAG_Int(0xcccccc) entity = nbt.TAG_Compound() entity["id"] = nbt.TAG_String("Creeper") entity["Pos"] = nbt.TAG_List([nbt.TAG_Float(d) for d in (32.5, 64.0, 33.3)]) level["Entities"] = nbt.TAG_List([entity]) # You can also create and name a tag before adding it to the compound. spawn = nbt.TAG_List((nbt.TAG_Short(100), nbt.TAG_Short(45), nbt.TAG_Short(55))) spawn.name = "Spawn" mapTag = nbt.TAG_Compound() mapTag.add(spawn) mapTag.name = "Map" level.add(mapTag) mapTag2 = nbt.TAG_Compound([spawn]) mapTag2.name = "Map" # I think it looks more familiar with [] syntax. l, w, h = 128, 128, 128 mapTag["Height"] = nbt.TAG_Short(h) # y dimension mapTag["Length"] = nbt.TAG_Short(l) # z dimension mapTag["Width"] = nbt.TAG_Short(w) # x dimension # Byte arrays are stored as numpy.uint8 arrays. mapTag["Blocks"] = nbt.TAG_Byte_Array() mapTag["Blocks"].value = numpy.zeros(l * w * h, dtype=numpy.uint8) # create lots of air! # The blocks array is indexed (y,z,x) for indev levels, so reshape the blocks mapTag["Blocks"].value.shape = (h, l, w) # Replace the bottom layer of the indev level with wood mapTag["Blocks"].value[0, :, :] = 5 # This is a great way to learn the power of numpy array slicing and indexing. mapTag["Data"] = nbt.TAG_Byte_Array() mapTag["Data"].value = numpy.zeros(l * w * h, dtype=numpy.uint8) # Save a few more tag types for completeness level["ShortArray"] = nbt.TAG_Short_Array(numpy.zeros((16, 16), dtype='uint16')) level["IntArray"] = nbt.TAG_Int_Array(numpy.zeros((16, 16), dtype='uint32')) level["Float"] = nbt.TAG_Float(0.3) return level def testToStrings(self): level = self.testCreate() repr(level) repr(level["Map"]["Blocks"]) repr(level["Entities"]) str(level) def testModify(self): level = self.testCreate() # Most of the value types work as expected. Here, we replace the entire tag with a TAG_String level["About"]["Author"] = nbt.TAG_String("YARRR~!") # Because the tag type usually doesn't change, # we can replace the string tag's value instead of replacing the entire tag. level["About"]["Author"].value = "Stew Pickles" # Remove members of a TAG_Compound using del, similar to a python dict. del (level["About"]) # Replace all of the wood blocks with gold using a boolean index array blocks = level["Map"]["Blocks"].value blocks[blocks == 5] = 41 level["Entities"][0] = nbt.TAG_Compound([nbt.TAG_String("Creeper", "id"), nbt.TAG_List([nbt.TAG_Double(d) for d in (1, 1, 1)], "Pos")]) @staticmethod def testMultipleCompound(): """ According to rumor, some TAG_Compounds store several tags with the same name. Once I find a chunk file with such a compound, I need to test TAG_Compound.get_all()""" pass def testSave(self): level = self.testCreate() level["Environment"]["SurroundingWaterHeight"].value += 6 # Save the entire TAG structure to a different file. TempLevel("atlantis.mclevel", createFunc=level.save) # xxx don't use templevel here @staticmethod def testList(): tag = nbt.TAG_List() tag.append(nbt.TAG_Int(258)) del tag[0] def testErrors(self): """ attempt to name elements of a TAG_List named list elements are not allowed by the NBT spec, so we must discard any names when writing a list. """ level = self.testCreate() level["Map"]["Spawn"][0].name = "Torg Potter" data = level.save() newlevel = nbt.load(buf=data) n = newlevel["Map"]["Spawn"][0].name if n: print "Named list element failed: %s" % n # attempt to delete non-existent TAG_Compound elements # this generates a KeyError like a python dict does. level = self.testCreate() try: del level["DEADBEEF"] except KeyError: pass else: assert False @staticmethod def testSpeed(): d = join("testfiles", "TileTicks_chunks") files = [join(d, f) for f in os.listdir(d)] startTime = time.time() for f in files[:40]: n = nbt.load(f) duration = time.time() - startTime assert duration < 1.0 # Will fail when not using _nbt.pyx
6,328
32.486772
114
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/test/entity_test.py
from pymclevel import fromFile from templevel import TempLevel __author__ = 'Rio' def test_command_block(): level = TempLevel("AnvilWorld").level cmdblock = fromFile("testfiles/Commandblock.schematic") point = level.bounds.origin + [p / 2 for p in level.bounds.size] level.copyBlocksFrom(cmdblock, cmdblock.bounds, point) te = level.tileEntityAt(*point) command = te['Command'].value words = command.split(' ') x, y, z = words[2:5] assert x == str(point[0]) assert y == str(point[1] + 10) assert z == str(point[2])
565
24.727273
68
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/test/java_test.py
import unittest import numpy from templevel import TempLevel from pymclevel.box import BoundingBox __author__ = 'Rio' class TestJavaLevel(unittest.TestCase): def setUp(self): self.creativelevel = TempLevel("Dojo_64_64_128.dat") self.indevlevel = TempLevel("hell.mclevel") def testCopy(self): indevlevel = self.indevlevel.level creativelevel = self.creativelevel.level creativelevel.copyBlocksFrom(indevlevel, BoundingBox((0, 0, 0), (64, 64, 64,)), (0, 0, 0)) assert (numpy.array((indevlevel.Blocks[0:64, 0:64, 0:64]) == (creativelevel.Blocks[0:64, 0:64, 0:64])).all()) creativelevel.saveInPlace() # xxx old survival levels
701
29.521739
117
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/test/extended_id_test.py
from pymclevel import BoundingBox from pymclevel.schematic import MCSchematic from pymclevel import MCInfdevOldLevel from templevel import TempLevel __author__ = 'Rio' def test_schematic_extended_ids(): s = MCSchematic(shape=(1, 1, 5)) s.Blocks[0, 0, 0] = 2048 temp = TempLevel("schematic", createFunc=s.saveToFile) s = temp.level assert s.Blocks[0, 0, 0] == 2048 def alpha_test_level(): temp = TempLevel("alpha", createFunc=lambda f: MCInfdevOldLevel(f, create=True)) level = temp.level level.createChunk(0, 0) for x in range(0, 10): level.setBlockAt(x, 2, 5, 2048) level.saveInPlace() level.close() level = MCInfdevOldLevel(filename=level.filename) return level def testExport(): level = alpha_test_level() for size in [(16, 16, 16), (15, 16, 16), (15, 16, 15), (15, 15, 15), ]: schem = level.extractSchematic(BoundingBox((0, 0, 0), size)) schem = TempLevel("schem", createFunc=lambda f: schem.saveToFile(f)).level assert (schem.Blocks > 255).any() def testAlphaIDs(): level = alpha_test_level() assert level.blockAt(0, 2, 5) == 2048
1,205
23.612245
84
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/test/time_relight.py
from pymclevel.infiniteworld import MCInfdevOldLevel from pymclevel import mclevel from timeit import timeit import templevel # import logging #logging.basicConfig(level=logging.INFO) def natural_relight(): world = mclevel.fromFile("testfiles/AnvilWorld") t = timeit(lambda: world.generateLights(world.allChunks), number=1) print "Relight natural terrain: %d chunks in %.02f seconds (%.02fms per chunk)" % ( world.chunkCount, t, t / world.chunkCount * 1000) def manmade_relight(): t = templevel.TempLevel("TimeRelight", createFunc=lambda f: MCInfdevOldLevel(f, create=True)) world = t.level station = mclevel.fromFile("testfiles/station.schematic") times = 2 for x in range(times): for z in range(times): world.copyBlocksFrom(station, station.bounds, (x * station.Width, 63, z * station.Length), create=True) t = timeit(lambda: world.generateLights(world.allChunks), number=1) print "Relight manmade building: %d chunks in %.02f seconds (%.02fms per chunk)" % ( world.chunkCount, t, t / world.chunkCount * 1000) if __name__ == '__main__': natural_relight() manmade_relight()
1,163
29.631579
115
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/test/indev_test.py
import unittest from templevel import TempLevel from pymclevel.box import BoundingBox from pymclevel.entity import Entity, TileEntity __author__ = 'Rio' class TestIndevLevel(unittest.TestCase): def setUp(self): self.srclevel = TempLevel("hell.mclevel") self.indevlevel = TempLevel("hueg.mclevel") def testEntities(self): level = self.indevlevel.level entityTag = Entity.Create("Zombie") tileEntityTag = TileEntity.Create("Painting") level.addEntity(entityTag) level.addTileEntity(tileEntityTag) schem = level.extractSchematic(level.bounds) level.copyBlocksFrom(schem, schem.bounds, (0, 0, 0)) # raise Failure def testCopy(self): indevlevel = self.indevlevel.level srclevel = self.srclevel.level indevlevel.copyBlocksFrom(srclevel, BoundingBox((0, 0, 0), (64, 64, 64,)), (0, 0, 0)) assert ((indevlevel.Blocks[0:64, 0:64, 0:64] == srclevel.Blocks[0:64, 0:64, 0:64]).all()) def testFill(self): indevlevel = self.indevlevel.level indevlevel.fillBlocks(BoundingBox((0, 0, 0), (64, 64, 64,)), indevlevel.materials.Sand, [indevlevel.materials.Stone, indevlevel.materials.Dirt]) indevlevel.saveInPlace()
1,287
32.894737
97
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/test/templevel.py
import atexit import os from os.path import join import shutil import tempfile from pymclevel import mclevel __author__ = 'Rio' tempdir = os.path.join(tempfile.gettempdir(), "pymclevel_test") if not os.path.exists(tempdir): os.mkdir(tempdir) def mktemp(suffix): td = tempfile.mkdtemp(suffix, dir=tempdir) os.rmdir(td) return td class TempLevel(object): def __init__(self, filename, createFunc=None): if not os.path.exists(filename): filename = join("testfiles", filename) tmpname = mktemp(os.path.basename(filename)) if os.path.exists(filename): if os.path.isdir(filename): shutil.copytree(filename, tmpname) else: shutil.copy(filename, tmpname) elif createFunc: createFunc(tmpname) else: raise IOError("File %s not found." % filename) self.tmpname = tmpname self.level = mclevel.fromFile(tmpname) atexit.register(self.removeTemp) def __del__(self): if hasattr(self, 'level'): self.level.close() del self.level self.removeTemp() def removeTemp(self): if hasattr(self, 'tmpname'): filename = self.tmpname if os.path.isdir(filename): shutil.rmtree(filename) else: os.unlink(filename)
1,394
23.910714
63
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/test/mcr_test.py
import anvil_test from templevel import TempLevel __author__ = 'Rio' class TestMCR(anvil_test.TestAnvilLevel): def setUp(self): self.indevLevel = TempLevel("hell.mclevel") self.anvilLevel = TempLevel("PyTestWorld")
238
20.727273
51
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/test/pocket_test.py
import unittest import numpy from templevel import TempLevel __author__ = 'Rio' class TestPocket(unittest.TestCase): def setUp(self): # self.alphaLevel = TempLevel("Dojo_64_64_128.dat") self.level = TempLevel("PocketWorld") self.alphalevel = TempLevel("AnvilWorld") def testPocket(self): level = self.level.level # alphalevel = self.alphalevel.level print "Chunk count", len(level.allChunks) chunk = level.getChunk(1, 5) a = numpy.array(chunk.SkyLight) chunk.dirty = True chunk.needsLighting = True level.generateLights() level.saveInPlace() assert (a == chunk.SkyLight).all() # level.copyBlocksFrom(alphalevel, BoundingBox((0, 0, 0), (64, 64, 64,)), (0, 0, 0)) # assert((level.Blocks[0:64, 0:64, 0:64] == alphalevel.Blocks[0:64, 0:64, 0:64]).all())
883
30.571429
95
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/test/time_nbt.py
from StringIO import StringIO __author__ = 'Rio' import pymclevel.nbt as nbt from timeit import timeit path = "testfiles/TileTicks.nbt" test_data = file(path, "rb").read() test_file = None resaved_test_file = None def load_file(): global test_file test_file = nbt.load(buf=test_data) def save_file(): global resaved_test_file resaved_test_file = test_file.save(compressed=False) # resaved_test_file = test_file.save(buf=s) # resaved_test_file = s.getvalue() print "File: ", path print "Load: %0.1f ms" % (timeit(load_file, number=1) * 1000) print "Save: %0.1f ms" % (timeit(save_file, number=1) * 1000) print "Length: ", len(resaved_test_file) assert test_data == resaved_test_file __author__ = 'Rio'
737
20.085714
61
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/test/__init__.py
__author__ = 'Rio'
19
9
18
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/test/server_test.py
import unittest from pymclevel.minecraft_server import MCServerChunkGenerator from templevel import TempLevel from pymclevel.box import BoundingBox __author__ = 'Rio' class TestServerGen(unittest.TestCase): def setUp(self): # self.alphaLevel = TempLevel("Dojo_64_64_128.dat") self.alphalevel = TempLevel("AnvilWorld") def testCreate(self): gen = MCServerChunkGenerator() print "Version: ", gen.serverVersion def _testCreate(filename): gen.createLevel(filename, BoundingBox((-128, 0, -128), (128, 128, 128))) TempLevel("ServerCreate", createFunc=_testCreate) def testServerGen(self): gen = MCServerChunkGenerator() print "Version: ", gen.serverVersion level = self.alphalevel.level gen.generateChunkInLevel(level, 50, 50) gen.generateChunksInLevel(level, [(120, 50), (121, 50), (122, 50), (123, 50), (244, 244), (244, 245), (244, 246)]) c = level.getChunk(50, 50) assert c.Blocks.any()
1,056
30.088235
115
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/test/session_lock_test.py
from pymclevel.infiniteworld import SessionLockLost, MCInfdevOldLevel from templevel import TempLevel import unittest class SessionLockTest(unittest.TestCase): def test_session_lock(self): temp = TempLevel("AnvilWorld") level = temp.level def touch(): level.saveInPlace() self.assertRaises(SessionLockLost, touch)
366
23.466667
69
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/test/anvil_test.py
import itertools import os import shutil import unittest import numpy from pymclevel import mclevel from pymclevel.infiniteworld import MCInfdevOldLevel from pymclevel import nbt from pymclevel.schematic import MCSchematic from pymclevel.box import BoundingBox from pymclevel import block_copy from templevel import mktemp, TempLevel __author__ = 'Rio' class TestAnvilLevelCreate(unittest.TestCase): def testCreate(self): temppath = mktemp("AnvilCreate") self.anvilLevel = MCInfdevOldLevel(filename=temppath, create=True) self.anvilLevel.close() shutil.rmtree(temppath) class TestAnvilLevel(unittest.TestCase): def setUp(self): self.indevLevel = TempLevel("hell.mclevel") self.anvilLevel = TempLevel("AnvilWorld") def testUnsetProperties(self): level = self.anvilLevel.level del level.root_tag['Data']['LastPlayed'] import time assert 0 != level.LastPlayed level.LastPlayed = time.time() * 1000 - 1000000 def testGetEntities(self): level = self.anvilLevel.level print len(level.getEntitiesInBox(level.bounds)) def testCreateChunks(self): level = self.anvilLevel.level for ch in list(level.allChunks): level.deleteChunk(*ch) level.createChunksInBox(BoundingBox((0, 0, 0), (32, 0, 32))) def testCopyChunks(self): level = self.anvilLevel.level temppath = mktemp("AnvilCreate") newLevel = MCInfdevOldLevel(filename=temppath, create=True) for cx, cz in level.allChunks: newLevel.copyChunkFrom(level, cx, cz) newLevel.close() shutil.rmtree(temppath) def testCopyConvertBlocks(self): indevlevel = self.indevLevel.level level = self.anvilLevel.level x, y, z = level.bounds.origin x += level.bounds.size[0] / 2 & ~15 z += level.bounds.size[2] / 2 & ~15 x -= indevlevel.Width / 2 z -= indevlevel.Height / 2 middle = (x, y, z) oldEntityCount = len(level.getEntitiesInBox(BoundingBox(middle, indevlevel.bounds.size))) level.copyBlocksFrom(indevlevel, indevlevel.bounds, middle) convertedSourceBlocks, convertedSourceData = block_copy.convertBlocks(indevlevel, level, indevlevel.Blocks[0:16, 0:16, 0:indevlevel.Height], indevlevel.Data[0:16, 0:16, 0:indevlevel.Height]) assert ((level.getChunk(x >> 4, z >> 4).Blocks[0:16, 0:16, 0:indevlevel.Height] == convertedSourceBlocks).all()) assert (oldEntityCount + len(indevlevel.getEntitiesInBox(indevlevel.bounds)) == len(level.getEntitiesInBox(BoundingBox(middle, indevlevel.bounds.size)))) def testImportSchematic(self): level = self.anvilLevel.level cx, cz = level.allChunks.next() schem = mclevel.fromFile("schematics/CreativeInABox.schematic") box = BoundingBox((cx * 16, 64, cz * 16), schem.bounds.size) level.copyBlocksFrom(schem, schem.bounds, (0, 64, 0)) schem = MCSchematic(shape=schem.bounds.size) schem.copyBlocksFrom(level, box, (0, 0, 0)) convertedSourceBlocks, convertedSourceData = block_copy.convertBlocks(schem, level, schem.Blocks, schem.Data) assert (level.getChunk(cx, cz).Blocks[0:1, 0:3, 64:65] == convertedSourceBlocks).all() def testRecreateChunks(self): level = self.anvilLevel.level for x, z in itertools.product(xrange(-1, 3), xrange(-1, 2)): level.deleteChunk(x, z) assert not level.containsChunk(x, z) level.createChunk(x, z) def testFill(self): level = self.anvilLevel.level cx, cz = level.allChunks.next() box = BoundingBox((cx * 16, 0, cz * 16), (32, level.Height, 32)) level.fillBlocks(box, level.materials.WoodPlanks) level.fillBlocks(box, level.materials.WoodPlanks, [level.materials.Stone]) level.saveInPlace() c = level.getChunk(cx, cz) assert (c.Blocks == 5).all() def testReplace(self): level = self.anvilLevel.level level.fillBlocks(BoundingBox((-11, 0, -7), (38, level.Height, 25)), level.materials.WoodPlanks, [level.materials.Dirt, level.materials.Grass]) def testSaveRelight(self): indevlevel = self.indevLevel.level level = self.anvilLevel.level cx, cz = -3, -1 level.deleteChunk(cx, cz) level.createChunk(cx, cz) level.copyBlocksFrom(indevlevel, BoundingBox((0, 0, 0), (32, 64, 32,)), level.bounds.origin) level.generateLights() level.saveInPlace() def testRecompress(self): level = self.anvilLevel.level cx, cz = level.allChunks.next() ch = level.getChunk(cx, cz) ch.dirty = True ch.Blocks[:] = 6 ch.Data[:] = 13 d = {} keys = 'Blocks Data SkyLight BlockLight'.split() for key in keys: d[key] = numpy.array(getattr(ch, key)) for i in range(5): level.saveInPlace() ch = level.getChunk(cx, cz) ch.dirty = True assert (ch.Data == 13).all() for key in keys: assert (d[key] == getattr(ch, key)).all() def testPlayerSpawn(self): level = self.anvilLevel.level level.setPlayerSpawnPosition((0, 64, 0), "Player") level.getPlayerPosition() assert len(level.players) != 0 def testBigEndianIntHeightMap(self): """ Test modifying, saving, and loading the new TAG_Int_Array heightmap added with the Anvil format. """ chunk = nbt.load("testfiles/AnvilChunk.dat") hm = chunk["Level"]["HeightMap"] hm.value[2] = 500 oldhm = numpy.array(hm.value) filename = mktemp("ChangedChunk") chunk.save(filename) changedChunk = nbt.load(filename) os.unlink(filename) eq = (changedChunk["Level"]["HeightMap"].value == oldhm) assert eq.all()
6,338
33.82967
117
py
MCEdit-Unified
MCEdit-Unified-master/pymclevel/test/test_primordial.py
from templevel import TempLevel def testPrimordialDesert(): templevel = TempLevel("PrimordialDesert") level = templevel.level for chunk in level.allChunks: level.getChunk(*chunk)
201
21.444444
45
py
MCEdit-Unified
MCEdit-Unified-master/utilities/mcworld_support.py
import tempfile import shutil import zipfile import atexit import os import glob DO_REMOVE = True def trim_any_leftovers(): print tempfile.gettempdir() leftovers = glob.glob(os.path.join(tempfile.gettempdir(), 'mcworld_*', '')) for d in leftovers: print "Found left over directory: {}".format(d) if DO_REMOVE: shutil.rmtree(d, ignore_errors=True) def close_all_temp_dirs(): for d in glob.glob(os.path.join(tempfile.gettempdir(), 'mcworld_*', '')): #print d #print os.path.dirname(d) #print '=====' print "Found temp directory to cleanup: {}".format(d) if DO_REMOVE: shutil.rmtree(d, ignore_errors=True) #shutil.rmtree(os.path.dirname(os.path.dirname(d)), ignore_errors=True) def _find_level_dat(directory): for root, dirs, files in os.walk(directory): if 'level.dat' in files and 'db' in dirs: return os.path.join(root, 'level.dat') def open_world(file_path): temp_dir = tempfile.mkdtemp(prefix="mcworld_") zip_fd = zipfile.ZipFile(file_path, 'r') zip_fd.extractall(temp_dir) zip_fd.close() return _find_level_dat(temp_dir) def save_world(world_path, dest_path): zip_fd = zipfile.ZipFile(dest_path, 'w') for root, dirs, files in os.walk(world_path): for f in files: result = os.path.join(root, f) result = result.replace(world_path, '')[1:] fp = open(os.path.join(root, f), 'rb') zip_fd.writestr(result, fp.read()) fp.close() zip_fd.close() return os.path.basename(dest_path) atexit.register(close_all_temp_dirs) trim_any_leftovers()
1,674
29.454545
79
py
MCEdit-Unified
MCEdit-Unified-master/utilities/misc.py
# Taken from: http://stackoverflow.com/a/7346105 class Singleton: """ A non-thread-safe helper class to ease implementing singletons. This should be used as a decorator -- not a metaclass -- to the class that should be a singleton. The decorated class can define one `__init__` function that takes only the `self` argument. Other than that, there are no restrictions that apply to the decorated class. To get the singleton instance, use the `Instance` method. Trying to use `__call__` will result in a `TypeError` being raised. Limitations: The decorated class cannot be inherited from. """ def __init__(self, decorated): self._decorated = decorated def Instance(self): """ Returns the singleton instance. Upon its first call, it creates a new instance of the decorated class and calls its `__init__` method. On all subsequent calls, the already created instance is returned. """ try: return self._instance except AttributeError: self._instance = self._decorated() return self._instance def __call__(self): raise TypeError('Singletons must be accessed through `Instance()`.') def __instancecheck__(self, inst): return isinstance(inst, self._decorated) def deprecated(func): ''' Function decorator to denote that a function shouldn't be used :param func: The function that is deprecated ''' def new_func(*args, **kwargs): #logger.warn("Function \""+str(func.__name__)+"\" is deprecated and should not be used") return func(*args, **kwargs) new_func.__name__ = func.__name__ if func.__doc__ is not None: new_func.__doc__ = '''*Deprecated*\n%s'''%func.__doc__ else: new_func.__doc__ = '''*Deprecated*''' new_func.__dict__.update(func.__dict__) return new_func def unicoded(func): def wrapper(*args, **kwargs): return unicode(func(*args, **kwargs)) return wrapper
2,054
30.615385
96
py
MCEdit-Unified
MCEdit-Unified-master/utilities/gl_display_context.py
from OpenGL import GL, GLU from config import config import pygame from pygame import display, image import logging import sys import directories import os import mcplatform import numpy import pymclevel from resource_packs import ResourcePackHandler import glutils import mceutils import functools DEBUG_WM = mcplatform.DEBUG_WM USE_WM = mcplatform.USE_WM class GLDisplayContext(object): def __init__(self, splash=None, caption=("", "")): self.win = None self.reset(splash, caption=caption) @staticmethod def getWindowSize(): w, h = (config.settings.windowWidth.get(), config.settings.windowHeight.get()) return max(20, w), max(20, h) @staticmethod def displayMode(): return pygame.OPENGL | pygame.RESIZABLE | pygame.DOUBLEBUF def reset(self, splash=None, caption=("", "")): pygame.key.set_repeat(500, 100) try: display.gl_set_attribute(pygame.GL_SWAP_CONTROL, config.settings.vsync.get()) except Exception as e: logging.warning('Unable to set vertical sync: {0!r}'.format(e)) display.gl_set_attribute(pygame.GL_ALPHA_SIZE, 8) if DEBUG_WM: print "config.settings.windowMaximized.get()", config.settings.windowMaximized.get() wwh = self.getWindowSize() if DEBUG_WM: print "wwh 1", wwh d = display.set_mode(wwh, self.displayMode()) # Let initialize OpenGL stuff after the splash. GL.glEnableClientState(GL.GL_VERTEX_ARRAY) GL.glAlphaFunc(GL.GL_NOTEQUAL, 0) GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA) # textures are 256x256, so with this we can specify pixel coordinates # GL.glMatrixMode(GL.GL_TEXTURE) # GL.glScale(1 / 256., 1 / 256., 1 / 256.) display.set_caption(*caption) if mcplatform.WindowHandler: self.win = mcplatform.WindowHandler(mode=self.displayMode()) # The following Windows specific code won't be executed if we're using '--debug-wm' switch. if not USE_WM and sys.platform == 'win32' and config.settings.setWindowPlacement.get(): config.settings.setWindowPlacement.set(False) config.save() X, Y = config.settings.windowX.get(), config.settings.windowY.get() if X: hwndOwner = display.get_wm_info()['window'] flags, showCmd, ptMin, ptMax, rect = mcplatform.win32gui.GetWindowPlacement(hwndOwner) realW = rect[2] - rect[0] realH = rect[3] - rect[1] showCmd = config.settings.windowShowCmd.get() rect = (X, Y, X + realW, Y + realH) mcplatform.win32gui.SetWindowPlacement(hwndOwner, (0, showCmd, ptMin, ptMax, rect)) config.settings.setWindowPlacement.set(True) config.save() elif self.win: maximized = config.settings.windowMaximized.get() if DEBUG_WM: print "maximized", maximized if maximized: geom = self.win.get_root_rect() in_w, in_h = self.win.get_size() x, y = int((geom[2] - in_w) / 2), int((geom[3] - in_h) / 2) os.environ['SDL_VIDEO_CENTERED'] = '1' else: os.environ['SDL_VIDEO_CENTERED'] = '0' x, y = config.settings.windowX.get(), config.settings.windowY.get() wwh = self.win.get_size() if DEBUG_WM: print "x", x, "y", y print "wwh 2", wwh if splash: # Setup the OGL display GL.glLoadIdentity() GLU.gluOrtho2D(0, wwh[0], 0, wwh[1]) GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT | GL.GL_ACCUM_BUFFER_BIT | GL.GL_STENCIL_BUFFER_BIT) swh = splash.get_size() _x, _y = (wwh[0] / 2 - swh[0] / 2, wwh[1] / 2 - swh[1] / 2) w, h = swh try: data = image.tostring(splash, 'RGBA_PREMULT', 1) except ValueError: data = image.tostring(splash, 'RGBA', 1) except ValueError: data = image.tostring(splash, 'RGB', 1) # Set the raster position GL.glRasterPos(_x, _y) GL.glDrawPixels(w, h, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, numpy.fromstring(data, dtype='uint8')) if splash: display.flip() if self.win: if not maximized: wwh = self.getWindowSize() if DEBUG_WM: print "wwh 3", wwh self.win.set_position((x, y), update=True) if DEBUG_WM: print "* self.win.get_position()", self.win.get_position() try: #iconpath = os.path.join(directories.getDataDir(), 'favicon.png') iconpath = directories.getDataFile('favicon.png') iconfile = file(iconpath, 'rb') icon = pygame.image.load(iconfile, 'favicon.png') display.set_icon(icon) except Exception as e: logging.warning('Unable to set icon: {0!r}'.format(e)) # Let initialize OpenGL stuff after the splash. # GL.glEnableClientState(GL.GL_VERTEX_ARRAY) # GL.glAlphaFunc(GL.GL_NOTEQUAL, 0) # GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA) # textures are 256x256, so with this we can specify pixel coordinates GL.glMatrixMode(GL.GL_TEXTURE) GL.glScale(1 / 256., 1 / 256., 1 / 256.) self.display = d self.loadTextures() def getTerrainTexture(self, level): return self.terrainTextures.get(level.materials.name, self.terrainTextures["Alpha"]) def loadTextures(self): self.terrainTextures = {} def makeTerrainTexture(mats): w, h = 1, 1 teximage = numpy.zeros((w, h, 4), dtype='uint8') teximage[:] = 127, 127, 127, 255 GL.glTexImage2D( GL.GL_TEXTURE_2D, 0, GL.GL_RGBA8, w, h, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, teximage ) textures = ( (pymclevel.classicMaterials, 'terrain-classic.png'), (pymclevel.indevMaterials, 'terrain-classic.png'), (pymclevel.alphaMaterials, ResourcePackHandler.Instance().get_selected_resource_pack().terrain_path()), (pymclevel.pocketMaterials, 'terrain-pocket.png') ) for mats, matFile in textures: try: if mats.name == 'Alpha': tex = mceutils.loadAlphaTerrainTexture() else: tex = mceutils.loadPNGTexture(matFile) self.terrainTextures[mats.name] = tex except Exception as e: logging.warning( 'Unable to load terrain from {0}, using flat colors.' 'Error was: {1!r}'.format(matFile, e) ) self.terrainTextures[mats.name] = glutils.Texture( functools.partial(makeTerrainTexture, mats) ) mats.terrainTexture = self.terrainTextures[mats.name]
7,347
34.497585
123
py
MCEdit-Unified
MCEdit-Unified-master/utilities/__init__.py
0
0
0
py
MCEdit-Unified
MCEdit-Unified-master/utilities/mcver_updater.py
import urllib2 import json import os from logging import getLogger def run(): log = getLogger(__name__) num = False def download(_gamePlatform, _gameVersionNumber, url): _download = False dir_path = os.path.join(base, "mcver", _gamePlatform, _gameVersionNumber) file_path = os.path.join(dir_path, os.path.basename(url)) if not (os.path.exists(dir_path) or os.path.isdir(dir_path)): os.makedirs(dir_path) _download = True if not os.path.exists(file_path): _download = True else: conn = urllib2.urlopen(url, timeout=7.5) new_data = conn.read().strip() current = open(file_path, 'rb') current_data = current.read().strip() conn.close() current.close() if new_data != current_data: fp = open(file_path, 'wb') fp.write(new_data.strip()) fp.close() log.info("Updated {} {}::{}".format(_gamePlatform, _gameVersionNumber, os.path.basename(file_path))) return True if _download: conn = urllib2.urlopen(url, timeout=7.5) fp = open(file_path, 'wb') fp.write(conn.read()) conn.close() fp.close() log.info("Downloaded {} {}::{}".format(_gamePlatform, _gameVersionNumber, os.path.basename(file_path))) return True return False base = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ver = [] try: manifest = urllib2.urlopen("https://raw.githubusercontent.com/Podshot/MCEdit-Unified/master/mcver/mcver.json") data = json.loads(manifest.read()) manifest.close() except: return for gamePlatform in data.iterkeys(): for gameVersionNumber in data[gamePlatform].iterkeys(): for f in data[gamePlatform][gameVersionNumber]: if download(gamePlatform, gameVersionNumber, f): num = True return num
2,062
33.966102
118
py
MCEdit-Unified
MCEdit-Unified-master/panels/control.py
from __future__ import unicode_literals from config import config import release import platform from albow import AttrRef, Row, Column from albow.resource import get_font from albow.controls import Label from albow.extended_widgets import HotkeyColumn from pygame import key from glbackground import Panel arch = platform.architecture()[0] class ControlPanel(Panel): @classmethod def getHeader(cls): header = Label("MCEdit {0} ({1})".format(release.get_version(), arch), font=get_font(18, "DejaVuSans-Bold.ttf")) return header def __init__(self, editor): Panel.__init__(self, name='Panel.ControlPanel') self.editor = editor self.bg_color = (0, 0, 0, 0.8) header = self.getHeader() keysColumn = [Label("")] buttonsColumn = [header] hotkeys = ([(config.keys.newWorld.get(), "Create New World", editor.mcedit.createNewWorld), (config.keys.quickLoad.get(), "Quick Load", editor.askLoadWorld), (config.keys.open.get(), "Open...", editor.askOpenFile), (config.keys.save.get(), "Save", editor.saveFile), (config.keys.saveAs.get(), "Save As", editor.saveAs), (config.keys.reloadWorld.get(), "Reload", editor.reload), (config.keys.closeWorld.get(), "Close", editor.closeEditor), (config.keys.uploadWorld.get(), "Upload to FTP Server", editor.uploadChanges), (config.keys.gotoPanel.get(), "Waypoints/Goto", editor.showWaypointsDialog), (config.keys.worldInfo.get(), "World Info", editor.showWorldInfo), (config.keys.undo.get(), "Undo", editor.undo), (config.keys.redo.get(), "Redo", editor.redo), (config.keys.selectAll.get(), "Select All", editor.selectAll), (config.keys.deselect.get(), "Deselect", editor.deselect), (config.keys.viewDistance.get(), AttrRef(editor, 'viewDistanceLabelText'), editor.swapViewDistance), (config.keys.quit.get(), "Quit", editor.quit), ]) buttons = HotkeyColumn(hotkeys, keysColumn, buttonsColumn, item_spacing=2) sideColumn1 = editor.mcedit.makeSideColumn1() sideColumn2 = editor.mcedit.makeSideColumn2() spaceLabel = Label("") sideColumn = Column((sideColumn1, spaceLabel, sideColumn2)) self.add(Row([buttons, sideColumn])) self.shrink_wrap() def key_down(self, evt): if key.name(evt.key) == 'escape': self.dismiss() else: self.editor.key_down(evt) def key_up(self, evt): self.editor.key_up(evt) def mouse_down(self, e): if e not in self: self.dismiss()
2,874
37.333333
120
py
MCEdit-Unified
MCEdit-Unified-master/panels/graphics.py
from __future__ import unicode_literals import albow from albow.dialogs import Dialog from resource_packs import ResourcePackHandler import pymclevel from config import config class GraphicsPanel(Dialog): anchor = 'wh' def __init__(self, mcedit): Dialog.__init__(self) self.mcedit = mcedit self.saveOldConfig = { config.settings.fov: config.settings.fov.get(), config.settings.targetFPS: config.settings.targetFPS.get(), config.settings.vertexBufferLimit: config.settings.vertexBufferLimit.get(), config.settings.fastLeaves: config.settings.fastLeaves.get(), config.settings.roughGraphics: config.settings.roughGraphics.get(), config.settings.enableMouseLag: config.settings.enableMouseLag.get(), config.settings.maxViewDistance: config.settings.maxViewDistance.get() } self.saveOldResourcePack = ResourcePackHandler.Instance().get_selected_resource_pack_name() self.fieldOfViewRow = albow.FloatInputRow("Field of View: ", ref=config.settings.fov, width=100, min=25, max=120) self.targetFPSRow = albow.IntInputRow("Target FPS: ", ref=config.settings.targetFPS, width=100, min=1, max=60) self.bufferLimitRow = albow.IntInputRow("Vertex Buffer Limit (MB): ", ref=config.settings.vertexBufferLimit, width=100, min=0) fastLeavesRow = albow.CheckBoxLabel("Fast Leaves", ref=config.settings.fastLeaves, tooltipText="Leaves are solid, like Minecraft's 'Fast' graphics") roughGraphicsRow = albow.CheckBoxLabel("Rough Graphics", ref=config.settings.roughGraphics, tooltipText="All blocks are drawn the same way (overrides 'Fast Leaves')") enableMouseLagRow = albow.CheckBoxLabel("Enable Mouse Lag", ref=config.settings.enableMouseLag, tooltipText="Enable choppy mouse movement for faster loading.") playerSkins = albow.CheckBoxLabel("Show Player Skins", ref=config.settings.downloadPlayerSkins, tooltipText="Show player skins while editing the world") self.maxView = albow.IntInputRow("Max View Distance", ref=config.settings.maxViewDistance, tooltipText="Sets the maximum view distance for the renderer. Values over 32 can possibly be unstable, so use it at your own risk" ) self.maxView.subwidgets[1]._increment = 2 packs = ResourcePackHandler.Instance().get_available_resource_packs() packs.remove('Default Resource Pack') packs.sort() packs.insert(0, 'Default Resource Pack') self.resourcePackButton = albow.ChoiceButton(packs, choose=self.change_texture, doNotTranslate=True) self.resourcePackButton.selectedChoice = self.saveOldResourcePack settingsColumn = albow.Column((fastLeavesRow, roughGraphicsRow, enableMouseLagRow, # texturePackRow, self.fieldOfViewRow, self.targetFPSRow, self.bufferLimitRow, self.maxView, playerSkins, self.resourcePackButton, ), align='r') settingsColumn = albow.Column((albow.Label("Graphics Settings"), settingsColumn)) settingsRow = albow.Row((settingsColumn,)) buttonsRow = albow.Row((albow.Button("OK", action=self.dismiss), albow.Button("Cancel", action=self.cancel))) resetToDefaultRow = albow.Row((albow.Button("Reset to default", action=self.resetDefault),)) optionsColumn = albow.Column((settingsRow, buttonsRow, resetToDefaultRow)) self.add(optionsColumn) self.shrink_wrap() def _reloadTextures(self, pack): if hasattr(pymclevel.alphaMaterials, "terrainTexture"): self.mcedit.displayContext.loadTextures() def change_texture(self): ResourcePackHandler.Instance().set_selected_resource_pack_name(self.resourcePackButton.selectedChoice) self.mcedit.displayContext.loadTextures() texturePack = config.settings.skin.property(_reloadTextures) def checkMaxView(self): if (config.settings.maxViewDistance.get() % 2) != 0: config.settings.maxViewDistance.set(config.settings.maxViewDistance.get()-1) def dismiss(self, *args, **kwargs): self.reshowNumberFields() self.checkMaxView() for key in self.saveOldConfig.keys(): self.saveOldConfig[key] = key.get() self.saveOldResourcePack = self.resourcePackButton.selectedChoice config.save() Dialog.dismiss(self, *args, **kwargs) def cancel(self, *args, **kwargs): Changes = False self.reshowNumberFields() for key in self.saveOldConfig.keys(): if key.get() != self.saveOldConfig[key]: Changes = True if self.saveOldResourcePack != self.resourcePackButton.selectedChoice: Changes = True if not Changes: Dialog.dismiss(self, *args, **kwargs) return result = albow.ask("Do you want to save your changes?", ["Save", "Don't Save", "Cancel"]) if result == "Cancel": return if result == "Save": self.dismiss(*args, **kwargs) return for key in self.saveOldConfig.keys(): key.set(self.saveOldConfig[key]) if self.resourcePackButton.selectedChoice != self.saveOldResourcePack: self.resourcePackButton.selectedChoice = self.saveOldResourcePack self.change_texture() config.save() Dialog.dismiss(self, *args, **kwargs) def resetDefault(self): for key in self.saveOldConfig.keys(): key.set(key.default) self.reshowNumberFields() if self.resourcePackButton.selectedChoice != "Default Resource Pack": self.resourcePackButton.selectedChoice = "Default Resource Pack" self.change_texture() config.save() def reshowNumberFields(self): self.fieldOfViewRow.subwidgets[1].editing = False self.targetFPSRow.subwidgets[1].editing = False self.bufferLimitRow.subwidgets[1].editing = False self.maxView.subwidgets[1].editing = False def dispatch_key(self, name, evt): super(GraphicsPanel, self).dispatch_key(name, evt) if name == "key_down": keyname = self.get_root().getKey(evt) if keyname == 'Escape': self.cancel()
7,380
42.934524
169
py
MCEdit-Unified
MCEdit-Unified-master/panels/options.py
from __future__ import unicode_literals import albow from albow.dialogs import Dialog from config import config import pygame from albow.translate import _, buildTemplate import sys import os import logging import traceback import directories old_lang = None old_fprop = None class OptionsPanel(Dialog): anchor = 'wh' def __init__(self, mcedit): Dialog.__init__(self) self.mcedit = mcedit self.langs = {} self.sgnal = {} self.portableVar = albow.AttrRef(self, 'portableLabelText') self.saveOldPortable = self.portableVar.get() self.saveOldConfig = { config.controls.autobrake: config.controls.autobrake.get(), config.controls.swapAxes: config.controls.swapAxes.get(), config.controls.cameraAccel: config.controls.cameraAccel.get(), config.controls.cameraDrag: config.controls.cameraDrag.get(), config.controls.cameraMaxSpeed: config.controls.cameraMaxSpeed.get(), config.controls.cameraBrakingSpeed: config.controls.cameraBrakingSpeed.get(), config.controls.mouseSpeed: config.controls.mouseSpeed.get(), config.settings.undoLimit: config.settings.undoLimit.get(), config.settings.maxCopies: config.settings.maxCopies.get(), config.controls.invertMousePitch: config.controls.invertMousePitch.get(), config.settings.spaceHeight: config.settings.spaceHeight.get(), albow.AttrRef(self, 'blockBuffer'): albow.AttrRef(self, 'blockBuffer').get(), config.settings.setWindowPlacement: config.settings.setWindowPlacement.get(), config.settings.rotateBlockBrush: config.settings.rotateBlockBrush.get(), config.settings.shouldResizeAlert: config.settings.shouldResizeAlert.get(), config.settings.superSecretSettings: config.settings.superSecretSettings.get(), config.settings.longDistanceMode: config.settings.longDistanceMode.get(), config.settings.flyMode: config.settings.flyMode.get(), config.settings.langCode: config.settings.langCode.get(), config.settings.compassToggle: config.settings.compassToggle.get(), config.settings.compassSize: config.settings.compassSize.get(), config.settings.fontProportion: config.settings.fontProportion.get(), config.settings.fogIntensity: config.settings.fogIntensity.get(), config.schematicCopying.cancelCommandBlockOffset: config.schematicCopying.cancelCommandBlockOffset.get() } global old_lang if old_lang == None: old_lang = config.settings.langCode.get() global old_fprop if old_fprop == None: old_fprop = config.settings.fontProportion.get() def initComponents(self): """Initilize the window components. Call this after translation hs been loaded.""" autoBrakeRow = albow.CheckBoxLabel("Autobrake", ref=config.controls.autobrake, tooltipText="Apply brake when not pressing movement keys") swapAxesRow = albow.CheckBoxLabel("Swap Axes Looking Down", ref=config.controls.swapAxes, tooltipText="Change the direction of the Forward and Backward keys when looking down") cameraAccelRow = albow.FloatInputRow("Camera Acceleration: ", ref=config.controls.cameraAccel, width=100, min=5.0) cameraDragRow = albow.FloatInputRow("Camera Drag: ", ref=config.controls.cameraDrag, width=100, min=1.0) cameraMaxSpeedRow = albow.FloatInputRow("Camera Max Speed: ", ref=config.controls.cameraMaxSpeed, width=100, min=1.0) cameraBrakeSpeedRow = albow.FloatInputRow("Camera Braking Speed: ", ref=config.controls.cameraBrakingSpeed, width=100, min=1.0) mouseSpeedRow = albow.FloatInputRow("Mouse Speed: ", ref=config.controls.mouseSpeed, width=100, min=0.1, max=20.0) undoLimitRow = albow.IntInputRow("Undo Limit: ", ref=config.settings.undoLimit, width=100, min=0) maxCopiesRow = albow.IntInputRow("Copy Stack Size: ", ref=config.settings.maxCopies, width=100, min=0, tooltipText="Maximum number of copied objects.") compassSizeRow = albow.IntInputRow("Compass Size (%): ", ref=config.settings.compassSize, width=100, min=0, max=100) fontProportion = albow.IntInputRow("Fonts Proportion (%): ", ref=config.settings.fontProportion, width=100, min=0, tooltipText="Fonts sizing proportion. The number is a percentage.\nRestart needed!") albow.resource.font_proportion = config.settings.fontProportion.get() fogIntensityRow = albow.IntInputRow("Fog Intensity (%): ", ref=config.settings.fogIntensity, width=100, min=0, max=100) invertRow = albow.CheckBoxLabel("Invert Mouse", ref=config.controls.invertMousePitch, tooltipText="Reverse the up and down motion of the mouse.") spaceHeightRow = albow.IntInputRow("Low Detail Height", ref=config.settings.spaceHeight, tooltipText="When you are this far above the top of the world, move fast and use low-detail mode.") blockBufferRow = albow.IntInputRow("Block Buffer (MB):", ref=albow.AttrRef(self, 'blockBuffer'), min=1, tooltipText="Amount of memory used for temporary storage. When more than this is needed, the disk is used instead.") setWindowPlacementRow = albow.CheckBoxLabel("Set Window Placement", ref=config.settings.setWindowPlacement, tooltipText="Try to save and restore the window position.") rotateBlockBrushRow = albow.CheckBoxLabel("Rotate block with brush", ref=config.settings.rotateBlockBrush, tooltipText="When rotating your brush, also rotate the orientation of the block your brushing with") compassToggleRow =albow.CheckBoxLabel("Toggle compass", ref=config.settings.compassToggle) windowSizeRow = albow.CheckBoxLabel("Window Resize Alert", ref=config.settings.shouldResizeAlert, tooltipText="Reminds you that the cursor won't work correctly after resizing the window.") superSecretSettingsRow = albow.CheckBoxLabel("Super Secret Settings", ref=config.settings.superSecretSettings, tooltipText="Weird stuff happen!") longDistanceRow = albow.CheckBoxLabel("Long-Distance Mode", ref=config.settings.longDistanceMode, tooltipText="Always target the farthest block under the cursor, even in mouselook mode.") flyModeRow = albow.CheckBoxLabel("Fly Mode", ref=config.settings.flyMode, tooltipText="Moving forward and Backward will not change your altitude in Fly Mode.") showCommandsRow = albow.CheckBoxLabel("Show Block Info when hovering", ref=config.settings.showQuickBlockInfo, tooltipText="Shows summarized info of some Blocks when hovering over it.") cancelCommandBlockOffset = albow.CheckBoxLabel("Cancel Command Block Offset", ref=config.schematicCopying.cancelCommandBlockOffset, tooltipText="Cancels the command blocks coords changed when copied.") lng = config.settings.langCode.get() langs = sorted(self.getLanguageChoices().items()) langNames = [k for k, v in langs] self.languageButton = albow.ChoiceButton(langNames, choose=self.changeLanguage, doNotTranslate=True) if self.sgnal[lng] in self.languageButton.choices: self.languageButton.selectedChoice = self.sgnal[lng] langButtonRow = albow.Row((albow.Label("Language", tooltipText="Choose your language."), self.languageButton)) portableList = ["Portable", "Fixed"] self.goPortableButton = goPortableButton = albow.ChoiceButton(portableList, choose=self.togglePortable) goPortableButton.selectedChoice = self.saveOldPortable goPortableButton.tooltipText = self.portableButtonTooltip() goPortableRow = albow.Row((albow.Label("Install Mode"), goPortableButton)) # Disabled Crash Reporting Option # reportRow = albow.CheckBoxLabel("Report Errors", # ref=config.settings.reportCrashes, # tooltipText="Automatically report errors to the developer.") self.inputs = ( spaceHeightRow, cameraAccelRow, cameraDragRow, cameraMaxSpeedRow, cameraBrakeSpeedRow, blockBufferRow, mouseSpeedRow, undoLimitRow, maxCopiesRow, compassSizeRow, fontProportion, fogIntensityRow, ) options = ( longDistanceRow, flyModeRow, autoBrakeRow, swapAxesRow, invertRow, superSecretSettingsRow, rotateBlockBrushRow, compassToggleRow, showCommandsRow, cancelCommandBlockOffset, langButtonRow, ) + ( ((sys.platform == "win32" and pygame.version.vernum == (1, 9, 1)) and (windowSizeRow,) or ()) ) + ( (sys.platform == "win32") and (setWindowPlacementRow,) or () ) + ( (not sys.platform == "darwin") and (goPortableRow,) or () ) rightcol = albow.Column(options, align='r') leftcol = albow.Column(self.inputs, align='r') optionsColumn = albow.Column((albow.Label("Options"), albow.Row((leftcol, rightcol), align="t"))) settingsRow = albow.Row((optionsColumn,)) buttonsRow = albow.Row((albow.Button("OK", action=self.dismiss), albow.Button("Cancel", action=self.cancel))) resetToDefaultRow = albow.Row((albow.Button("Reset to default", action=self.resetDefault),)) optionsColumn = albow.Column((settingsRow, buttonsRow, resetToDefaultRow)) optionsColumn.key_down = self.key_down self.add(optionsColumn) self.shrink_wrap() @property def blockBuffer(self): return config.settings.blockBuffer.get() / 1048576 @blockBuffer.setter def blockBuffer(self, val): config.settings.blockBuffer.set(int(val * 1048576)) def getLanguageChoices(self, current=None): files = os.listdir(albow.translate.langPath) langs = {} sgnal = {} for file in files: name, ext = os.path.splitext(file) if ext == ".trn" and len(name) == 5 and name[2] == "_": langName = albow.translate.getLangName(file) langs[langName] = name sgnal[name] = langName if "English (US)" not in langs.keys(): langs[u"English (US)"] = "en_US" sgnal["en_US"] = u"English (US)" self.langs = langs self.sgnal = sgnal logging.debug("Detected languages: %s"%self.langs) return langs def changeLanguage(self): if albow.translate.buildTemplate: self.languageButton.selectedChoice = 'English (US)' return langName = self.languageButton.selectedChoice if langName not in self.langs: lng = "en_US" else: lng = self.langs[langName] config.settings.langCode.set(lng) #-# Translation live update preparation logging.debug('*** Language change detected.') logging.debug(' Former language: %s.'%albow.translate.getLang()) logging.debug(' New language: %s.'%lng) #albow.translate.langPath = os.sep.join((directories.getDataDir(), "lang")) albow.translate.langPath = directories.getDataFile('lang') update = albow.translate.setLang(lng)[2] logging.debug(' Update done? %s (Magic %s)'%(update, update or lng == 'en_US')) self.mcedit.root.set_update_ui(update or lng == 'en_US') self.mcedit.root.set_update_ui(False) self.mcedit.editor.set_update_ui(update or lng == 'en_US') self.mcedit.editor.set_update_ui(False) #-# @staticmethod def portableButtonTooltip(): return ( "Click to make your MCEdit install self-contained by moving the settings and schematics into the program folder", "Click to make your MCEdit install persistent by moving the settings and schematics into your Documents folder")[ directories.portable] @property def portableLabelText(self): return ("Portable", "Fixed")[1 - directories.portable] @portableLabelText.setter def portableLabelText(self, *args, **kwargs): pass def togglePortable(self): if sys.platform == "darwin": return False textChoices = [ _("This will make your MCEdit \"portable\" by moving your settings and schematics into the same folder as {0}. Continue?").format( (sys.platform == "darwin" and _("the MCEdit application") or _("MCEditData"))), _("This will move your settings and schematics to your Documents folder. Continue?"), ] useExisting = False alertText = textChoices[directories.portable] if albow.ask(alertText) == "OK": if [directories.hasPreviousPortableInstallation, directories.hasPreviousFixedInstallation][directories.portable](): asked = albow.ask("Found a previous %s installation"%["portable", "fixed"][directories.portable], responses=["Use", "Overwrite", "Cancel"]) if asked == "Use": useExisting = True elif asked == "Overwrite": useExisting = False elif asked == "Cancel": return False try: [directories.goPortable, directories.goFixed][directories.portable](useExisting) except Exception as e: traceback.print_exc() albow.alert(_(u"Error while moving files: {0}").format(repr(e))) else: self.goPortableButton.selectedChoice = self.saveOldPortable self.goPortableButton.tooltipText = self.portableButtonTooltip() return True def dismiss(self, *args, **kwargs): """Used to change the font proportion.""" # If font proportion setting has changed, update the UI. if config.settings.fontProportion.get() != self.saveOldConfig[config.settings.fontProportion]: albow.resource.reload_fonts(proportion=config.settings.fontProportion.get()) self.mcedit.root.set_update_ui(True) self.mcedit.root.set_update_ui(False) self.mcedit.editor.set_update_ui(True) self.mcedit.editor.set_update_ui(False) self.reshowNumberFields() for key in self.saveOldConfig.keys(): self.saveOldConfig[key] = key.get() config.save() Dialog.dismiss(self, *args, **kwargs) def cancel(self, *args, **kwargs): Changes = False self.reshowNumberFields() for key in self.saveOldConfig.keys(): if key.get() != self.saveOldConfig[key]: Changes = True oldLanguage = self.saveOldConfig[config.settings.langCode] if config.settings.langCode.get() != oldLanguage: Changes = True newPortable = self.portableVar.get() if newPortable != self.saveOldPortable: Changes = True if not Changes: Dialog.dismiss(self, *args, **kwargs) return result = albow.ask("Do you want to save your changes?", ["Save", "Don't Save", "Cancel"]) if result == "Cancel": return if result == "Save": self.dismiss(*args, **kwargs) return if config.settings.langCode.get() != oldLanguage: self.languageButton.selectedChoice = self.sgnal[oldLanguage] self.changeLanguage() if _(newPortable) != _(self.saveOldPortable): self.portableVar.set(newPortable) self.togglePortable() for key in self.saveOldConfig.keys(): key.set(self.saveOldConfig[key]) config.save() Dialog.dismiss(self, *args, **kwargs) def resetDefault(self): self.reshowNumberFields() for key in self.saveOldConfig.keys(): if "AttrRef" in str(key): key.set(config.settings.blockBuffer.default / 1048576) elif "lang" not in str(key): key.set(key.default) if config.settings.langCode.get() != "en_US": config.settings.langCode.set("en_US") self.changeLanguage() if "Fixed" != self.portableVar.get(): self.portableVar.set("Fixed") self.togglePortable() config.save() def reshowNumberFields(self): for key in self.inputs: key.subwidgets[1].editing = False def dispatch_key(self, name, evt): super(OptionsPanel, self).dispatch_key(name, evt) if name == "key_down": keyname = self.get_root().getKey(evt) if keyname == 'Escape': self.cancel()
19,479
46.745098
163
py
MCEdit-Unified
MCEdit-Unified-master/panels/__init__.py
from graphics import GraphicsPanel from options import OptionsPanel from control import ControlPanel
101
24.5
34
py
MCEdit-Unified
MCEdit-Unified-master/viewports/camera.py
# -*- coding: utf_8 -*- # The above line is necessary, unless we want problems with encodings... from __future__ import unicode_literals import sys from compass import CompassOverlay from raycaster import TooFarException import raycaster import keys import pygame import math import copy import numpy from config import config import frustum import logging import glutils import mceutils import itertools import pymclevel from math import isnan from datetime import datetime, timedelta from OpenGL import GL from OpenGL import GLU from albow import alert, AttrRef, Button, Column, input_text, Row, TableColumn, TableView, Widget, CheckBox, \ TextFieldWrapped, MenuButton, ChoiceButton, IntInputRow, TextInputRow, showProgress, IntField, ask from albow.controls import Label, ValueDisplay from albow.dialogs import Dialog, wrapped_label from albow.openglwidgets import GLViewport from albow.extended_widgets import BasicTextInputRow, CheckBoxLabel from albow.translate import _ from albow.root import get_top_widget from pygame import mouse from depths import DepthOffset from editortools.operation import Operation from glutils import gl from editortools.nbtexplorer import SlotEditor class SignEditOperation(Operation): def __init__(self, tool, level, tileEntity, backupTileEntity): self.tool = tool self.level = level self.tileEntity = tileEntity self.undoBackupEntityTag = backupTileEntity self.canUndo = False def perform(self, recordUndo=True): if self.level.saving: alert("Cannot perform action while saving is taking place") return self.level.addTileEntity(self.tileEntity) self.canUndo = True def undo(self): self.redoBackupEntityTag = copy.deepcopy(self.tileEntity) self.level.addTileEntity(self.undoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(self.tileEntity), (1, 1, 1)) def redo(self): self.level.addTileEntity(self.redoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(self.tileEntity), (1, 1, 1)) class CameraViewport(GLViewport): anchor = "tlbr" oldMousePosition = None dontShowMessageAgain = False def __init__(self, editor, def_enc=None): self.editor = editor global DEF_ENC DEF_ENC = def_enc or editor.mcedit.def_enc rect = editor.mcedit.rect GLViewport.__init__(self, rect) # Declare a pseudo showCommands function, since it is called by other objects before its creation in mouse_move. self.showCommands = lambda:None near = 0.5 far = 4000.0 self.near = near self.far = far self.brake = False self.lastTick = datetime.now() # self.nearheight = near * tang self.cameraPosition = (16., 45., 16.) self.velocity = [0., 0., 0.] self.yaw = -45. # degrees self._pitch = 0.1 self.cameraVector = self._cameraVector() # A state machine to dodge an apparent bug in pygame that generates erroneous mouse move events # 0 = bad event already happened # 1 = app just started or regained focus since last bad event # 2 = mouse cursor was hidden after state 1, next event will be bad self.avoidMouseJumpBug = 1 config.settings.drawSky.addObserver(self) config.settings.drawFog.addObserver(self) config.settings.superSecretSettings.addObserver(self) config.settings.showCeiling.addObserver(self) config.controls.cameraAccel.addObserver(self, "accelFactor") config.controls.cameraMaxSpeed.addObserver(self, "maxSpeed") config.controls.cameraBrakingSpeed.addObserver(self, "brakeMaxSpeed") config.controls.invertMousePitch.addObserver(self) config.controls.autobrake.addObserver(self) config.controls.swapAxes.addObserver(self) config.settings.compassToggle.addObserver(self) config.settings.fov.addObserver(self, "fovSetting", callback=self.updateFov) self.mouseVector = (0, 0, 0) self.root = self.get_root() self.hoveringCommandBlock = [False, ""] self.block_info_parsers = None # self.add(DebugDisplay(self, "cameraPosition", "blockFaceUnderCursor", "mouseVector", "mouse3dPoint")) @property def pitch(self): return self._pitch @pitch.setter def pitch(self, val): self._pitch = min(89.999, max(-89.999, val)) def updateFov(self, val=None): hfov = self.fovSetting fov = numpy.degrees(2.0 * numpy.arctan(self.size[0] / self.size[1] * numpy.tan(numpy.radians(hfov) * 0.5))) self.fov = fov self.tang = numpy.tan(numpy.radians(fov)) def stopMoving(self): self.velocity = [0, 0, 0] def brakeOn(self): self.brake = True def brakeOff(self): self.brake = False tickInterval = 1000 / config.settings.targetFPS.get() oldPosition = (0, 0, 0) flyMode = config.settings.flyMode.property() def tickCamera(self, frameStartTime, inputs, inSpace): timePassed = (frameStartTime - self.lastTick).microseconds if timePassed <= self.tickInterval * 1000 or not pygame.key.get_focused(): return self.lastTick = frameStartTime timeDelta = float(timePassed) / 1000000. timeDelta = min(timeDelta, 0.125) # 8fps lower limit! drag = config.controls.cameraDrag.get() accel_factor = drag + config.controls.cameraAccel.get() # if we're in space, move faster drag_epsilon = 10.0 * timeDelta if self.brake: max_speed = self.brakeMaxSpeed else: max_speed = self.maxSpeed if inSpace or self.root.sprint: accel_factor *= 3.0 max_speed *= 3.0 self.root.sprint = False elif config.settings.viewMode.get() == "Chunk": accel_factor *= 2.0 max_speed *= 2.0 pi = self.editor.cameraPanKeys mouseSpeed = config.controls.mouseSpeed.get() self.yaw += pi[0] * mouseSpeed self.pitch += pi[1] * mouseSpeed if config.settings.viewMode.get() == "Chunk": (dx, dy, dz) = (0, -0.25, -1) self.yaw = -180 self.pitch = 10 elif self.flyMode: (dx, dy, dz) = self._anglesToVector(self.yaw, 0) elif self.swapAxes: p = self.pitch if p > 80: p = 0 (dx, dy, dz) = self._anglesToVector(self.yaw, p) else: (dx, dy, dz) = self._cameraVector() velocity = self.velocity # xxx learn to use matrix/vector libs i = inputs yaw = numpy.radians(self.yaw) cosyaw = -numpy.cos(yaw) sinyaw = numpy.sin(yaw) directedInputs = mceutils.normalize(( i[0] * cosyaw + i[2] * dx, i[1] + i[2] * dy, i[2] * dz - i[0] * sinyaw, )) # give the camera an impulse according to the state of the inputs and in the direction of the camera cameraAccel = map(lambda x: x * accel_factor * timeDelta, directedInputs) # cameraImpulse = map(lambda x: x*impulse_factor, directedInputs) newVelocity = map(lambda a, b: a + b, velocity, cameraAccel) velocityDir, speed = mceutils.normalize_size(newVelocity) # apply drag if speed: if self.autobrake and not any(inputs): speed *= 0.15 else: sign = speed / abs(speed) speed = abs(speed) speed = speed - (drag * timeDelta) if speed < 0.0: speed = 0.0 speed *= sign speed = max(-max_speed, min(max_speed, speed)) if abs(speed) < drag_epsilon: speed = 0 velocity = map(lambda a: a * speed, velocityDir) # velocity = map(lambda p,d: p + d, velocity, cameraImpulse) d = map(lambda a, b: abs(a - b), self.cameraPosition, self.oldPosition) if d[0] + d[2] > 32.0: self.oldPosition = self.cameraPosition self.updateFloorQuad() self.cameraPosition = map(lambda p, d: p + d * timeDelta, self.cameraPosition, velocity) if self.cameraPosition[1] > 3800.: self.cameraPosition[1] = 3800. elif self.cameraPosition[1] < -1000.: self.cameraPosition[1] = -1000. self.velocity = velocity self.cameraVector = self._cameraVector() self.editor.renderer.position = self.cameraPosition if self.editor.currentTool.previewRenderer: self.editor.currentTool.previewRenderer.position = self.cameraPosition def setModelview(self): pos = self.cameraPosition look = numpy.array(self.cameraPosition) look = look.astype(float) + self.cameraVector up = (0, 1, 0) GLU.gluLookAt(pos[0], pos[1], pos[2], look[0], look[1], look[2], up[0], up[1], up[2]) def _cameraVector(self): return self._anglesToVector(self.yaw, self.pitch) @staticmethod def _anglesToVector(yaw, pitch): def nanzero(x): if isnan(x): return 0 else: return x dx = -math.sin(math.radians(yaw)) * math.cos(math.radians(pitch)) dy = -math.sin(math.radians(pitch)) dz = math.cos(math.radians(yaw)) * math.cos(math.radians(pitch)) return map(nanzero, (dx, dy, dz)) def updateMouseVector(self): self.mouseVector = self._mouseVector() def _mouseVector(self): """ returns a vector reflecting a ray cast from the camera position to the mouse position on the near plane """ x, y = mouse.get_pos() # if (x, y) not in self.rect: # return (0, 0, 0); # xxx y = self.root.height - y point1 = unproject(x, y, 0.0) point2 = unproject(x, y, 1.0) v = numpy.array(point2) - point1 v = mceutils.normalize(v) return v def _blockUnderCursor(self, center=False): """ returns a point in 3d space that was determined by reading the depth buffer value """ try: GL.glReadBuffer(GL.GL_BACK) except Exception: logging.exception('Exception during glReadBuffer') ws = self.root.size if center: x, y = ws x //= 2 y //= 2 else: x, y = mouse.get_pos() if (x < 0 or y < 0 or x >= ws[0] or y >= ws[1]): return 0, 0, 0 y = ws[1] - y try: pixel = GL.glReadPixels(x, y, 1, 1, GL.GL_DEPTH_COMPONENT, GL.GL_FLOAT) newpoint = unproject(x, y, pixel[0]) except Exception: return 0, 0, 0 return newpoint def updateBlockFaceUnderCursor(self): focusPair = None if not self.enableMouseLag or self.editor.frames & 1: self.updateMouseVector() if self.editor.mouseEntered: if not self.mouseMovesCamera: try: focusPair = raycaster.firstBlock(self.cameraPosition, self._mouseVector(), self.editor.level, 100, config.settings.viewMode.get()) except TooFarException: mouse3dPoint = self._blockUnderCursor() focusPair = self._findBlockFaceUnderCursor(mouse3dPoint) elif self.editor.longDistanceMode: mouse3dPoint = self._blockUnderCursor(True) focusPair = self._findBlockFaceUnderCursor(mouse3dPoint) # otherwise, find the block at a controllable distance in front of the camera if focusPair is None: if self.blockFaceUnderCursor is None or self.mouseMovesCamera: focusPair = (self.getCameraPoint(), (0, 0, 0)) else: focusPair = self.blockFaceUnderCursor try: if focusPair[0] is not None and self.editor.level.tileEntityAt(*focusPair[0]): changed = False te = self.editor.level.tileEntityAt(*focusPair[0]) backupTE = copy.deepcopy(te) if te["id"].value == "Sign" or self.editor.level.defsIds.mcedit_ids.get(te["id"].value) in ("DEF_BLOCKS_STANDING_SIGN", "DEFS_BLOCKS_WALL_SIGN"): if "Text1" in te and "Text2" in te and "Text3" in te and "Text4" in te: for i in xrange(1,5): if len(te["Text"+str(i)].value) > 32767: te["Text"+str(i)] = pymclevel.TAG_String(str(te["Text"+str(i)].value)[:32767]) changed = True if changed: response = None if not self.dontShowMessageAgain: response = ask("Found a sign that exceeded the maximum character limit. Automatically trimmed the sign to prevent crashes.", responses=["Ok", "Don't show this again"]) if response is not None and response == "Don't show this again": self.dontShowMessageAgain = True op = SignEditOperation(self.editor, self.editor.level, te, backupTE) self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() except: pass self.blockFaceUnderCursor = focusPair def _findBlockFaceUnderCursor(self, projectedPoint): """Returns a (pos, Face) pair or None if one couldn't be found""" d = [0, 0, 0] try: intProjectedPoint = map(int, map(numpy.floor, projectedPoint)) except ValueError: return None # catch NaNs intProjectedPoint[1] = max(-1, intProjectedPoint[1]) # find out which face is under the cursor. xxx do it more precisely faceVector = ((projectedPoint[0] - (intProjectedPoint[0] + 0.5)), (projectedPoint[1] - (intProjectedPoint[1] + 0.5)), (projectedPoint[2] - (intProjectedPoint[2] + 0.5)) ) av = map(abs, faceVector) i = av.index(max(av)) delta = faceVector[i] if delta < 0: d[i] = -1 else: d[i] = 1 potentialOffsets = [] try: block = self.editor.level.blockAt(*intProjectedPoint) except (EnvironmentError, pymclevel.ChunkNotPresent): return intProjectedPoint, d if block == pymclevel.alphaMaterials.SnowLayer.ID: potentialOffsets.append((0, 1, 0)) else: # discard any faces that aren't likely to be exposed for face, offsets in pymclevel.faceDirections: point = map(lambda a, b: a + b, intProjectedPoint, offsets) try: neighborBlock = self.editor.level.blockAt(*point) if block != neighborBlock: potentialOffsets.append(offsets) except (EnvironmentError, pymclevel.ChunkNotPresent): pass # check each component of the face vector to see if that face is exposed if tuple(d) not in potentialOffsets: av[i] = 0 i = av.index(max(av)) d = [0, 0, 0] delta = faceVector[i] if delta < 0: d[i] = -1 else: d[i] = 1 if tuple(d) not in potentialOffsets: av[i] = 0 i = av.index(max(av)) d = [0, 0, 0] delta = faceVector[i] if delta < 0: d[i] = -1 else: d[i] = 1 if tuple(d) not in potentialOffsets: if len(potentialOffsets): d = potentialOffsets[0] else: # use the top face as a fallback d = [0, 1, 0] return intProjectedPoint, d @property def ratio(self): return self.width / float(self.height) startingMousePosition = None def mouseLookOn(self): self.root.capture_mouse(self) self.focus_switch = None self.startingMousePosition = mouse.get_pos() if self.avoidMouseJumpBug == 1: self.avoidMouseJumpBug = 2 def mouseLookOff(self): self.root.capture_mouse(None) if self.startingMousePosition: mouse.set_pos(*self.startingMousePosition) self.startingMousePosition = None @property def mouseMovesCamera(self): return self.root.captured_widget is not None def toggleMouseLook(self): if not self.mouseMovesCamera: self.mouseLookOn() else: self.mouseLookOff() # mobs is overrided in __init__ mobs = pymclevel.Entity.monsters + ["[Custom]"] @mceutils.alertException def editMonsterSpawner(self, point): mobs = self.mobs _mobs = {} # Get the mobs from the versionned data defsIds = self.editor.level.defsIds mcedit_defs = defsIds.mcedit_defs mcedit_ids = defsIds.mcedit_ids if mcedit_defs.get('spawner_monsters'): mobs = [] for a in mcedit_defs['spawner_monsters']: _id = mcedit_ids[a] name = _(mcedit_defs[_id]['name']) _mobs[name] = a _mobs[a] = name mobs.append(name) tileEntity = self.editor.level.tileEntityAt(*point) undoBackupEntityTag = copy.deepcopy(tileEntity) if not tileEntity: tileEntity = pymclevel.TAG_Compound() tileEntity["id"] = pymclevel.TAG_String(mcedit_defs.get("MobSpawner", "MobSpawner")) tileEntity["x"] = pymclevel.TAG_Int(point[0]) tileEntity["y"] = pymclevel.TAG_Int(point[1]) tileEntity["z"] = pymclevel.TAG_Int(point[2]) tileEntity["Delay"] = pymclevel.TAG_Short(120) tileEntity["EntityId"] = pymclevel.TAG_String(mcedit_defs.get(mobs[0], mobs[0])) self.editor.level.addTileEntity(tileEntity) panel = Dialog() def addMob(id): if id not in mobs: mobs.insert(0, id) mobTable.selectedIndex = 0 def selectTableRow(i, evt): if mobs[i] == "[Custom]": id = input_text("Type in an EntityID for this spawner. Invalid IDs may crash Minecraft.", 150) if id: addMob(id) else: return mobTable.selectedIndex = mobs.index(id) else: mobTable.selectedIndex = i if evt.num_clicks == 2: panel.dismiss() mobTable = TableView(columns=( TableColumn("", 200), ) ) mobTable.num_rows = lambda: len(mobs) mobTable.row_data = lambda i: (mobs[i],) mobTable.row_is_selected = lambda x: x == mobTable.selectedIndex mobTable.click_row = selectTableRow mobTable.selectedIndex = 0 def selectedMob(): val = mobs[mobTable.selectedIndex] return _mobs.get(val, val) def cancel(): mobs[mobTable.selectedIndex] = id panel.dismiss() if "EntityId" in tileEntity: _id = tileEntity["EntityId"].value elif "SpawnData" in tileEntity: _id = tileEntity["SpawnData"]["id"].value else: _id = "[Custom]" # Something weird here since the first implementation of the versionned definition. # It may happen 'mcedit_defs.get(mcedit_ids.get(_id, _id), {}).get("name", _id)' # does not return the wanted data (dict). # Could not yet debug that, but I guess it is related to the versionned data loading... # -- D.C.-G. # print mcedit_ids.get(_id, _id) # print mcedit_defs.get(mcedit_ids.get(_id, _id), {}) _id2 = mcedit_defs.get(mcedit_ids.get(_id, _id), {}) if isinstance(_id2, (str, unicode)): _id = _id2 id = mcedit_defs.get(mcedit_ids.get(_id, _id), {}).get("name", _id) addMob(id) mobTable.selectedIndex = mobs.index(id) oldChoiceCol = Column((Label(_("Current: ") + _mobs.get(id, id), align='l', width=200), )) newChoiceCol = Column((ValueDisplay(width=200, get_value=lambda: _("Change to: ") + selectedMob()), mobTable)) lastRow = Row((Button("OK", action=panel.dismiss), Button("Cancel", action=cancel))) panel.add(Column((oldChoiceCol, newChoiceCol, lastRow))) panel.shrink_wrap() panel.present() class MonsterSpawnerEditOperation(Operation): def __init__(self, tool, level): self.tool = tool self.level = level self.undoBackupEntityTag = undoBackupEntityTag self.canUndo = False def perform(self, recordUndo=True): if self.level.saving: alert("Cannot perform action while saving is taking place") return self.level.addTileEntity(tileEntity) self.canUndo = True def undo(self): self.redoBackupEntityTag = copy.deepcopy(tileEntity) self.level.addTileEntity(self.undoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) def redo(self): self.level.addTileEntity(self.redoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) if id != selectedMob(): # If the level has a 'setSpawnerData, call it instead of using the code here if hasattr(self.editor.level, "setSpawnerData"): tileEntity = self.editor.level.setSpawnerData(tileEntity, selectedMob()) else: if "EntityId" in tileEntity: tileEntity["EntityId"] = pymclevel.TAG_String(selectedMob()) if "SpawnData" in tileEntity: # Try to not clear the spawn data, but only update the mob id # tileEntity["SpawnData"] = pymclevel.TAG_Compound() tag_id = pymclevel.TAG_String(selectedMob()) if "id" in tileEntity["SpawnData"]: tag_id.name = "id" tileEntity["SpawnData"]["id"] = tag_id if "EntityId" in tileEntity["SpawnData"]: tileEntity["SpawnData"]["EntityId"] = tag_id if "SpawnPotentials" in tileEntity: for potential in tileEntity["SpawnPotentials"]: if "Entity" in potential: # MC 1.9+ if potential["Entity"]["id"].value == id or ("EntityId" in potential["Entity"] and potential["Entity"]["EntityId"].value == id): potential["Entity"] = pymclevel.TAG_Compound() potential["Entity"]["id"] = pymclevel.TAG_String(selectedMob()) elif "Properties" in potential: # MC before 1.9 if "Type" in potential and potential["Type"].value == id: potential["Type"] = pymclevel.TAG_String(selectedMob()) # We also can change some other values in the Properties tag, but it is useless in MC 1.8+. # The fact is this data will not be updated by the game after the mob type is changed, but the old mob will not spawn. # put_entityid = False # put_id = False # if "EntityId" in potential["Properties"] and potential["Properties"]["EntityId"].value == id: # put_entityid = True # if "id" in potential["Properties"] and potential["Properties"]["id"].value == id: # put_id = True # new_props = pymclevel.TAG_Compound() # if put_entityid: # new_props["EntityId"] = pymclevel.TAG_String(selectedMob()) # if put_id: # new_props["id"] = pymclevel.TAG_String(selectedMob()) # potential["Properties"] = new_props op = MonsterSpawnerEditOperation(self.editor, self.editor.level) self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() @mceutils.alertException def editJukebox(self, point): discs = { "[No Record]": None, "13": 2256, "cat": 2257, "blocks": 2258, "chirp": 2259, "far": 2260, "mall": 2261, "mellohi": 2262, "stal": 2263, "strad": 2264, "ward": 2265, "11": 2266, "wait": 2267 } tileEntity = self.editor.level.tileEntityAt(*point) undoBackupEntityTag = copy.deepcopy(tileEntity) if not tileEntity: tileEntity = pymclevel.TAG_Compound() tileEntity["id"] = pymclevel.TAG_String("RecordPlayer") tileEntity["x"] = pymclevel.TAG_Int(point[0]) tileEntity["y"] = pymclevel.TAG_Int(point[1]) tileEntity["z"] = pymclevel.TAG_Int(point[2]) self.editor.level.addTileEntity(tileEntity) panel = Dialog() def selectTableRow(i, evt): discTable.selectedIndex = i if evt.num_clicks == 2: panel.dismiss() discTable = TableView(columns=( TableColumn("", 200), ) ) discTable.num_rows = lambda: len(discs) discTable.row_data = lambda i: (selectedDisc(i),) discTable.row_is_selected = lambda x: x == discTable.selectedIndex discTable.click_row = selectTableRow discTable.selectedIndex = 0 def selectedDisc(id): if id == 0: return "[No Record]" return discs.keys()[discs.values().index(id + 2255)] def cancel(): if id == "[No Record]": discTable.selectedIndex = 0 else: discTable.selectedIndex = discs[id] - 2255 panel.dismiss() if "RecordItem" in tileEntity: if tileEntity["RecordItem"]["id"].value == "minecraft:air": id = "[No Record]" else: id = tileEntity["RecordItem"]["id"].value[17:] elif "Record" in tileEntity: if tileEntity["Record"].value == 0: id = "[No Record]" else: id = selectedDisc(tileEntity["Record"].value - 2255) else: id = "[No Record]" if id == "[No Record]": discTable.selectedIndex = 0 else: discTable.selectedIndex = discs[id] - 2255 oldChoiceCol = Column((Label(_("Current: ") + id, align='l', width=200), )) newChoiceCol = Column((ValueDisplay(width=200, get_value=lambda: _("Change to: ") + selectedDisc(discTable.selectedIndex)), discTable)) lastRow = Row((Button("OK", action=panel.dismiss), Button("Cancel", action=cancel))) panel.add(Column((oldChoiceCol, newChoiceCol, lastRow))) panel.shrink_wrap() panel.present() class JukeboxEditOperation(Operation): def __init__(self, tool, level): self.tool = tool self.level = level self.undoBackupEntityTag = undoBackupEntityTag self.canUndo = False def perform(self, recordUndo=True): if self.level.saving: alert("Cannot perform action while saving is taking place") return self.level.addTileEntity(tileEntity) self.canUndo = True def undo(self): self.redoBackupEntityTag = copy.deepcopy(tileEntity) self.level.addTileEntity(self.undoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) def redo(self): self.level.addTileEntity(self.redoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) if id != selectedDisc(discTable.selectedIndex): if "RecordItem" in tileEntity: del tileEntity["RecordItem"] if discTable.selectedIndex == 0: tileEntity["Record"] = pymclevel.TAG_Int(0) self.editor.level.setBlockDataAt(tileEntity["x"].value, tileEntity["y"].value, tileEntity["z"].value, 0) else: tileEntity["Record"] = pymclevel.TAG_Int(discTable.selectedIndex + 2255) self.editor.level.setBlockDataAt(tileEntity["x"].value, tileEntity["y"].value, tileEntity["z"].value, 1) op = JukeboxEditOperation(self.editor, self.editor.level) self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() @mceutils.alertException def editNoteBlock(self, point): notes = [ "F# (0.5)", "G (0.53)", "G# (0.56)", "A (0.6)", "A# (0.63)", "B (0.67)", "C (0.7)", "C# (0.75)", "D (0.8)", "D# (0.85)", "E (0.9)", "F (0.95)", "F# (1.0)", "G (1.05)", "G# (1.1)", "A (1.2)", "A# (1.25)", "B (1.32)", "C (1.4)", "C# (1.5)", "D (1.6)", "D# (1.7)", "E (1.8)", "F (1.9)", "F# (2.0)" ] tileEntity = self.editor.level.tileEntityAt(*point) undoBackupEntityTag = copy.deepcopy(tileEntity) if not tileEntity: tileEntity = pymclevel.TAG_Compound() tileEntity["id"] = pymclevel.TAG_String(self.editor.level.defsIds.mcedit_defs.get("MobSpawner", "MobSpawner")) tileEntity["x"] = pymclevel.TAG_Int(point[0]) tileEntity["y"] = pymclevel.TAG_Int(point[1]) tileEntity["z"] = pymclevel.TAG_Int(point[2]) tileEntity["note"] = pymclevel.TAG_Byte(0) self.editor.level.addTileEntity(tileEntity) panel = Dialog() def selectTableRow(i, evt): noteTable.selectedIndex = i if evt.num_clicks == 2: panel.dismiss() noteTable = TableView(columns=( TableColumn("", 200), ) ) noteTable.num_rows = lambda: len(notes) noteTable.row_data = lambda i: (notes[i],) noteTable.row_is_selected = lambda x: x == noteTable.selectedIndex noteTable.click_row = selectTableRow noteTable.selectedIndex = 0 def selectedNote(): return notes[noteTable.selectedIndex] def cancel(): noteTable.selectedIndex = id panel.dismiss() id = tileEntity["note"].value noteTable.selectedIndex = id oldChoiceCol = Column((Label(_("Current: ") + notes[id], align='l', width=200), )) newChoiceCol = Column((ValueDisplay(width=200, get_value=lambda: _("Change to: ") + selectedNote()), noteTable)) lastRow = Row((Button("OK", action=panel.dismiss), Button("Cancel", action=cancel))) panel.add(Column((oldChoiceCol, newChoiceCol, lastRow))) panel.shrink_wrap() panel.present() class NoteBlockEditOperation(Operation): def __init__(self, tool, level): self.tool = tool self.level = level self.undoBackupEntityTag = undoBackupEntityTag self.canUndo = False def perform(self, recordUndo=True): if self.level.saving: alert("Cannot perform action while saving is taking place") return self.level.addTileEntity(tileEntity) self.canUndo = True def undo(self): self.redoBackupEntityTag = copy.deepcopy(tileEntity) self.level.addTileEntity(self.undoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) def redo(self): self.level.addTileEntity(self.redoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) if id != noteTable.selectedIndex: tileEntity["note"] = pymclevel.TAG_Byte(noteTable.selectedIndex) op = NoteBlockEditOperation(self.editor, self.editor.level) self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() @mceutils.alertException def editSign(self, point): tileEntity = self.editor.level.tileEntityAt(*point) undoBackupEntityTag = copy.deepcopy(tileEntity) linekeys = ["Text" + str(i) for i in xrange(1, 5)] # From version 1.8, signs accept Json format. # 1.9 does no more support the old raw string fomat. if self.editor.level.gamePlatform == "Java": splitVersion = self.editor.level.gameVersionNumber.split('.') else: splitVersion = self.editor.level.gamePlatform.split('.') newFmtVersion = ['1','9'] fmt = "" json_fmt = False f = lambda a,b: (a + (['0'] * max(len(b) - len(a), 0)), b + (['0'] * max(len(a) - len(b), 0))) if False not in map(lambda x,y: (int(x) if x.isdigit() else x) >= (int(y) if y.isdigit() else y),*f(splitVersion, newFmtVersion))[:2]: json_fmt = True fmt = '{"text":""}' if not tileEntity: tileEntity = pymclevel.TAG_Compound() # Don't know how to handle the difference between wall and standing signs for now... # Just let this like it is until we can find the way! tileEntity["id"] = pymclevel.TAG_String("Sign") tileEntity["x"] = pymclevel.TAG_Int(point[0]) tileEntity["y"] = pymclevel.TAG_Int(point[1]) tileEntity["z"] = pymclevel.TAG_Int(point[2]) for l in linekeys: tileEntity[l] = pymclevel.TAG_String(fmt) self.editor.level.addTileEntity(tileEntity) panel = Dialog() oneText = False if "Text1" not in tileEntity: oneText = True text_parts = tileEntity["Text"].value.split("\n") for i, text_part in enumerate(text_parts): tileEntity["Text"+str(i+1)] = pymclevel.TAG_String(text_part) lineFields = [TextFieldWrapped(width=400) for l in linekeys] for l, f in zip(linekeys, lineFields): if l not in tileEntity: tileEntity[l] = pymclevel.TAG_String("") f.value = tileEntity[l].value # Double quotes handling for olf sign text format. if f.value == 'null': f.value = fmt elif json_fmt and f.value == '': f.value = fmt else: if f.value.startswith('"') and f.value.endswith('"'): f.value = f.value[1:-1] if '\\"' in f.value: f.value = f.value.replace('\\"', '"') colors = [ u"§0 Black", u"§1 Dark Blue", u"§2 Dark Green", u"§3 Dark Aqua", u"§4 Dark Red", u"§5 Dark Purple", u"§6 Gold", u"§7 Gray", u"§8 Dark Gray", u"§9 Blue", u"§a Green", u"§b Aqua", u"§c Red", u"§d Light Purple", u"§e Yellow", u"§f White", ] def menu_picked(index): c = u"§%d"%index currentField = panel.focus_switch.focus_switch if currentField.insertion_step is not None: currentField.text = currentField.text[:currentField.insertion_step] + c + currentField.text[currentField.insertion_step:] else: currentField.text += c currentField.insertion_point = len(currentField.text) currentField.attention_lost() currentField.get_focus() def changeSign(): unsavedChanges = False fmt = '"{}"' u_fmt = u'"%s"' if json_fmt or oneText: fmt = '{}' u_fmt = u'%s' for l, f in zip(linekeys, lineFields): oldText = fmt.format(tileEntity[l]) tileEntity[l] = pymclevel.TAG_String(u_fmt%f.value[:255]) if fmt.format(tileEntity[l]) != oldText and not unsavedChanges: unsavedChanges = True if oneText: tileEntity["Text"] = pymclevel.TAG_String("\n".join([tileEntity[l].value for l in linekeys])) if unsavedChanges: op = SignEditOperation(self.editor, self.editor.level, tileEntity, undoBackupEntityTag) self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() panel.dismiss() colorMenu = MenuButton("Add Color Code...", colors, menu_picked=menu_picked) row = Row((Button("OK", action=changeSign), Button("Cancel", action=panel.dismiss))) column = [Label("Edit Sign")] + lineFields + [colorMenu, row] panel.add(Column(column)) panel.shrink_wrap() panel.present() @mceutils.alertException def editSkull(self, point): tileEntity = self.editor.level.tileEntityAt(*point) undoBackupEntityTag = copy.deepcopy(tileEntity) skullTypes = { "Skeleton": 0, "Wither Skeleton": 1, "Zombie": 2, "Player": 3, "Creeper": 4, } inverseSkullType = { 0: "Skeleton", 1: "Wither Skeleton", 2: "Zombie", 3: "Player", 4: "Creeper", } if not tileEntity: tileEntity = pymclevel.TAG_Compound() # Don't know how to handle the difference between skulls in this context signs for now... # Tests nedded! tileEntity["id"] = pymclevel.TAG_String("Skull") tileEntity["x"] = pymclevel.TAG_Int(point[0]) tileEntity["y"] = pymclevel.TAG_Int(point[1]) tileEntity["z"] = pymclevel.TAG_Int(point[2]) tileEntity["SkullType"] = pymclevel.TAG_Byte(3) self.editor.level.addTileEntity(tileEntity) titleLabel = Label("Edit Skull Data") usernameField = TextFieldWrapped(width=150) panel = Dialog() skullMenu = ChoiceButton(map(str, skullTypes)) if "Owner" in tileEntity: if "Owner" not in tileEntity["Owner"]: tileEntity["Owner"]["Name"] = pymclevel.TAG_String() usernameField.value = str(tileEntity["Owner"]["Name"].value) elif "ExtraType" in tileEntity: usernameField.value = str(tileEntity["ExtraType"].value) else: usernameField.value = "" oldUserName = usernameField.value skullMenu.selectedChoice = inverseSkullType[tileEntity["SkullType"].value] oldSelectedSkull = skullMenu.selectedChoice class SkullEditOperation(Operation): def __init__(self, tool, level): self.tool = tool self.level = level self.undoBackupEntityTag = undoBackupEntityTag self.canUndo = False def perform(self, recordUndo=True): if self.level.saving: alert("Cannot perform action while saving is taking place") return self.level.addTileEntity(tileEntity) self.canUndo = True def undo(self): self.redoBackupEntityTag = copy.deepcopy(tileEntity) self.level.addTileEntity(self.undoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) def redo(self): self.level.addTileEntity(self.redoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) def updateSkull(): if usernameField.value != oldUserName or oldSelectedSkull != skullMenu.selectedChoice: tileEntity["ExtraType"] = pymclevel.TAG_String(usernameField.value) tileEntity["SkullType"] = pymclevel.TAG_Byte(skullTypes[skullMenu.selectedChoice]) if "Owner" in tileEntity: del tileEntity["Owner"] op = SkullEditOperation(self.editor, self.editor.level) self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() chunk = self.editor.level.getChunk(int(int(point[0]) / 16), int(int(point[2]) / 16)) chunk.dirty = True panel.dismiss() okBTN = Button("OK", action=updateSkull) cancel = Button("Cancel", action=panel.dismiss) column = [titleLabel, usernameField, skullMenu, okBTN, cancel] panel.add(Column(column)) panel.shrink_wrap() panel.present() @mceutils.alertException def editCommandBlock(self, point): panel = Dialog() tileEntity = self.editor.level.tileEntityAt(*point) undoBackupEntityTag = copy.deepcopy(tileEntity) if not tileEntity: tileEntity = pymclevel.TAG_Compound() tileEntity["id"] = pymclevel.TAG_String(self.editor.level.defsIds.mcedit_defs.get("Control", "Control")) tileEntity["x"] = pymclevel.TAG_Int(point[0]) tileEntity["y"] = pymclevel.TAG_Int(point[1]) tileEntity["z"] = pymclevel.TAG_Int(point[2]) tileEntity["Command"] = pymclevel.TAG_String() tileEntity["CustomName"] = pymclevel.TAG_String("@") tileEntity["TrackOutput"] = pymclevel.TAG_Byte(0) tileEntity["SuccessCount"] = pymclevel.TAG_Int(0) self.editor.level.addTileEntity(tileEntity) titleLabel = Label("Edit Command Block") commandField = TextFieldWrapped(width=650) nameField = TextFieldWrapped(width=200) successField = IntInputRow("SuccessCount", min=0, max=15) trackOutput = CheckBox() # Fix for the '§ is ħ' issue # try: # commandField.value = tileEntity["Command"].value.decode("unicode-escape") # except: # commandField.value = tileEntity["Command"].value commandField.value = tileEntity["Command"].value oldCommand = commandField.value trackOutput.value = tileEntity.get("TrackOutput", pymclevel.TAG_Byte(0)).value oldTrackOutput = trackOutput.value nameField.value = tileEntity.get("CustomName", pymclevel.TAG_String("@")).value oldNameField = nameField.value successField.subwidgets[1].value = tileEntity.get("SuccessCount", pymclevel.TAG_Int(0)).value oldSuccess = successField.subwidgets[1].value class CommandBlockEditOperation(Operation): def __init__(self, tool, level): self.tool = tool self.level = level self.undoBackupEntityTag = undoBackupEntityTag self.canUndo = False def perform(self, recordUndo=True): if self.level.saving: alert("Cannot perform action while saving is taking place") return self.level.addTileEntity(tileEntity) self.canUndo = True def undo(self): self.redoBackupEntityTag = copy.deepcopy(tileEntity) self.level.addTileEntity(self.undoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) def redo(self): self.level.addTileEntity(self.redoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) def updateCommandBlock(): if oldCommand != commandField.value or oldTrackOutput != trackOutput.value or oldNameField != nameField.value or oldSuccess != successField.subwidgets[1].value: tileEntity["Command"] = pymclevel.TAG_String(commandField.value) tileEntity["TrackOutput"] = pymclevel.TAG_Byte(trackOutput.value) tileEntity["CustomName"] = pymclevel.TAG_String(nameField.value) tileEntity["SuccessCount"] = pymclevel.TAG_Int(successField.subwidgets[1].value) op = CommandBlockEditOperation(self.editor, self.editor.level) self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() chunk = self.editor.level.getChunk(int(int(point[0]) / 16), int(int(point[2]) / 16)) chunk.dirty = True panel.dismiss() okBTN = Button("OK", action=updateCommandBlock) cancel = Button("Cancel", action=panel.dismiss) column = [titleLabel, Label("Command:"), commandField, Row((Label("Custom Name:"), nameField)), successField, Row((Label("Track Output"), trackOutput)), okBTN, cancel] panel.add(Column(column)) panel.shrink_wrap() panel.present() return @mceutils.alertException def editContainer(self, point, containerID): tileEntityTag = self.editor.level.tileEntityAt(*point) if tileEntityTag is None: tileEntityTag = pymclevel.TileEntity.Create(containerID) pymclevel.TileEntity.setpos(tileEntityTag, point) self.editor.level.addTileEntity(tileEntityTag) if tileEntityTag["id"].value != containerID: return undoBackupEntityTag = copy.deepcopy(tileEntityTag) def itemProp(key): # xxx do validation here def getter(self): if 0 == len(tileEntityTag["Items"]): return 0 return tileEntityTag["Items"][self.selectedItemIndex][key].value def setter(self, val): if 0 == len(tileEntityTag["Items"]): return self.dirty = True tileEntityTag["Items"][self.selectedItemIndex][key].value = val return property(getter, setter) class ChestWidget(Widget): dirty = False Slot = itemProp("Slot") id = itemProp("id") Damage = itemProp("Damage") Count = itemProp("Count") itemLimit = pymclevel.TileEntity.maxItems.get(containerID, 26) def slotFormat(slot): slotNames = pymclevel.TileEntity.slotNames.get(containerID) if slotNames: return slotNames.get(slot, slot) return slot chestWidget = ChestWidget() chestItemTable = TableView(columns=[ TableColumn("Slot", 60, "l", fmt=slotFormat), TableColumn("ID / ID Name", 345, "l"), TableColumn("DMG", 50, "l"), TableColumn("Count", 65, "l"), TableColumn("Name", 260, "l"), ]) def itemName(id, damage): try: return pymclevel.items.items.findItem(id, damage).name except pymclevel.items.ItemNotFound: return "Unknown Item" def getRowData(i): item = tileEntityTag["Items"][i] slot, id, damage, count = item["Slot"].value, item["id"].value, item["Damage"].value, item["Count"].value return slot, id, damage, count, itemName(id, damage) chestWidget.selectedItemIndex = 0 def selectTableRow(i, evt): chestWidget.selectedItemIndex = i # Disabling the item selector for now, since we need PE items resources. # if evt.num_clicks > 1: # selectButtonAction() def changeValue(data): s, i, c, d = data s = int(s) chestWidget.Slot = s chestWidget.id = i chestWidget.Count = int(c) chestWidget.Damage = int(d) chestItemTable.num_rows = lambda: len(tileEntityTag["Items"]) chestItemTable.row_data = getRowData chestItemTable.row_is_selected = lambda x: x == chestWidget.selectedItemIndex chestItemTable.click_row = selectTableRow chestItemTable.change_value = changeValue def selectButtonAction(): SlotEditor(chestItemTable, (chestWidget.Slot, chestWidget.id or u"", chestWidget.Count, chestWidget.Damage) ).present() maxSlot = pymclevel.TileEntity.maxItems.get(tileEntityTag["id"].value, 27) - 1 fieldRow = ( IntInputRow("Slot: ", ref=AttrRef(chestWidget, 'Slot'), min=0, max=maxSlot), BasicTextInputRow("ID / ID Name: ", ref=AttrRef(chestWidget, 'id'), width=300), # Text to allow the input of internal item names IntInputRow("DMG: ", ref=AttrRef(chestWidget, 'Damage'), min=0, max=32767), IntInputRow("Count: ", ref=AttrRef(chestWidget, 'Count'), min=-1, max=64), # This button is inactive for now, because we need to work with different IDs types: # * The 'human' IDs: Stone, Glass, Swords... # * The MC ones: minecraft:stone, minecraft:air... # * The PE ones: 0:0, 1:0... # Button("Select", action=selectButtonAction) ) def deleteFromWorld(): i = chestWidget.selectedItemIndex item = tileEntityTag["Items"][i] id = item["id"].value Damage = item["Damage"].value deleteSameDamage = CheckBoxLabel("Only delete items with the same damage value") deleteBlocksToo = CheckBoxLabel("Also delete blocks placed in the world") if id not in (8, 9, 10, 11): # fluid blocks deleteBlocksToo.value = True w = wrapped_label( "WARNING: You are about to modify the entire world. This cannot be undone. Really delete all copies of this item from all land, chests, furnaces, dispensers, dropped items, item-containing tiles, and player inventories in this world?", 60) col = (w, deleteSameDamage) if id < 256: col += (deleteBlocksToo,) d = Dialog(Column(col), ["OK", "Cancel"]) if d.present() == "OK": def deleteItemsIter(): i = 0 if deleteSameDamage.value: def matches(t): return t["id"].value == id and t["Damage"].value == Damage else: def matches(t): return t["id"].value == id def matches_itementity(e): if e["id"].value != "Item": return False if "Item" not in e: return False t = e["Item"] return matches(t) for player in self.editor.level.players: tag = self.editor.level.getPlayerTag(player) tag["Inventory"].value = [t for t in tag["Inventory"].value if not matches(t)] for chunk in self.editor.level.getChunks(): if id < 256 and deleteBlocksToo.value: matchingBlocks = chunk.Blocks == id if deleteSameDamage.value: matchingBlocks &= chunk.Data == Damage if any(matchingBlocks): chunk.Blocks[matchingBlocks] = 0 chunk.Data[matchingBlocks] = 0 chunk.chunkChanged() self.editor.invalidateChunks([chunk.chunkPosition]) for te in chunk.TileEntities: if "Items" in te: l = len(te["Items"]) te["Items"].value = [t for t in te["Items"].value if not matches(t)] if l != len(te["Items"]): chunk.dirty = True entities = [e for e in chunk.Entities if matches_itementity(e)] if len(entities) != len(chunk.Entities): chunk.Entities.value = entities chunk.dirty = True yield (i, self.editor.level.chunkCount) i += 1 progressInfo = _("Deleting the item {0} from the entire world ({1} chunks)").format( itemName(chestWidget.id, 0), self.editor.level.chunkCount) showProgress(progressInfo, deleteItemsIter(), cancel=True) self.editor.addUnsavedEdit() chestWidget.selectedItemIndex = min(chestWidget.selectedItemIndex, len(tileEntityTag["Items"]) - 1) def deleteItem(): i = chestWidget.selectedItemIndex item = tileEntityTag["Items"][i] tileEntityTag["Items"].value = [t for t in tileEntityTag["Items"].value if t is not item] chestWidget.selectedItemIndex = min(chestWidget.selectedItemIndex, len(tileEntityTag["Items"]) - 1) def deleteEnable(): return len(tileEntityTag["Items"]) and chestWidget.selectedItemIndex != -1 def addEnable(): return len(tileEntityTag["Items"]) < chestWidget.itemLimit def addItem(): slot = 0 for item in tileEntityTag["Items"]: if slot == item["Slot"].value: slot += 1 if slot >= chestWidget.itemLimit: return item = pymclevel.TAG_Compound() item["id"] = pymclevel.TAG_String("minecraft:") item["Damage"] = pymclevel.TAG_Short(0) item["Slot"] = pymclevel.TAG_Byte(slot) item["Count"] = pymclevel.TAG_Byte(1) tileEntityTag["Items"].append(item) addItemButton = Button("New Item (1.7+)", action=addItem, enable=addEnable) deleteItemButton = Button("Delete This Item", action=deleteItem, enable=deleteEnable) deleteFromWorldButton = Button("Delete All Instances Of This Item From World", action=deleteFromWorld, enable=deleteEnable) deleteCol = Column((addItemButton, deleteItemButton, deleteFromWorldButton)) fieldRow = Row(fieldRow) col = Column((chestItemTable, fieldRow, deleteCol)) chestWidget.add(col) chestWidget.shrink_wrap() Dialog(client=chestWidget, responses=["Done"]).present() level = self.editor.level class ChestEditOperation(Operation): def __init__(self, tool, level): self.tool = tool self.level = level self.undoBackupEntityTag = undoBackupEntityTag self.canUndo = False def perform(self, recordUndo=True): if self.level.saving: alert("Cannot perform action while saving is taking place") return level.addTileEntity(tileEntityTag) self.canUndo = True def undo(self): self.redoBackupEntityTag = copy.deepcopy(tileEntityTag) level.addTileEntity(self.undoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntityTag), (1, 1, 1)) def redo(self): level.addTileEntity(self.redoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntityTag), (1, 1, 1)) if chestWidget.dirty: op = ChestEditOperation(self.editor, self.editor.level) self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() @mceutils.alertException def editFlowerPot(self, point): panel = Dialog() tileEntity = self.editor.level.tileEntityAt(*point) undoBackupEntityTag = copy.deepcopy(tileEntity) if not tileEntity: tileEntity = pymclevel.TAG_Compound() tileEntity["id"] = pymclevel.TAG_String(self.editor.level.mcedit_defs.get("FlowerPot", "FlowerPot")) tileEntity["x"] = pymclevel.TAG_Int(point[0]) tileEntity["y"] = pymclevel.TAG_Int(point[1]) tileEntity["z"] = pymclevel.TAG_Int(point[2]) tileEntity["Item"] = pymclevel.TAG_String("") tileEntity["Data"] = pymclevel.TAG_Int(0) self.editor.level.addTileEntity(tileEntity) titleLabel = Label("Edit Flower Pot") Item = TextFieldWrapped(width=300, text=tileEntity["Item"].value) oldItem = Item.value Data = IntField(width=300,text=str(tileEntity["Data"].value)) oldData = Data.value class FlowerPotEditOperation(Operation): def __init__(self, tool, level): self.tool = tool self.level = level self.undoBackupEntityTag = undoBackupEntityTag self.canUndo = False def perform(self, recordUndo=True): if self.level.saving: alert("Cannot perform action while saving is taking place") return self.level.addTileEntity(tileEntity) self.canUndo = True def undo(self): self.redoBackupEntityTag = copy.deepcopy(tileEntity) self.level.addTileEntity(self.undoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) def redo(self): self.level.addTileEntity(self.redoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) def updateFlowerPot(): if oldData != Data.value or oldItem != Item.value: tileEntity["Item"] = pymclevel.TAG_String(Item.value) tileEntity["Data"] = pymclevel.TAG_Int(Data.value) op = FlowerPotEditOperation(self.editor, self.editor.level) self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() chunk = self.editor.level.getChunk(int(int(point[0]) / 16), int(int(point[2]) / 16)) chunk.dirty = True panel.dismiss() okBtn = Button("OK", action=updateFlowerPot) cancel = Button("Cancel", action=panel.dismiss) panel.add(Column((titleLabel, Row((Label("Item"), Item)), Row((Label("Data"), Data)), okBtn, cancel))) panel.shrink_wrap() panel.present() @mceutils.alertException def editEnchantmentTable(self, point): panel = Dialog() tileEntity = self.editor.level.tileEntityAt(*point) undoBackupEntityTag = copy.deepcopy(tileEntity) if not tileEntity: tileEntity = pymclevel.TAG_Compound() tileEntity["id"] = pymclevel.TAG_String(self.editor.level.defsIds.mcedit_defs.get("EnchantTable", "EnchantTable")) tileEntity["x"] = pymclevel.TAG_Int(point[0]) tileEntity["y"] = pymclevel.TAG_Int(point[1]) tileEntity["z"] = pymclevel.TAG_Int(point[2]) tileEntity["CustomName"] = pymclevel.TAG_String("") self.editor.level.addTileEntity(tileEntity) titleLabel = Label("Edit Enchantment Table") try: name = tileEntity["CustomName"].value except: name = "" name = TextFieldWrapped(width=300, text=name) oldName = name.value class EnchantmentTableEditOperation(Operation): def __init__(self, tool, level): self.tool = tool self.level = level self.undoBackupEntityTag = undoBackupEntityTag self.canUndo = False def perform(self, recordUndo=True): if self.level.saving: alert("Cannot perform action while saving is taking place") return self.level.addTileEntity(tileEntity) self.canUndo = True def undo(self): self.redoBackupEntityTag = copy.deepcopy(tileEntity) self.level.addTileEntity(self.undoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) def redo(self): self.level.addTileEntity(self.redoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) def updateEnchantmentTable(): if oldName != name.value: tileEntity["CustomName"] = pymclevel.TAG_String(name.value) op = EnchantmentTableEditOperation(self.editor, self.editor.level) self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() chunk = self.editor.level.getChunk(int(int(point[0]) / 16), int(int(point[2]) / 16)) chunk.dirty = True panel.dismiss() okBtn = Button("OK", action=updateEnchantmentTable) cancel = Button("Cancel", action=panel.dismiss) panel.add(Column((titleLabel, Row((Label("Custom Name"), name)), okBtn, cancel))) panel.shrink_wrap() panel.present() should_lock = False def rightClickDown(self, evt): # self.rightMouseDragStart = datetime.now() self.should_lock = True self.toggleMouseLook() def rightClickUp(self, evt): if not get_top_widget().is_modal: return if not self.should_lock and self.editor.level: self.should_lock = False self.toggleMouseLook() # if self.rightMouseDragStart is None: # return # td = datetime.now() - self.rightMouseDragStart # # except AttributeError: # # return # # print "RightClickUp: ", td # if td.microseconds > 180000: # self.mouseLookOff() def leftClickDown(self, evt): self.editor.toolMouseDown(evt, self.blockFaceUnderCursor) if evt.num_clicks == 2: def distance2(p1, p2): return numpy.sum(map(lambda a, b: (a - b) ** 2, p1, p2)) point, face = self.blockFaceUnderCursor if point: point = map(lambda x: int(numpy.floor(x)), point) if self.editor.currentTool is self.editor.selectionTool: try: block = self.editor.level.blockAt(*point) materials = self.editor.level.materials if distance2(point, self.cameraPosition) > 4: blockEditors = { materials.MonsterSpawner.ID: self.editMonsterSpawner, materials.Sign.ID: self.editSign, materials.WallSign.ID: self.editSign, materials.MobHead.ID: self.editSkull, materials.CommandBlock.ID: self.editCommandBlock, materials.CommandBlockRepeating.ID: self.editCommandBlock, materials.CommandBlockChain.ID: self.editCommandBlock, pymclevel.alphaMaterials.Jukebox.ID: self.editJukebox, materials.NoteBlock.ID: self.editNoteBlock, materials.FlowerPot.ID: self.editFlowerPot, materials.EnchantmentTable.ID: self.editEnchantmentTable } edit = blockEditors.get(block) if edit: self.editor.endSelection() edit(point) else: # detect "container" tiles te = self.editor.level.tileEntityAt(*point) if te and "Items" in te and "id" in te: self.editor.endSelection() self.editContainer(point, te["id"].value) except (EnvironmentError, pymclevel.ChunkNotPresent): pass def leftClickUp(self, evt): self.editor.toolMouseUp(evt, self.blockFaceUnderCursor) # --- Event handlers --- def mouse_down(self, evt): button = keys.remapMouseButton(evt.button) logging.debug("Mouse down %d @ %s", button, evt.pos) if button == 1: if sys.platform == "darwin" and evt.ctrl: self.rightClickDown(evt) else: self.leftClickDown(evt) elif button == 2: self.rightClickDown(evt) elif button == 3 and sys.platform == "darwin" and evt.alt: self.leftClickDown(evt) else: evt.dict['keyname'] = "mouse{}".format(button) self.editor.key_down(evt) self.editor.focus_on(None) # self.focus_switch = None def mouse_up(self, evt): button = keys.remapMouseButton(evt.button) logging.debug("Mouse up %d @ %s", button, evt.pos) if button == 1: if sys.platform == "darwin" and evt.ctrl: self.rightClickUp(evt) else: self.leftClickUp(evt) elif button == 2: self.rightClickUp(evt) elif button == 3 and sys.platform == "darwin" and evt.alt: self.leftClickUp(evt) else: evt.dict['keyname'] = "mouse{}".format(button) self.editor.key_up(evt) def mouse_drag(self, evt): self.mouse_move(evt) self.editor.mouse_drag(evt) lastRendererUpdate = datetime.now() def mouse_move(self, evt): if self.avoidMouseJumpBug == 2: self.avoidMouseJumpBug = 0 return def sensitivityAdjust(d): return d * config.controls.mouseSpeed.get() / 10.0 self.editor.mouseEntered = True if self.mouseMovesCamera: self.should_lock = False pitchAdjust = sensitivityAdjust(evt.rel[1]) if self.invertMousePitch: pitchAdjust = -pitchAdjust self.yaw += sensitivityAdjust(evt.rel[0]) self.pitch += pitchAdjust if datetime.now() - self.lastRendererUpdate > timedelta(0, 0, 500000): self.editor.renderer.loadNearbyChunks() self.lastRendererUpdate = datetime.now() # adjustLimit = 2 # self.oldMousePosition = (x, y) # if (self.startingMousePosition[0] - x > adjustLimit or self.startingMousePosition[1] - y > adjustLimit or # self.startingMousePosition[0] - x < -adjustLimit or self.startingMousePosition[1] - y < -adjustLimit): # mouse.set_pos(*self.startingMousePosition) # event.get(MOUSEMOTION) # self.oldMousePosition = (self.startingMousePosition) #if config.settings.showCommands.get(): def activeevent(self, evt): if evt.state & 0x2 and evt.gain != 0: self.avoidMouseJumpBug = 1 @property def tooltipText(self): #if self.hoveringCommandBlock[0] and (self.editor.currentTool is self.editor.selectionTool and self.editor.selectionTool.infoKey == 0): # return self.hoveringCommandBlock[1] or "[Empty]" if self.editor.currentTool is self.editor.selectionTool and self.editor.selectionTool.infoKey == 0 and config.settings.showQuickBlockInfo.get(): point, face = self.blockFaceUnderCursor if point: if not self.block_info_parsers or (BlockInfoParser.last_level != self.editor.level): self.block_info_parsers = BlockInfoParser.get_parsers(self.editor) block = self.editor.level.blockAt(*point) if block: if block in self.block_info_parsers: return self.block_info_parsers[block](point) return self.editor.currentTool.worldTooltipText floorQuad = numpy.array(((-4000.0, 0.0, -4000.0), (-4000.0, 0.0, 4000.0), (4000.0, 0.0, 4000.0), (4000.0, 0.0, -4000.0), ), dtype='float32') def updateFloorQuad(self): floorQuad = ((-4000.0, 0.0, -4000.0), (-4000.0, 0.0, 4000.0), (4000.0, 0.0, 4000.0), (4000.0, 0.0, -4000.0), ) floorQuad = numpy.array(floorQuad, dtype='float32') if self.editor.renderer.inSpace(): floorQuad *= 8.0 floorQuad += (self.cameraPosition[0], 0.0, self.cameraPosition[2]) self.floorQuad = floorQuad self.floorQuadList.invalidate() def drawFloorQuad(self): self.floorQuadList.call(self._drawFloorQuad) @staticmethod def _drawCeiling(): lines = [] minz = minx = -256 maxz = maxx = 256 append = lines.append for x in xrange(minx, maxx + 1, 16): append((x, 0, minz)) append((x, 0, maxz)) for z in xrange(minz, maxz + 1, 16): append((minx, 0, z)) append((maxx, 0, z)) GL.glColor(0.3, 0.7, 0.9) GL.glVertexPointer(3, GL.GL_FLOAT, 0, numpy.array(lines, dtype='float32')) GL.glEnable(GL.GL_DEPTH_TEST) GL.glDepthMask(False) GL.glDrawArrays(GL.GL_LINES, 0, len(lines)) GL.glDisable(GL.GL_DEPTH_TEST) GL.glDepthMask(True) def drawCeiling(self): GL.glMatrixMode(GL.GL_MODELVIEW) # GL.glPushMatrix() x, y, z = self.cameraPosition x -= x % 16 z -= z % 16 y = self.editor.level.Height GL.glTranslate(x, y, z) self.ceilingList.call(self._drawCeiling) GL.glTranslate(-x, -y, -z) _floorQuadList = None @property def floorQuadList(self): if not self._floorQuadList: self._floorQuadList = glutils.DisplayList() return self._floorQuadList _ceilingList = None @property def ceilingList(self): if not self._ceilingList: self._ceilingList = glutils.DisplayList() return self._ceilingList @property def floorColor(self): if self.drawSky: return 0.0, 0.0, 1.0, 0.3 else: return 0.0, 1.0, 0.0, 0.15 # floorColor = (0.0, 0.0, 1.0, 0.1) def _drawFloorQuad(self): GL.glDepthMask(True) GL.glPolygonOffset(DepthOffset.ChunkMarkers + 2, DepthOffset.ChunkMarkers + 2) GL.glVertexPointer(3, GL.GL_FLOAT, 0, self.floorQuad) GL.glColor(*self.floorColor) with gl.glEnable(GL.GL_BLEND, GL.GL_DEPTH_TEST, GL.GL_POLYGON_OFFSET_FILL): GL.glDrawArrays(GL.GL_QUADS, 0, 4) @property def drawSky(self): return self._drawSky @drawSky.setter def drawSky(self, val): self._drawSky = val if self.skyList: self.skyList.invalidate() if self._floorQuadList: self._floorQuadList.invalidate() skyList = None def drawSkyBackground(self): if self.skyList is None: self.skyList = glutils.DisplayList() self.skyList.call(self._drawSkyBackground) def _drawSkyBackground(self): GL.glMatrixMode(GL.GL_MODELVIEW) GL.glPushMatrix() GL.glLoadIdentity() GL.glMatrixMode(GL.GL_PROJECTION) GL.glPushMatrix() GL.glLoadIdentity() GL.glEnableClientState(GL.GL_COLOR_ARRAY) quad = numpy.array([-1, -1, -1, 1, 1, 1, 1, -1], dtype='float32') if self.editor.level.dimNo == -1: colors = numpy.array([0x90, 0x00, 0x00, 0xff, 0x90, 0x00, 0x00, 0xff, 0x90, 0x00, 0x00, 0xff, 0x90, 0x00, 0x00, 0xff, ], dtype='uint8') elif self.editor.level.dimNo == 1: colors = numpy.array([0x22, 0x27, 0x28, 0xff, 0x22, 0x27, 0x28, 0xff, 0x22, 0x27, 0x28, 0xff, 0x22, 0x27, 0x28, 0xff, ], dtype='uint8') else: colors = numpy.array([0x48, 0x49, 0xBA, 0xff, 0x8a, 0xaf, 0xff, 0xff, 0x8a, 0xaf, 0xff, 0xff, 0x48, 0x49, 0xBA, 0xff, ], dtype='uint8') alpha = 1.0 if alpha > 0.0: if alpha < 1.0: GL.glEnable(GL.GL_BLEND) GL.glVertexPointer(2, GL.GL_FLOAT, 0, quad) GL.glColorPointer(4, GL.GL_UNSIGNED_BYTE, 0, colors) GL.glDrawArrays(GL.GL_QUADS, 0, 4) if alpha < 1.0: GL.glDisable(GL.GL_BLEND) GL.glDisableClientState(GL.GL_COLOR_ARRAY) GL.glMatrixMode(GL.GL_PROJECTION) GL.glPopMatrix() GL.glMatrixMode(GL.GL_MODELVIEW) GL.glPopMatrix() enableMouseLag = config.settings.enableMouseLag.property() @property def drawFog(self): return self._drawFog and not self.editor.renderer.inSpace() @drawFog.setter def drawFog(self, val): self._drawFog = val fogColor = numpy.array([0.6, 0.8, 1.0, 1.0], dtype='float32') fogColorBlack = numpy.array([0.0, 0.0, 0.0, 1.0], dtype='float32') def enableFog(self): GL.glEnable(GL.GL_FOG) if self.drawSky: GL.glFogfv(GL.GL_FOG_COLOR, self.fogColor) else: GL.glFogfv(GL.GL_FOG_COLOR, self.fogColorBlack) GL.glFogf(GL.GL_FOG_DENSITY, 0.0001 * config.settings.fogIntensity.get()) @staticmethod def disableFog(): GL.glDisable(GL.GL_FOG) def getCameraPoint(self): distance = self.editor.currentTool.cameraDistance return [i for i in itertools.imap(lambda p, d: int(numpy.floor(p + d * distance)), self.cameraPosition, self.cameraVector)] blockFaceUnderCursor = (0, 0, 0), (0, 0, 0) viewingFrustum = None def setup_projection(self): distance = 1.0 if self.editor.renderer.inSpace(): distance = 8.0 GLU.gluPerspective(max(self.fov, 25.0), self.ratio, self.near * distance, self.far * distance) def setup_modelview(self): self.setModelview() def gl_draw(self): self.tickCamera(self.editor.frameStartTime, self.editor.cameraInputs, self.editor.renderer.inSpace()) self.render() def render(self): self.viewingFrustum = frustum.Frustum.fromViewingMatrix() if self.superSecretSettings: self.editor.drawStars() if self.drawSky: self.drawSkyBackground() if self.drawFog: self.enableFog() self.drawFloorQuad() self.editor.renderer.viewingFrustum = self.viewingFrustum self.editor.renderer.draw() if self.showCeiling and not self.editor.renderer.inSpace(): self.drawCeiling() if self.editor.level: try: self.updateBlockFaceUnderCursor() except (EnvironmentError, pymclevel.ChunkNotPresent) as e: logging.debug("Updating cursor block: %s", e) self.blockFaceUnderCursor = (None, None) self.root.update_tooltip() (blockPosition, faceDirection) = self.blockFaceUnderCursor if blockPosition: self.editor.updateInspectionString(blockPosition) if self.find_widget(mouse.get_pos()) == self: ct = self.editor.currentTool if ct: ct.drawTerrainReticle() ct.drawToolReticle() else: self.editor.drawWireCubeReticle() for t in self.editor.toolbar.tools: t.drawTerrainMarkers() t.drawToolMarkers() if self.drawFog: self.disableFog() if self.compassToggle: if self._compass is None: self._compass = CompassOverlay() x = getattr(getattr(self.editor, 'copyPanel', None), 'width', 0) if x: x = x /float( self.editor.mainViewport.width) self._compass.x = x self._compass.yawPitch = self.yaw, 0 with gl.glPushMatrix(GL.GL_PROJECTION): GL.glLoadIdentity() GL.glOrtho(0., 1., float(self.height) / self.width, 0, -200, 200) self._compass.draw() else: self._compass = None _compass = None class BlockInfoParser(object): last_level = None nbt_ending = "\n\nPress ALT for NBT" edit_ending = ", Double-Click to Edit" @classmethod def get_parsers(cls, editor): cls.last_level = editor.level parser_map = {} for subcls in cls.__subclasses__(): instance = subcls(editor.level) try: blocks = instance.getBlocks() except KeyError: continue if isinstance(blocks, (str, int)): parser_map[blocks] = instance.parse_info elif isinstance(blocks, (list, tuple)): for block in blocks: parser_map[block] = instance.parse_info return parser_map def getBlocks(self): raise NotImplementedError() def parse_info(self, pos): raise NotImplementedError() class SpawnerInfoParser(BlockInfoParser): def __init__(self, level): self.level = level def getBlocks(self): return self.level.materials["minecraft:mob_spawner"].ID def parse_info(self, pos): tile_entity = self.level.tileEntityAt(*pos) if tile_entity: spawn_data = tile_entity.get("SpawnData", {}) if spawn_data: id = spawn_data.get('EntityId', None) if not id: id = spawn_data.get('id', None) if not id: value = repr(NameError("Malformed spawn data: could not find 'EntityId' or 'id' tag.")) else: value = id.value return "{} Spawner{}{}".format(value, self.nbt_ending, self.edit_ending) return "[Empty]{}{}".format(self.nbt_ending, self.edit_ending) class JukeboxInfoParser(BlockInfoParser): id_records = { 2256: "13", 2257: "Cat", 2258: "Blocks", 2259: "Chirp", 2260: "Far", 2261: "Mall", 2262: "Mellohi", 2263: "Stal", 2264: "Strad", 2265: "Ward", 2266: "11", 2267: "Wait" } name_records = { "minecraft:record_13": "13", "minecraft:record_cat": "Cat", "minecraft:record_blocks": "Blocks", "minecraft:record_chirp": "Chirp", "minecraft:record_far": "Far", "minecraft:record_mall": "Mall", "minecraft:record_mellohi": "Mellohi", "minecraft:record_stal": "Stal", "minecraft:record_strad": "Strad", "minecraft:record_ward": "Ward", "minecraft:record_11": "11", "minecraft:record_wait": "Wait" } def __init__(self, level): self.level = level def getBlocks(self): return self.level.materials["minecraft:jukebox"].ID def parse_info(self, pos): tile_entity = self.level.tileEntityAt(*pos) if tile_entity: if "Record" in tile_entity: value = tile_entity["Record"].value if value in self.id_records: return self.id_records[value] + " Record" + self.nbt_ending + self.edit_ending elif "RecordItem" in tile_entity: value = tile_entity["RecordItem"]["id"].value if value in self.name_records: return "{} Record{}{}".format(self.name_records[value], self.nbt_ending, self.edit_ending) return "[No Record]{}{}".format(self.nbt_ending, self.edit_ending) class CommandBlockInfoParser(BlockInfoParser): def __init__(self, level): self.level = level def getBlocks(self): return [ self.level.materials["minecraft:command_block"].ID, self.level.materials["minecraft:repeating_command_block"].ID, self.level.materials["minecraft:chain_command_block"].ID ] def parse_info(self, pos): tile_entity = self.level.tileEntityAt(*pos) if tile_entity: value = tile_entity.get("Command", pymclevel.TAG_String("")).value if value: if len(value) > 1500: return u"{}\n**COMMAND IS TOO LONG TO SHOW MORE**{}{}".format(value[:1500], self.nbt_ending, self.edit_ending) try: return u"{}{}{}".format(value, self.nbt_ending, self.edit_ending) except: return u"[Command Block Parsing Failed]" return u"[Empty Command Block]{}{}".format(self.nbt_ending, self.edit_ending) class ContainerInfoParser(BlockInfoParser): def __init__(self, level): self.level = level def getBlocks(self): return [ self.level.materials["minecraft:dispenser"].ID, self.level.materials["minecraft:chest"].ID, self.level.materials["minecraft:furnace"].ID, self.level.materials["minecraft:lit_furnace"].ID, self.level.materials["minecraft:trapped_chest"].ID, self.level.materials["minecraft:hopper"].ID, self.level.materials["minecraft:dropper"].ID, self.level.materials["minecraft:brewing_stand"].ID ] def parse_info(self, pos): tile_entity = self.level.tileEntityAt(*pos) if tile_entity: return "Contains {} Items {}{}".format(len(tile_entity.get("Items", [])), self.nbt_ending, self.edit_ending) return "[Empty Container]{}{}".format(self.nbt_ending, self.edit_ending) def unproject(x, y, z): try: return GLU.gluUnProject(x, y, z) except ValueError: # projection failed return 0, 0, 0
84,320
38.31049
251
py
MCEdit-Unified
MCEdit-Unified-master/viewports/chunk.py
from camera import CameraViewport from OpenGL import GL import mceutils class ChunkViewport(CameraViewport): defaultScale = 1.0 # pixels per block def __init__(self, *a, **kw): CameraViewport.__init__(self, *a, **kw) def setup_projection(self): w, h = (0.5 * s / self.defaultScale for s in self.size) minx, maxx = - w, w miny, maxy = - h, h minz, maxz = -4000, 4000 GL.glOrtho(minx, maxx, miny, maxy, minz, maxz) def setup_modelview(self): x, y, z = self.cameraPosition GL.glRotate(90.0, 1.0, 0.0, 0.0) GL.glTranslate(-x, 0, -z) def zoom(self, f): x, y, z = self.cameraPosition if self.blockFaceUnderCursor[0] is None: return mx, my, mz = self.blockFaceUnderCursor[0] dx, dz = mx - x, mz - z s = min(4.0, max(1 / 16., self.defaultScale / f)) if s != self.defaultScale: self.defaultScale = s f = 1.0 - f self.cameraPosition = x + dx * f, self.editor.level.Height, z + dz * f self.editor.renderer.loadNearbyChunks() incrementFactor = 1.4 def zoomIn(self): self.zoom(1.0 / self.incrementFactor) def zoomOut(self): self.zoom(self.incrementFactor) def mouse_down(self, evt): if evt.button == 4: # wheel up - zoom in # if self.defaultScale == 4.0: # self.editor.swapViewports() # else: self.zoomIn() elif evt.button == 5: # wheel down - zoom out self.zoomOut() else: super(ChunkViewport, self).mouse_down(evt) def rightClickDown(self, evt): pass def rightClickUp(self, evt): pass def mouse_move(self, evt): pass @mceutils.alertException def mouse_drag(self, evt): if evt.buttons[2]: x, y, z = self.cameraPosition dx, dz = evt.rel self.cameraPosition = ( x - dx / self.defaultScale, y, z - dz / self.defaultScale) else: super(ChunkViewport, self).mouse_drag(evt) def render(self): super(ChunkViewport, self).render() @property def tooltipText(self): text = super(ChunkViewport, self).tooltipText if text == "1 W x 1 L x 1 H": return None return text def drawCeiling(self): pass
2,489
25.489362
82
py
MCEdit-Unified
MCEdit-Unified-master/viewports/__init__.py
from camera import CameraViewport from chunk import ChunkViewport
66
21.333333
33
py
MCEdit-Unified
MCEdit-Unified-master/editortools/nudgebutton.py
#-# Modified by D.C.-G. for translation purpose from albow import Label from albow.translate import _ from config import config from glbackground import GLBackground import pygame class NudgeButton(GLBackground): """ A button that captures movement keys while pressed and sends them to a listener as nudge events. Poorly planned. """ is_gl_container = True def __init__(self, editor): GLBackground.__init__(self) nudgeLabel = Label("Nudge", margin=8) self.editor = editor self.add(nudgeLabel) self.shrink_wrap() self.root = self.get_root() # tooltipBacking = Panel() # tooltipBacking.bg_color = (0, 0, 0, 0.6) keys = [_(config.keys[config.convert(k)].get()) for k in ("forward", "back", "left", "right", "up", "down", "fast nudge")] if config.keys[config.convert("fast nudge")].get() == "None": keys[6] = _("Right mouse") nudgeLabel.tooltipText = _("Click and hold. While holding, use the movement keys ({0}/{1}/{2}/{3}/{4}/{5}) to nudge. Left mouse to nudge a block.\n{6} to nudge a greater distance.").format( *keys) # tooltipBacking.shrink_wrap() def mouse_down(self, event): self.root.notMove = True self.root.nudge = self self.focus() if event.button == 3 and config.keys.fastNudge.get() == "None": self.editor.rightClickNudge = True def mouse_up(self, event): self.root.notMove = False self.root.nudge = None if event.button == 3 and config.keys.fastNudge.get() == "None": self.editor.rightClickNudge = False self.editor.turn_off_focus() if event.button == 1: self.editor.turn_off_focus() def key_down(self, evt): if not pygame.key.get_focused(): return keyname = evt.dict.get('keyname', None) or self.root.getKey(evt) if keyname == config.keys.fastNudge.get(): self.editor.rightClickNudge = True def key_up(self, evt): keyname = evt.dict.get('keyname', None) or self.root.getKey(evt) if keyname == config.keys.fastNudge.get(): self.editor.rightClickNudge = False
2,225
33.78125
198
py
MCEdit-Unified
MCEdit-Unified-master/editortools/filter.py
"""Copyright (c) 2010-2012 David Rio Vierra Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.""" # Modified by D.C.-G. for translation purpose import collections import os import traceback import copy from albow import FloatField, IntField, AttrRef, Row, Label, Widget, TabPanel, \ CheckBox, Column, Button, TextFieldWrapped, translate from editortools.tooloptions import ToolOptions from albow.extended_widgets import CheckBoxLabel _ = translate._ import albow from config import config from editortools.blockview import BlockButton from editortools.editortool import EditorTool from glbackground import Panel from mceutils import setWindowCaption, alertException from albow import ChoiceButton, showProgress, TextInputRow import mcplatform from operation import Operation from albow.dialogs import wrapped_label, alert, Dialog import pymclevel # from pymclevel import BoundingBox, MCEDIT_DEFS, MCEDIT_IDS from pymclevel import BoundingBox from pymclevel.id_definitions import version_defs_ids import json import directories import sys import keys import imp from nbtexplorer import NBTExplorerToolPanel import logging log = logging.getLogger(__name__) class FilterUtils(object): def __init__(self, **kwargs): self._given_data = [] for arg in kwargs: self._given_data.append(arg) self.__dict__[arg] = kwargs[arg] def Available_Attributes(self): return self._given_data def alertFilterException(func): def _func(*args, **kw): try: func(*args, **kw) except Exception as e: print traceback.format_exc() alert(_(u"Exception during filter operation. See console for details.\n\n{0}").format(e)) return _func def addNumField(page, optionName, oName, val, min_value=None, max_value=None, increment=0.1): if isinstance(val, float): field_type = FloatField if isinstance(increment, int): increment = float(increment) else: field_type = IntField if increment == 0.1: increment = 1 if isinstance(increment, float): increment = int(round(increment)) if min_value == max_value: min_value = None max_value = None field = field_type(value=val, width=200, min=min_value, max=max_value) field._increment = increment page.optionDict[optionName] = AttrRef(field, 'value') row = Row([Label(oName, doNotTranslate=True), field]) return row class JsonDictProperty(dict): def __init__(self, filename, **kwargs): super(JsonDictProperty, self).__init__(**kwargs) self._filename = filename def __setitem__(self, key, value): data = self._getJson() data[key] = value self._putJson(data) def __getitem__(self, key): return self._getJson()[key] def __delitem__(self, key): data = self._getJson() del data[key] self._putJson(data) def _putJson(self, data): with open(self._filename, 'wb') as f: json.dump(data, f) def _getJson(self): fp = None try: fp = open(self._filename, 'rb') filter_json = json.load(fp) if "Macros" not in filter_json.keys(): filter_json["Macros"] = {} return filter_json except (ValueError, IOError): return {"Macros": {}} finally: if fp: fp.close() class SingleFileChooser(Widget): OPEN_FILE = 0 SAVE_FILE = 1 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 _save_file(self): file_types = 'Custom File\0{}\0'.format(';'.join(self.file_types)) if not self.file_types[0].startswith("*"): name = self.file_types[0] else: name = self.file_types[0][1:] file_path = mcplatform.askSaveFile(".", "Save as...", name, file_types, self.file_types[0][1:]) if file_path: self._button.set_text(os.path.basename(file_path), True) self.file_path = file_path else: self._button.set_text('Save a file') self.file_path = None self._button.shrink_wrap() self.shrink_wrap() def __init__(self, file_types=None, operation=0, **kwds): Widget.__init__(self, **kwds) if file_types is None: self.file_types = ["*.*",] else: self.file_types = file_types self.file_path = None self._button = None if operation == self.OPEN_FILE: self._button = Button("Choose a file", action=self._open_file) elif operation == self.SAVE_FILE: self._button = Button("Save a file", action=self._save_file) self.add(self._button) self.shrink_wrap() class MacroModuleOptions(Widget): is_gl_container = True def __init__(self, macro_data, *args, **kw): self._parent = None self._macro_data = macro_data if '_parent' in kw.keys(): self._parent = kw.pop('_parent') Widget.__init__(self, *args, **kw) infoColList = [] stepsLabel = wrapped_label("Number of steps: %s" % macro_data["Number of steps"], 300) infoColList.append(stepsLabel) for step in sorted(macro_data.keys()): if step != "Number of steps": infoColList.append(wrapped_label("Step %s: %s" % (int(step) + 1, macro_data[step]["Name"]), 300)) self.add(Column(infoColList)) self.shrink_wrap() @property def options(self): return {} @options.setter def options(self, value): pass def run(self): pass @alertFilterException def confirm(self, tool): with setWindowCaption("Applying Macro..."): options = [] filters = [] for step in sorted(self._macro_data.keys()): if step != "Number of steps": filters.append(tool.filterModules[self._macro_data[step]["Name"]]) for module_input in self._macro_data[step]["Inputs"].keys(): if not isinstance(self._macro_data[step]["Inputs"][module_input], (str, unicode)): continue if not self._macro_data[step]["Inputs"][module_input].startswith("block-"): continue toFind = self._macro_data[step]["Inputs"][module_input][6:].split(":") block = tool.editor.materials.get((toFind[0], toFind[1])) self._macro_data[step]["Inputs"][module_input] = block options.append(self._macro_data[step]["Inputs"]) op = MacroOperation(tool.editor, tool.editor.level, tool.selectionBox(), filters, options) tool.editor.level.showProgress = showProgress tool.editor.addOperation(op) tool.editor.addUnsavedEdit() tool.editor.invalidateBox(tool.selectionBox()) class FilterModuleOptions(Widget): is_gl_container = True def __init__(self, tool, module, *args, **kw): self._parent = None self.nbttree = None self.module = module if '_parent' in kw.keys(): self._parent = kw.pop('_parent') Widget.__init__(self, *args, **kw) self.spacing = 2 self.tool = tool self.pages = pages = TabPanel() pages.is_gl_container = True self.optionDict = {} self.giveEditorObject(module) log.info("Creating options for " + str(module)) if hasattr(module, "inputs"): trn = getattr(module, "trn", None) self.trn = trn if isinstance(module.inputs, list): self.pgs = [] for tabData in module.inputs: title, page, pageRect = self.makeTabPage(self.tool, tabData, trn=trn) self.pgs.append((title, page)) pages.set_parent(None) self.pages = pages = TabPanel(self.pgs) elif isinstance(module.inputs, tuple): title, page, pageRect = self.makeTabPage(self.tool, module.inputs, trn=trn) pages.add_page(title, page) pages.set_rect(pageRect) else: self.size = (0, 0) pages.shrink_wrap() self.add(pages) self.shrink_wrap() if len(pages.pages): if pages.current_page is not None: pages.show_page(pages.current_page) else: pages.show_page(pages.pages[0]) for eachPage in pages.pages: self.optionDict = dict(self.optionDict.items() + eachPage.optionDict.items()) def rebuildTabPage(self, inputs, **kwargs): title, page, rect = self.makeTabPage(self.tool, inputs, self.trn, **kwargs) for i, t, p, s, r in self.pages.iter_tabs(): if t == title: self.pages.remove_page(p) self.pages.add_page(title, page, idx=i) self.pages.show_page(page) break def makeTabPage(self, tool, inputs, trn=None, **kwargs): page = Widget(**kwargs) page.is_gl_container = True rows = [] cols = [] max_height = tool.editor.mainViewport.height - tool.editor.toolbar.height - tool.editor.subwidgets[0].height -\ self._parent.filterSelectRow.height - self._parent.confirmButton.height - self.pages.tab_height page.optionDict = {} page.tool = tool title = "Tab" for optionSpec in inputs: optionName = optionSpec[0] optionType = optionSpec[1] if trn is not None: n = trn._(optionName) else: n = optionName if n == optionName: oName = _(optionName) else: oName = n if isinstance(optionType, tuple): if isinstance(optionType[0], (int, long, float)): if len(optionType) == 3: val, min, max = optionType increment = 0.1 elif len(optionType) == 2: min, max = optionType val = min increment = 0.1 else: val, min, max, increment = optionType rows.append(addNumField(page, optionName, oName, val, min, max, increment)) if isinstance(optionType[0], (str, unicode)): isChoiceButton = False if optionType[0] == "string": kwds = [] wid = None val = None for keyword in optionType: if isinstance(keyword, (str, unicode)) and keyword != "string": kwds.append(keyword) for keyword in kwds: splitWord = keyword.split('=') if len(splitWord) > 1: v = None try: v = int(splitWord[1]) except ValueError: pass key = splitWord[0] if v is not None: if key == "width": wid = v else: if key == "value": val = "=".join(splitWord[1:]) if val is None: val = "" if wid is None: wid = 200 field = TextFieldWrapped(value=val, width=wid) page.optionDict[optionName] = AttrRef(field, 'value') row = Row((Label(oName, doNotTranslate=True), field)) rows.append(row) elif optionType[0] == "block": blockButton = BlockButton(tool.editor.level.materials) try: blockButton.blockInfo = tool.editor.level.materials[optionType[1]] except AttributeError: blockButton.blockInfo = tool.editor.level.materials[0] except KeyError: if tool.editor.level.materials == pymclevel.pocketMaterials: blockButton.blockInfo = pymclevel.alphaMaterials[optionType[1]] else: raise row = Column((Label(oName, doNotTranslate=True), blockButton)) page.optionDict[optionName] = AttrRef(blockButton, 'blockInfo') rows.append(row) elif optionType[0] == "file-save": if len(optionType) == 2: file_chooser = SingleFileChooser(file_types=optionType[1], operation=SingleFileChooser.SAVE_FILE) else: file_chooser = SingleFileChooser(operation=SingleFileChooser.SAVE_FILE) row = Row((Label(oName, doNotTranslate=True), file_chooser)) page.optionDict[optionName] = AttrRef(file_chooser, 'file_path') rows.append(row) elif optionType[0] == "file-open": if len(optionType) == 2: file_chooser = SingleFileChooser(file_types=optionType[1], operation=SingleFileChooser.OPEN_FILE) else: file_chooser = SingleFileChooser(operation=SingleFileChooser.OPEN_FILE) row = Row((Label(oName, doNotTranslate=True), file_chooser)) page.optionDict[optionName] = AttrRef(file_chooser, 'file_path') rows.append(row) else: isChoiceButton = True if isChoiceButton: if trn is not None: __ = trn._ else: __ = _ choices = [__("%s" % a) for a in optionType] choiceButton = ChoiceButton(choices, doNotTranslate=True) page.optionDict[optionName] = AttrRef(choiceButton, 'selectedChoice') rows.append(Row((Label(oName, doNotTranslate=True), choiceButton))) elif isinstance(optionType, bool): cbox = CheckBox(value=optionType) page.optionDict[optionName] = AttrRef(cbox, 'value') row = Row((Label(oName, doNotTranslate=True), cbox)) rows.append(row) elif isinstance(optionType, (int, float)): rows.append(addNumField(self, optionName, oName, optionType)) elif optionType == "blocktype" or isinstance(optionType, pymclevel.materials.Block): blockButton = BlockButton(tool.editor.level.materials) if isinstance(optionType, pymclevel.materials.Block): blockButton.blockInfo = optionType row = Column((Label(oName, doNotTranslate=True), blockButton)) page.optionDict[optionName] = AttrRef(blockButton, 'blockInfo') rows.append(row) elif optionType == "label": rows.append(wrapped_label(oName, 50, doNotTranslate=True)) elif optionType == "string": inp = None # not sure how to pull values from filters, # but leaves it open for the future. Use this variable to set field width. if inp is not None: size = inp else: size = 200 field = TextFieldWrapped(value="") row = TextInputRow(oName, ref=AttrRef(field, 'value'), width=size, doNotTranslate=True) page.optionDict[optionName] = AttrRef(field, 'value') rows.append(row) elif optionType == "title": title = oName elif optionType == "file-save": file_chooser = SingleFileChooser(operation=SingleFileChooser.SAVE_FILE) row = Row((Label(oName, doNotTranslate=True), file_chooser)) page.optionDict[optionName] = AttrRef(file_chooser, 'file_path') rows.append(row) elif optionType == "file-open": file_chooser = SingleFileChooser(operation=SingleFileChooser.OPEN_FILE) row = Row((Label(oName, doNotTranslate=True), file_chooser)) page.optionDict[optionName] = AttrRef(file_chooser, 'file_path') rows.append(row) elif isinstance(optionType, list) and optionType[0].lower() == "nbttree": kw = {'close_text': None, 'load_text': None} if len(optionType) >= 3: def close(): self.pages.show_page(self.pages.pages[optionType[2]]) kw['close_action'] = close kw['close_text'] = "Go Back" if len(optionType) >= 4: if optionType[3]: kw['load_text'] = optionType[3] if hasattr(self.module, 'nbt_ok_action'): kw['ok_action'] = getattr(self.module, 'nbt_ok_action') self.nbttree = NBTExplorerToolPanel(self.tool.editor, nbtObject=optionType[1], height=max_height, no_header=True, copy_data=False, **kw) self.module.set_tree(self.nbttree.tree) for meth_name in dir(self.module): if meth_name.startswith('nbttree_'): setattr(self.nbttree.tree.treeRow, meth_name.split('nbttree_')[-1], getattr(self.module, meth_name)) # elif meth_name.startswith('nbt_'): # setattr(self.nbttree, meth_name.split('nbt_')[-1], getattr(self.module, meth_name)) page.optionDict[optionName] = AttrRef(self, 'rebuildTabPage') rows.append(self.nbttree) self.nbttree.page = len(self.pgs) else: raise ValueError(("Unknown option type", optionType)) height = sum(r.height for r in rows) + (len(rows) - 1) * self.spacing if height > max_height: h = 0 for i, r in enumerate(rows): h += r.height if h > height / 2: if rows[:i]: cols.append(Column(rows[:i], spacing=0)) rows = rows[i:] break if len(rows): cols.append(Column(rows, spacing=0)) if len(cols): page.add(Row(cols, spacing=0)) page.shrink_wrap() return title, page, page._rect @property def options(self): options = {} for k, v in self.optionDict.iteritems(): options[k] = v.get() if not isinstance(v.get(), pymclevel.materials.Block) else copy.copy(v.get()) if self.pages.current_page is not None: options["__page_index__"] = self.pages.pages.index(self.pages.current_page) return options @options.setter def options(self, val): for k in val: if k in self.optionDict: self.optionDict[k].set(val[k]) index = val.get("__page_index__", -1) if len(self.pages.pages) > index > -1: self.pages.show_page(self.pages.pages[index]) def giveEditorObject(self, module): module.editor = self.tool.editor @staticmethod def confirm(tool): with setWindowCaption("Applying Filter... - "): filterModule = tool.filterModules[tool.panel.filterSelect.selectedChoice] op = FilterOperation(tool.editor, tool.editor.level, tool.selectionBox(), filterModule, tool.panel.filterOptionsPanel.options) tool.editor.level.showProgress = showProgress tool.editor.addOperation(op) tool.editor.addUnsavedEdit() tool.editor.invalidateBox(tool.selectionBox()) class FilterToolPanel(Panel): BACKUP_FILTER_JSON = False """If set to true, the filter.json is backed up to the hard disk every time it's edited. The default is false, which makes the file save only whenever the tool gets closed. If MCEdit were to crash, any recorded macros would not be saved.""" def __init__(self, tool): Panel.__init__(self, name='Panel.FilterToolPanel') self.macro_steps = [] self.current_step = 0 self._filter_json = None self.keys_panel = None self.filterOptionsPanel = None self.filterSelect = ChoiceButton([], choose=self.filterChanged, doNotTranslate=True) self.binding_button = Button("", action=self.bind_key, tooltipText="Click to bind this filter to a key") self.filterLabel = Label("Filter:", fg_color=(177, 177, 255, 255)) self.filterLabel.mouse_down = lambda x: mcplatform.platform_open(directories.getFiltersDir()) self.filterLabel.tooltipText = "Click to open filters folder" self.macro_button = Button("Record Macro", action=self.start_record_macro) self.filterSelectRow = Row((self.filterLabel, self.filterSelect, self.macro_button, self.binding_button)) self.confirmButton = Button("Filter", action=self.confirm) self._recording = False self._save_macro = False self.tool = tool self.selectedName = self.filter_json.get("Last Filter Opened", "") utils = FilterUtils( editor=tool.editor, materials=self.tool.editor.level.materials, custom_widget=tool.editor.addExternalWidget, resize_selection_box=tool.editor._resize_selection_box ) utils_module = imp.new_module("filter_utils") utils_module = utils sys.modules["filter_utils"] = utils_module @staticmethod def load_filter_json(): #filter_json_file = os.path.join(directories.getDataDir(), "filters.json") filter_json_file = directories.getDataFile('filters.json') filter_json = {} if FilterToolPanel.BACKUP_FILTER_JSON: filter_json = JsonDictProperty(filter_json_file) else: fp = None try: if os.path.exists(filter_json_file): fp = open(filter_json_file, 'rb') filter_json = json.load(fp) except (ValueError, IOError) as e: log.error("Error while loading filters.json %s", e) finally: if fp: fp.close() if "Macros" not in filter_json.keys(): filter_json["Macros"] = {} return filter_json @property def filter_json(self): if self._filter_json is None: self._filter_json = FilterToolPanel.load_filter_json() return self._filter_json def close(self): self._saveOptions() self.filter_json["Last Filter Opened"] = self.selectedName if not FilterToolPanel.BACKUP_FILTER_JSON: #with open(os.path.join(directories.getDataDir(), "filters.json"), 'w') as f: with open(directories.getDataFile('filters.json'), 'w') as f: json.dump(self.filter_json, f) def reload(self): for i in list(self.subwidgets): self.remove(i) tool = self.tool # Display "No filter modules found" if there are no filters if len(tool.filterModules) is 0: self.add(Label("No filter modules found!")) self.shrink_wrap() return names_list = sorted([n for n in tool.filterNames if not n.startswith("[")]) # We get a list of names like ["[foo] bar", "[test] thing"] # The to sort on is created by splitting on "[": "[foo", " bar" and then # removing the first char: "foo", "bar" subfolder_names_list = sorted([n for n in tool.filterNames if n.startswith("[")], key=lambda x: x.split("]")[0][1:]) names_list.extend(subfolder_names_list) names_list.extend([macro for macro in self.filter_json["Macros"].keys()]) if self.selectedName is None or self.selectedName not in names_list: self.selectedName = names_list[0] # Remove any keybindings that don't have a filter for (i, j) in config.config.items("Filter Keys"): if i == "__name__": continue if not any([i == m.lower() for m in names_list]): config.config.remove_option("Filter Keys", i) self.filterSelect.choices = names_list name = self.selectedName.lower() names = [k for (k, v) in config.config.items("Filter Keys")] btn_name = config.config.get("Filter Keys", name) if name in names else "*" self.binding_button.set_text(btn_name) self.filterOptionsPanel = None while self.filterOptionsPanel is None: module = self.tool.filterModules.get(self.selectedName, None) if module is not None: try: self.filterOptionsPanel = FilterModuleOptions(self.tool, module, _parent=self) except Exception as e: alert(_("Error creating filter inputs for {0}: {1}").format(module, e)) traceback.print_exc() self.tool.filterModules.pop(self.selectedName) self.selectedName = tool.filterNames[0] if len(tool.filterNames) == 0: raise ValueError("No filters loaded!") if not self._recording: self.confirmButton.set_text("Filter") else: # We verified it was an existing macro already macro_data = self.filter_json["Macros"][self.selectedName] self.filterOptionsPanel = MacroModuleOptions(macro_data) self.confirmButton.set_text("Run Macro") # This has to be recreated every time in case a macro has a longer name then everything else. self.filterSelect = ChoiceButton(names_list, choose=self.filterChanged, doNotTranslate=True) self.filterSelect.selectedChoice = self.selectedName self.filterSelectRow = Row((self.filterLabel, self.filterSelect, self.macro_button, self.binding_button)) self.add(Column((self.filterSelectRow, self.filterOptionsPanel, self.confirmButton))) self.shrink_wrap() if self.parent: height = self.parent.mainViewport.height - self.parent.toolbar.height self.centery = height / 2 + self.parent.subwidgets[0].height if self.selectedName in self.tool.savedOptions: self.filterOptionsPanel.options = self.tool.savedOptions[self.selectedName] @property def macroSelected(self): return self.filterSelect.selectedChoice not in self.tool.filterNames def filterChanged(self): # if self.filterSelect.selectedChoice not in self.tool.filterModules: # return self._saveOptions() self.selectedName = self.filterSelect.selectedChoice if self.macroSelected: # Is macro self.macro_button.set_text("Delete Macro") self.macro_button.action = self.delete_macro elif not self._recording: self.macro_button.set_text("Record Macro") self.macro_button.action = self.start_record_macro self.reload() def delete_macro(self): macro_name = self.selectedName if macro_name in self.filter_json["Macros"]: del self.filter_json["Macros"][macro_name] if len(self.filterSelect.choices) == 1: # Just this macro available self.reload() return choices = self.filterSelect.choices self.filterSelect.selectedChoice = choices[0] if choices[0] != macro_name else choices[1] self.filterChanged() def stop_record_macro(self): macro_dialog = Dialog() macroNameLabel = Label("Macro Name: ") macroNameField = TextFieldWrapped(width=200) def save_macro(): macro_name = "{Macro} " + macroNameField.get_text() self.filter_json["Macros"][macro_name] = {} self.filter_json["Macros"][macro_name]["Number of steps"] = len(self.macro_steps) self.filterSelect.choices.append(macro_name) for entry in self.macro_steps: for inp in entry["Inputs"].keys(): if not isinstance(entry["Inputs"][inp], pymclevel.materials.Block): if not entry["Inputs"][inp] == "blocktype": continue _inp = entry["Inputs"][inp] entry["Inputs"][inp] = "block-{0}:{1}".format(_inp.ID, _inp.blockData) self.filter_json["Macros"][macro_name][entry["Step"]] = {"Name": entry["Name"], "Inputs": entry["Inputs"]} stop_dialog() self.filterSelect.selectedChoice = macro_name self.filterChanged() def stop_dialog(): self.macro_button.text = "Record Macro" self.macro_button.tooltipText = None self.macro_button.action = self.start_record_macro macro_dialog.dismiss() self.macro_steps = [] self.current_step = 0 self._recording = False input_row = Row((macroNameLabel, macroNameField)) saveButton = Button("Save", action=save_macro) closeButton = Button("Cancel", action=stop_dialog) button_row = Row((saveButton, closeButton)) macro_dialog.add(Column((input_row, button_row))) macro_dialog.shrink_wrap() macro_dialog.present() def start_record_macro(self): self.macro_button.text = "Stop recording" self.macro_button.tooltipText = "Currently recording a macro" self.macro_button.action = self.stop_record_macro self.confirmButton.text = "Add macro" self.confirmButton.width += 75 self.confirmButton.centerx = self.centerx self._recording = True def _addMacroStep(self, name=None, inputs=None): data = {"Name": name, "Step": self.current_step, "Inputs": inputs} self.current_step += 1 self.macro_steps.append(data) def unbind_key(self): config.config.remove_option("Filter Keys", self.selectedName) self.binding_button.text = "*" self.keys_panel.dismiss() # self.saveOptions() self.reload() def bind_key(self, message=None): panel = Panel(name='Panel.FilterToolPanel.bind_key') panel.bg_color = (0.5, 0.5, 0.6, 1.0) if not message: message = _("Press a key to assign to the filter \"{0}\"\n\n" "Press ESC to cancel.").format(self.selectedName) label = albow.Label(message) unbind_button = Button("Press to unbind", action=self.unbind_key) column = Column((label, unbind_button)) panel.add(column) panel.shrink_wrap() def panelKeyUp(evt): _key_name = self.root.getKey(evt) panel.dismiss(_key_name) def panelMouseUp(evt): button = keys.remapMouseButton(evt.button) _key_name = None if button == 3: _key_name = "Button 3" elif button == 4: _key_name = "Scroll Up" elif button == 5: _key_name = "Scroll Down" elif button == 6: _key_name = "Button 4" elif button == 7: _key_name = "Button 5" if 2 < button < 8: panel.dismiss(_key_name) panel.key_up = panelKeyUp panel.mouse_up = panelMouseUp self.keys_panel = panel key_name = panel.present() if isinstance(key_name, bool): return True if key_name != "Escape": if key_name in ["Alt-F4", "F1", "F2", "F3", "F4", "F5", "1", "2", "3", "4", "5", "6", "7", "8", "9", "Ctrl-Alt-F9", "Ctrl-Alt-F10"]: self.bind_key(_("You can't use the key {0}.\n" "Press a key to assign to the filter \"{1}\"\n\n" "" "Press ESC to cancel.").format(_(key_name), self.selectedName)) return True keysUsed = [(j, i) for (j, i) in config.config.items("Keys") if i == key_name] if keysUsed: self.bind_key(_("Can't bind. {0} is already used by {1}.\n" "Press a key to assign to the filter \"{2}\"\n\n" "" "Press ESC to cancel.").format(_(key_name), keysUsed[0][0], self.selectedName)) return True filter_keys = [i for (i, j) in config.config.items("Filter Keys") if j == key_name] if filter_keys: self.bind_key(_("Can't bind. {0} is already used by the \"{1}\" filter.\n" "Press a new key.\n\n" "" "Press ESC to cancel.").format(_(key_name), filter_keys[0])) return True config.config.set("Filter Keys", self.selectedName.lower(), key_name) config.save() self.reload() def _saveOptions(self): """Should never be called. Call filterchanged() or close() instead, which will then call this. :return: """ if self.filterOptionsPanel is not None: options = {} options.update(self.filterOptionsPanel.options) options.pop("", "") self.tool.savedOptions[self.selectedName] = options @alertFilterException def confirm(self): if self._recording: self._addMacroStep(self.selectedName, self.filterOptionsPanel.options) else: self.filterOptionsPanel.confirm(self.tool) class FilterOperation(Operation): def __init__(self, editor, level, box, filter, options): super(FilterOperation, self).__init__(editor, level) self.box = box self.filter = filter self.options = options self.canUndo = False def perform(self, recordUndo=True): if self.level.saving: alert(_("Cannot perform action while saving is taking place")) return # Override 'recordUndo' with filter RECORD_UNDO. # Some filters, like Find does not need to record undo stuff, since they're not changing anything recordUndo = getattr(self.filter, 'RECORD_UNDO', recordUndo) if recordUndo: self.undoLevel = self.extractUndo(self.level, self.box) # Inject the defs for blocks/entities in the module # Need to reimport the defs and ids to get the 'fresh' ones # from pymclevel import MCEDIT_DEFS, MCEDIT_IDS self.filter.MCEDIT_DEFS = self.level.defsIds.mcedit_defs self.filter.MCEDIT_IDS = self.level.defsIds.mcedit_ids self.filter.perform(self.level, BoundingBox(self.box), self.options) self.canUndo = True def dirtyBox(self): return self.box class MacroOperation(Operation): def __init__(self, editor, level, box, filters, options): super(MacroOperation, self).__init__(editor, level) self._box = box self.options = options self.filters = filters self.canUndo = False def perform(self, recordUndo=True): if self.level.saving: alert(_("Cannot perform action while saving is taking place")) return if recordUndo: self.undoLevel = self.extractUndo(self.level, self._box) for o, f in zip(self.options, self.filters): f.perform(self.level, BoundingBox(self._box), o) self.canUndo = True def dirtyBox(self): return self._box class FilterToolOptions(ToolOptions): def __init__(self, tool): ToolOptions.__init__(self, name='Panel.FilterToolOptions') self.tool = tool self.notifications_disabled = False disable_error_popup = CheckBoxLabel("Disable Error Notification", ref=AttrRef(self, 'notifications_disabled')) ok_button = Button("Ok", action=self.dismiss) col = Column((disable_error_popup, ok_button,), spacing=2) self.add(col) self.shrink_wrap() class FilterTool(EditorTool): tooltipText = "Filter" toolIconName = "filter" def __init__(self, editor): EditorTool.__init__(self, editor) self.filterModules = {} self.savedOptions = {} self.filters_not_imported = [] self.optionsPanel = FilterToolOptions(self) @property def statusText(self): return "Choose a filter, then click Filter or press Enter to apply it." def toolEnabled(self): return not (self.selectionBox() is None) def toolSelected(self): self.showPanel() @alertException def showPanel(self): self.panel = FilterToolPanel(self) self.not_imported_filters = [] self.reloadFilters() self.panel.reload() height = self.editor.mainViewport.height - self.editor.toolbar.height self.panel.centery = height / 2 + self.editor.subwidgets[0].height self.panel.left = self.editor.left self.editor.add(self.panel) def hidePanel(self): if self.panel is None: return self.panel.close() if self.panel.parent: self.panel.parent.remove(self.panel) self.panel = None def reloadFilters(self): filterFiles = [] unicode_module_names = [] # Tracking stock and custom filters names in order to load correctly the translations. stock_filters = [] cust_filters = [] def searchForFiltersInDir(searchFolder, stock=False): for root, folders, files in os.walk(os.path.join(searchFolder), True): filter_dir = os.path.basename(root) if filter_dir.startswith('demo'): continue subFolderString = root.replace(searchFolder, "") if subFolderString.endswith(os.sep): subFolderString = subFolderString[:len(os.sep)] if subFolderString.startswith(os.sep): subFolderString = subFolderString[len(os.sep):] if len(subFolderString) > 0: subFolderString = "[" + subFolderString + "]" try: root = str(root) if root not in sys.path: sys.path.append(root) except UnicodeEncodeError: unicode_module_names.extend([filter_name for filter_name in files]) for possible_filter in files: if possible_filter.endswith(".py"): if stock: stock_filters.append(possible_filter) _stock = True else: cust_filters.append(possible_filter) _stock = False # Force the 'stock' parameter if the filter was found in the stock-filters directory if possible_filter in stock_filters: _stock = True filterFiles.append((root, possible_filter, _stock, subFolderString)) # Search first for the stock filters. #searchForFiltersInDir(os.path.join(directories.getDataDir(), "stock-filters"), True) searchForFiltersInDir(directories.getDataFile('stock-filters'), True) searchForFiltersInDir(directories.getFiltersDir(), False) filterModules = [] org_lang = albow.translate.lang # If the path has unicode chars, there's no way of knowing what order to add the # files to the sys.modules. To fix this, we keep trying to import until we import # fail to import all leftover files. shouldContinue = True while shouldContinue: shouldContinue = False for f in filterFiles: if f[1] in self.not_imported_filters: continue module = tryImport(f[0], f[1], org_lang, f[2], f[3], f[1] in unicode_module_names, notify=(not self.optionsPanel.notifications_disabled)) if module is None: self.not_imported_filters.append(f[1]) continue filterModules.append(module) filterFiles.remove(f) shouldContinue |= True displayNames = [] for m in filterModules: while m.displayName in displayNames: m.displayName += "_" displayNames.append(m) filterModules = filter(lambda mod: hasattr(mod, "perform"), filterModules) self.filterModules = collections.OrderedDict(sorted( [(FilterTool.moduleDisplayName(x), x) for x in filterModules], key=lambda module_name: (module_name[0].lower(), module_name[1]))) @staticmethod def moduleDisplayName(module): subFolderString = getattr(module, 'foldersForDisplayName', "") subFolderString = subFolderString if len(subFolderString) < 1 else subFolderString + " " name = getattr(module, "displayName", module.__name__) return subFolderString + _(name[0].upper() + name[1:]) @property def filterNames(self): return [FilterTool.moduleDisplayName(module) for module in self.filterModules.itervalues()] #-# WIP. Reworking on the filters translations. #-# The 'new_method' variable is used to select the latest working code or the actual under development one. #-# This variable must be on False when releasing unless the actual code is fully working. new_method = True def tryImport_old(_root, name, org_lang, stock=False, subFolderString="", unicode_name=False, notify=True): with open(os.path.join(_root, name)) as module_file: module_name = name.split(os.path.sep)[-1].replace(".py", "") try: if unicode_name: source_code = module_file.read() module = imp.new_module(module_name) exec (source_code, module.__dict__) if module_name not in sys.modules.keys(): sys.modules[module_name] = module else: module = imp.load_source(module_name, os.path.join(_root, name), module_file) module.foldersForDisplayName = subFolderString if not (hasattr(module, 'displayName')): module.displayName = module_name # Python is awesome if not stock: if "trn" in sys.modules.keys(): del sys.modules["trn"] if "albow.translate" in sys.modules.keys(): del sys.modules["albow.translate"] from albow import translate as trn if directories.getFiltersDir() in name: trn_path = os.path.split(name)[0] else: trn_path = directories.getFiltersDir() trn_path = os.path.join(trn_path, subFolderString[1:-1], module_name) module.trn = trn if os.path.exists(trn_path): module.trn.setLangPath(trn_path) module.trn.buildTranslation(config.settings.langCode.get()) n = module.displayName if hasattr(module, "trn"): n = module.trn._(module.displayName) if n == module.displayName: n = _(module.displayName) module.displayName = n import albow.translate albow.translate.lang = org_lang return module except Exception as e: traceback.print_exc() if notify: alert(_(u"Exception while importing filter module {}. " + u"See console for details.\n\n{}").format(name, e)) return None def tryImport_new(_root, name, org_lang, stock=False, subFolderString="", unicode_name=False, notify=True): with open(os.path.join(_root, name)) as module_file: module_name = name.split(os.path.sep)[-1].replace(".py", "") try: if unicode_name: source_code = module_file.read() module = imp.new_module(module_name) exec (source_code, module.__dict__) if module_name not in sys.modules.keys(): sys.modules[module_name] = module else: module = imp.load_source(module_name, os.path.join(_root, name), module_file) module.foldersForDisplayName = subFolderString if not (hasattr(module, 'displayName')): module.displayName = module_name # Python is awesome if not stock: # This work fine with custom filters, but the choice buttons are broken for the stock ones... if directories.getFiltersDir() in name: trn_path = os.path.split(name)[0] else: trn_path = directories.getFiltersDir() trn_path = os.path.join(trn_path, subFolderString[1:-1], module_name) if os.path.exists(trn_path): albow.translate.buildTranslation(config.settings.langCode.get(), extend=True, langPath=trn_path) # module.trn = albow.translate module.displayName = _(module.displayName) module.trn = albow.translate return module except Exception as e: traceback.print_exc() if notify: alert(_(u"Exception while importing filter module {}. " + u"See console for details.\n\n{}").format(name, e)) return None if new_method: tryImport = tryImport_new else: tryImport = tryImport_old
48,824
39.755426
153
py
MCEdit-Unified
MCEdit-Unified-master/editortools/tooloptions.py
from glbackground import Panel class ToolOptions(Panel): def key_down(self, evt): if self.root.getKey(evt) == 'Escape': self.escape_action() def escape_action(self, *args, **kwargs): self.dismiss()
238
18.916667
45
py
MCEdit-Unified
MCEdit-Unified-master/editortools/timeditor.py
import directories from albow.controls import RotatableImage, Label import pygame from albow.widget import Widget from albow.layout import Column, Row from albow.fields import TimeField, IntField class ModifiedTimeField(TimeField): _callback = None def __init__(self, callback=None, **kwds): super(ModifiedTimeField, self).__init__(**kwds) self._callback = callback def __setattr__(self, *args, **kwargs): if self._callback and args[0] == "value": self._callback(args[1]) return TimeField.__setattr__(self, *args, **kwargs) class TimeEditor(Widget): # Do Not Change These Fields (unless necessary) ticksPerDay = 24000 ticksPerHour = ticksPerDay / 24 ticksPerMinute = ticksPerDay / (24 * 60) _maxRotation = 360.04 _tickToDegree = 66.66 _distance = 600.0 _time_adjustment = (ticksPerHour * 30) # -- Conversion Methods -- # @classmethod def fromTicks(cls, time): day = time / cls.ticksPerDay tick = time % cls.ticksPerDay hour = tick / cls.ticksPerHour tick %= cls.ticksPerHour minute = tick / cls.ticksPerMinute tick %= cls.ticksPerMinute return day, hour, minute, tick @classmethod def toTicks(cls, (day, hour, minute, ticks)): time = (day * cls.ticksPerDay) + (hour * cls.ticksPerHour) + (minute * cls.ticksPerMinute) + ticks return time def deltaToDegrees(self, delta): return (delta * (24000 / self._distance)) * (1 / self._tickToDegree) def degreesToTicks(self, deg): return deg * self._tickToDegree def ticksToDegrees(self, ticks): return ticks * (1 / self._tickToDegree) def doTimeAdjustment(self, ticks): return ticks + self._time_adjustment def undoTimeAdjustment(self, ticks): return ticks - self._time_adjustment # -- Special Callback -- # def _timeFieldCallback(self, (h, m)): ticks = self.undoTimeAdjustment(self.toTicks((1, h, m, 0))) deg = 0 if ticks > 0: deg = self.ticksToDegrees(self.undoTimeAdjustment(self.toTicks((1, h, m, 0)))) else: deg = self.ticksToDegrees(24000 + ticks) self.rot_image.set_angle(0) self.rot_image.add_angle(deg) self._current_tick_time = max(min(self.degreesToTicks(self.rot_image.get_angle() * -1), 24000.0), 0) self._current_time = self.fromTicks(self.doTimeAdjustment(self._current_tick_time)) def __init__(self, current_tick_time=0, **kwds): super(TimeEditor, self).__init__(**kwds) self._current_tick_time = current_tick_time self._current_time = self.fromTicks(self.doTimeAdjustment(self._current_tick_time)) self.__original_value = current_tick_time self.__original_time = self._current_time self.last_pos = (None, None) self.day_input = IntField(value=self.__original_time[0], min=1) __deg = self.ticksToDegrees(current_tick_time) self.rot_image = RotatableImage( image=pygame.image.load(directories.getDataFile("toolicons", "day_night_cycle.png")), min_angle=-self._maxRotation, max_angle=0, angle=__deg ) self.rot_image.mouse_drag = self.mouse_drag self.rot_image.mouse_up = self.mouse_up self.rot_image.tooltipText = "Left-Click and drag to the left or the right" self.time_field = ModifiedTimeField( value=(self.__original_time[1], self.__original_time[2]), callback=self._timeFieldCallback ) #__time_field_old_value = self.time_field.value self.add(Column(( Row((Label("Day: "), self.day_input)), self.rot_image, Row((Label("Time of day:"), self.time_field)) )) ) self.shrink_wrap() def get_time_value(self): if self.time_field.editing: self._timeFieldCallback(self.time_field.value) rot_ticks = max(min(self.degreesToTicks(self.rot_image.get_angle() * -1), 24000.0), 0) return ((self.day_input.value * self.ticksPerDay) + rot_ticks) - self.ticksPerDay def get_daytime_value(self): if self.time_field.editing: self._timeFieldCallback(self.time_field.value) ticks = max(min(self.degreesToTicks(self.rot_image.get_angle() * -1), 24000), 0) return ticks def mouse_down(self, event): if "tooltipText" in self.rot_image.__dict__: del self.rot_image.tooltipText def mouse_drag(self, event): if self.last_pos == (None, None): self.last_pos = event.pos delta = (event.pos[0] - self.last_pos[0]) self.rot_image.add_angle(self.deltaToDegrees(delta)) self._current_tick_time = max(min(self.degreesToTicks(self.rot_image.get_angle() * -1), 24000.0), 0) self._current_time = self.fromTicks(self.doTimeAdjustment(self._current_tick_time)) self.time_field.set_value((self._current_time[1], self._current_time[2])) self.last_pos = event.pos def mouse_up(self, event): self.last_pos = (None, None)
5,657
37.753425
125
py
MCEdit-Unified
MCEdit-Unified-master/editortools/editortool.py
from OpenGL import GL import numpy from depths import DepthOffset from pymclevel import BoundingBox from config import config from albow.translate import _ class EditorTool(object): surfaceBuild = False panel = None optionsPanel = None toolIconName = None worldTooltipText = None previewRenderer = None tooltipText = "???" def levelChanged(self): """ called after a level change """ pass @property def statusText(self): return "" @property def cameraDistance(self): return self.editor.cameraToolDistance def toolEnabled(self): return True def __init__(self, editor): self.editor = editor self.__hotkey = None @property def hotkey(self): return _(self.__hotkey) @hotkey.setter def hotkey(self, k): self.__hotkey = k def toolReselected(self): pass def toolSelected(self): pass def toolDeselected(self): pass def drawTerrainReticle(self): pass def drawTerrainMarkers(self): pass def drawTerrainPreview(self, origin): if self.previewRenderer is None: return self.previewRenderer.origin = map(lambda a, b: a - b, origin, self.level.bounds.origin) GL.glPolygonOffset(DepthOffset.ClonePreview, DepthOffset.ClonePreview) GL.glEnable(GL.GL_POLYGON_OFFSET_FILL) self.previewRenderer.draw() GL.glDisable(GL.GL_POLYGON_OFFSET_FILL) def rotate(self, amount=1, blocksOnly=False): pass def roll(self, amount=1, blocksOnly=False): pass def flip(self, amount=1, blocksOnly=False): pass def mirror(self, amount=1, blocksOnly=False): pass def swap(self, amount=1): pass def mouseDown(self, evt, pos, direction): """ pos is the coordinates of the block under the cursor, direction indicates which face is under it. the tool performs its action on the specified block """ pass def mouseUp(self, evt, pos, direction): pass def mouseDrag(self, evt, pos, direction): pass def keyDown(self, evt): pass def keyUp(self, evt): pass def increaseToolReach(self): """ Return True if the tool handles its own reach """ return False def decreaseToolReach(self): """ Return True if the tool handles its own reach """ return False def resetToolReach(self): """ Return True if the tool handles its own reach """ return False def confirm(self): """ Called when user presses enter """ pass def cancel(self): """ Cancel the current operation. called when a different tool is picked, escape is pressed, or etc etc """ self.hidePanel() # pass def findBestTrackingPlane(self, face): cv = list(self.editor.mainViewport.cameraVector) cv[face >> 1] = 0 cv = map(abs, cv) return cv.index(max(cv)) def drawToolReticle(self): """ Get self.editor.blockFaceUnderCursor for pos and direction. pos is the coordinates of the block under the cursor, direction indicates which face is under it. draw something to let the user know where the tool is going to act. e.g. a transparent block for the block placing tool. """ pass def drawToolMarkers(self): """ Draw any markers the tool wants to leave in the field while another tool is out. e.g. the current selection for SelectionTool """ pass def selectionChanged(self): """ called when the selection changes due to nudge. other tools can be active. """ pass edge_factor = 0.1 def boxFaceUnderCursor(self, box): if self.editor.mainViewport.mouseMovesCamera: return None, None p0 = self.editor.mainViewport.cameraPosition normal = self.editor.mainViewport.mouseVector if normal is None: return None, None points = {} # glPointSize(5.0) # glColor(1.0, 1.0, 0.0, 1.0) # glBegin(GL_POINTS) for dim in xrange(3): dim1 = dim + 1 dim2 = dim + 2 dim1 %= 3 dim2 %= 3 def pointInBounds(point, x): return box.origin[x] <= point[x] <= box.maximum[x] neg = normal[dim] < 0 for side in 0, 1: d = (box.maximum, box.origin)[side][dim] - p0[dim] if d >= 0 or (neg and d <= 0): if normal[dim]: scale = d / normal[dim] point = map(lambda a, p: (a * scale + p), normal, p0) # glVertex3f(*point) if pointInBounds(point, dim1) and pointInBounds(point, dim2): points[dim * 2 + side] = point # glEnd() if not len(points): return None, None cp = self.editor.mainViewport.cameraPosition distances = dict( (numpy.sum(map(lambda a, b: (b - a) ** 2, cp, point)), (face, point)) for face, point in points.iteritems()) if not len(distances): return None, None # When holding alt, pick the face opposite the camera # if key.get_mods() & KMOD_ALT: # minmax = max # else: face, point = distances[min(distances.iterkeys())] # if the point is near the edge of the face, and the edge is facing away, # return the away-facing face dim = face // 2 dim1, dim2 = dim + 1, dim + 2 dim1, dim2 = dim1 % 3, dim2 % 3 cv = self.editor.mainViewport.cameraVector # determine if a click was within self.edge_factor of the edge of a selection box side. if so, click through # to the opposite side for d in dim1, dim2: edge_width = box.size[d] * self.edge_factor facenormal = [0, 0, 0] cameraBehind = False if point[d] - box.origin[d] < edge_width: facenormal[d] = -1 cameraBehind = cp[d] - box.origin[d] > 0 if point[d] - box.maximum[d] > -edge_width: facenormal[d] = 1 cameraBehind = cp[d] - box.maximum[d] < 0 if numpy.dot(facenormal, cv) > 0 or cameraBehind: # the face adjacent to the clicked edge faces away from the cam return distances[max(distances.iterkeys())] return face, point def selectionCorners(self): """ returns the positions of the two selection corners as a pair of 3-tuples, each ordered x,y,z """ if (None != self.editor.selectionTool.bottomLeftPoint and None != self.editor.selectionTool.topRightPoint): return (self.editor.selectionTool.bottomLeftPoint, self.editor.selectionTool.topRightPoint) return None def selectionBoxForCorners(self, p1, p2): ''' considers p1,p2 as the marked corners of a selection. returns a BoundingBox containing all the blocks within.''' if self.editor.level is None: return None p1, p2 = list(p1), list(p2) # d = [(a-b) for a,b in zip(p1,p2)] for i in xrange(3): if p1[i] > p2[i]: t = p2[i] p2[i] = p1[i] p1[i] = t p2[i] += 1 size = map(lambda a, b: a - b, p2, p1) if p1[1] < 0: size[1] += p1[1] p1[1] = 0 h = self.editor.level.Height if p1[1] >= h: p1[1] = h - 1 size[1] = 1 if p1[1] + size[1] >= h: size[1] = h - p1[1] return BoundingBox(p1, size) def selectionBox(self): ''' selection corners, ordered, with the greater point moved up one block for use as the ending value of an array slice ''' c = self.selectionCorners() if c: return self.selectionBoxForCorners(*c) return None def selectionSize(self): ''' returns a tuple containing the size of the selection (x,y,z)''' c = self.selectionBox() if c is None: return None return c.size @property def maxBlocks(self): return config.settings.blockBuffer.get() / 2 # assume block buffer in bytes def showPanel(self): pass def hidePanel(self): if self.panel and self.panel.parent: self.panel.parent.remove(self.panel) self.panel = None
8,857
25.842424
131
py
MCEdit-Unified
MCEdit-Unified-master/editortools/select.py
"""Copyright (c) 2010-2012 David Rio Vierra Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.""" from __future__ import unicode_literals # -# Modified by D.C.-G. for translation purpose # .# Marks the layout modifications. -- D.C.-G. import os import sys import subprocess from OpenGL import GL import numpy import pygame from albow import Row, Label, Button, AttrRef, Column, ask, alert, ChoiceButton, CheckBoxLabel, IntInputRow, \ showProgress, TextInputRow from albow.translate import _ from config import config from depths import DepthOffset from editortools.editortool import EditorTool from editortools.nudgebutton import NudgeButton from editortools.tooloptions import ToolOptions from glbackground import Panel from mceutils import alertException, drawCube, drawFace, drawTerrainCuttingWire, setWindowCaption from operation import Operation import pymclevel from pymclevel.box import Vector, BoundingBox, FloatBox from fill import BlockFillOperation import tempfile from pymclevel import nbt import logging from albow.root import get_root from fileEdits import fileEdit, GetSort log = logging.getLogger(__name__) def GetSelectionColor(colorWord=None): return config.selectionColors[config.convert(colorWord or config.selection.color.get())].get() class SelectionToolOptions(ToolOptions): def updateColors(self): names = [name.lower() for (name, value) in config.selectionColors.items()] self.colorPopupButton.choices = [name.capitalize() for name in names] color = config.selection.color.get() if color.lower() not in names: config.selection.color.set("White") color = "White" self.colorPopupButton.choiceIndex = names.index(color.lower()) def __init__(self, tool): ToolOptions.__init__(self, name='Panel.SelectionToolOptions') self.tool = tool self.colorPopupButton = ChoiceButton([], choose=self.colorChanged) self.updateColors() colorRow = Row((Label("Color: ", align="r"), self.colorPopupButton)) okButton = Button("OK", action=self.dismiss) showPreviousRow = CheckBoxLabel("Show Previous Selection", ref=AttrRef(tool, 'showPreviousSelection')) spaceLabel = Label("") # .# spaceLabel.height /= 1.5 # .# blocksNudgeLabel = Label("Blocks Fast Nudge Settings:") blocksNudgeCheckBox = CheckBoxLabel("Move by the width of selection ", ref=config.fastNudgeSettings.blocksWidth, tooltipText="Moves selection by his width") blocksNudgeNumber = IntInputRow("Width of blocks movement: ", ref=config.fastNudgeSettings.blocksWidthNumber, width=100, min=2, max=50) selectionNudgeLabel = Label("Selection Fast Nudge Settings:") selectionNudgeCheckBox = CheckBoxLabel("Move by the width of selection ", ref=config.fastNudgeSettings.selectionWidth, tooltipText="Moves selection by his width") selectionNudgeNumber = IntInputRow("Width of selection movement: ", ref=config.fastNudgeSettings.selectionWidthNumber, width=100, min=2, max=50) pointsNudgeLabel = Label("Points Fast Nudge Settings:") pointsNudgeCheckBox = CheckBoxLabel("Move by the width of selection ", ref=config.fastNudgeSettings.pointsWidth, tooltipText="Moves points by the selection's width") pointsNudgeNumber = IntInputRow("Width of points movement: ", ref=config.fastNudgeSettings.pointsWidthNumber, width=100, min=2, max=50) staticCommandsNudgeRow = CheckBoxLabel("Static Coords While Nudging", ref=config.settings.staticCommandsNudge, tooltipText="Change static coordinates in command blocks while nudging.") moveSpawnerPosNudgeRow = CheckBoxLabel("Change Spawners While Nudging", ref=config.settings.moveSpawnerPosNudge, tooltipText="Change the position of the mobs in spawners while nudging.") def set_colorvalue(ch): i = "RGB".index(ch) def _set(val): choice = self.colorPopupButton.selectedChoice values = GetSelectionColor(choice) values = values[:i] + (val / 255.0,) + values[i + 1:] config.selectionColors[config.convert(choice)].set(str(values)) self.colorChanged() return _set def get_colorvalue(ch): i = "RGB".index(ch) def _get(): return int(GetSelectionColor()[i] * 255) return _get colorValuesInputs = [IntInputRow(ch + ":", get_value=get_colorvalue(ch), set_value=set_colorvalue(ch), min=0, max=255) for ch in "RGB"] colorValuesRow = Row(colorValuesInputs) # .# # col = Column((Label("Selection Options"), colorRow, colorValuesRow, showPreviousRow, spaceLabel, blocksNudgeLabel, blocksNudgeCheckBox, blocksNudgeNumber, spaceLabel, selectionNudgeLabel, selectionNudgeCheckBox, selectionNudgeNumber, spaceLabel, pointsNudgeLabel, pointsNudgeCheckBox, pointsNudgeNumber, okButton)) col = Column((Label("Selection Options"), colorRow, colorValuesRow, showPreviousRow, spaceLabel, blocksNudgeLabel, blocksNudgeCheckBox, blocksNudgeNumber, spaceLabel, selectionNudgeLabel, selectionNudgeCheckBox, selectionNudgeNumber, spaceLabel, pointsNudgeLabel, pointsNudgeCheckBox, pointsNudgeNumber, spaceLabel, staticCommandsNudgeRow, moveSpawnerPosNudgeRow, okButton), spacing=2) # .# self.add(col) self.shrink_wrap() def colorChanged(self): config.selection.color.set(self.colorPopupButton.selectedChoice) self.tool.updateSelectionColor() class SelectionToolPanel(Panel): def __init__(self, tool, editor): Panel.__init__(self, name='Panel.SelectionToolPanel') self.tool = tool self.editor = editor nudgeBlocksButton = NudgeButton(self.editor) nudgeBlocksButton.nudge = tool.nudgeBlocks nudgeBlocksButton.bg_color = (0.3, 1.0, 0.3, 0.35) self.nudgeBlocksButton = nudgeBlocksButton deleteBlocksButton = Button("Delete Blocks", action=self.tool.deleteBlocks) deleteBlocksButton.tooltipText = _("Fill the selection with Air. Shortcut: {0}").format( _(config.keys.deleteBlocks.get())) deleteEntitiesButton = Button("Delete Entities", action=self.tool.deleteEntities) deleteEntitiesButton.tooltipText = "Remove all entities within the selection" deleteTileTicksButton = Button("Delete Tile Ticks", action=self.tool.deleteTileTicks) deleteTileTicksButton.tooltipText = "Removes all tile ticks within selection. Tile ticks are scheduled block updates" analyzeButton = Button("Analyze", action=self.tool.analyzeSelection) analyzeButton.tooltipText = "Count the different blocks and entities in the selection and display the totals." cutButton = Button("Cut", action=self.tool.cutSelection) cutButton.tooltipText = _( "Take a copy of all blocks and entities within the selection, then delete everything within the selection. Shortcut: {0}").format( config.keys.cut.get()) copyButton = Button("Copy", action=self.tool.copySelection) copyButton.tooltipText = _("Take a copy of all blocks and entities within the selection. Shortcut: {0}").format( _(config.keys.copy.get())) pasteButton = Button("Paste", action=self.tool.editor.pasteSelection) pasteButton.tooltipText = _("Import the last item taken by Cut or Copy. Shortcut: {0}").format( _(config.keys.paste.get())) exportButton = Button("Export", action=self.tool.exportSelection) exportButton.tooltipText = _("Export the selection to a .schematic file. Shortcut: {0}").format( _(config.keys.exportSelection.get())) selectButton = Button("Select Chunks") selectButton.tooltipText = "Expand the selection to the edges of the chunks within" selectButton.action = tool.selectChunks selectButton.highlight_color = (0, 255, 0) deselectButton = Button("Deselect") deselectButton.tooltipText = _("Remove the selection. Shortcut: {0}").format(_(config.keys.deselect.get())) deselectButton.action = tool.deselect deselectButton.highlight_color = (0, 255, 0) openButton = Button("CB Commands") openButton.tooltipText = _( 'Open a text file with all command block commands in the currently selected area.\n' 'Save file to update command blocks.\nRight-click for options') openButton.action = tool.openCommands openButton.highlight_color = (0, 255, 0) openButton.rightClickAction = tool.CBCommandsOptions buttonsColumn = [ nudgeBlocksButton, deselectButton, selectButton, deleteBlocksButton, deleteEntitiesButton, ] if not hasattr(self.editor.level, "noTileTicks"): buttonsColumn.append(deleteTileTicksButton) buttonsColumn.extend([ analyzeButton, cutButton, copyButton, pasteButton, exportButton, ]) if hasattr(self.editor.level, "editFileNumber"): buttonsColumn.append(openButton) buttonsColumn = Column(buttonsColumn) self.add(buttonsColumn) self.shrink_wrap() class NudgeBlocksOperation(Operation): def __init__(self, editor, level, sourceBox, direction): super(NudgeBlocksOperation, self).__init__(editor, level) self.sourceBox = sourceBox self.destBox = BoundingBox(sourceBox.origin + direction, sourceBox.size) self.nudgeSelection = NudgeSelectionOperation(editor.selectionTool, direction) self.canUndo = False def dirtyBox(self): return self.sourceBox.union(self.destBox) def perform(self, recordUndo=True): if self.level.saving: alert("Cannot perform action while saving is taking place") return level = self.editor.level tempSchematic = level.extractSchematic(self.sourceBox) if tempSchematic: dirtyBox = self.dirtyBox() if recordUndo: self.undoLevel = self.extractUndo(level, dirtyBox) level.fillBlocks(self.sourceBox, level.materials.Air) level.removeTileEntitiesInBox(self.sourceBox) level.removeTileEntitiesInBox(self.destBox) level.removeEntitiesInBox(self.sourceBox) level.removeEntitiesInBox(self.destBox) staticCommandsNudge = config.settings.staticCommandsNudge.get() moveSpawnerPosNudge = config.settings.moveSpawnerPosNudge.get() level.copyBlocksFrom(tempSchematic, tempSchematic.bounds, self.destBox.origin, staticCommands=staticCommandsNudge, moveSpawnerPos=moveSpawnerPosNudge) self.editor.invalidateBox(dirtyBox) self.nudgeSelection.perform(recordUndo) if self.nudgeSelection.canUndo: self.canUndo = True def undo(self): super(NudgeBlocksOperation, self).undo() self.nudgeSelection.undo() def redo(self): super(NudgeBlocksOperation, self).redo() self.nudgeSelection.redo() class SelectionTool(EditorTool): color = (0.7, 0., 0.7) surfaceBuild = False toolIconName = "selection2" tooltipText = "Select\nRight-click for options" bottomLeftPoint = topRightPoint = None bottomLeftColor = (0., 0., 1.) bottomLeftSelectionColor = (0.75, 0.62, 1.0) topRightColor = (0.89, 0.89, 0.35) topRightSelectionColor = (1, 0.99, 0.65) nudgePanel = None def __init__(self, editor): self.editor = editor editor.selectionTool = self self.selectionPoint = None self.infoKey = 0 self.selectKey = 0 self.deselectKey = 0 self.root = get_root() self.optionsPanel = SelectionToolOptions(self) self.updateSelectionColor() # --- Tooltips --- def describeBlockAt(self, pos): blockID = self.editor.level.blockAt(*pos) blockdata = self.editor.level.blockDataAt(*pos) text = "X: {pos[0]}\nY: {pos[1]}\nZ: {pos[2]}\n".format(pos=pos) text += "Light: {0} Sky: {1}\n".format(self.editor.level.blockLightAt(*pos), self.editor.level.skylightAt(*pos)) text += "{name} ({bid}:{bdata})\n".format(name=self.editor.level.materials.names[blockID][blockdata], bid=blockID, pos=pos, bdata=blockdata) t = self.editor.level.tileEntityAt(*pos) if t: text += "TileEntity:\n" try: text += "{id}: {pos}\n".format(id=t["id"].value, pos=[t[a].value for a in "xyz"]) except Exception as e: text += repr(e) if "Items" in t and self.infoKey == 0: text += _("--Items omitted. {0} to view. Double-click to edit.--\n").format( _(config.keys.showBlockInfoModifier.get())) t = nbt.TAG_Compound(list(t.value)) del t["Items"] text += str(t) return text @property def worldTooltipText(self): if self.infoKey == 0: return pos, face = self.editor.blockFaceUnderCursor if pos is None: return try: size = None box = self.selectionBoxInProgress() if box: size = "{s[0]} W x {s[2]} L x {s[1]} H".format(s=box.size) if size: return size elif self.dragResizeFace is not None: return None else: return self.describeBlockAt(pos) except Exception as e: return repr(e) @alertException def selectChunks(self): box = self.selectionBox() newBox = BoundingBox((box.mincx << 4, 0, box.mincz << 4), (box.maxcx - box.mincx << 4, self.editor.level.Height, box.maxcz - box.mincz << 4)) self.editor.selectionTool.setSelection(newBox) def updateSelectionColor(self): self.selectionColor = GetSelectionColor() from albow import theme theme.root.sel_color = tuple(int(x * 112) for x in self.selectionColor) if self.nudgePanel is not None: self.hideNudgePanel() self.showPanel() # --- Nudge functions --- @alertException def nudgeBlocks(self, direction): if self.editor.rightClickNudge: if config.fastNudgeSettings.blocksWidth.get(): direction = map(int.__mul__, direction, self.selectionBox().size) else: nudgeWidth = config.fastNudgeSettings.blocksWidthNumber.get() direction = [x * nudgeWidth for x in direction] points = self.getSelectionPoints() bounds = self.editor.level.bounds if not all((p + direction) in bounds for p in points): return op = NudgeBlocksOperation(self.editor, self.editor.level, self.selectionBox(), direction) self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() def nudgeSelection(self, direction): if self.editor.rightClickNudge == 1: if config.fastNudgeSettings.selectionWidth.get(): direction = map(int.__mul__, direction, self.selectionBox().size) else: nudgeWidth = config.fastNudgeSettings.selectionWidthNumber.get() direction = [x * nudgeWidth for x in direction] points = self.getSelectionPoints() bounds = self.editor.level.bounds if not all((p + direction) in bounds for p in points): return op = NudgeSelectionOperation(self, direction) self.editor.addOperation(op) def nudgePoint(self, p, n): if self.selectionBox() is None: return if self.editor.rightClickNudge == 1: if config.fastNudgeSettings.pointsWidth.get(): n = map(int.__mul__, n, self.selectionBox().size) else: nudgeWidth = config.fastNudgeSettings.pointsWidthNumber.get() n = [x * nudgeWidth for x in n] self.setSelectionPoint(p, self.getSelectionPoint(p) + n) def nudgeBottomLeft(self, n): return self.nudgePoint(1 - self._oldCurrentCorner, n) def nudgeTopRight(self, n): return self.nudgePoint(self._oldCurrentCorner, n) # --- Panel functions --- def sizeLabelText(self): size = self.selectionSize() if self.dragResizeFace is not None: size = self.draggingSelectionBox().size return "{0}W x {2}L x {1}H".format(*size) def showPanel(self): if self.selectionBox() is None: return if self.nudgePanel is None: self.nudgePanel = Panel(name='Panel.SelectionTool.nudgePanel') self.nudgePanel.bg_color = [x * 0.5 for x in self.selectionColor] + [0.5, ] self.bottomLeftNudge = bottomLeftNudge = NudgeButton(self.editor) bottomLeftNudge.anchor = "brwh" self.topRightNudge = topRightNudge = NudgeButton(self.editor) topRightNudge.anchor = "blwh" if self.currentCorner == 0: bottomLeftNudge.nudge = self.nudgeTopRight topRightNudge.nudge = self.nudgeBottomLeft bottomLeftNudge.bg_color = self.topRightColor + (0.33,) topRightNudge.bg_color = self.bottomLeftColor + (0.33,) else: bottomLeftNudge.nudge = self.nudgeBottomLeft topRightNudge.nudge = self.nudgeTopRight bottomLeftNudge.bg_color = self.bottomLeftColor + (0.33,) topRightNudge.bg_color = self.topRightColor + (0.33,) self.nudgeRow = Row((bottomLeftNudge, topRightNudge)) self.nudgeRow.anchor = "blrh" self.nudgePanel.add(self.nudgeRow) self.editor.add(self.nudgePanel) self.nudgeSelectionButton = NudgeButton(self.editor) self.nudgeSelectionButton.nudge = self.nudgeSelection self.nudgeSelectionButton.bg_color = self.selectionColor + (0.7,) self.nudgeSelectionButton.anchor = "twh" self.spaceLabel = Label("") self.spaceLabel.anchor = "twh" self.spaceLabel.height = 3 self.nudgePanel.add(self.spaceLabel) if hasattr(self, 'sizeLabel'): self.nudgePanel.remove(self.sizeLabel) self.sizeLabel = Label(self.sizeLabelText()) self.sizeLabel.anchor = "wh" self.sizeLabel.tooltipText = _("{0:n} blocks").format(self.selectionBox().volume) self.nudgePanel.top = 0 self.nudgePanel.left = 0 self.nudgePanel.add(self.sizeLabel) self.nudgePanel.add(self.nudgeSelectionButton) self.spaceLabel.height = 3 self.nudgeSelectionButton.top = self.spaceLabel.bottom self.sizeLabel.top = self.nudgeSelectionButton.bottom self.nudgeRow.top = self.sizeLabel.bottom self.nudgePanel.shrink_wrap() self.sizeLabel.centerx = self.nudgePanel.centerx self.nudgeRow.centerx = self.nudgePanel.centerx self.nudgeSelectionButton.centerx = self.nudgePanel.centerx self.nudgePanel.bottom = self.editor.toolbar.top self.nudgePanel.centerx = self.editor.centerx self.nudgePanel.anchor = "bwh" if self.panel is None and self.editor.currentTool in (self, None): if self.bottomLeftPoint is not None and self.topRightPoint is not None: self.panel = SelectionToolPanel(self, self.editor) self.panel.left = self.editor.left self.panel.centery = self.editor.centery self.editor.add(self.panel) def hidePanel(self): self.editor.remove(self.panel) self.panel = None def hideNudgePanel(self): self.editor.remove(self.nudgePanel) self.nudgePanel = None selectionInProgress = False dragStartPoint = None # --- Event handlers --- def toolReselected(self): self.selectOtherCorner() def toolSelected(self): self.showPanel() def clampPos(self, pos): x, y, z = pos w, h, l = self.editor.level.Width, self.editor.level.Height, self.editor.level.Length if w > 0: if x >= w: x = w - 1 if x < 0: x = 0 if l > 0: if z >= l: z = l - 1 if z < 0: z = 0 if y >= h: y = h - 1 if y < 0: y = 0 pos = [x, y, z] return pos @property def currentCornerName(self): return (_("Blue"), _("Yellow"))[self.currentCorner] @property def statusText(self): if self.selectionInProgress: pd = self.editor.blockFaceUnderCursor if pd: p, d = pd if self.dragStartPoint == p: if self.clickSelectionInProgress: return _( "Click the mouse button again to place the {0} selection corner. Press {1} to switch corners.").format( self.currentCornerName, self.hotkey) else: return _( "Release the mouse button here to place the {0} selection corner. Press {1} to switch corners.").format( self.currentCornerName, self.hotkey) if self.clickSelectionInProgress: return _("Click the mouse button again to place the other selection corner.") return _("Release the mouse button to finish the selection") return _( "Click or drag to make a selection. Drag the selection walls to resize. Click near the edge to drag the opposite wall.").format( self.currentCornerName, self.hotkey) clickSelectionInProgress = False def endSelection(self): self.selectionInProgress = False self.clickSelectionInProgress = False self.dragResizeFace = None self.dragStartPoint = None def cancel(self): self.endSelection() EditorTool.cancel(self) dragResizeFace = None dragResizeDimension = None dragResizePosition = None def mouseDown(self, evt, pos, direction): pos = self.clampPos(pos) if self.selectionBox() and not self.selectionInProgress: face, point = self.boxFaceUnderCursor(self.selectionBox()) if face is not None: self.dragResizeFace = face self.dragResizeDimension = self.findBestTrackingPlane(face) self.dragResizePosition = point[self.dragResizeDimension] return if self.selectionInProgress is False: self.dragStartPoint = pos self.selectionInProgress = True def mouseUp(self, evt, pos, direction): pos = self.clampPos(pos) if self.dragResizeFace is not None: box = self.selectionBox() if box is not None: o, m = self.selectionPointsFromDragResize() x, y, z = self.bottomLeftPoint if (x == o[0] or x == m[0]) and (y == o[1] or y == m[1]) and (z == o[2] or z == m[2]): first = self.bottomLeftPoint isFirst = True else: first = self.topRightPoint isFirst = False second = [] for i in xrange(3): if o[i] == first[i]: second.append(m[i]) else: second.append(o[i]) if isFirst: o = first m = second else: o = second m = first op = SelectionOperation(self, (o, m)) self.editor.addOperation(op) self.dragResizeFace = None return if self.editor.viewMode == "Chunk": self.clickSelectionInProgress = True if self.dragStartPoint is None and not self.clickSelectionInProgress: return if self.dragStartPoint != pos or self.clickSelectionInProgress: self._oldCurrentCorner = self.currentCorner if self.panel is not None: if self.currentCorner == 0: self.bottomLeftNudge.nudge = self.nudgeTopRight self.topRightNudge.nudge = self.nudgeBottomLeft self.bottomLeftNudge.bg_color = self.topRightColor + (0.33,) self.topRightNudge.bg_color = self.bottomLeftColor + (0.33,) else: self.bottomLeftNudge.nudge = self.nudgeBottomLeft self.topRightNudge.nudge = self.nudgeTopRight self.bottomLeftNudge.bg_color = self.bottomLeftColor + (0.33,) self.topRightNudge.bg_color = self.topRightColor + (0.33,) op = SelectionOperation(self, (self.dragStartPoint, pos)) self.editor.addOperation(op) self.selectionInProgress = False self.clickSelectionInProgress = False self.dragStartPoint = None else: points = self.getSelectionPoints() if not all(points): points = (pos, pos) # set both points on the first click else: points[self.currentCorner] = pos if not self.clickSelectionInProgress: self.clickSelectionInProgress = True else: op = SelectionOperation(self, points) self.editor.addOperation(op) self.selectOtherCorner() self.selectionInProgress = False self.clickSelectionInProgress = False if self.chunkMode: if self.selectKey == 1: selectKeyBool = True else: selectKeyBool = False if self.deselectKey == 1: deselectKeyBool = True else: deselectKeyBool = False self.editor.selectionToChunks(remove=deselectKeyBool, add=selectKeyBool) self.editor.toolbar.selectTool(8) def keyDown(self, evt): keyname = evt.dict.get('keyname', None) or self.root.getKey(evt) if keyname == config.keys.showBlockInfo.get(): self.infoKey = 1 if keyname == config.keys.selectChunks.get(): self.selectKey = 1 if keyname == config.keys.deselectChunks.get(): self.deselectKey = 1 def keyUp(self, evt): keyname = evt.dict.get('keyname', None) or self.root.getKey(evt) if keyname == config.keys.selectChunks.get(): self.selectKey = 0 if keyname == config.keys.deselectChunks.get(): self.deselectKey = 0 @property def chunkMode(self): return self.editor.viewMode == "Chunk" or self.editor.currentTool is self.editor.toolbar.tools[8] def selectionBoxInProgress(self): if self.editor.blockFaceUnderCursor is None: return pos = self.editor.blockFaceUnderCursor[0] if self.selectionInProgress or self.clickSelectionInProgress: return self.selectionBoxForCorners(pos, self.dragStartPoint) # requires a selection def dragResizePoint(self): # returns a point representing the intersection between the mouse ray # and an imaginary plane perpendicular to the dragged face pos = self.editor.mainViewport.cameraPosition dim = self.dragResizeDimension distance = self.dragResizePosition - pos[dim] mouseVector = self.editor.mainViewport.mouseVector scale = distance / (mouseVector[dim] or 0.0001) point = map(lambda a, b: a * scale + b, mouseVector, pos) return point def draggingSelectionBox(self): p1, p2 = self.selectionPointsFromDragResize() box = self.selectionBoxForCorners(p1, p2) return box def selectionPointsFromDragResize(self): point = self.dragResizePoint() # glColor(1.0, 1.0, 0.0, 1.0) # glPointSize(9.0) # glBegin(GL_POINTS) # glVertex3f(*point) # glEnd() # # facebox = BoundingBox(box.origin, box.size) # facebox.origin[dim] = self.dragResizePosition # facebox.size[dim] = 0 # glEnable(GL_BLEND) # # drawFace(facebox, dim * 2) # # glDisable(GL_BLEND) # side = self.dragResizeFace & 1 dragdim = self.dragResizeFace >> 1 box = self.selectionBox() o, m = list(box.origin), list(box.maximum) (m, o)[side][dragdim] = int(numpy.floor(point[dragdim] + 0.5)) m = map(lambda a: a - 1, m) return o, m def option1(self): self.selectOtherCorner() _currentCorner = 1 _oldCurrentCorner = 1 @property def currentCorner(self): return self._currentCorner @currentCorner.setter def currentCorner(self, value): self._currentCorner = value & 1 self.toolIconName = ("selection", "selection2")[self._currentCorner] self.editor.toolbar.toolTextureChanged() def selectOtherCorner(self): self.currentCorner = 1 - self.currentCorner showPreviousSelection = config.selection.showPreviousSelection.property() alpha = 0.25 def drawToolMarkers(self): selectionBox = self.selectionBox() if selectionBox: widg = self.editor.find_widget(pygame.mouse.get_pos()) # these corners stay even while using the chunk tool. GL.glPolygonOffset(DepthOffset.SelectionCorners, DepthOffset.SelectionCorners) lineWidth = 3 if self._oldCurrentCorner == 1: bottomLeftColor = self.bottomLeftColor topRightColor = self.topRightColor else: bottomLeftColor = self.topRightColor topRightColor = self.bottomLeftColor for t, c, n in ((self.bottomLeftPoint, bottomLeftColor, self.bottomLeftNudge), (self.topRightPoint, topRightColor, self.topRightNudge)): if t is not None and not self.selectionInProgress: (sx, sy, sz) = t # draw a blue or yellow wireframe box at the selection corner r, g, b = c alpha = 0.4 try: bt = self.editor.level.blockAt(sx, sy, sz) if bt: alpha = 0.2 except (EnvironmentError, pymclevel.ChunkNotPresent): pass GL.glLineWidth(lineWidth) lineWidth += 1 # draw highlighted block faces when nudging if widg.parent == n or widg == n: GL.glEnable(GL.GL_BLEND) nudgefaces = numpy.array([ selectionBox.minx, selectionBox.miny, selectionBox.minz, selectionBox.minx, selectionBox.maxy, selectionBox.minz, selectionBox.minx, selectionBox.maxy, selectionBox.maxz, selectionBox.minx, selectionBox.miny, selectionBox.maxz, selectionBox.minx, selectionBox.miny, selectionBox.minz, selectionBox.maxx, selectionBox.miny, selectionBox.minz, selectionBox.maxx, selectionBox.miny, selectionBox.maxz, selectionBox.minx, selectionBox.miny, selectionBox.maxz, selectionBox.minx, selectionBox.miny, selectionBox.minz, selectionBox.minx, selectionBox.maxy, selectionBox.minz, selectionBox.maxx, selectionBox.maxy, selectionBox.minz, selectionBox.maxx, selectionBox.miny, selectionBox.minz, ], dtype='float32') if sx != selectionBox.minx: nudgefaces[0:12:3] = selectionBox.maxx if sy != selectionBox.miny: nudgefaces[13:24:3] = selectionBox.maxy if sz != selectionBox.minz: nudgefaces[26:36:3] = selectionBox.maxz GL.glColor(r, g, b, 0.3) GL.glVertexPointer(3, GL.GL_FLOAT, 0, nudgefaces) GL.glEnable(GL.GL_DEPTH_TEST) GL.glDrawArrays(GL.GL_QUADS, 0, 12) GL.glDisable(GL.GL_DEPTH_TEST) GL.glDisable(GL.GL_BLEND) GL.glColor(r, g, b, alpha) drawCube(BoundingBox((sx, sy, sz), (1, 1, 1)), GL.GL_LINE_STRIP) if not (not self.showPreviousSelection and self.selectionInProgress): # draw the current selection as a white box. hangs around when you use other tools. GL.glPolygonOffset(DepthOffset.Selection, DepthOffset.Selection) color = self.selectionColor + (self.alpha,) if self.dragResizeFace is not None: box = self.draggingSelectionBox() else: box = selectionBox if self.panel and (widg is self.panel.nudgeBlocksButton or widg.parent is self.panel.nudgeBlocksButton): color = (0.3, 1.0, 0.3, self.alpha) self.editor.drawConstructionCube(box, color) # highlight the face under the cursor, or the face being dragged if self.dragResizeFace is None: if self.selectionInProgress or self.clickSelectionInProgress: pass else: face, point = self.boxFaceUnderCursor(box) if face is not None: GL.glEnable(GL.GL_BLEND) GL.glColor(*color) # Shrink the highlighted face to show the click-through edges offs = [s * self.edge_factor for s in box.size] offs[face >> 1] = 0 origin = [o + off for o, off in zip(box.origin, offs)] size = [s - off * 2 for s, off in zip(box.size, offs)] cv = self.editor.mainViewport.cameraVector for i in xrange(3): if cv[i] > 0: origin[i] -= offs[i] size[i] += offs[i] else: size[i] += offs[i] smallbox = FloatBox(origin, size) drawFace(smallbox, face) GL.glColor(0.9, 0.6, 0.2, 0.8) GL.glLineWidth(2.0) drawFace(box, face, type=GL.GL_LINE_STRIP) GL.glDisable(GL.GL_BLEND) else: face = self.dragResizeFace point = self.dragResizePoint() dim = face >> 1 pos = point[dim] side = face & 1 o, m = selectionBox.origin, selectionBox.maximum otherFacePos = (m, o)[side ^ 1][dim] # ugly direction = (-1, 1)[side] # print "pos", pos, "otherFace", otherFacePos, "dir", direction # print "m", (pos - otherFacePos) * direction if (pos - otherFacePos) * direction > 0: face ^= 1 GL.glColor(0.9, 0.6, 0.2, 0.5) drawFace(box, face, type=GL.GL_LINE_STRIP) GL.glEnable(GL.GL_BLEND) GL.glEnable(GL.GL_DEPTH_TEST) drawFace(box, face) GL.glDisable(GL.GL_BLEND) GL.glDisable(GL.GL_DEPTH_TEST) selectionColor = map(lambda a: a * a * a * a, self.selectionColor) # draw a colored box representing the possible selection otherCorner = self.dragStartPoint if self.dragResizeFace is not None: self.showPanel() # xxx do this every frame while dragging because our UI kit is bad if (self.selectionInProgress or self.clickSelectionInProgress) and otherCorner is not None: GL.glPolygonOffset(DepthOffset.PotentialSelection, DepthOffset.PotentialSelection) pos, direction = self.editor.blockFaceUnderCursor if pos is not None: box = self.selectionBoxForCorners(otherCorner, pos) if self.chunkMode: box = box.chunkBox(self.editor.level) if self.deselectKey == 1: selectionColor = [1., 0., 0.] self.editor.drawConstructionCube(box, selectionColor + [self.alpha, ]) else: # don't draw anything at the mouse cursor if we're resizing the box if self.dragResizeFace is None: box = self.selectionBox() if box: face, point = self.boxFaceUnderCursor(box) if face is not None: return else: return def drawToolReticle(self): GL.glPolygonOffset(DepthOffset.SelectionReticle, DepthOffset.SelectionReticle) pos, direction = self.editor.blockFaceUnderCursor # draw a selection-colored box for the cursor reticle selectionColor = map(lambda a: a * a * a * a, self.selectionColor) r, g, b = selectionColor alpha = 0.3 try: bt = self.editor.level.blockAt(*pos) if bt: # # textureCoords = materials[bt][0] alpha = 0.12 except (EnvironmentError, pymclevel.ChunkNotPresent): pass # cube sides GL.glColor(r, g, b, alpha) GL.glDepthMask(False) GL.glEnable(GL.GL_BLEND) GL.glEnable(GL.GL_DEPTH_TEST) drawCube(BoundingBox(pos, (1, 1, 1))) GL.glDepthMask(True) GL.glDisable(GL.GL_DEPTH_TEST) drawTerrainCuttingWire(BoundingBox(pos, (1, 1, 1)), (r, g, b, 0.4), (1., 1., 1., 1.0) ) GL.glDisable(GL.GL_BLEND) def setSelection(self, box): if box is None: self.selectNone() else: self.setSelectionPoints(self.selectionPointsFromBox(box)) @staticmethod def selectionPointsFromBox(box): return box.origin, map(lambda x: x - 1, box.maximum) def selectNone(self): self.setSelectionPoints(None) def selectAll(self): box = self.editor.level.bounds op = SelectionOperation(self, self.selectionPointsFromBox(box)) self.editor.addOperation(op) def deselect(self): if self.selectionBox() is not None: op = SelectionOperation(self, None) self.editor.addOperation(op) def setSelectionPoint(self, pointNumber, newPoint): points = self.getSelectionPoints() points[pointNumber] = newPoint self.setSelectionPoints(points) def setSelectionPoints(self, points, changeSelection=True): if points: if all(points) and (points[0][1] < 0 or points[1][1] >= self.editor.level.Height): return self.bottomLeftPoint, self.topRightPoint = [Vector(*p) if p else None for p in points] else: self.bottomLeftPoint = self.topRightPoint = None if changeSelection: self._selectionChanged() self.editor.selectionChanged() def _selectionChanged(self): if self.selectionBox(): self.showPanel() else: self.hidePanel() self.hideNudgePanel() def getSelectionPoint(self, pointNumber): return (self.bottomLeftPoint, self.topRightPoint)[pointNumber] def getSelectionPoints(self): return [self.bottomLeftPoint, self.topRightPoint] @alertException def deleteBlocks(self): box = self.selectionBox() if None is box: return if box == box.chunkBox(self.editor.level): resp = ask( "You are deleting a chunk-shaped selection. Fill the selection with Air, or delete the chunks themselves?", responses=["Fill with Air", "Delete Chunks", "Cancel"]) if resp == "Delete Chunks": self.editor.toolbar.tools[8].destroyChunks(box.chunkPositions) elif resp == "Fill with Air": self._deleteBlocks() self.editor.renderer.discardAllChunks() else: self._deleteBlocks() def _deleteBlocks(self): box = self.selectionBox() if None is box: return op = BlockFillOperation(self.editor, self.editor.level, box, self.editor.level.materials.Air, []) with setWindowCaption("DELETING - "): self.editor.freezeStatus(_("Deleting {0} blocks").format(box.volume)) self.editor.addOperation(op) self.editor.invalidateBox(box) if op.canUndo: self.editor.addUnsavedEdit() @alertException def deleteTileTicks(self, recordUndo=True): box = self.selectionBox() with setWindowCaption("WORKING - "): self.editor.freezeStatus("Removing Tile Ticks...") level = self.editor.level editor = self.editor class DeleteTileTicksOperation(Operation): def __init__(self, editor, level): self.editor = editor self.level = level self.canUndo = True def perform(self, recordUndo=True): self.undoTileTicks = level.getTileTicksInBox(box) level.removeTileTicksInBox(box) editor.renderer.invalidateTileTicksInBox(box) def undo(self): self.redoTileTicks = level.getTileTicksInBox(box) level.removeTileTicksInBox(box) level.addTileTicks(self.undoTileTicks) editor.renderer.invalidateTileTicksInBox(box) def redo(self): self.undoTileTicks = level.getTileTicksInBox(box) level.removeTileTicksInBox(box) level.addTileTicks(self.redoTileTicks) editor.renderer.invalidateTileTicksInBox(box) op = DeleteTileTicksOperation(self.editor, self.editor.level) op.canUndo = recordUndo self.editor.addOperation(op) self.editor.invalidateBox(box) if op.canUndo: self.editor.addUnsavedEdit() @alertException def deleteEntities(self, recordUndo=True): box = self.selectionBox() if box is None: return with setWindowCaption("WORKING - "): self.editor.freezeStatus("Removing entities...") level = self.editor.level editor = self.editor class DeleteEntitiesOperation(Operation): def __init__(self, editor, level): self.editor = editor self.level = level self.canUndo = True def perform(self, recordUndo=True): self.undoEntities = level.getEntitiesInBox(box) level.removeEntitiesInBox(box) editor.renderer.invalidateEntitiesInBox(box) def undo(self): self.redoEntities = level.getEntitiesInBox(box) level.removeEntitiesInBox(box) level.addEntities(self.undoEntities) editor.renderer.invalidateEntitiesInBox(box) def redo(self): self.undoEntities = level.getEntitiesInBox(box) level.removeEntitiesInBox(box) level.addEntities(self.redoEntities) editor.renderer.invalidateEntitiesInBox(box) op = DeleteEntitiesOperation(self.editor, self.editor.level) op.canUndo = recordUndo self.editor.addOperation(op) self.editor.invalidateBox(box) if op.canUndo: self.editor.addUnsavedEdit() @alertException def analyzeSelection(self): box = self.selectionBox() self.editor.analyzeBox(self.editor.level, box) @alertException def cutSelection(self): if not self.selectionBox(): return self.copySelection() self.deleteBlocks() self.deleteEntities(False) self.deleteTileTicks(False) @alertException def copySelection(self): schematic = self._copySelection() if schematic: self.editor.addCopiedSchematic(schematic) def _copySelection(self): box = self.selectionBox() if not box: return shape = box.size self.editor.mouseLookOff() print "Clipping: ", shape fileFormat = "schematic" if box.volume > self.maxBlocks: fileFormat = "schematic.zip" if fileFormat == "schematic.zip": missingChunks = filter(lambda x: not self.editor.level.containsChunk(*x), box.chunkPositions) if len(missingChunks): if not ((box.origin[0] & 0xf == 0) and (box.origin[2] & 0xf == 0)): if ask( "This is an uneven selection with missing chunks. Expand the selection to chunk edges, or copy air within the missing chunks?", ["Expand Selection", "Copy Air"]) == "Expand Selection": self.selectChunks() box = self.selectionBox() cancelCommandBlockOffset = config.schematicCopying.cancelCommandBlockOffset.get() with setWindowCaption("Copying - "): filename = tempfile.mkdtemp(".zip", "mceditcopy") os.rmdir(filename) status = _("Copying {0:n} blocks...").format(box.volume) if fileFormat == "schematic": schematic = showProgress(status, self.editor.level.extractSchematicIter(box, cancelCommandBlockOffset=cancelCommandBlockOffset), cancel=True) else: schematic = showProgress(status, self.editor.level.extractZipSchematicIter(box, filename, cancelCommandBlockOffset=cancelCommandBlockOffset), cancel=True) if schematic == "Canceled": return None return schematic @alertException def exportSelection(self): schematic = self._copySelection() if schematic: self.editor.exportSchematic(schematic) @alertException def openCommands(self): name = "CommandsFile" + str(self.editor.level.editFileNumber) + "." + config.commands.fileFormat.get() filename = os.path.join(self.editor.level.fileEditsFolder.filename, name) fp = open(filename, 'w') first = True space = config.commands.space.get() sorting = config.commands.sorting.get() edit = fileEdit(filename, os.path.getmtime(filename), self.editor.selectionBox(), self.editor, self.editor.level) platform = self.editor.level.gamePlatform repeatID, chainID = {'PE':(188,189),'Java':(210,211)}.get(platform, (210,211)) order = [] if sorting == "chain": skip = [] done = [] chainStored = [] for coords in GetSort(self.editor.selectionBox(), sorting): (x, y, z) = coords if (x, y, z) in skip: skip.remove((x, y, z)) continue blockID = self.editor.level.blockAt(x, y, z) if blockID == chainID: chainStored.append((x, y, z)) continue if blockID == 137 or blockID == repeatID: edit.writeCommandInFile(first, space, (x, y, z), fp, skip, True, done, order) first = False for (x, y, z) in chainStored: if (x, y, z) in done: continue edit.writeCommandInFile(first, space, (x, y, z), fp, skip, True, done, order) else: for coords in GetSort(self.editor.selectionBox(), sorting): if sorting == "xz": (x, y, z) = coords else: (z, y, x) = coords blockID = self.editor.level.blockAt(x, y, z) if blockID == 137 or blockID == repeatID or blockID == chainID: edit.writeCommandInFile(first, space, (x, y, z), fp, None, False, None, order) first = False fp.close() if first: os.remove(filename) alert("No command blocks found") del edit return edit.order = order self.editor.level.editFileNumber += 1 self.root.filesToChange.append(edit) if sys.platform == "win32": os.startfile(filename) else: opener = "open" if sys.platform == "darwin" else "xdg-open" subprocess.call([opener, filename]) def CBCommandsOptions(self): panel = CBCommandsOptionsPanel() panel.present() class CBCommandsOptionsPanel(ToolOptions): def __init__(self): Panel.__init__(self, name='Panel.CBCommandsOptionsPanel') empty = Label("") self.sorting = ChoiceButton(["chain", "xz", "zx"], choose=self.changeSorting) self.sorting.selectedChoice = config.commands.sorting.get() sortingRow = Row((Label("Sort Order"), self.sorting)) space = CheckBoxLabel("Space between lines", tooltipText="Make space between the lines", ref=config.commands.space) fileFormat = TextInputRow("File format", tooltipText="Choose the file format for the files", ref=config.commands.fileFormat) okButton = Button("OK", action=self.dismiss) col = Column((Label("Command Blocks Commands Options"), sortingRow, empty, space, empty, fileFormat, okButton), spacing=2) self.add(col) self.shrink_wrap() def changeSorting(self): config.commands.sorting.set(self.sorting.selectedChoice) class SelectionOperation(Operation): changedLevel = False def __init__(self, selectionTool, points): super(SelectionOperation, self).__init__(selectionTool.editor, selectionTool.editor.level) self.selectionTool = selectionTool self.points = points self.canUndo = True def perform(self, recordUndo=True): self.undoPoints = self.selectionTool.getSelectionPoints() self.selectionTool.setSelectionPoints(self.points) def undo(self): self.redoPoints = self.selectionTool.getSelectionPoints() points = self.points self.points = self.undoPoints self.undoPoints = self.selectionTool.getSelectionPoints() changeSelection = "select" in "{}".format(self.editor.currentTool) self.selectionTool.setSelectionPoints(self.points, changeSelection) self.points = points def redo(self): self.undoPoints = self.selectionTool.getSelectionPoints() points = self.points self.points = self.redoPoints self.undoPoints = self.selectionTool.getSelectionPoints() changeSelection = "select" in "{}".format(self.editor.currentTool) self.selectionTool.setSelectionPoints(self.points, changeSelection) self.points = points class NudgeSelectionOperation(Operation): changedLevel = False def __init__(self, selectionTool, direction): super(NudgeSelectionOperation, self).__init__(selectionTool.editor, selectionTool.editor.level) self.selectionTool = selectionTool self.direction = direction self.undoPoints = selectionTool.getSelectionPoints() self.newPoints = [p + direction for p in self.undoPoints] self.canUndo = True def perform(self, recordUndo=True): self.selectionTool.setSelectionPoints(self.newPoints) oldSelection = None def undo(self): self.redoPoints = self.selectionTool.getSelectionPoints() self.selectionTool.setSelectionPoints(self.undoPoints) def redo(self): self.undoPoints = self.selectionTool.getSelectionPoints() self.selectionTool.setSelectionPoints(self.redoPoints)
55,133
39.039216
332
py
MCEdit-Unified
MCEdit-Unified-master/editortools/chunk.py
"""Copyright (c) 2010-2012 David Rio Vierra Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.""" #-# Modified by D.C.-G. for translation purpose import traceback from OpenGL import GL import numpy from numpy import newaxis from albow import Label, ValueDisplay, AttrRef, Button, Column, ask, Row, alert, Widget, Menu, showProgress, \ ChoiceButton, IntInputRow, CheckBoxLabel from albow.translate import _ from editortools.editortool import EditorTool from glbackground import Panel from glutils import DisplayList, gl from mceutils import alertException, setWindowCaption import mcplatform import pymclevel from pymclevel.minecraft_server import MCServerChunkGenerator from config import config from albow.dialogs import Dialog import renderer class ChunkToolPanel(Panel): def __init__(self, tool, *a, **kw): if 'name' not in kw.keys(): kw['name'] = 'Panel.ChunkToolPanel' Panel.__init__(self, *a, **kw) self.tool = tool self.anchor = "whl" chunkToolLabel = Label("Selected Chunks:") self.chunksLabel = ValueDisplay(ref=AttrRef(self, 'chunkSizeText'), width=115) self.chunksLabel.align = "c" self.chunksLabel.tooltipText = "..." deselectButton = Button("Deselect", tooltipText=None, action=tool.editor.deselect, ) createButton = Button("Create") createButton.tooltipText = "Create new chunks within the selection." createButton.action = tool.createChunks createButton.highlight_color = (0, 255, 0) destroyButton = Button("Delete") destroyButton.tooltipText = "Delete the selected chunks from disk. Minecraft will recreate them the next time you are near." destroyButton.action = tool.destroyChunks pruneButton = Button("Prune") pruneButton.tooltipText = "Prune the world, leaving only the selected chunks. Any chunks outside of the selection will be removed, and empty region files will be deleted from disk" pruneButton.action = tool.pruneChunks relightButton = Button("Relight") relightButton.tooltipText = "Recalculate light values across the selected chunks" relightButton.action = tool.relightChunks relightButton.highlight_color = (255, 255, 255) repopButton = Button("Repop") repopButton.tooltipText = "Mark the selected chunks for repopulation. The next time you play Minecraft, the chunks will have trees, ores, and other features regenerated." repopButton.action = tool.repopChunks repopButton.highlight_color = (255, 200, 155) dontRepopButton = Button("Don't Repop") dontRepopButton.tooltipText = "Unmark the selected chunks. They will not repopulate the next time you play the game." dontRepopButton.action = tool.dontRepopChunks dontRepopButton.highlight_color = (255, 255, 255) col = Column(( chunkToolLabel, self.chunksLabel, deselectButton, createButton, destroyButton, pruneButton, relightButton, repopButton, dontRepopButton)) # col.right = self.width - 10; self.width = col.width self.height = col.height #self.width = 120 self.add(col) @property def chunkSizeText(self): return _("{0} chunks").format(len(self.tool.selectedChunks())) def updateText(self): pass # self.chunksLabel.text = self.chunksLabelText() class ChunkTool(EditorTool): toolIconName = "chunk" tooltipText = "Chunk Control" @property def statusText(self): return _("Click and drag to select chunks. Hold {0} to deselect chunks. Hold {1} to select chunks.").format(_(config.keys.deselectChunks.get()), _(config.keys.selectChunks.get())) def toolEnabled(self): return isinstance(self.editor.level, pymclevel.ChunkedLevelMixin) _selectedChunks = None _displayList = None def drawToolMarkers(self): if self._displayList is None: self._displayList = DisplayList(self._drawToolMarkers) # print len(self._selectedChunks) if self._selectedChunks else None, "!=", len(self.editor.selectedChunks) if self._selectedChunks != self.editor.selectedChunks or True: # xxx # TODO Pod self._selectedChunks = set(self.editor.selectedChunks) self._displayList.invalidate() self._displayList.call() def _drawToolMarkers(self): lines = ( ((-1, 0), (0, 0, 0, 1), []), ((1, 0), (1, 0, 1, 1), []), ((0, -1), (0, 0, 1, 0), []), ((0, 1), (0, 1, 1, 1), []), ) for ch in self._selectedChunks: cx, cz = ch for (dx, dz), points, positions in lines: n = (cx + dx, cz + dz) if n not in self._selectedChunks: positions.append([ch]) color = self.editor.selectionTool.selectionColor + (0.3, ) GL.glColor(*color) with gl.glEnable(GL.GL_BLEND): #import renderer sizedChunks = renderer.chunkMarkers(self._selectedChunks) for size, chunks in sizedChunks.iteritems(): if not len(chunks): continue chunks = numpy.array(chunks, dtype='float32') chunkPosition = numpy.zeros(shape=(chunks.shape[0], 4, 3), dtype='float32') chunkPosition[..., (0, 2)] = numpy.array(((0, 0), (0, 1), (1, 1), (1, 0)), dtype='float32') chunkPosition[..., (0, 2)] *= size chunkPosition[..., (0, 2)] += chunks[:, newaxis, :] chunkPosition *= 16 chunkPosition[..., 1] = self.editor.level.Height GL.glVertexPointer(3, GL.GL_FLOAT, 0, chunkPosition.ravel()) # chunkPosition *= 8 GL.glDrawArrays(GL.GL_QUADS, 0, len(chunkPosition) * 4) for d, points, positions in lines: if 0 == len(positions): continue vertexArray = numpy.zeros((len(positions), 4, 3), dtype='float32') vertexArray[..., [0, 2]] = positions vertexArray.shape = len(positions), 2, 2, 3 vertexArray[..., 0, 0, 0] += points[0] vertexArray[..., 0, 0, 2] += points[1] vertexArray[..., 0, 1, 0] += points[2] vertexArray[..., 0, 1, 2] += points[3] vertexArray[..., 1, 0, 0] += points[2] vertexArray[..., 1, 0, 2] += points[3] vertexArray[..., 1, 1, 0] += points[0] vertexArray[..., 1, 1, 2] += points[1] vertexArray *= 16 vertexArray[..., 1, :, 1] = self.editor.level.Height GL.glVertexPointer(3, GL.GL_FLOAT, 0, vertexArray) GL.glPolygonMode(GL.GL_FRONT_AND_BACK, GL.GL_LINE) GL.glDrawArrays(GL.GL_QUADS, 0, len(positions) * 4) GL.glPolygonMode(GL.GL_FRONT_AND_BACK, GL.GL_FILL) with gl.glEnable(GL.GL_BLEND, GL.GL_DEPTH_TEST): GL.glDepthMask(False) GL.glDrawArrays(GL.GL_QUADS, 0, len(positions) * 4) GL.glDepthMask(True) @property def worldTooltipText(self): box = self.editor.selectionTool.selectionBoxInProgress() if box: box = box.chunkBox(self.editor.level) l, w = box.length // 16, box.width // 16 return _("%s x %s chunks") % (l, w) else: if config.settings.viewMode.get() == "Chunk": point, face = self.editor.chunkViewport.blockFaceUnderCursor else: point, face = self.editor.mainViewport.blockFaceUnderCursor if point: return "Chunk ({}, {})".format(point[0] // 16, point[2] // 16) def toolSelected(self): self.editor.selectionToChunks() self.panel = ChunkToolPanel(self) self.panel.centery = self.editor.centery self.panel.left = 10 self.editor.add(self.panel) def toolDeselected(self): self.editor.chunksToSelection() def cancel(self): self.editor.remove(self.panel) def selectedChunks(self): return self.editor.selectedChunks @alertException def destroyChunks(self, chunks=None): if "No" == ask("Really delete these chunks? This cannot be undone.", ("Yes", "No")): return if chunks is None: chunks = self.selectedChunks() chunks = list(chunks) def _destroyChunks(): i = 0 chunkCount = len(chunks) for cx, cz in chunks: i += 1 yield (i, chunkCount) if self.editor.level.containsChunk(cx, cz): try: self.editor.level.deleteChunk(cx, cz) except Exception as e: print "Error during chunk delete: ", e with setWindowCaption("DELETING - "): showProgress("Deleting chunks...", _destroyChunks()) self.editor.renderer.invalidateChunkMarkers() self.editor.renderer.discardAllChunks() # self.editor.addUnsavedEdit() @alertException def pruneChunks(self): if "No" == ask("Save these chunks and remove the rest? This cannot be undone.", ("Yes", "No")): return self.editor.saveFile() def _pruneChunks(): maxChunks = self.editor.level.chunkCount selectedChunks = self.selectedChunks() for i, cPos in enumerate(list(self.editor.level.allChunks)): if cPos not in selectedChunks: try: self.editor.level.deleteChunk(*cPos) except Exception as e: print "Error during chunk delete: ", e yield i, maxChunks with setWindowCaption("PRUNING - "): showProgress("Pruning chunks...", _pruneChunks()) self.editor.renderer.invalidateChunkMarkers() self.editor.discardAllChunks() # self.editor.addUnsavedEdit() @alertException def relightChunks(self): def _relightChunks(): for i in self.editor.level.generateLightsIter(self.selectedChunks()): yield i with setWindowCaption("RELIGHTING - "): showProgress(_("Lighting {0} chunks...").format(len(self.selectedChunks())), _relightChunks(), cancel=True) self.editor.invalidateChunks(self.selectedChunks()) self.editor.addUnsavedEdit() @alertException def createChunks(self): panel = GeneratorPanel() col = [panel] label = Label("Create chunks using the settings above? This cannot be undone.") col.append(Row([Label("")])) col.append(label) col = Column(col) if Dialog(client=col, responses=["OK", "Cancel"]).present() == "Cancel": return chunks = self.selectedChunks() createChunks = panel.generate(self.editor.level, chunks) try: with setWindowCaption("CREATING - "): showProgress("Creating {0} chunks...".format(len(chunks)), createChunks, cancel=True) except Exception as e: traceback.print_exc() alert(_("Failed to start the chunk generator. {0!r}").format(e)) finally: self.editor.renderer.invalidateChunkMarkers() self.editor.renderer.loadNearbyChunks() @alertException def repopChunks(self): for cpos in self.selectedChunks(): try: chunk = self.editor.level.getChunk(*cpos) chunk.TerrainPopulated = False except pymclevel.ChunkNotPresent: continue self.editor.renderer.invalidateChunks(self.selectedChunks(), layers=["TerrainPopulated"]) @alertException def dontRepopChunks(self): for cpos in self.selectedChunks(): try: chunk = self.editor.level.getChunk(*cpos) chunk.TerrainPopulated = True except pymclevel.ChunkNotPresent: continue self.editor.renderer.invalidateChunks(self.selectedChunks(), layers=["TerrainPopulated"]) def mouseDown(self, *args): return self.editor.selectionTool.mouseDown(*args) def mouseUp(self, evt, *args): self.editor.selectionTool.mouseUp(evt, *args) def keyDown(self, evt): self.editor.selectionTool.keyDown(evt) def keyUp(self, evt): self.editor.selectionTool.keyUp(evt) def GeneratorPanel(): panel = Widget() panel.chunkHeight = 64 panel.grass = True panel.simulate = False panel.snapshot = False jarStorage = MCServerChunkGenerator.getDefaultJarStorage() if jarStorage: jarStorage.reloadVersions() generatorChoice = ChoiceButton(["Minecraft Server", "Flatland"]) panel.generatorChoice = generatorChoice col = [Row((Label("Generator:"), generatorChoice))] noVersionsRow = Label("Will automatically download and use the latest version") versionContainer = Widget() heightinput = IntInputRow("Height: ", ref=AttrRef(panel, "chunkHeight"), min=0, max=255) grassinput = CheckBoxLabel("Grass", ref=AttrRef(panel, "grass")) flatPanel = Column([heightinput, grassinput], align="l") def generatorChoiceChanged(): serverPanel.visible = generatorChoice.selectedChoice == "Minecraft Server" flatPanel.visible = not serverPanel.visible generatorChoice.choose = generatorChoiceChanged versionChoice = None if len(jarStorage.versions): def checkForUpdates(): def _check(): yield jarStorage.downloadCurrentServer(panel.snapshot) yield showProgress("Checking for server updates...", _check()) versionChoice.choices = sorted(jarStorage.versions, reverse=True) versionChoice.choiceIndex = 0 versionChoice = ChoiceButton(sorted(jarStorage.versions, reverse=True)) versionChoice.set_size_for_text(200) versionChoiceRow = (Row(( Label("Server version:"), versionChoice, Label("or"), Button("Check for Updates", action=checkForUpdates)))) panel.versionChoice = versionChoice versionContainer.add(versionChoiceRow) else: versionContainer.add(noVersionsRow) versionContainer.shrink_wrap() menu = Menu("Advanced", [ ("Open Server Storage", "revealStorage"), ("Reveal World Cache", "revealCache"), ("Delete World Cache", "clearCache") ]) def presentMenu(): i = menu.present(advancedButton.parent, advancedButton.topleft) if i != -1: (revealStorage, revealCache, clearCache)[i]() advancedButton = Button("Advanced...", presentMenu) @alertException def revealStorage(): mcplatform.platform_open(jarStorage._cacheDir) @alertException def revealCache(): mcplatform.platform_open(MCServerChunkGenerator.worldCacheDir) # revealCacheRow = Row((Label("Minecraft Server Storage: "), Button("Open Folder", action=revealCache, tooltipText="Click me to install your own minecraft_server.jar if you have any."))) @alertException def clearCache(): MCServerChunkGenerator.clearWorldCache() simRow = CheckBoxLabel("Simulate world", ref=AttrRef(panel, "simulate"), tooltipText="Simulate the world for a few seconds after generating it. Reduces the save file size by processing all of the TileTicks.") useSnapshotServer = CheckBoxLabel("Use snapshot versions", ref=AttrRef(panel, "snapshot"), tooltipText="Uses the Latest Snapshot Terrain Generation") simRow = Row((simRow, advancedButton), anchor="lrh") #deleteCacheRow = Row((Label("Delete Temporary World File Cache?"), Button("Delete Cache!", action=clearCache, tooltipText="Click me if you think your chunks are stale."))) serverPanel = Column([useSnapshotServer, versionContainer, simRow], align="l") col.append(serverPanel) col = Column(col, align="l") col.add(flatPanel) flatPanel.topleft = serverPanel.topleft flatPanel.visible = False panel.add(col) panel.shrink_wrap() def generate(level, arg, useWorldType="DEFAULT"): useServer = generatorChoice.selectedChoice == "Minecraft Server" if useServer: def _createChunks(): if versionChoice: version = versionChoice.selectedChoice else: version = None gen = MCServerChunkGenerator(version=version) if isinstance(arg, pymclevel.BoundingBox): for i in gen.createLevelIter(level, arg, simulate=panel.simulate, worldType=useWorldType): yield i else: for i in gen.generateChunksInLevelIter(level, arg, simulate=panel.simulate): yield i else: def _createChunks(): height = panel.chunkHeight grass = panel.grass and pymclevel.alphaMaterials.Grass.ID or pymclevel.alphaMaterials.Dirt.ID if isinstance(arg, pymclevel.BoundingBox): chunks = list(arg.chunkPositions) else: chunks = arg if level.dimNo in (-1, 1): maxskylight = 0 else: maxskylight = 15 for i, (cx, cz) in enumerate(chunks): yield i, len(chunks) #surface = blockInput.blockInfo #for cx, cz in : try: level.createChunk(cx, cz) except ValueError as e: # chunk already present print e continue else: ch = level.getChunk(cx, cz) if height > 0: stoneHeight = max(0, height - 5) grassHeight = max(0, height - 1) ch.Blocks[:, :, grassHeight] = grass ch.Blocks[:, :, stoneHeight:grassHeight] = pymclevel.alphaMaterials.Dirt.ID ch.Blocks[:, :, :stoneHeight] = pymclevel.alphaMaterials.Stone.ID ch.Blocks[:, :, 0] = pymclevel.alphaMaterials.Bedrock.ID ch.SkyLight[:, :, height:] = maxskylight if maxskylight: ch.HeightMap[:] = height else: ch.SkyLight[:] = maxskylight ch.needsLighting = False ch.dirty = True return _createChunks() panel.generate = generate panel.kill_process = MCServerChunkGenerator.terminateProcesses return panel
19,830
36.773333
190
py
MCEdit-Unified
MCEdit-Unified-master/editortools/fill.py
"""Copyright (c) 2010-2012 David Rio Vierra Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.""" #-# Modified by D.C.-G. for translation purpose from OpenGL import GL import numpy from albow import Label, Button, Column, alert, AttrRef, showProgress, CheckBoxLabel from albow.translate import _ from depths import DepthOffset from editortools.blockpicker import BlockPicker from editortools.blockview import BlockButton from editortools.editortool import EditorTool from editortools.tooloptions import ToolOptions from glbackground import Panel from glutils import Texture from mceutils import alertException, setWindowCaption from operation import Operation from pymclevel.blockrotation import Roll, RotateLeft, FlipVertical, FlipEastWest, FlipNorthSouth from config import config from albow.root import get_root import pymclevel class BlockFillOperation(Operation): def __init__(self, editor, destLevel, destBox, blockInfo, blocksToReplace, noData=False): super(BlockFillOperation, self).__init__(editor, destLevel) self.noData = noData self.destBox = destBox self.blockInfo = blockInfo self.blocksToReplace = blocksToReplace self.canUndo = False def name(self): return _("Fill with ") + self.blockInfo.name def perform(self, recordUndo=True): if self.level.saving: alert("Cannot perform action while saving is taking place") return if recordUndo: self.undoLevel = self.extractUndo(self.level, self.destBox) destBox = self.destBox if self.level.bounds == self.destBox: destBox = None fill = self.level.fillBlocksIter(destBox, self.blockInfo, blocksToReplace=self.blocksToReplace, noData=self.noData) showProgress("Replacing blocks...", fill, cancel=True) self.canUndo = True def bufferSize(self): return self.destBox.volume * 2 def dirtyBox(self): return self.destBox class FillToolPanel(Panel): def __init__(self, tool): Panel.__init__(self, name='Panel.FillToolPanel') self.tool = tool replacing = tool.replacing self.blockButton = BlockButton(tool.editor.level.materials) self.blockButton.blockInfo = tool.blockInfo self.blockButton.action = self.pickFillBlock self.fillWithLabel = Label("Fill with:", width=self.blockButton.width, align="c") self.fillButton = Button("Fill", action=tool.confirm, width=self.blockButton.width) self.fillButton.tooltipText = "Shortcut: Enter" rollkey = config.keys.replaceShortcut.get() self.replaceLabel = replaceLabel = Label("Replace", width=self.blockButton.width) replaceLabel.mouse_down = lambda a: self.tool.toggleReplacing() replaceLabel.fg_color = (177, 177, 255, 255) # replaceLabelRow = Row( (Label(rollkey), replaceLabel) ) replaceLabel.tooltipText = _("Shortcut: {0}").format(_(rollkey)) replaceLabel.align = "c" self.noDataCheckBox = CheckBoxLabel("Keep Data Intact", ref=AttrRef(self.tool, "noData")) col = (self.fillWithLabel, self.blockButton, # swapRow, replaceLabel, # self.replaceBlockButton, self.fillButton) if replacing: self.fillWithLabel = Label("Find:", width=self.blockButton.width, align="c") self.replaceBlockButton = BlockButton(tool.editor.level.materials) self.replaceBlockButton.blockInfo = tool.replaceBlockInfo self.replaceBlockButton.action = self.pickReplaceBlock self.replaceLabel.text = "Replace with:" self.replaceLabel.tooltipText = _("Shortcut: {0}").format(_("Esc")) self.swapButton = Button("Swap", action=self.swapBlockTypes, width=self.blockButton.width) self.swapButton.fg_color = (255, 255, 255, 255) self.swapButton.highlight_color = (60, 255, 60, 255) swapkey = config.keys.swap.get() self.swapButton.tooltipText = _("Shortcut: {0}").format(_(swapkey)) self.fillButton = Button("Replace", action=tool.confirm, width=self.blockButton.width) self.fillButton.tooltipText = "Shortcut: Enter" col = (self.fillWithLabel, self.blockButton, replaceLabel, self.replaceBlockButton, self.noDataCheckBox, self.swapButton, self.fillButton) col = Column(col) self.add(col) self.shrink_wrap() def swapBlockTypes(self): t = self.tool.replaceBlockInfo self.tool.replaceBlockInfo = self.tool.blockInfo self.tool.blockInfo = t self.replaceBlockButton.blockInfo = self.tool.replaceBlockInfo self.blockButton.blockInfo = self.tool.blockInfo # xxx put this in a property def pickReplaceBlock(self): blockPicker = BlockPicker(self.tool.replaceBlockInfo, self.tool.editor.level.materials) if blockPicker.present(): self.replaceBlockButton.blockInfo = self.tool.replaceBlockInfo = blockPicker.blockInfo def pickFillBlock(self): blockPicker = BlockPicker(self.tool.blockInfo, self.tool.editor.level.materials, allowWildcards=True) if blockPicker.present(): self.tool.blockInfo = blockPicker.blockInfo class FillToolOptions(ToolOptions): def __init__(self, tool): ToolOptions.__init__(self, name='Panel.FillToolOptions') self.tool = tool self.autoChooseCheckBoxFill = CheckBoxLabel("Open Block Picker for Fill", ref=config.fill.chooseBlockImmediately, tooltipText="When the fill tool is chosen, prompt for a block type.") self.autoChooseCheckBoxReplace = CheckBoxLabel("Open Block Picker for Replace", ref=config.fill.chooseBlockImmediatelyReplace, tooltipText="When the replace tool is chosen, prompt for a block type.") col = Column((Label("Fill and Replace Options"), self.autoChooseCheckBoxFill, self.autoChooseCheckBoxReplace, Button("OK", action=self.dismiss))) self.add(col) self.shrink_wrap() class FillTool(EditorTool): toolIconName = "fill" _blockInfo = None tooltipText = "Fill and Replace\nRight-click for options" replacing = False color = (0.75, 1.0, 1.0, 0.7) def __init__(self, *args, **kw): EditorTool.__init__(self, *args, **kw) self.optionsPanel = FillToolOptions(self) self.pickBlockKey = 0 self.root = get_root() noData = False @property def blockInfo(self): if not self._blockInfo: self._blockInfo = pymclevel.alphaMaterials.Stone self.replaceBlockInfo = pymclevel.alphaMaterials.Air return self._blockInfo @blockInfo.setter def blockInfo(self, bt): self._blockInfo = bt if self.panel: self.panel.blockButton.blockInfo = bt def levelChanged(self): pass def showPanel(self): if self.panel: self.panel.parent.remove(self.panel) panel = FillToolPanel(self) panel.centery = self.editor.centery panel.left = self.editor.left panel.anchor = "lwh" self.panel = panel self.editor.add(panel) def toolEnabled(self): return not (self.selectionBox() is None) def toolSelected(self): box = self.selectionBox() if box is None: return self.replacing = False self.showPanel() if self.chooseBlockImmediately: blockPicker = BlockPicker(self.blockInfo, self.editor.level.materials, allowWildcards=True) if blockPicker.present(): self.blockInfo = blockPicker.blockInfo self.showPanel() chooseBlockImmediately = config.fill.chooseBlockImmediately.property() chooseBlockImmediatelyReplace = config.fill.chooseBlockImmediatelyReplace.property() def toolReselected(self): if not self.replacing: self.showPanel() self.panel.pickFillBlock() def cancel(self): self.hidePanel() @alertException def confirm(self): box = self.selectionBox() if box is None: return with setWindowCaption("REPLACING - "): self.editor.freezeStatus("Replacing %0.1f million blocks" % (float(box.volume) / 1048576.,)) self.blockInfo = self.panel.blockButton.blockInfo if self.replacing: self.replaceBlockInfo = self.panel.replaceBlockButton.blockInfo if self.blockInfo.wildcard: print "Wildcard replace" blocksToReplace = [] for i in xrange(16): blocksToReplace.append(self.editor.level.materials.blockWithID(self.blockInfo.ID, i)) else: blocksToReplace = [self.blockInfo] op = BlockFillOperation(self.editor, self.editor.level, self.selectionBox(), self.replaceBlockInfo, blocksToReplace, noData=self.noData) else: blocksToReplace = [] op = BlockFillOperation(self.editor, self.editor.level, self.selectionBox(), self.blockInfo, blocksToReplace) self.editor.addOperation(op) self.editor.addUnsavedEdit() self.editor.invalidateBox(box) self.editor.toolbar.selectTool(-1) def roll(self, amount=1, blocksOnly=False): if blocksOnly: bid = [self._blockInfo.ID] data = [self._blockInfo.blockData] Roll(bid,data) self.blockInfo = self.editor.level.materials[(bid[0], data[0])] else: self.toggleReplacing() def mirror(self, amount=1, blocksOnly=False): if blocksOnly: bid = [self._blockInfo.ID] data = [self._blockInfo.blockData] yaw = int(self.editor.mainViewport.yaw) % 360 if (45 <= yaw < 135) or (225 < yaw <= 315): FlipEastWest(bid,data) else: FlipNorthSouth(bid,data) self.blockInfo = self.editor.level.materials[(bid[0], data[0])] def flip(self, amount=1, blocksOnly=False): if blocksOnly: bid = [self._blockInfo.ID] data = [self._blockInfo.blockData] FlipVertical(bid,data) self.blockInfo = self.editor.level.materials[(bid[0], data[0])] def rotate(self, amount=1, blocksOnly=False): if blocksOnly: bid = [self._blockInfo.ID] data = [self._blockInfo.blockData] RotateLeft(bid,data) self.blockInfo = self.editor.level.materials[(bid[0], data[0])] def toggleReplacing(self): self.replacing = not self.replacing self.hidePanel() self.showPanel() if self.replacing and self.chooseBlockImmediatelyReplace: self.panel.pickReplaceBlock() def openReplace(self): if not self.replacing: self.replacing = True self.hidePanel() self.showPanel() if self.chooseBlockImmediatelyReplace: self.panel.pickReplaceBlock() else: self.panel.pickReplaceBlock() @alertException def swap(self, amount=1): if self.panel and self.replacing: self.panel.swapBlockTypes() def blockTexFunc(self, terrainTexture, tex): def _func(): s, t = tex if not hasattr(terrainTexture, "data"): return w, h = terrainTexture.data.shape[:2] pixelWidth = 512 if self.editor.level.materials.name in ("Pocket", "Alpha") else 256 s = s * w / pixelWidth t = t * h / pixelWidth texData = numpy.array(terrainTexture.data[t:t + h / 32, s:s + w / 32]) GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA, w / 32, h / 32, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, texData) return _func def drawToolReticle(self): if self.pickBlockKey == 1: # eyedropper mode self.editor.drawWireCubeReticle(color=(0.2, 0.6, 0.9, 1.0)) def drawToolMarkers(self): if self.editor.currentTool != self: return if self.panel and self.replacing: blockInfo = self.replaceBlockInfo else: blockInfo = self.blockInfo color = 1.0, 1.0, 1.0, 0.35 if blockInfo: terrainTexture = self.editor.level.materials.terrainTexture tex = self.editor.level.materials.blockTextures[blockInfo.ID, blockInfo.blockData, 0] # xxx tex = Texture(self.blockTexFunc(terrainTexture, tex)) # color = (1.5 - alpha, 1.0, 1.5 - alpha, alpha - 0.35) GL.glMatrixMode(GL.GL_TEXTURE) GL.glPushMatrix() GL.glScale(16., 16., 16.) else: tex = None # color = (1.0, 0.3, 0.3, alpha - 0.35) GL.glPolygonOffset(DepthOffset.FillMarkers, DepthOffset.FillMarkers) self.editor.drawConstructionCube(self.selectionBox(), color, texture=tex) if blockInfo: GL.glMatrixMode(GL.GL_TEXTURE) GL.glPopMatrix() @property def statusText(self): return _("Press {hotkey} to choose a block. Press {R} to enter replace mode. Click Fill or press Enter to confirm.").format( hotkey=self.hotkey, R=config.keys.replaceShortcut.get()) @property def worldTooltipText(self): if self.pickBlockKey == 1: try: if self.editor.blockFaceUnderCursor is None: return pos = self.editor.blockFaceUnderCursor[0] blockID = self.editor.level.blockAt(*pos) blockdata = self.editor.level.blockDataAt(*pos) return _("Click to use {0} ({1}:{2})").format( self.editor.level.materials.blockWithID(blockID, blockdata).name, blockID, blockdata) except Exception as e: return repr(e) def mouseUp(self, *args): return self.editor.selectionTool.mouseUp(*args) @alertException def mouseDown(self, evt, pos, dir): if self.pickBlockKey == 1: id = self.editor.level.blockAt(*pos) data = self.editor.level.blockDataAt(*pos) self.blockInfo = self.editor.level.materials.blockWithID(id, data) else: return self.editor.selectionTool.mouseDown(evt, pos, dir) def keyDown(self, evt): keyname = evt.dict.get('keyname', None) or self.root.getKey(evt) if keyname == config.keys.pickBlock.get(): self.pickBlockKey = 1 def keyUp(self, evt): keyname = evt.dict.get('keyname', None) or self.root.getKey(evt) if keyname == config.keys.pickBlock.get(): self.pickBlockKey = 0
16,035
36.555035
153
py
MCEdit-Unified
MCEdit-Unified-master/editortools/player.py
"""Copyright (c) 2010-2012 David Rio Vierra Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.""" #-# Modifiedby D.C.-G. for translation purpose from OpenGL import GL import numpy import os from albow import TableView, TableColumn, Label, Button, Column, CheckBox, AttrRef, Row, ask, alert, input_text_buttons, TabPanel from albow.table_view import TableRowView from albow.translate import _ from config import config from editortools.editortool import EditorTool from editortools.tooloptions import ToolOptions from glbackground import Panel from glutils import DisplayList from mceutils import loadPNGTexture, alertException, drawTerrainCuttingWire, drawCube from operation import Operation import pymclevel from pymclevel.box import BoundingBox, FloatBox from pymclevel import nbt import logging from player_cache import PlayerCache, ThreadRS from nbtexplorer import loadFile, saveFile, NBTExplorerToolPanel import pygame log = logging.getLogger(__name__) class PlayerRemoveOperation(Operation): undoTag = None def __init__(self, tool, player="Player (Single Player)"): super(PlayerRemoveOperation, self).__init__(tool.editor, tool.editor.level) self.tool = tool self.player = player self.level = self.tool.editor.level self.canUndo = False self.playercache = PlayerCache() def perform(self, recordUndo=True): if self.level.saving: alert(_("Cannot perform action while saving is taking place")) return if self.player == "Player (Single Player)": answer = ask(_("Are you sure you want to delete the default player?"), ["Yes", "Cancel"]) if answer == "Cancel": return self.player = "Player" if recordUndo: self.undoTag = self.level.getPlayerTag(self.player) self.level.players.remove(self.player) if self.tool.panel: if self.player != "Player": #self.tool.panel.players.remove(player_cache.getPlayerNameFromUUID(self.player)) #self.tool.panel.players.remove(self.playercache.getPlayerInfo(self.player)[0]) str() else: self.tool.panel.players.remove("Player (Single Player)") while self.tool.panel.table.index >= len(self.tool.panel.players): self.tool.panel.table.index -= 1 #if len(self.tool.panel.players) == 0: # self.tool.hidePanel() # self.tool.showPanel() self.tool.hidePanel() self.tool.showPanel() self.tool.markerList.invalidate() self.tool.movingPlayer = None pos = self.tool.revPlayerPos[self.editor.level.dimNo][self.player] del self.tool.playerPos[self.editor.level.dimNo][pos] if self.player != "Player": del self.tool.playerTexture[self.player] else: del self.level.root_tag["Data"]["Player"] del self.tool.revPlayerPos[self.editor.level.dimNo][self.player] self.canUndo = True def undo(self): if not (self.undoTag is None): if self.player != "Player": self.level.playerTagCache[self.level.getPlayerPath(self.player)] = self.undoTag else: self.level.root_tag["Data"]["Player"] = self.undoTag self.level.players.append(self.player) if self.tool.panel: #if self.player != "Player": # self.tool.panel.players.append(self.playercache.getPlayerInfo(self.player)[0]) #else: # self.tool.panel.players.append("Player (Single Player)") if "[No players]" in self.tool.panel.players: self.tool.panel.players.remove("[No players]") self.tool.hidePanel() self.tool.showPanel() self.tool.markerList.invalidate() def redo(self): self.perform() class PlayerAddOperation(Operation): playerTag = None def __init__(self, tool): super(PlayerAddOperation, self).__init__(tool.editor, tool.editor.level) self.tool = tool self.level = self.tool.editor.level self.canUndo = False self.playercache = PlayerCache() def perform(self, recordUndo=True): initial = "" allowed_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_" while True: self.player = input_text_buttons("Enter a Player Name: ", 160, initial=initial, allowed_chars=allowed_chars) if self.player is None: return elif len(self.player) > 16: alert("Name too long. Maximum name length is 16.") initial = self.player elif len(self.player) < 1: alert("Name too short. Minimum name length is 1.") initial = self.player else: break # print 1 data = self.playercache.getPlayerInfo(self.player) if "<Unknown UUID>" not in data and "Server not ready" not in data: self.uuid = data[0] self.player = data[1] else: action = ask("Could not get {}'s UUID. Please make sure that you are connected to the internet and that the player \"{}\" exists.".format(self.player, self.player), ["Enter UUID manually", "Cancel"]) if action != "Enter UUID manually": return self.uuid = input_text_buttons("Enter a Player UUID: ", 160) if not self.uuid: return # print 2 self.player = self.playercache.getPlayerInfo(self.uuid) if self.player == self.uuid.replace("-", ""): if ask("UUID was not found. Continue anyways?") == "Cancel": return # print "PlayerAddOperation.perform::self.uuid", self.uuid if self.uuid in self.level.players: alert("Player already exists in this World.") return self.playerTag = self.newPlayer() #if self.tool.panel: # self.tool.panel.players.append(self.player) if self.level.oldPlayerFolderFormat: self.level.playerTagCache[self.level.getPlayerPath(self.player)] = self.playerTag self.level.players.append(self.player) #if self.tool.panel: #self.tool.panel.player_UUID[self.player] = self.player else: self.level.playerTagCache[self.level.getPlayerPath(self.uuid)] = self.playerTag self.level.players.append(self.uuid) if self.tool.panel: self.tool.panel.player_UUID["UUID"].append(self.uuid) self.tool.panel.player_UUID["Name"].append(self.player) self.tool.playerPos[self.editor.level.dimNo][(0,0,0)] = self.uuid self.tool.revPlayerPos[self.editor.level.dimNo][self.uuid] = (0,0,0) # print 3 r = self.playercache.getPlayerSkin(self.uuid, force_download=False) if not isinstance(r, (str, unicode)): # print 'r 1', r r = r.join() # print 'r 2', r self.tool.playerTexture[self.uuid] = loadPNGTexture(r) self.tool.markerList.invalidate() self.tool.recordMove = False self.tool.movingPlayer = self.uuid if self.tool.panel: self.tool.hidePanel() self.tool.showPanel() self.canUndo = True self.playerTag.save(self.level.getPlayerPath(self.uuid)) self.tool.nonSavedPlayers.append(self.level.getPlayerPath(self.uuid)) self.tool.inOtherDimension[self.editor.level.dimNo].append(self.uuid) def newPlayer(self): playerTag = nbt.TAG_Compound() playerTag['Air'] = nbt.TAG_Short(300) playerTag['AttackTime'] = nbt.TAG_Short(0) playerTag['DeathTime'] = nbt.TAG_Short(0) playerTag['Fire'] = nbt.TAG_Short(-20) playerTag['Health'] = nbt.TAG_Short(20) playerTag['HurtTime'] = nbt.TAG_Short(0) playerTag['Score'] = nbt.TAG_Int(0) playerTag['FallDistance'] = nbt.TAG_Float(0) playerTag['OnGround'] = nbt.TAG_Byte(0) playerTag['Dimension'] = nbt.TAG_Int(self.editor.level.dimNo) playerTag["Inventory"] = nbt.TAG_List() playerTag['Motion'] = nbt.TAG_List([nbt.TAG_Double(0) for i in xrange(3)]) spawn = self.level.playerSpawnPosition() spawnX = spawn[0] spawnZ = spawn[2] blocks = [self.level.blockAt(spawnX, i, spawnZ) for i in xrange(self.level.Height)] i = self.level.Height done = False for index, b in enumerate(reversed(blocks)): if b != 0 and not done: i = index done = True spawnY = self.level.Height - i playerTag['Pos'] = nbt.TAG_List([nbt.TAG_Double([spawnX, spawnY, spawnZ][i]) for i in xrange(3)]) playerTag['Rotation'] = nbt.TAG_List([nbt.TAG_Float(0), nbt.TAG_Float(0)]) return playerTag def undo(self): self.level.players.remove(self.uuid) self.tool.movingPlayer = None if self.tool.panel: #self.tool.panel.players.remove(self.player) self.tool.panel.player_UUID["UUID"].remove(self.uuid) self.tool.panel.player_UUID["Name"].remove(self.player) self.tool.hidePanel() self.tool.showPanel() if self.tool.movingPlayer is None: del self.tool.playerPos[self.tool.revPlayerPos[self.uuid]] else: del self.tool.playerPos[(0,0,0)] del self.tool.revPlayerPos[self.uuid] del self.tool.playerTexture[self.uuid] os.remove(self.level.getPlayerPath(self.uuid)) if self.level.getPlayerPath(self.uuid) in self.tool.nonSavedPlayers: self.tool.nonSavedPlayers.remove(self.level.getPlayerPath(self.uuid)) self.tool.markerList.invalidate() def redo(self): if not (self.playerTag is None): self.level.playerTagCache[self.level.getPlayerPath(self.uuid)] = self.playerTag self.level.players.append(self.uuid) if self.tool.panel: #self.tool.panel.players.append(self.uuid) #self.tool.panel.player_UUID[self.player] = self.uuid self.tool.panel.player_UUID["UUID"].append(self.uuid) self.tool.panel.player_UUID["Name"].append(self.player) # print 4 r = self.playercache.getPlayerSkin(self.uuid) if isinstance(r, (str, unicode)): r = r.join() self.tool.playerTexture[self.uuid] = loadPNGTexture(r) self.tool.playerPos[(0,0,0)] = self.uuid self.tool.revPlayerPos[self.uuid] = (0,0,0) self.playerTag.save(self.level.getPlayerPath(self.uuid)) self.tool.nonSavedPlayers.append(self.level.getPlayerPath(self.uuid)) self.tool.markerList.invalidate() class PlayerMoveOperation(Operation): undoPos = None redoPos = None def __init__(self, tool, pos, player="Player", yp=(None, None)): super(PlayerMoveOperation, self).__init__(tool.editor, tool.editor.level) self.tool = tool self.canUndo = False self.pos = pos self.player = player self.yp = yp def perform(self, recordUndo=True): if self.level.saving: alert(_("Cannot perform action while saving is taking place")) return try: level = self.tool.editor.level try: self.undoPos = level.getPlayerPosition(self.player) self.undoDim = level.getPlayerDimension(self.player) self.undoYP = level.getPlayerOrientation(self.player) except Exception as e: log.info(_("Couldn't get player position! ({0!r})").format(e)) yaw, pitch = self.yp if yaw is not None and pitch is not None: level.setPlayerOrientation((yaw, pitch), self.player) level.setPlayerPosition(self.pos, self.player) level.setPlayerDimension(level.dimNo, self.player) self.tool.playerPos[tuple(self.pos)] = self.player self.tool.revPlayerPos[self.player] = self.pos self.tool.markerList.invalidate() self.canUndo = True except pymclevel.PlayerNotFound as e: print "Player move failed: ", e def undo(self): if not (self.undoPos is None): level = self.tool.editor.level try: self.redoPos = level.getPlayerPosition(self.player) self.redoDim = level.getPlayerDimension(self.player) self.redoYP = level.getPlayerOrientation(self.player) except Exception as e: log.info(_("Couldn't get player position! ({0!r})").format(e)) level.setPlayerPosition(self.undoPos, self.player) level.setPlayerDimension(self.undoDim, self.player) level.setPlayerOrientation(self.undoYP, self.player) self.tool.markerList.invalidate() def redo(self): if not (self.redoPos is None): level = self.tool.editor.level try: self.undoPos = level.getPlayerPosition(self.player) self.undoDim = level.getPlayerDimension(self.player) self.undoYP = level.getPlayerOrientation(self.player) except Exception as e: log.info(_("Couldn't get player position! ({0!r})").format(e)) level.setPlayerPosition(self.redoPos, self.player) level.setPlayerDimension(self.redoDim, self.player) level.setPlayerOrientation(self.redoYP, self.player) self.tool.markerList.invalidate() @staticmethod def bufferSize(): return 20 class SpawnPositionInvalid(Exception): pass def okayAt63(level, pos): """blocks 63 or 64 must be occupied""" # return level.blockAt(pos[0], 63, pos[2]) != 0 or level.blockAt(pos[0], 64, pos[2]) != 0 return True def okayAboveSpawn(level, pos): """3 blocks above spawn must be open""" return not any([level.blockAt(pos[0], pos[1] + i, pos[2]) for i in xrange(1, 4)]) def positionValid(level, pos): try: return okayAt63(level, pos) and okayAboveSpawn(level, pos) except EnvironmentError: return False class PlayerSpawnMoveOperation(Operation): undoPos = None redoPos = None def __init__(self, tool, pos): super(PlayerSpawnMoveOperation, self).__init__(tool.editor, tool.editor.level) self.tool, self.pos = tool, pos self.canUndo = False def perform(self, recordUndo=True): if self.level.saving: alert(_("Cannot perform action while saving is taking place")) return level = self.tool.editor.level ''' if isinstance(level, pymclevel.MCInfdevOldLevel): if not positionValid(level, self.pos): if config.spawn.spawnProtection.get(): raise SpawnPositionInvalid( "You cannot have two air blocks at Y=63 and Y=64 in your spawn point's column. Additionally, you cannot have a solid block in the three blocks above your spawn point. It's weird, I know.") ''' self.undoPos = level.playerSpawnPosition() level.setPlayerSpawnPosition(self.pos) self.tool.markerList.invalidate() self.canUndo = True def undo(self): if self.undoPos is not None: level = self.tool.editor.level self.redoPos = level.playerSpawnPosition() level.setPlayerSpawnPosition(self.undoPos) self.tool.markerList.invalidate() def redo(self): if self.redoPos is not None: level = self.tool.editor.level self.undoPos = level.playerSpawnPosition() level.setPlayerSpawnPosition(self.redoPos) self.tool.markerList.invalidate() class PlayerPositionPanel(Panel): def __init__(self, tool): Panel.__init__(self, name='Panel.PlayerPositionPanel') self.tool = tool self.player_UUID = {"UUID": [], "Name": []} self.level = tool.editor.level self.playercache = PlayerCache() # Add this instance to PlayerCache 'targets'. PlayerCache generated processes will call # this instance 'update_player' method when they have finished their execution. self.playercache.add_target(self.update_player) if hasattr(self.level, 'players'): players = self.level.players or ["[No players]"] if not self.level.oldPlayerFolderFormat: for player in players: if player != "Player" and player != "[No players]": if len(player) > 4 and player[4] == "-": os.rename(os.path.join(self.level.worldFolder.getFolderPath("playerdata"), player+".dat"), os.path.join(self.level.worldFolder.getFolderPath("playerdata"), player.replace("-", "", 1)+".dat")) player = player.replace("-", "", 1) # print 5 data = self.playercache.getPlayerInfo(player, use_old_data=True) #self.player_UUID[data[0]] = data[1] self.player_UUID["UUID"].append(data[0]) self.player_UUID["Name"].append(data[1]) #self.player_UUID[player] = data if "Player" in players: #self.player_UUID["Player (Single Player)"] = "Player" self.player_UUID["UUID"].append("Player") self.player_UUID["Name"].append("Player (Single Player)") if "[No players]" not in players: self.player_names = sorted(self.player_UUID.values(), key=lambda x: False if x == "Player (Single Player)" else x) else: self.player_UUID["UUID"].append("[No players]") self.player_UUID["Name"].append("[No players]") else: players = ["Player (Single Player)"] self.players = players if 'Player' in self.player_UUID['UUID'] and 'Player (Single Player)' in self.player_UUID['Name']: self.player_UUID['UUID'].insert(0, self.player_UUID['UUID'].pop(self.player_UUID['UUID'].index('Player'))) self.player_UUID['Name'].insert(0, self.player_UUID['Name'].pop(self.player_UUID['Name'].index('Player (Single Player)'))) self.pages = TabPanel() tab_height = self.pages.tab_height max_height = tab_height + self.tool.editor.mainViewport.height - self.tool.editor.toolbar.height - self.tool.editor.subwidgets[0].height - self.pages.margin * 2 #-# Uncomment the following line to have a maximum height for this panel. # max_height = min(max_height, 500) self.editNBTDataButton = Button("Edit NBT", action=self.editNBTData, tooltipText="Open the NBT Explorer to edit player's attributes and inventory") addButton = Button("Add", action=self.tool.addPlayer) removeButton = Button("Remove", action=self.tool.removePlayer) gotoButton = Button("Goto", action=self.tool.gotoPlayer) gotoCameraButton = Button("Goto View", action=self.tool.gotoPlayerCamera) moveButton = Button("Move", action=self.tool.movePlayer) moveToCameraButton = Button("Align to Camera", action=self.tool.movePlayerToCamera) reloadSkin = Button("Reload Skins", action=self.tool.reloadSkins, tooltipText="This pulls skins from the online server, so this may take a while") btns = [self.editNBTDataButton] if not isinstance(self.level, pymclevel.leveldbpocket.PocketLeveldbWorld): btns.extend([addButton, removeButton]) btns.extend([gotoButton, gotoCameraButton, moveButton, moveToCameraButton, reloadSkin]) btns = Column(btns, margin=0, spacing=2) h = max_height - btns.height - self.pages.margin * 2 - 2 - self.font.get_linesize() * 2 col = Label('') def close(): self.pages.show_page(col) self.nbttree = NBTExplorerToolPanel(self.tool.editor, nbtObject={}, height=max_height, \ close_text="Go Back", no_header=True, close_action=close, load_text=None) self.nbttree.shrink_wrap() self.nbtpage = Column([self.nbttree]) self.nbtpage.shrink_wrap() self.pages.add_page("NBT Data", self.nbtpage) self.pages.set_rect(map(lambda x:x+self.margin, self.nbttree._rect)) tableview = TableView(nrows=(h - (self.font.get_linesize() * 2.5)) / self.font.get_linesize(), header_height=self.font.get_linesize(), columns=[TableColumn("Player Name(s):", (self.nbttree.width - (self.margin * 3)) / 3), TableColumn("Player UUID(s):", (self.nbttree.width - (self.margin * 3)))], ) tableview.index = 0 tableview.num_rows = lambda: len(self.player_UUID["UUID"]) tableview.row_data = lambda i: (self.player_UUID["Name"][i],self.player_UUID["UUID"][i]) tableview.row_is_selected = lambda x: x == tableview.index tableview.zebra_color = (0, 0, 0, 48) def selectTableRow(i, evt): tableview.index = i tableview.click_row = selectTableRow def mouse_down(e): if e.button == 1 and e.num_clicks > 1: self.editNBTData() TableRowView.mouse_down(tableview.rows, e) tableview.rows.mouse_down = mouse_down tableview.rows.tooltipText = "Double-click or use the button below to edit the NBT Data." self.table = tableview col.set_parent(None) self.col = col = Column([tableview, btns], spacing=2) self.pages.add_page("Players", col, 0) self.pages.shrink_wrap() self.pages.show_page(col) self.add(self.pages) self.shrink_wrap() self.max_height = max_height def editNBTData(self): player = self.selectedPlayer if player == 'Player (Single Player)': alert("Not yet implemented.\nUse the NBT Explorer to edit this player.") elif player == '[No players]': return else: player = self.level.getPlayerTag(self.selectedPlayer) if player is not None: self.pages.remove_page(self.nbtpage) def close(): self.pages.show_page(self.col) self.nbttree = NBTExplorerToolPanel(self.tool.editor, nbtObject=player, fileName=None, savePolicy=-1, dataKeyName=None, height=self.max_height, no_header=True, close_text="Go Back", close_action=close, load_text=None, copy_data=False) self.nbtpage = Column([self.nbttree,]) self.nbtpage.shrink_wrap() self.pages.add_page("NBT Data", self.nbtpage) self.pages.show_page(self.nbtpage) else: alert(_("Unable to load player %s" % self.selectedPlayer())) @property def selectedPlayer(self): if not self.level.oldPlayerFolderFormat: player = self.players[self.table.index] if player != "Player (Single Player)" and player != "[No players]" and player != "~local_player": return self.player_UUID["UUID"][self.table.index] else: return player else: return self.players[self.table.index] def key_down(self, evt): self.dispatch_key('key_down', evt) def dispatch_key(self, name, evt): if not hasattr(evt, 'key'): return if name == "key_down": keyname = self.root.getKey(evt) if self.pages.current_page == self.col: if keyname == "Up" and self.table.index > 0: self.table.index -= 1 self.table.rows.scroll_to_item(self.table.index) elif keyname == "Down" and self.table.index < len(self.players) - 1: self.table.index += 1 self.table.rows.scroll_to_item(self.table.index) elif keyname == 'Page down': self.table.index = min(len(self.players) - 1, self.table.index + self.table.rows.num_rows()) elif keyname == 'Page up': self.table.index = max(0, self.table.index - self.table.rows.num_rows()) elif keyname == 'Return': if self.selectedPlayer: self.editNBTData() if self.table.rows.cell_to_item_no(0, 0) + self.table.rows.num_rows() -1 > self.table.index or self.table.rows.cell_to_item_no(0, 0) + self.table.rows.num_rows() -1 < self.table.index: self.table.rows.scroll_to_item(self.table.index) elif self.pages.current_page == self.nbtpage: self.nbttree.dispatch_key(name, evt) def update_player(self, data): if isinstance(data, tuple): if data[0] in self.player_UUID['UUID']: idx = self.player_UUID['UUID'].index(data[0]) self.player_UUID['UUID'][idx] = data[0] self.player_UUID['Name'][idx] = data[1] class PlayerPositionTool(EditorTool): surfaceBuild = True toolIconName = "player" tooltipText = "Players" movingPlayer = None recordMove = True def reloadTextures(self): self.charTex = loadPNGTexture('char.png') @alertException def addPlayer(self): op = PlayerAddOperation(self) self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() @alertException def removePlayer(self): player = self.panel.selectedPlayer if player != "[No players]": op = PlayerRemoveOperation(self, player) self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() @alertException def movePlayer(self): if self.panel.selectedPlayer != "[No players]": self.movingPlayer = self.panel.selectedPlayer if self.movingPlayer == "Player (Single Player)": self.movingPlayer = "Player" @alertException def movePlayerToCamera(self): player = self.panel.selectedPlayer if player == "Player (Single Player)": player = "Player" if player != "[No players]": pos = self.editor.mainViewport.cameraPosition y = self.editor.mainViewport.yaw p = self.editor.mainViewport.pitch op = PlayerMoveOperation(self, pos, player, (y, p)) self.movingPlayer = None self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() def delete_skin(self, uuid): del self.playerTexture[uuid] self.playerTexture[uuid] = self.charTex @alertException def reloadSkins(self): #result = ask("This pulls skins from the online server, so this may take a while", ["Ok", "Cancel"]) #if result == "Ok": try: for player in self.editor.level.players: if player != "Player" and player in self.playerTexture.keys(): del self.playerTexture[player] # print 6 r = self.playercache.getPlayerSkin(player, force_download=True, instance=self) if isinstance(r, (str, unicode)): r = r.join() self.playerTexture[player] = loadPNGTexture(r) #self.markerList.call(self._drawToolMarkers) except: raise Exception("Could not connect to the skins server, please check your Internet connection and try again.") def gotoPlayerCamera(self): player = self.panel.selectedPlayer if player == "Player (Single Player)": player = "Player" try: pos = self.editor.level.getPlayerPosition(player) y, p = self.editor.level.getPlayerOrientation(player) self.editor.gotoDimension(self.editor.level.getPlayerDimension(player)) self.editor.mainViewport.cameraPosition = pos self.editor.mainViewport.yaw = y self.editor.mainViewport.pitch = p self.editor.mainViewport.stopMoving() self.editor.mainViewport.invalidate() except pymclevel.PlayerNotFound: pass def gotoPlayer(self): player = self.panel.selectedPlayer if player == "Player (Single Player)": player = "Player" try: if self.editor.mainViewport.pitch < 0: self.editor.mainViewport.pitch = -self.editor.mainViewport.pitch self.editor.mainViewport.cameraVector = self.editor.mainViewport._cameraVector() cv = self.editor.mainViewport.cameraVector pos = self.editor.level.getPlayerPosition(player) pos = map(lambda p, c: p - c * 5, pos, cv) self.editor.gotoDimension(self.editor.level.getPlayerDimension(player)) self.editor.mainViewport.cameraPosition = pos self.editor.mainViewport.stopMoving() except pymclevel.PlayerNotFound: pass def __init__(self, *args): EditorTool.__init__(self, *args) self.reloadTextures() self.nonSavedPlayers = [] textureVerticesHead = numpy.array( ( # Backside of Head 24, 16, # Bottom Left 24, 8, # Top Left 32, 8, # Top Right 32, 16, # Bottom Right # Front of Head 8, 16, 8, 8, 16, 8, 16, 16, # 24, 0, 16, 0, 16, 8, 24, 8, # 16, 0, 8, 0, 8, 8, 16, 8, # 8, 8, 0, 8, 0, 16, 8, 16, 16, 16, 24, 16, 24, 8, 16, 8, ), dtype='f4') textureVerticesHat = numpy.array( ( 56, 16, 56, 8, 64, 8, 64, 16, 48, 16, 48, 8, 40, 8, 40, 16, 56, 0, 48, 0, 48, 8, 56, 8, 48, 0, 40, 0, 40, 8, 48, 8, 40, 8, 32, 8, 32, 16, 40, 16, 48, 16, 56, 16, 56, 8, 48, 8, ), dtype='f4') textureVerticesHead.shape = (24, 2) textureVerticesHat.shape = (24, 2) textureVerticesHead *= 4 textureVerticesHead[:, 1] *= 2 textureVerticesHat *= 4 textureVerticesHat[:, 1] *= 2 self.texVerts = (textureVerticesHead, textureVerticesHat) self.playerPos = {0:{}, -1:{}, 1:{}} self.playerTexture = {} self.revPlayerPos = {0:{}, -1:{}, 1:{}} self.inOtherDimension = {0: [], 1: [], -1: []} self.playercache = PlayerCache() self.markerList = DisplayList() panel = None def showPanel(self): if not self.panel: self.panel = PlayerPositionPanel(self) self.panel.centery = (self.editor.mainViewport.height - self.editor.toolbar.height) / 2 + self.editor.subwidgets[0].height self.panel.left = self.editor.left self.editor.add(self.panel) def hidePanel(self): if self.panel and self.panel.parent: self.panel.parent.remove(self.panel) self.panel = None def drawToolReticle(self): if self.movingPlayer is None: return pos, direction = self.editor.blockFaceUnderCursor dim = self.editor.level.getPlayerDimension(self.movingPlayer) pos = (pos[0], pos[1] + 2, pos[2]) x, y, z = pos # x,y,z=map(lambda p,d: p+d, pos, direction) GL.glEnable(GL.GL_BLEND) GL.glColor(1.0, 1.0, 1.0, 0.5) self.drawCharacterHead(x + 0.5, y + 0.75, z + 0.5, self.revPlayerPos[dim][self.movingPlayer], dim) GL.glDisable(GL.GL_BLEND) GL.glEnable(GL.GL_DEPTH_TEST) self.drawCharacterHead(x + 0.5, y + 0.75, z + 0.5, self.revPlayerPos[dim][self.movingPlayer], dim) drawTerrainCuttingWire(BoundingBox((x, y, z), (1, 1, 1))) drawTerrainCuttingWire(BoundingBox((x, y - 1, z), (1, 1, 1))) #drawTerrainCuttingWire( BoundingBox((x,y-2,z), (1,1,1)) ) GL.glDisable(GL.GL_DEPTH_TEST) markerLevel = None def drawToolMarkers(self): if not config.settings.drawPlayerHeads.get(): return if self.markerLevel != self.editor.level: self.markerList.invalidate() self.markerLevel = self.editor.level self.markerList.call(self._drawToolMarkers) def _drawToolMarkers(self): GL.glColor(1.0, 1.0, 1.0, 0.5) GL.glEnable(GL.GL_DEPTH_TEST) GL.glMatrixMode(GL.GL_MODELVIEW) for player in self.editor.level.players: try: pos = self.editor.level.getPlayerPosition(player) yaw, pitch = self.editor.level.getPlayerOrientation(player) dim = self.editor.level.getPlayerDimension(player) self.inOtherDimension[dim].append(player) self.playerPos[dim][pos] = player self.revPlayerPos[dim][player] = pos if player != "Player" and config.settings.downloadPlayerSkins.get(): # print 7 r = self.playercache.getPlayerSkin(player, force_download=False) if not isinstance(r, (str, unicode)): r = r.join() self.playerTexture[player] = loadPNGTexture(r) else: self.playerTexture[player] = self.charTex if dim != self.editor.level.dimNo: continue x, y, z = pos GL.glPushMatrix() GL.glTranslate(x, y, z) GL.glRotate(-yaw, 0, 1, 0) GL.glRotate(pitch, 1, 0, 0) GL.glColor(1, 1, 1, 1) self.drawCharacterHead(0, 0, 0, (x,y,z), self.editor.level.dimNo) GL.glPopMatrix() # GL.glEnable(GL.GL_BLEND) drawTerrainCuttingWire(FloatBox((x - .5, y - .5, z - .5), (1, 1, 1)), c0=(0.3, 0.9, 0.7, 1.0), c1=(0, 0, 0, 0), ) #GL.glDisable(GL.GL_BLEND) except Exception, e: print "Exception in editortools.player.PlayerPositionTool._drawToolMarkers:", repr(e) import traceback print traceback.format_exc() continue GL.glDisable(GL.GL_DEPTH_TEST) def drawCharacterHead(self, x, y, z, realCoords=None, dim=0): GL.glEnable(GL.GL_CULL_FACE) origin = (x - 0.25, y - 0.25, z - 0.25) size = (0.5, 0.5, 0.5) box = FloatBox(origin, size) hat_origin = (x - 0.275, y - 0.275, z - 0.275) hat_size = (0.55, 0.55, 0.55) hat_box = FloatBox(hat_origin, hat_size) if realCoords is not None and self.playerPos[dim][realCoords] != "Player" and config.settings.downloadPlayerSkins.get(): drawCube(box, texture=self.playerTexture[self.playerPos[dim][realCoords]], textureVertices=self.texVerts[0]) GL.glEnable(GL.GL_BLEND) GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA) drawCube(hat_box, texture=self.playerTexture[self.playerPos[dim][realCoords]], textureVertices=self.texVerts[1]) GL.glDisable(GL.GL_BLEND) else: drawCube(box, texture=self.charTex, textureVertices=self.texVerts[0]) GL.glDisable(GL.GL_CULL_FACE) #@property #def statusText(self): # if not self.panel: # return "" # player = self.panel.selectedPlayer # if player == "Player": # return "Click to move the player" # # return _("Click to move the player \"{0}\"").format(player) @alertException def mouseDown(self, evt, pos, direction): if self.movingPlayer is None: return pos = (pos[0] + 0.5, pos[1] + 2.75, pos[2] + 0.5) op = PlayerMoveOperation(self, pos, self.movingPlayer) self.movingPlayer = None if self.recordMove: self.editor.addOperation(op) addingMoving = False else: self.editor.performWithRetry(op) #Prevent recording of Undo when adding player self.recordMove = True addingMoving = True if op.canUndo and not addingMoving: self.editor.addUnsavedEdit() def keyDown(self, evt): keyname = evt.dict.get('keyname', None) or self.editor.get_root().getKey(evt) if not self.recordMove: if not pygame.key.get_focused(): return if keyname == "Escape": self.recordMove = True if self.panel and self.panel.__class__ == PlayerPositionPanel: self.panel.key_down(evt) def keyUp(self, evt): pass def levelChanged(self): self.markerList.invalidate() @alertException def toolSelected(self): self.showPanel() self.movingPlayer = None @alertException def toolReselected(self): if self.panel: self.gotoPlayer() class PlayerSpawnPositionOptions(ToolOptions): def __init__(self, tool): ToolOptions.__init__(self, name='Panel.PlayerSpawnPositionOptions') self.tool = tool self.spawnProtectionCheckBox = CheckBox(ref=AttrRef(tool, "spawnProtection")) self.spawnProtectionLabel = Label("Spawn Position Safety") self.spawnProtectionLabel.mouse_down = self.spawnProtectionCheckBox.mouse_down tooltipText = "Minecraft will randomly move your spawn point if you try to respawn in a column where there are no blocks at Y=63 and Y=64. Only uncheck this box if Minecraft is changed." self.spawnProtectionLabel.tooltipText = self.spawnProtectionCheckBox.tooltipText = tooltipText row = Row((self.spawnProtectionCheckBox, self.spawnProtectionLabel)) col = Column((Label("Spawn Point Options"), row, Button("OK", action=self.dismiss))) self.add(col) self.shrink_wrap() class PlayerSpawnPositionTool(PlayerPositionTool): surfaceBuild = True toolIconName = "playerspawn" tooltipText = "Move Spawn Point\nRight-click for options" def __init__(self, *args): PlayerPositionTool.__init__(self, *args) self.optionsPanel = PlayerSpawnPositionOptions(self) def toolEnabled(self): return self.editor.level.dimNo == 0 def showPanel(self): self.panel = Panel(name='Panel.PlayerSpawnPositionTool') button = Button("Goto Spawn", action=self.gotoSpawn) self.panel.add(button) self.panel.shrink_wrap() self.panel.left = self.editor.left self.panel.centery = self.editor.centery self.editor.add(self.panel) def gotoSpawn(self): cv = self.editor.mainViewport.cameraVector pos = self.editor.level.playerSpawnPosition() pos = map(lambda p, c: p - c * 5, pos, cv) self.editor.mainViewport.cameraPosition = pos self.editor.mainViewport.stopMoving() @property def statusText(self): return "Click to set the spawn position." spawnProtection = config.spawn.spawnProtection.property() def drawToolReticle(self): pos, direction = self.editor.blockFaceUnderCursor x, y, z = map(lambda p, d: p + d, pos, direction) color = (1.0, 1.0, 1.0, 0.5) if isinstance(self.editor.level, pymclevel.MCInfdevOldLevel) and self.spawnProtection: if not positionValid(self.editor.level, (x, y, z)): color = (1.0, 0.0, 0.0, 0.5) GL.glColor(*color) GL.glEnable(GL.GL_BLEND) self.drawCage(x, y, z) self.drawCharacterHead(x + 0.5, y + 0.5, z + 0.5) GL.glDisable(GL.GL_BLEND) GL.glEnable(GL.GL_DEPTH_TEST) self.drawCage(x, y, z) self.drawCharacterHead(x + 0.5, y + 0.5, z + 0.5) color2 = map(lambda a: a * 0.4, color) drawTerrainCuttingWire(BoundingBox((x, y, z), (1, 1, 1)), color2, color) GL.glDisable(GL.GL_DEPTH_TEST) def _drawToolMarkers(self): x, y, z = self.editor.level.playerSpawnPosition() GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA) GL.glEnable(GL.GL_BLEND) color = config.selectionColors.black.get() + (0.35,) GL.glColor(*color) GL.glPolygonMode(GL.GL_FRONT_AND_BACK, GL.GL_LINE) GL.glLineWidth(2.0) drawCube(FloatBox((x, y, z), (1, 1, 1))) GL.glPolygonMode(GL.GL_FRONT_AND_BACK, GL.GL_FILL) drawCube(FloatBox((x, y, z), (1, 1, 1))) GL.glDisable(GL.GL_BLEND) GL.glEnable(GL.GL_DEPTH_TEST) GL.glColor(1.0, 1.0, 1.0, 1.0) self.drawCage(x, y, z) self.drawCharacterHead(x + 0.5, y + 0.5 + 0.125 * numpy.sin(self.editor.frames * 0.05), z + 0.5) GL.glDisable(GL.GL_DEPTH_TEST) def drawCage(self, x, y, z): cageTexVerts = numpy.array(pymclevel.MCInfdevOldLevel.materials.blockTextures[52, 0]) pixelScale = 0.5 if self.editor.level.materials.name in ("Pocket", "Alpha") else 1.0 texSize = 16 * pixelScale cageTexVerts = cageTexVerts.astype(float) * pixelScale cageTexVerts = numpy.array( [((tx, ty), (tx + texSize, ty), (tx + texSize, ty + texSize), (tx, ty + texSize)) for (tx, ty) in cageTexVerts], dtype='float32') GL.glEnable(GL.GL_ALPHA_TEST) drawCube(BoundingBox((x, y, z), (1, 1, 1)), texture=pymclevel.alphaMaterials.terrainTexture, textureVertices=cageTexVerts) GL.glDisable(GL.GL_ALPHA_TEST) @alertException def mouseDown(self, evt, pos, direction): pos = map(lambda p, d: p + d, pos, direction) op = PlayerSpawnMoveOperation(self, pos) try: self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() self.markerList.invalidate() except SpawnPositionInvalid, e: if "Okay" != ask(str(e), responses=["Okay", "Fix it for me!"]): level = self.editor.level status = "" if not okayAt63(level, pos): level.setBlockAt(pos[0], 63, pos[2], 1) status += _("Block added at y=63.\n") if 59 < pos[1] < 63: pos[1] = 63 status += _("Spawn point moved upward to y=63.\n") if not okayAboveSpawn(level, pos): if pos[1] > 63 or pos[1] < 59: lpos = (pos[0], pos[1] - 1, pos[2]) if level.blockAt(*pos) == 0 and level.blockAt(*lpos) != 0 and okayAboveSpawn(level, lpos): pos = lpos status += _("Spawn point shifted down by one block.\n") if not okayAboveSpawn(level, pos): for i in xrange(1, 4): level.setBlockAt(pos[0], pos[1] + i, pos[2], 0) status += _("Blocks above spawn point cleared.\n") self.editor.invalidateChunks([(pos[0] // 16, pos[2] // 16)]) op = PlayerSpawnMoveOperation(self, pos) try: self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() self.markerList.invalidate() except SpawnPositionInvalid, e: alert(str(e)) return if len(status): alert(_("Spawn point fixed. Changes: \n\n") + status) @alertException def toolReselected(self): self.gotoSpawn()
46,013
38.633075
219
py
MCEdit-Unified
MCEdit-Unified-master/editortools/brush.py
"""Copyright (c) 2010-2012 David Rio Vierra Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.""" #Modified by D.C.-G. for translation purposes import imp import traceback import copy from OpenGL import GL import os import sys from albow import AttrRef, ItemRef, Button, ValueDisplay, Row, Label, ValueButton, Column, IntField, FloatField, alert, CheckBox, TextFieldWrapped, TableView, TableColumn from albow.dialogs import Dialog import albow.translate _ = albow.translate._ import ast import bresenham from clone import CloneTool from config import config import directories from editortools.blockpicker import BlockPicker from editortools.blockview import BlockButton from editortools.editortool import EditorTool from editortools.tooloptions import ToolOptions from glbackground import Panel, GLBackground from glutils import gl from albow.root import get_root import logging from mceutils import alertException, drawTerrainCuttingWire from albow import ChoiceButton, CheckBoxLabel, showProgress, IntInputRow, FloatInputRow import mcplatform from numpy import newaxis import numpy from operation import Operation from pymclevel import BoundingBox, blockrotation import pymclevel from pymclevel.mclevelbase import exhaust from pymclevel.entity import TileEntity import types from pymclevel.materials import Block from locale import getdefaultlocale DEF_ENC = getdefaultlocale()[1] if DEF_ENC is None: DEF_ENC = "UTF-8" log = logging.getLogger(__name__) class BrushOperation(Operation): def __init__(self, tool): super(BrushOperation, self).__init__(tool.editor, tool.editor.level) self.tool = tool self.points = tool.draggedPositions self.options = tool.options self.brushMode = tool.brushMode boxes = [self.tool.getDirtyBox(p, self.tool) for p in self.points] self._dirtyBox = reduce(lambda a, b: a.union(b), boxes) self.canUndo = False def dirtyBox(self): return self._dirtyBox def perform(self, recordUndo=True): if self.level.saving: alert(_("Cannot perform action while saving is taking place")) return if recordUndo: self.canUndo = True self.undoLevel = self.extractUndo(self.level, self._dirtyBox) def _perform(): yield 0, len(self.points), _("Applying {0} brush...").format(_(self.brushMode.displayName)) if hasattr(self.brushMode, 'apply'): for i, point in enumerate(self.points): f = self.brushMode.apply(self.brushMode, self, point) if hasattr(f, "__iter__"): for progress in f: yield progress else: yield i, len(self.points), _("Applying {0} brush...").format(_(self.brushMode.displayName)) if hasattr(self.brushMode, 'applyToChunkSlices'): for j, cPos in enumerate(self._dirtyBox.chunkPositions): if not self.level.containsChunk(*cPos): continue chunk = self.level.getChunk(*cPos) for i, point in enumerate(self.points): brushBox = self.tool.getDirtyBox(point, self.tool) brushBoxThisChunk, slices = chunk.getChunkSlicesForBox(brushBox) f = self.brushMode.applyToChunkSlices(self.brushMode, self, chunk, slices, brushBox, brushBoxThisChunk) if brushBoxThisChunk.volume == 0: f = None if hasattr(f, "__iter__"): for progress in f: yield progress else: yield j * len(self.points) + i, len(self.points) * self._dirtyBox.chunkCount, _("Applying {0} brush...").format(_(self.brushMode.displayName)) chunk.chunkChanged() if len(self.points) > 10: showProgress("Performing brush...", _perform(), cancel=True) else: exhaust(_perform()) class BrushPanel(Panel): def __init__(self, tool): Panel.__init__(self, name='Panel.BrushPanel') self.tool = tool """ presets, modeRow and styleRow are always created, no matter what brush is selected. styleRow can be disabled by putting disableStyleButton = True in the brush file. """ presets = self.createPresetRow() self.brushModeButtonLabel = Label("Mode:") self.brushModeButton = ChoiceButton(sorted([mode for mode in tool.brushModes]), width=150, choose=self.brushModeChanged, doNotTranslate=True, ) modeRow = Row([self.brushModeButtonLabel, self.brushModeButton]) self.brushStyleButtonLabel = Label("Style:") self.brushStyleButton = ValueButton(ref=ItemRef(self.tool.options, "Style"), action=self.tool.swapBrushStyles, width=150) styleRow = Row([self.brushStyleButtonLabel, self.brushStyleButton]) self.brushModeButton.selectedChoice = self.tool.selectedBrushMode optionsColumn = [] optionsColumn.extend([presets, modeRow]) if not getattr(tool.brushMode, 'disableStyleButton', False): optionsColumn.append(styleRow) """ We're going over all options in the selected brush module, and making a field for all of them. """ for r in tool.brushMode.inputs: row = [] for key, value in r.iteritems(): field = self.createField(key, value) row.append(field) row = Row(row) optionsColumn.append(row) if getattr(tool.brushMode, 'addPasteButton', False): importButton = Button("Import", action=tool.importPaste) importRow = Row([importButton]) optionsColumn.append(importRow) optionsColumn = Column(optionsColumn, spacing=0) self.add(optionsColumn) self.shrink_wrap() def createField(self, key, value): """ Creates a field matching the input type. :param key, key to store the value in, also the name of the label if type is float or int. :param value, default value for the field. """ doNotTranslate = bool(hasattr(self.tool.brushMode, "trn")) check_value = value mi = 0 ma = 100 if key in ('W', 'H', 'L'): reference = AttrRef(self.tool, key) else: reference = ItemRef(self.tool.options, key) if isinstance(check_value, tuple): check_value = value[0] mi = value[1] ma = value[2] if isinstance(check_value, Block): if key not in self.tool.recentBlocks: self.tool.recentBlocks[key] = [] wcb = getattr(self.tool.brushMode, 'wildcardBlocks', []) aw = False if key in wcb: aw = True field = BlockButton(self.tool.editor.level.materials, ref=reference, recentBlocks=self.tool.recentBlocks[key], allowWildcards=aw ) elif isinstance(check_value, types.MethodType): field = Button(key, action=value) else: if doNotTranslate: key = self.tool.brushMode.trn._(key) value = self.tool.brushMode.trn._(value) if isinstance(check_value, int): field = IntInputRow(key, ref=reference, width=50, min=mi, max=ma, doNotTranslate=doNotTranslate) elif isinstance(check_value, float): field = FloatInputRow(key, ref=reference, width=50, min=mi, max=ma, doNotTranslate=doNotTranslate) elif isinstance(check_value, bool): field = CheckBoxLabel(key, ref=reference, doNotTranslate=doNotTranslate) elif isinstance(check_value, str): field = Label(value, doNotTranslate=doNotTranslate) else: print type(check_value) field = None return field def brushModeChanged(self): """ Called on selecting a brushMode, sets it in BrushTool as well. """ self.tool.selectedBrushMode = self.brushModeButton.selectedChoice self.tool.brushMode = self.tool.brushModes[self.tool.selectedBrushMode] self.tool.saveBrushPreset('__temp__') self.tool.setupPreview() self.tool.showPanel() @staticmethod def getBrushFileList(): """ Returns a list of strings of all .preset files in the brushes directory. """ list = [] presetdownload = os.listdir(directories.brushesDir) for p in presetdownload: if p.endswith('.preset'): list.append(os.path.splitext(p)[0]) if '__temp__' in list: list.remove('__temp__') return list def createPresetRow(self): """ Creates the brush preset widget, called by BrushPanel when creating the panel. """ self.presets = ["Load Preset"] self.presets.extend(self.getBrushFileList()) self.presets.append('Remove Presets') self.presetListButton = ChoiceButton(self.presets, width=100, choose=self.presetSelected) self.presetListButton.selectedChoice = "Load Preset" self.saveButton = Button("Save as Preset", action=self.openSavePresetDialog) presetListButtonRow = Row([self.presetListButton]) saveButtonRow = Row([self.saveButton]) row = Row([presetListButtonRow, saveButtonRow]) widget = GLBackground() widget.bg_color = (0.8, 0.8, 0.8, 0.8) widget.add(row) widget.shrink_wrap() widget.anchor = "whtr" return widget def openSavePresetDialog(self): """ Opens up a dialgo to input the name of the to save Preset. """ panel = Dialog() label = Label("Preset Name:") nameField = TextFieldWrapped(width=200) def okPressed(): panel.dismiss() name = nameField.value if name in ['Load Preset', 'Remove Presets', '__temp__']: alert("That preset name is reserved. Try pick another preset name.") return for p in ['<','>',':','\"', '/', '\\', '|', '?', '*', '.']: if p in name: alert('Invalid character in file name') return self.tool.saveBrushPreset(name) self.tool.showPanel() okButton = Button("OK", action=okPressed) cancelButton = Button("Cancel", action=panel.dismiss) namerow = Row([label,nameField]) buttonRow = Row([okButton,cancelButton]) panel.add(Column([namerow, buttonRow])) panel.shrink_wrap() panel.present() def removePreset(self): """ Brings up a panel to remove presets. """ panel = Dialog() p = self.getBrushFileList() if not p: alert('No presets saved') return def okPressed(): panel.dismiss() name = p[presetTable.selectedIndex] + ".preset" os.remove(os.path.join(directories.brushesDir, name)) self.tool.showPanel() def selectTableRow(i, evt): presetTable.selectedIndex = i if evt.num_clicks == 2: okPressed() presetTable = TableView(columns=(TableColumn("", 200),)) presetTable.num_rows = lambda: len(p) presetTable.row_data = lambda i: (p[i],) presetTable.row_is_selected = lambda x: x == presetTable.selectedIndex presetTable.click_row = selectTableRow presetTable.selectedIndex = 0 choiceCol = Column((ValueDisplay(width=200, get_value=lambda: "Select preset to delete"), presetTable)) okButton = Button("OK", action=okPressed) cancelButton = Button("Cancel", action=panel.dismiss) row = Row([okButton, cancelButton]) panel.add(Column((choiceCol, row))) panel.shrink_wrap() panel.present() def presetSelected(self): """ Called ons selecting item on Load Preset, to check if remove preset is selected. Calls removePreset if true, loadPreset(name) otherwise. """ choice = self.presetListButton.selectedChoice if choice == 'Remove Presets': self.removePreset() elif choice == 'Load Preset': return else: self.tool.loadBrushPreset(choice) self.tool.showPanel() class BrushToolOptions(ToolOptions): def __init__(self, tool): ToolOptions.__init__(self, name='Panel.BrushToolOptions') alphaField = FloatField(ref=ItemRef(tool.settings, 'brushAlpha'), min=0.0, max=1.0, width=60) alphaField.increment = 0.1 alphaRow = Row((Label("Alpha: "), alphaField)) autoChooseCheckBox = CheckBoxLabel("Choose Block Immediately", ref=ItemRef(tool.settings, "chooseBlockImmediately"), tooltipText="When the brush tool is chosen, prompt for a block type.") updateOffsetCheckBox = CheckBoxLabel("Reset Distance When Brush Size Changes", ref=ItemRef(tool.settings, "updateBrushOffset"), tooltipText="Whenever the brush size changes, reset the distance to the brush blocks.") col = Column((Label("Brush Options"), alphaRow, autoChooseCheckBox, updateOffsetCheckBox, Button("OK", action=self.dismiss))) self.add(col) self.shrink_wrap() return class BrushTool(CloneTool): tooltipText = "Brush\nRight-click for options" toolIconName = "brush" options = { 'Style': 'Round', } settings = { 'chooseBlockImmediately': False, 'updateBrushOffset': False, 'brushAlpha': 1.0, } brushModes = {} recentBlocks = {} previewDirty = False cameraDistance = EditorTool.cameraDistance optionBackup = None def __init__(self, *args): """ Called on starting mcedit. Creates some basic variables. """ CloneTool.__init__(self, *args) self.optionsPanel = BrushToolOptions(self) self.recentFillBlocks = [] self.recentReplaceBlocks = [] self.draggedPositions = [] self.pickBlockKey = False self.lineToolKey = False self.lastPosition = None self.root = get_root() """ Property reticleOffset. Used to determine the distance between the block the cursor is pointing at, and the center of the brush. Increased by scrolling up, decreased by scrolling down (default keys) """ _reticleOffset = 1 @property def reticleOffset(self): if getattr(self.brushMode, 'draggableBrush', True): return self._reticleOffset return 0 @reticleOffset.setter def reticleOffset(self, val): self._reticleOffset = val """ Properties W,H,L. Used to reset the Brush Preview whenever they change. """ @property def W(self): return self.options['W'] @W.setter def W(self, val): self.options['W'] = val self.setupPreview() @property def H(self): return self.options['H'] @H.setter def H(self, val): self.options['H'] = val self.setupPreview() @property def L(self): return self.options['L'] @L.setter def L(self, val): self.options['L'] = val self.setupPreview() """ Statustext property, rendered in the black line at the bottom of the screen. """ @property def statusText(self): return _("Click and drag to place blocks. Pick block: {P}-Click. Increase: {R}. Decrease: {F}. Rotate: {E}. Roll: {G}. Mousewheel to adjust distance.").format( P=config.keys.pickBlock.get(), R=config.keys.increaseBrush.get(), F=config.keys.decreaseBrush.get(), E=config.keys.rotateBrush.get(), G=config.keys.rollBrush.get(), ) def toolEnabled(self): """ Brush tool is always enabled on the toolbar. It does not need a selection. """ return True def setupBrushModes(self): """ Makes a dictionary of all mode names and their corresponding module. If no name is found, it uses the name of the file. Creates dictionary entries for all inputs in import brush modules. Called by toolSelected """ self.importedBrushModes = self.importBrushModes() for m in self.importedBrushModes: if m.displayName: if hasattr(m, "trn"): displayName = m.trn._(m.displayName) else: displayName = _(m.displayName) self.brushModes[displayName] = m else: self.brushModes[m.__name__] = m if m.inputs: for r in m.inputs: for key in r: if not hasattr(self.options, key): if isinstance(r[key], tuple): self.options[key] = r[key][0] elif not isinstance(r[key], str): self.options[key] = r[key] if not hasattr(self.options, 'Minimum Spacing'): self.options['Minimum Spacing'] = 1 self.renderedBlock = None def importBrushModes(self): """ Imports all Stock Brush Modes from their files. Called by setupBrushModes """ #sys.path.append(os.path.join(directories.getDataDir(), u'stock-filters')) ### Why? Is 'stock-filters' needed here? Shouldn't be 'stock-brushes'? sys.path.append(directories.getDataFile('stock-filters')) #files = [x for x in os.listdir(os.path.join(directories.getDataDir(), u'stock-brushes')) if x.endswith(".py")] files = [x for x in os.listdir(directories.getDataFile('stock-brushes')) if x.endswith('.py')] more_files = [x for x in os.listdir(directories.brushesDir) if x.endswith(".py")] modes = [self.tryImport(x[:-3], 'stock-brushes') for x in files] cust_modes = [self.tryImport(x[:-3], directories.brushesDir) for x in more_files] modes = [m for m in modes if (hasattr(m, "apply") or hasattr(m, 'applyToChunkSlices')) and hasattr(m, 'inputs')] modes.extend([m for m in cust_modes if (hasattr(m, "apply") or hasattr(m, 'applyToChunkSlices')) and hasattr(m, 'inputs')]) return modes def tryImport(self, name, dir): """ Imports a brush module. Called by importBrushModules :param name, name of the module to import. """ embeded = bool(dir == "stock-brushes") try: path = os.path.join(dir, (name + ".py")) if isinstance(path, unicode) and DEF_ENC != "UTF-8": path = path.encode(DEF_ENC) globals()[name] = m = imp.load_source(name, path) if not embeded: old_trn_path = albow.translate.getLangPath() if "trn" in sys.modules.keys(): del sys.modules["trn"] import albow.translate as trn trn_path = os.path.join(directories.brushesDir, name) if os.path.exists(trn_path): trn.setLangPath(trn_path) trn.buildTranslation(config.settings.langCode.get()) m.trn = trn albow.translate.setLangPath(old_trn_path) albow.translate.buildTranslation(config.settings.langCode.get()) self.editor.mcedit.set_update_ui(True) self.editor.mcedit.set_update_ui(False) m.materials = self.editor.level.materials m.tool = self m.createInputs(m) return m except Exception as e: print traceback.format_exc() alert(_(u"Exception while importing brush mode {}. See console for details.\n\n{}").format(name, e)) return object() def toolSelected(self): """ Applies options of BrushToolOptions. It then imports all brush modes from their files, sets up the panel, and sets up the brush preview. Called on pressing "2" or pressing the brush button in the hotbar when brush is not selected. """ self.setupBrushModes() self.selectedBrushMode = [m for m in self.brushModes][0] self.brushMode = self.brushModes[self.selectedBrushMode] if self.settings['chooseBlockImmediately']: key = getattr(self.brushMode, 'mainBlock', 'Block') wcb = getattr(self.brushMode, 'wildcardBlocks', []) aw = False if key in wcb: aw = True blockPicker = BlockPicker(self.options[key], self.editor.level.materials, allowWildcards=aw) if blockPicker.present(): self.options[key] = blockPicker.blockInfo if self.settings['updateBrushOffset']: self.reticleOffset = self.offsetMax() self.resetToolDistance() if os.path.isfile(os.path.join(directories.brushesDir, '__temp__.preset')): self.loadBrushPreset('__temp__') else: print 'No __temp__ file found.' self.showPanel() self.setupPreview() if getattr(self.brushMode, 'addPasteButton', False): stack = self.editor.copyStack if len(stack) == 0: self.importPaste() else: self.loadLevel(stack[0]) def saveBrushPreset(self, name): """ Saves current brush presets in a file name.preset :param name, name of the file to store the preset in. """ optionsToSave = {} for key in self.options: if self.options[key].__class__.__name__ == 'Block': optionsToSave[key + 'blockID'] = self.options[key].ID optionsToSave[key + 'blockData'] = self.options[key].blockData saveList = [] if key in self.recentBlocks: blockList = self.recentBlocks[key] for b in blockList: saveList.append((b.ID, b.blockData)) optionsToSave[key + 'recentBlocks'] = saveList elif self.options[key].__class__.__name__ == 'instancemethod': continue else: optionsToSave[key] = self.options[key] optionsToSave["Mode"] = getattr(self, 'selectedBrushMode', 'Fill') name += ".preset" f = open(os.path.join(directories.brushesDir, name), "w") f.write(repr(optionsToSave)) def loadBrushPreset(self, name): """ Loads a brush preset name.preset :param name, name of the preset to load. """ name += '.preset' f = None try: f = open(os.path.join(directories.brushesDir, name), "r") except: alert('Exception while trying to load preset. See console for details.') loadedBrushOptions = ast.literal_eval(f.read()) if f: f.close() brushMode = self.brushModes.get(loadedBrushOptions.get("Mode", None), None) if brushMode is not None: self.selectedBrushMode = loadedBrushOptions["Mode"] self.brushMode = self.brushModes[self.selectedBrushMode] for key in loadedBrushOptions: if key.endswith('blockID'): key = key[:-7] self.options[key] = self.editor.level.materials.blockWithID(loadedBrushOptions[key + 'blockID'], loadedBrushOptions[key + 'blockData']) if key + 'recentBlocks' in loadedBrushOptions: list = [] blockList = loadedBrushOptions[key + 'recentBlocks'] for b in blockList: list.append(self.editor.level.materials.blockWithID(b[0], b[1])) self.recentBlocks[key] = list elif key.endswith('blockData'): continue elif key.endswith('recentBlocks'): continue else: self.options[key] = loadedBrushOptions[key] self.showPanel() self.setupPreview() @property def worldTooltipText(self): """ Displays the corresponding tooltip if ALT is pressed. Called by leveleditor every tick. """ if self.pickBlockKey: try: if self.editor.blockFaceUnderCursor is None: return pos = self.editor.blockFaceUnderCursor[0] blockID = self.editor.level.blockAt(*pos) blockdata = self.editor.level.blockDataAt(*pos) return _("Click to use {0} ({1}:{2})").format(self.editor.level.materials.names[blockID][blockdata], blockID, blockdata) except Exception as e: return repr(e) def keyDown(self, evt): """ Triggered on pressing a key, sets the corresponding variable to True """ keyname = evt.dict.get('keyname', None) or self.root.getKey(evt) if keyname == config.keys.pickBlock.get(): self.pickBlockKey = True if keyname == config.keys.brushLineTool.get(): self.lineToolKey = True def keyUp(self, evt): """ Triggered on releasing a key, sets the corresponding variable to False """ keyname = evt.dict.get('keyname', None) or self.root.getKey(evt) if keyname == config.keys.pickBlock.get(): self.pickBlockKey = False if keyname == config.keys.brushLineTool.get(): self.lineToolKey = False self.draggedPositions = [] @alertException def mouseDown(self, evt, pos, direction): """ Called on pressing the mouseButton. Sets bllockButton if pickBlock is True. Also starts dragging. """ if self.pickBlockKey: id = self.editor.level.blockAt(*pos) data = self.editor.level.blockDataAt(*pos) key = getattr(self.brushMode, 'mainBlock', 'Block') self.options[key] = self.editor.level.materials.blockWithID(id, data) self.showPanel() else: self.draggedDirection = direction point = [p + d * self.reticleOffset for p, d in zip(pos, direction)] self.dragLineToPoint(point) @alertException def mouseDrag(self, evt, pos, _dir): """ Called on dragging the mouse. Adds the current point to draggedPositions. """ if getattr(self.brushMode, 'draggableBrush', True): if len(self.draggedPositions): #If we're dragging the mouse self.lastPosition = lastPoint = self.draggedPositions[-1] direction = self.draggedDirection point = [p + d * self.reticleOffset for p, d in zip(pos, direction)] if any([abs(a - b) >= self.options['Minimum Spacing'] for a, b in zip(point, lastPoint)]): self.dragLineToPoint(point) def dragLineToPoint(self, point): """ Calculates the new point and adds it to self.draggedPositions. Called by mouseDown and mouseDrag """ if getattr(self.brushMode, 'draggableBrush', True): if self.lineToolKey: if len(self.draggedPositions): points = bresenham.bresenham(self.draggedPositions[0], point) self.draggedPositions = [self.draggedPositions[0]] self.draggedPositions.extend(points[::self.options['Minimum Spacing']][1:]) elif self.lastPosition is not None: points = bresenham.bresenham(self.lastPosition, point) self.draggedPositions.extend(points[::self.options['Minimum Spacing']][1:]) else: self.draggedPositions.append(point) else: self.draggedPositions = [point] @alertException def mouseUp(self, evt, pos, direction): """ Called on releasing the Mouse Button. Creates Operation object and passes it to the leveleditor. """ if not self.draggedPositions: return op = BrushOperation(self) self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() self.editor.invalidateBox(op.dirtyBox()) if self.draggedPositions: self.lastPosition = self.draggedPositions[-1] self.draggedPositions = [] def swapBrushStyles(self): """ Swaps the BrushStyleButton to the next Brush Style. Called by pressing BrushStyleButton in panel. """ styles = ["Square", "Round", "Diamond"] brushStyleIndex = styles.index(self.options["Style"]) + 1 brushStyleIndex %= 3 self.options["Style"] = styles[brushStyleIndex] self.setupPreview() def toolReselected(self): """ Called on reselecting the brush. Makes a blockpicker show up for the Main Block of the brush mode. """ if not self.panel: self.toolSelected() key = getattr(self.brushMode, 'mainBlock', 'Block') wcb = getattr(self.brushMode, 'wildcardBlocks', []) aw = (key in wcb) #if key in wcb: # aw = True blockPicker = BlockPicker(self.options[key], self.editor.level.materials, allowWildcards=aw) if blockPicker.present(): self.options[key] = blockPicker.blockInfo self.setupPreview() def showPanel(self): """ Removes old panels. Makes new panel instance and add it to leveleditor. """ if self.panel: self.panel.parent.remove(self.panel) panel = BrushPanel(self) panel.centery = self.editor.centery panel.left = self.editor.left panel.anchor = "lwh" self.panel = panel self.editor.add(panel) def offsetMax(self): """ Sets the Brush Offset (space between face the cursor is pointing at and center of brush. Called by toolSelected if updateBrushOffset is Checked in BrushOptions """ brushSizeOffset = max(self.getBrushSize()) + 1 return max(1, (0.5 * brushSizeOffset)) def resetToolDistance(self): """ Resets the distance of the brush in right-click mode, appropriate to the size of the brush. """ distance = 6 + max(self.getBrushSize()) * 1.25 self.editor.cameraToolDistance = distance def resetToolReach(self): """ Resets reticleOffset or tooldistance in right-click mode. """ if self.editor.mainViewport.mouseMovesCamera and not self.editor.longDistanceMode: self.resetToolDistance() else: self.reticleOffset = self.offsetMax() return True def getBrushSize(self): """ Returns an array of the sizes of the brush. Called by methods that need the size of the brush like createBrushMask """ size = [] if getattr(self.brushMode, 'disableStyleButton', False): return 1, 1, 1 for dim in ['W', 'H', 'L']: size.append(self.options[dim]) return size @alertException def setupPreview(self): """ Creates the Brush Preview Passes it as a FakeLevel object to the renderer Called whenever the preview needs to be recalculated """ brushSize = self.getBrushSize() brushStyle = self.options['Style'] key = getattr(self.brushMode, 'mainBlock', 'Block') blockInfo = self.options[key] class FakeLevel(pymclevel.MCLevel): filename = "Fake Level" materials = self.editor.level.materials root_tag = "Dummy" _gamePlatform = "Unknown" def __init__(self): self.chunkCache = {} Width, Height, Length = brushSize if self.editor.level.gamePlatform == "PE" and self.editor.level.world_version == "1.plus": Height = 16 else: Height = self.editor.level.Height zerolight = numpy.zeros((16, 16, Height), dtype='uint8') zerolight[:] = 15 def getChunk(self, cx, cz): if (cx, cz) in self.chunkCache: return self.chunkCache[cx, cz] class FakeBrushChunk(pymclevel.level.FakeChunk): Entities = [] TileEntities = [] f = FakeBrushChunk() f.world = self f.chunkPosition = (cx, cz) mask = createBrushMask(brushSize, brushStyle, (0, 0, 0), BoundingBox((cx << 4, 0, cz << 4), (16, self.Height, 16))) f.Blocks = numpy.zeros(mask.shape, dtype='uint8') f.Data = numpy.zeros(mask.shape, dtype='uint8') f.BlockLight = self.zerolight f.SkyLight = self.zerolight if blockInfo.ID: f.Blocks[mask] = blockInfo.ID f.Data[mask] = blockInfo.blockData else: f.Blocks[mask] = 255 self.chunkCache[cx, cz] = f return f self.level = FakeLevel() CloneTool.setupPreview(self, alpha=self.settings['brushAlpha']) def getReticlePoint(self, pos, direction): """ Calculates the position of the reticle. Called by drawTerrainReticle. """ if self.draggedPositions: direction = self.draggedDirection return map(lambda a, b: a + (b * self.reticleOffset), pos, direction) def increaseToolReach(self): """ Called on scrolling up (default). Increases the reticleOffset (distance between face and brush center) by 1. (unless you're in right-click mode and don't have long-distance mode enabled) """ if self.editor.mainViewport.mouseMovesCamera and not self.editor.longDistanceMode: return False self.reticleOffset += 1 return True def decreaseToolReach(self): """ Called on scrolling down (default). Decreases the reticleOffset (distance between face and brush center) by 1. (unless you're in right-click mode and don't have long-distance mode enabled) """ if self.editor.mainViewport.mouseMovesCamera and not self.editor.longDistanceMode: return False self.reticleOffset = max(self.reticleOffset - 1, 0) return True def drawToolReticle(self): """ Draws a yellow reticle at every position where you dragged the brush. Called by leveleditor.render """ for pos in self.draggedPositions: drawTerrainCuttingWire(BoundingBox(pos, (1, 1, 1)), (0.75, 0.75, 0.1, 0.4), (1.0, 1.0, 0.5, 1.0)) def getDirtyBox(self, point, tool): """ Returns a box around the Brush given point and size of the brush. """ if hasattr(self.brushMode, 'createDirtyBox'): return self.brushMode.createDirtyBox(self.brushMode, point, tool) else: size = tool.getBrushSize() origin = map(lambda x, s: x - (s >> 1), point, size) return BoundingBox(origin, size) def drawTerrainReticle(self): """ Draws the white reticle where the cursor is pointing. Called by leveleditor.render """ if self.optionBackup != self.options: self.saveBrushPreset('__temp__') self.optionBackup = copy.copy(self.options) if not hasattr(self, 'brushMode'): return if self.options[getattr(self.brushMode, 'mainBlock', 'Block')] != self.renderedBlock and not getattr(self.brushMode, 'addPasteButton', False): self.setupPreview() self.renderedBlock = self.options[getattr(self.brushMode, 'mainBlock', 'Block')] if self.pickBlockKey == 1: #Alt is pressed self.editor.drawWireCubeReticle(color=(0.2, 0.6, 0.9, 1.0)) else: pos, direction = self.editor.blockFaceUnderCursor reticlePoint = self.getReticlePoint(pos, direction) self.editor.drawWireCubeReticle(position=reticlePoint) if reticlePoint != pos: GL.glColor4f(1.0, 1.0, 0.0, 0.7) with gl.glBegin(GL.GL_LINES): GL.glVertex3f(*[a + 0.5 for a in reticlePoint]) #Center of reticle block GL.glVertex3f(*map(lambda a, b: a + 0.5 + b * 0.5, pos, direction)) #Top side of surface block dirtyBox = self.getDirtyBox(reticlePoint, self) self.drawTerrainPreview(dirtyBox.origin) if self.lineToolKey and self.lastPosition and getattr(self.brushMode, 'draggableBrush', True): #If dragging mouse with Linetool pressed. GL.glColor4f(1.0, 1.0, 1.0, 0.7) with gl.glBegin(GL.GL_LINES): GL.glVertex3f(*[a + 0.5 for a in self.lastPosition]) GL.glVertex3f(*[a + 0.5 for a in reticlePoint]) def decreaseBrushSize(self): """ Increases Brush Size, triggered by pressing corresponding key. """ for key in ('W', 'H', 'L'): self.options[key] = max(self.options[key] - 1, 0) self.setupPreview() def increaseBrushSize(self): """ Decreases Brush Size, triggered by pressing corresponding key. """ for key in ('W', 'H', 'L'): self.options[key] += 1 self.setupPreview() def swap(self, amount=1): main = getattr(self.brushMode, 'mainBlock', 'Block') secondary = getattr(self.brushMode, 'secondaryBlock', 'Block To Replace With') bi = self.options[main] self.options[main] = self.options[secondary] self.options[secondary] = bi self.showPanel() def rotate(self, amount=1, blocksOnly=False): """ Rotates the brush. :keyword blocksOnly: Also rotate the data value of the block we're brushing with. """ def rotateBlock(): list = [key for key in self.options if isinstance(self.options[key], Block)] list = getattr(self.brushMode, 'rotatableBlocks', list) for key in list: bl = self.options[key] data = [[[bl.blockData]]] blockrotation.RotateLeft([[[bl.ID]]], data) bl.blockData = data[0][0][0] self.showPanel() if config.settings.rotateBlockBrush.get() or blocksOnly: rotateBlock() if not blocksOnly: W = self.options['W'] self.options['W'] = self.options['L'] self.options['L'] = W self.setupPreview() def roll(self, amount=1, blocksOnly=False): """ Rolls the brush. :keyword blocksOnly: Also roll the data value of the block we're brushing with. """ def rollBlock(): list = [key for key in self.options if self.options[key].__class__.__name__ == 'Block'] # TODO Pod list = getattr(self.brushMode, 'rotatableBlocks', list) for key in list: bl = self.options[key] data = [[[bl.blockData]]] blockrotation.Roll([[[bl.ID]]], data) bl.blockData = data[0][0][0] self.showPanel() if config.settings.rotateBlockBrush.get() or blocksOnly: rollBlock() if not blocksOnly: H = self.options['H'] self.options['H'] = self.options['W'] self.options['W'] = H self.setupPreview() 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 loadLevel(self, level): self.level = level self.options['Minimum Spacing'] = min([s / 4 for s in level.size]) CloneTool.setupPreview(self, alpha = self.settings['brushAlpha']) def createBrushMask(shape, style="Round", offset=(0, 0, 0), box=None, chance=100, hollow=False): """ Return a boolean array for a brush with the given shape and style. If 'offset' and 'box' are given, then the brush is offset into the world and only the part of the world contained in box is returned as an array. :param shape, UNKWOWN :param style, style of the brush. Round if not given. :param offset, UNKWOWN :param box, UNKWOWN :param chance, also known as Noise. Input in stock-brushes like Fill and Replace. :param hollow, input to calculate a hollow brush. """ #We are returning indices for a Blocks array, so swap axes if box is None: box = BoundingBox(offset, shape) if chance < 100 or hollow: box = box.expand(1) outputShape = box.size outputShape = (outputShape[0], outputShape[2], outputShape[1]) shape = shape[0], shape[2], shape[1] offset = numpy.array(offset) - numpy.array(box.origin) offset = offset[[0, 2, 1]] inds = numpy.indices(outputShape, dtype=float) halfshape = numpy.array([(i >> 1) - ((i & 1 == 0) and 0.5 or 0) for i in shape]) blockCenters = inds - halfshape[:, newaxis, newaxis, newaxis] blockCenters -= offset[:, newaxis, newaxis, newaxis] # odd diameter means measure from the center of the block at 0,0,0 to each block center # even diameter means measure from the 0,0,0 grid point to each block center # if diameter & 1 == 0: blockCenters += 0.5 shape = numpy.array(shape, dtype='float32') # if not isSphere(shape): if style == "Round": blockCenters *= blockCenters shape /= 2 shape *= shape blockCenters /= shape[:, newaxis, newaxis, newaxis] distances = sum(blockCenters, 0) mask = distances < 1 elif style == "Cylinder": pass elif style == "Square": blockCenters /= shape[:, None, None, None] distances = numpy.absolute(blockCenters).max(0) mask = distances < .5 elif style == "Diamond": blockCenters = numpy.abs(blockCenters) shape /= 2 blockCenters /= shape[:, newaxis, newaxis, newaxis] distances = sum(blockCenters, 0) mask = distances < 1 else: raise ValueError("Unknown style: " + style) if (chance < 100 or hollow) and max(shape) > 1: threshold = chance / 100.0 exposedBlockMask = numpy.ones(shape=outputShape, dtype='bool') exposedBlockMask[:] = mask submask = mask[1:-1, 1:-1, 1:-1] exposedBlockSubMask = exposedBlockMask[1:-1, 1:-1, 1:-1] exposedBlockSubMask[:] = False for dim in (0, 1, 2): slices = [slice(1, -1), slice(1, -1), slice(1, -1)] slices[dim] = slice(None, -2) exposedBlockSubMask |= (submask & (mask[slices] != submask)) slices[dim] = slice(2, None) exposedBlockSubMask |= (submask & (mask[slices] != submask)) if hollow: mask[~exposedBlockMask] = False if chance < 100: rmask = numpy.random.random(mask.shape) < threshold mask[exposedBlockMask] = rmask[exposedBlockMask] if chance < 100 or hollow: return mask[1:-1, 1:-1, 1:-1] else: return mask def createTileEntities(block, box, chunk, defsIds=None): # If defIds is not None, it must be an instance of pymclevel.id_definitions.MCEditDefsIds. # Every Level instance has such an object attached as defsIds. if box is None or block.stringID not in TileEntity.stringNames.keys(): return tileEntity = TileEntity.stringNames[block.stringID] for (x, y, z) in box.positions: if chunk.world.blockAt(x, y, z) == block.ID: if chunk.tileEntityAt(x, y, z): chunk.removeTileEntitiesInBox(BoundingBox((x, y, z), (1, 1, 1))) tileEntityObject = TileEntity.Create(tileEntity, (x, y, z), defsIds=defsIds) chunk.TileEntities.append(tileEntityObject) chunk._fakeEntities = None
46,244
38.593322
170
py
MCEdit-Unified
MCEdit-Unified-master/editortools/thumbview.py
from OpenGL import GLU, GL from numpy import array from albow import Widget from albow.openglwidgets import GLPerspective from glutils import FramebufferTexture, gl import pymclevel from renderer import PreviewRenderer class ThumbView(GLPerspective): def __init__(self, sch, **kw): GLPerspective.__init__(self, **kw) # self, xmin= -32, xmax=32, ymin= -32, ymax=32, near= -1000, far=1000) self.p_margin = 0 self.p_spacing = 0 self.widget_index = 0 self.set_position_modifiers() self.far = 16000 self.schematic = sch self.renderer = PreviewRenderer(sch) self.fboSize = (128, 128) self.root = self.get_root() # self.renderer.position = (sch.Length / 2, 0, sch.Height / 2) def set_position_modifiers(self): if getattr(self, 'parent', None) is not None: self.p_margin = getattr(self.parent, 'margin', 0) self.p_spacing = getattr(self.parent, 'spacing', 0) if hasattr(self.parent, 'subwidgets') and self in self.parent.subwidgets: self.widget_index = self.parent.subwidgets.index(self) def setup_modelview(self): GLU.gluLookAt(-self.schematic.Width * 2.8, self.schematic.Height * 2.5 + 1, -self.schematic.Length * 1.5, self.schematic.Width, 0, self.schematic.Length, 0, 1, 0) fbo = None def gl_draw_tex(self): self.clear() self.renderer.draw() def clear(self): if self.drawBackground: GL.glClearColor(0.25, 0.27, 0.77, 1.0) else: GL.glClearColor(0.0, 0.0, 0.0, 0.0) GL.glClear(GL.GL_DEPTH_BUFFER_BIT | GL.GL_COLOR_BUFFER_BIT) def gl_draw(self): if self.schematic.chunkCount > len(self.renderer.chunkRenderers): self.gl_draw_thumb() else: if self.fbo is None: w, h = self.fboSize self.fbo = FramebufferTexture(w, h, self.gl_draw_tex) GL.glMatrixMode(GL.GL_PROJECTION) GL.glLoadIdentity() GL.glMatrixMode(GL.GL_MODELVIEW) GL.glLoadIdentity() GL.glEnableClientState(GL.GL_TEXTURE_COORD_ARRAY) GL.glColor(1.0, 1.0, 1.0, 1.0) GL.glVertexPointer(2, GL.GL_FLOAT, 0, array([-1, -1, - 1, 1, 1, 1, 1, -1, ], dtype='float32')) GL.glTexCoordPointer(2, GL.GL_FLOAT, 0, array([0, 0, 0, 256, 256, 256, 256, 0], dtype='float32')) e = (GL.GL_TEXTURE_2D,) if not self.drawBackground: e += (GL.GL_ALPHA_TEST,) with gl.glEnable(*e): self.fbo.bind() GL.glDrawArrays(GL.GL_QUADS, 0, 4) GL.glDisableClientState(GL.GL_TEXTURE_COORD_ARRAY) drawBackground = True def gl_draw_thumb(self): GL.glPushAttrib(GL.GL_SCISSOR_BIT) r = self.rect x, y = self.local_to_global_offset() self.set_position_modifiers() if hasattr(self.parent, 'axis'): s_sz = 0 if self.widget_index > 0: s_sz = getattr(self.parent.subwidgets[self.widget_index - 1], self.parent.longways, 0) #-# Do we have a bad hack or the real solution with `(self.parent.height - self.height) / 2 + 1` stuff? #-# Need extensive tests to confirm... if self.parent.axis == 'h': r = r.move(x + (self.parent.height - self.height) / 2 + 1 + self.p_margin - self.p_spacing - s_sz, y - (self.parent.height - self.height) / 2) else: r = r.move(x - (self.parent.width - self.height) / 2, y - (self.parent.width - self.height) / 2 + 1 + self.p_margin - self.p_spacing - s_sz) else: r = r.move(*self.local_to_global_offset()) GL.glScissor(r.x, self.root.height - r.y - r.height, r.width, r.height) with gl.glEnable(GL.GL_SCISSOR_TEST): self.clear() self.renderer.draw() GL.glPopAttrib() class BlockThumbView(Widget): is_gl_container = True def __init__(self, materials, blockInfo=None, **kw): Widget.__init__(self, **kw) self.materials = materials self.blockInfo = blockInfo thumb = None _blockInfo = None @property def blockInfo(self): return self._blockInfo @blockInfo.setter def blockInfo(self, b): if self._blockInfo != b: if self.thumb: self.thumb.set_parent(None) self._blockInfo = b if b is None: return sch = pymclevel.MCSchematic(shape=(1, 1, 1), mats=self.materials) if b: sch.Blocks[:] = b.ID sch.Data[:] = b.blockData self.thumb = ThumbView(sch) self.add(self.thumb) self.thumb.size = self.size self.thumb.drawBackground = False for _ in self.thumb.renderer.chunkWorker: pass
5,153
36.897059
158
py
MCEdit-Unified
MCEdit-Unified-master/editortools/clone.py
"""Copyright (c) 2010-2012 David Rio Vierra Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.""" #-# Modified by D.C.-G. for translation purpose import os import traceback from OpenGL import GL import numpy from albow import Widget, IntField, Column, Row, Label, Button, CheckBox, AttrRef, FloatField, alert, CheckBoxLabel, IntInputRow, \ showProgress from albow.translate import _ from depths import DepthOffset from editortools.editortool import EditorTool from editortools.nudgebutton import NudgeButton from editortools.tooloptions import ToolOptions from glbackground import Panel from glutils import gl from mceutils import setWindowCaption, alertException, drawFace import mcplatform from operation import Operation import pymclevel from pymclevel.box import Vector from renderer import PreviewRenderer import pygame from select import SelectionOperation from pymclevel.pocket import PocketWorld from pymclevel.leveldbpocket import PocketLeveldbWorld from pymclevel import block_copy, BoundingBox, BOParser import logging log = logging.getLogger(__name__) from config import config from albow.root import get_root class CoordsInput(Widget): is_gl_container = True def __init__(self, editor): Widget.__init__(self) self.nudgeButton = NudgeButton(editor) self.nudgeButton.nudge = self._nudge self.xField = IntField(value=0) self.yField = IntField(value=0) self.zField = IntField(value=0) for field in (self.xField, self.yField, self.zField): field.change_action = self._coordsChanged field.enter_passes = False offsetCol = Column((Row((Label('X'), self.xField)), Row((Label('Y'), self.yField)), Row((Label('Z'), self.zField)))) nudgeOffsetRow = Row((offsetCol, self.nudgeButton)) self.add(nudgeOffsetRow) self.shrink_wrap() def getCoords(self): return self.xField.value, self.yField.value, self.zField.value def setCoords(self, coords): x, y, z = coords self.xField.text = str(x) self.yField.text = str(y) self.zField.text = str(z) coords = property(getCoords, setCoords, None) def _coordsChanged(self): self.coordsChanged() def coordsChanged(self): # called when the inputs change. override or replace pass def _nudge(self, nudge): self.nudge(nudge) def nudge(self, nudge): # nudge is a 3-tuple where one of the elements is -1 or 1, and the others are 0. pass class BlockCopyOperation(Operation): def __init__(self, editor, sourceLevel, sourceBox, destLevel, destPoint, copyAir, copyWater, copyBiomes, staticCommands, moveSpawnerPos, regenerateUUID): super(BlockCopyOperation, self).__init__(editor, destLevel) self.sourceLevel = sourceLevel self.sourceBox = sourceBox self.destPoint = Vector(*destPoint) self.copyAir = copyAir self.copyWater = copyWater self.copyBiomes = copyBiomes self.staticCommands = staticCommands self.moveSpawnerPos = moveSpawnerPos self.regenerateUUID = regenerateUUID self.sourceBox, self.destPoint = block_copy.adjustCopyParameters(self.level, self.sourceLevel, self.sourceBox, self.destPoint) self.canUndo = False def dirtyBox(self): return BoundingBox(self.destPoint, self.sourceBox.size) def name(self): return _("Copy {0} blocks").format(self.sourceBox.volume) def perform(self, recordUndo=True): if self.level.saving: alert(_("Cannot perform action while saving is taking place")) return if recordUndo: self.canUndo = True self.undoLevel = self.extractUndo(self.level, BoundingBox(self.destPoint, self.sourceBox.size)) blocksToCopy = None if not (self.copyAir and self.copyWater): blocksToCopy = range(pymclevel.materials.id_limit) if not self.copyAir: blocksToCopy.remove(0) if not self.copyWater: blocksToCopy.remove(8) if not self.copyWater: blocksToCopy.remove(9) with setWindowCaption("Copying - "): i = self.level.copyBlocksFromIter(self.sourceLevel, self.sourceBox, self.destPoint, blocksToCopy, create=True, biomes=self.copyBiomes, staticCommands=self.staticCommands, moveSpawnerPos=self.moveSpawnerPos, regenerateUUID=self.regenerateUUID, first=False) showProgress(_("Copying {0:n} blocks...").format(self.sourceBox.volume), i) @staticmethod def bufferSize(): return 123456 class CloneOperation(Operation): def __init__(self, editor, sourceLevel, sourceBox, originSourceBox, destLevel, destPoint, copyAir, copyWater, copyBiomes, staticCommands, moveSpawnerPos, regenerateUUID, repeatCount): super(CloneOperation, self).__init__(editor, destLevel) self.blockCopyOps = [] dirtyBoxes = [] if repeatCount > 1: # clone tool only delta = destPoint - editor.toolbar.tools[0].selectionBox().origin else: delta = (0, 0, 0) for i in xrange(repeatCount): op = BlockCopyOperation(editor, sourceLevel, sourceBox, destLevel, destPoint, copyAir, copyWater, copyBiomes, staticCommands, moveSpawnerPos, regenerateUUID) dirty = op.dirtyBox() # bounds check - xxx move to BoundingBox if dirty.miny >= destLevel.Height or dirty.maxy < 0: continue if destLevel.Width != 0: if dirty.minx >= destLevel.Width or dirty.maxx < 0: continue if dirty.minz >= destLevel.Length or dirty.maxz < 0: continue dirtyBoxes.append(dirty) self.blockCopyOps.append(op) destPoint += delta if len(dirtyBoxes): def enclosingBox(dirtyBoxes): return reduce(lambda a, b: a.union(b), dirtyBoxes) self._dirtyBox = enclosingBox(dirtyBoxes) if repeatCount > 1 and self.selectOriginalAfterRepeat: dirtyBoxes.append(originSourceBox) dirty = enclosingBox(dirtyBoxes) points = (dirty.origin, dirty.maximum - (1, 1, 1)) self.selectionOps = [SelectionOperation(editor.selectionTool, points)] else: self._dirtyBox = None self.selectionOps = [] self.canUndo = False selectOriginalAfterRepeat = True def dirtyBox(self): return self._dirtyBox def perform(self, recordUndo=True): if self.level.saving: alert(_("Cannot perform action while saving is taking place")) return with setWindowCaption("COPYING - "): self.editor.freezeStatus(_("Copying %0.1f million blocks") % (float(self._dirtyBox.volume) / 1048576.,)) if recordUndo: chunks = set() for op in self.blockCopyOps: chunks.update(op.dirtyBox().chunkPositions) self.undoLevel = self.extractUndoChunks(self.level, chunks) [i.perform(False) for i in self.blockCopyOps] [i.perform(recordUndo) for i in self.selectionOps] self.canUndo = True def undo(self): super(CloneOperation, self).undo() [i.undo() for i in self.selectionOps] def redo(self): super(CloneOperation, self).redo() [i.redo() for i in self.selectionOps] class CloneToolPanel(Panel): useOffsetInput = True def transformEnable(self): return not isinstance(self.tool.level, pymclevel.MCInfdevOldLevel) def __init__(self, tool, editor, _parent=None): Panel.__init__(self, name='Panel.CloneToolPanel') self.tool = tool rotaterollRow = Row(( Label(config.keys.rotateClone.get()), Button("Rotate", width=80, action=tool.rotate, enable=self.transformEnable), Label(config.keys.rollClone.get()), Button("Roll", width=80, action=tool.roll, enable=self.transformEnable), )) flipmirrorRow = Row(( Label(config.keys.flip.get()), Button("Flip", width=80, action=tool.flip, enable=self.transformEnable), Label(config.keys.mirror.get()), Button("Mirror", width=80, action=tool.mirror, enable=self.transformEnable), )) self.alignCheckBox = CheckBox(ref=AttrRef(self.tool, 'chunkAlign')) self.alignLabel = Label("Chunk Align") self.alignLabel.mouse_down = self.alignCheckBox.mouse_down alignRow = Row(( self.alignCheckBox, self.alignLabel )) # headerLabel = Label("Clone Offset") if self.useOffsetInput: self.offsetInput = CoordsInput(editor) self.offsetInput.coordsChanged = tool.offsetChanged self.offsetInput.nudgeButton.bg_color = tool.color self.offsetInput.nudge = tool.nudge else: self.nudgeButton = NudgeButton(editor) self.nudgeButton.bg_color = tool.color self.nudgeButton.nudge = tool.nudge repeatField = IntField(ref=AttrRef(tool, 'repeatCount')) repeatField.min = 1 repeatField.max = 1000 repeatRow = Row(( Label("Repeat"), repeatField )) self.repeatField = repeatField scaleField = FloatField(ref=AttrRef(tool, 'scaleFactor')) scaleField.min = 0.1 scaleField.max = 8 if self.transformEnable(): scaleRow = Row(( Label("Scale Factor"), scaleField )) else: scaleRow = Row(( Label("Scale Factor: 1.0"), )) self.scaleField = scaleField self.copyAirCheckBox = CheckBox(ref=AttrRef(self.tool, "copyAir")) self.copyAirLabel = Label("Copy Air") self.copyAirLabel.mouse_down = self.copyAirCheckBox.mouse_down self.copyAirLabel.tooltipText = "Shortcut: Alt-1" self.copyAirCheckBox.tooltipText = self.copyAirLabel.tooltipText copyAirRow = Row((self.copyAirCheckBox, self.copyAirLabel)) self.copyWaterCheckBox = CheckBox(ref=AttrRef(self.tool, "copyWater")) self.copyWaterLabel = Label("Copy Water") self.copyWaterLabel.mouse_down = self.copyWaterCheckBox.mouse_down self.copyWaterLabel.tooltipText = "Shortcut: Alt-2" self.copyWaterCheckBox.tooltipText = self.copyWaterLabel.tooltipText copyWaterRow = Row((self.copyWaterCheckBox, self.copyWaterLabel)) self.copyBiomesCheckBox = CheckBox(ref=AttrRef(self.tool, "copyBiomes")) self.copyBiomesLabel = Label("Copy Biome(s)") self.copyBiomesLabel.mouse_down = self.copyBiomesCheckBox.mouse_down self.copyBiomesLabel.tooltipText = "Shortcut: Alt-3" self.copyBiomesCheckBox.tooltipText = self.copyBiomesLabel.tooltipText copyBiomesRow = Row((self.copyBiomesCheckBox, self.copyBiomesLabel)) self.staticCommandsCheckBox = CheckBox(ref=AttrRef(self.tool, "staticCommands")) self.staticCommandsLabel = Label("Update Command Block Coords") self.staticCommandsLabel.mouse_down = self.staticCommandsCheckBox.mouse_down self.staticCommandsLabel.tooltipText = "When a command block is moved, and it contains a command, automatically update static coordinates (x y z) within that command.\nShortcut: Alt-4" self.staticCommandsCheckBox.tooltipText = self.staticCommandsLabel.tooltipText staticCommandsRow = Row((self.staticCommandsCheckBox, self.staticCommandsLabel)) self.moveSpawnerPosCheckBox = CheckBox(ref=AttrRef(self.tool, "moveSpawnerPos")) self.moveSpawnerPosLabel = Label("Update Spawner Coords") self.moveSpawnerPosLabel.mouse_down = self.moveSpawnerPosCheckBox.mouse_down self.moveSpawnerPosLabel.tooltipText = "When a spawner is moved, automatically update its spawning coordinates.\nShortcut: Alt-5" self.moveSpawnerPosCheckBox.tooltipText = self.moveSpawnerPosLabel.tooltipText moveSpawnerPosRow = Row((self.moveSpawnerPosCheckBox, self.moveSpawnerPosLabel)) self.regenerateUUIDCheckBox = CheckBox(ref=AttrRef(self.tool, "regenerateUUID")) self.regenerateUUIDLabel = Label("Regenerate Entity UUID") self.regenerateUUIDLabel.mouse_down = self.regenerateUUIDCheckBox.mouse_down self.regenerateUUIDLabel.tooltipText = "Automatically generate new UUIDs for every entity copied. [RECOMMENDED]\nShortcut: Alt-6" self.regenerateUUIDCheckBox.tooltipText = self.regenerateUUIDLabel.tooltipText regenerateUUIDRow = Row((self.regenerateUUIDCheckBox, self.regenerateUUIDLabel)) self.performButton = Button("Clone", width=100, align="c") self.performButton.tooltipText = "Shortcut: Enter" self.performButton.action = tool.confirm self.performButton.enable = lambda: (tool.destPoint is not None) max_height = self.tool.editor.mainViewport.height - self.tool.editor.toolbar.height - self.tool.editor.subwidgets[0].height # - self.performButton.height - 2 def buildPage(*items): height = 0 cls = [] idx = 0 for i, r in enumerate(items): r.margin=0 r.shrink_wrap() height += r.height if height > max_height: cls.append(Column(items[idx:i], spacing=2, margin=0)) idx = i height = 0 cls.append(Column(items[idx:], spacing=2, margin=0)) return cls if self.useOffsetInput: cols = buildPage(rotaterollRow, flipmirrorRow, alignRow, self.offsetInput, repeatRow, scaleRow, copyAirRow, copyWaterRow, copyBiomesRow, staticCommandsRow, moveSpawnerPosRow, regenerateUUIDRow) else: cols = buildPage(rotaterollRow, flipmirrorRow, alignRow, self.nudgeButton, scaleRow, copyAirRow, copyWaterRow, copyBiomesRow, staticCommandsRow, moveSpawnerPosRow, regenerateUUIDRow) row = Row(cols, spacing=0, margin=2) row.shrink_wrap() col = Column((row, self.performButton), spacing=2) self.add(col) self.anchor = "lwh" self.shrink_wrap() class CloneToolOptions(ToolOptions): def __init__(self, tool): ToolOptions.__init__(self, name='Panel.CloneToolOptions') self.tool = tool self.autoPlaceCheckBox = CheckBox(ref=AttrRef(tool, "placeImmediately")) self.autoPlaceLabel = Label("Place Immediately") self.autoPlaceLabel.mouse_down = self.autoPlaceCheckBox.mouse_down tooltipText = "When the clone tool is chosen, place the clone at the selection right away." self.autoPlaceLabel.tooltipText = self.autoPlaceCheckBox.tooltipText = tooltipText spaceLabel = Label("") cloneNudgeLabel = Label("Clone Fast Nudge Settings") cloneNudgeCheckBox = CheckBoxLabel("Move by the width of selection ", ref=config.fastNudgeSettings.cloneWidth, tooltipText="Moves clone by his width") cloneNudgeNumber = IntInputRow("Width of clone movement: ", ref=config.fastNudgeSettings.cloneWidthNumber, width=100, min=2, max=50) row = Row((self.autoPlaceCheckBox, self.autoPlaceLabel)) col = Column((Label("Clone Options"), row, spaceLabel, cloneNudgeLabel, cloneNudgeCheckBox, cloneNudgeNumber, Button("OK", action=self.dismiss))) self.add(col) self.shrink_wrap() class CloneTool(EditorTool): surfaceBuild = True toolIconName = "clone" tooltipText = "Clone\nRight-click for options" level = None repeatCount = 1 _scaleFactor = 1.0 _chunkAlign = False @property def scaleFactor(self): return self._scaleFactor @scaleFactor.setter def scaleFactor(self, val): self.rescaleLevel(val) self._scaleFactor = val @property def chunkAlign(self): return self._chunkAlign @chunkAlign.setter def chunkAlign(self, value): self._chunkAlign = value self.alignDestPoint() def alignDestPoint(self): if self.destPoint is not None: x, y, z = self.destPoint self.destPoint = Vector((x >> 4) << 4, y, (z >> 4) << 4) placeImmediately = config.clone.placeImmediately.property() panelClass = CloneToolPanel color = (0.3, 1.0, 0.3, 0.19) def __init__(self, *args): self.rotation = 0 EditorTool.__init__(self, *args) self.previewRenderer = None self.panel = None self.optionsPanel = CloneToolOptions(self) self.destPoint = None self.snapCloneKey = 0 self.root = get_root() @property def statusText(self): if self.destPoint is None: return "Click to set this item down." if self.draggingFace is not None: return _("Mousewheel to move along the third axis. Hold {0} to only move along one axis.").format(_(config.keys.snapCloneToAxis.get())) return "Click and drag to reposition the item. Double-click to pick it up. Click Clone or press Enter to confirm." def quickNudge(self, nudge): if config.fastNudgeSettings.cloneWidth.get(): return map(int.__mul__, nudge, self.selectionBox().size) nudgeWidth = config.fastNudgeSettings.cloneWidthNumber.get() return map(lambda x: x * nudgeWidth, nudge) copyAir = config.clone.copyAir.property() copyWater = config.clone.copyWater.property() copyBiomes = config.clone.copyBiomes.property() staticCommands = config.clone.staticCommands.property() moveSpawnerPos = config.clone.moveSpawnerPos.property() regenerateUUID = config.clone.regenerateUUID.property() def nudge(self, nudge): if self.destPoint is None: if self.selectionBox() is None: return self.destPoint = self.selectionBox().origin if self.chunkAlign: x, y, z = nudge nudge = x << 4, y, z << 4 if self.editor.rightClickNudge: nudge = self.quickNudge(nudge) # self.panel.performButton.enabled = True self.destPoint = self.destPoint + nudge self.updateOffsets() def selectionChanged(self): if self.selectionBox() is not None and "CloneToolPanel" in str(self.panel): self.updateSchematic() self.updateOffsets() def updateOffsets(self): if self.panel and self.panel.useOffsetInput and self.destPoint is not None: self.panel.offsetInput.setCoords(self.destPoint - self.selectionBox().origin) def offsetChanged(self): if self.panel: if not self.panel.useOffsetInput: return box = self.selectionBox() if box is None: return delta = self.panel.offsetInput.coords self.destPoint = box.origin + delta def toolEnabled(self): return not (self.selectionBox() is None) def cancel(self): self.discardPreviewer() if self.panel: self.panel.parent.remove(self.panel) self.panel = None self.destPoint = None self.level = None self.originalLevel = None def toolReselected(self): self.pickUp() def safeToolDistance(self): return numpy.sqrt(sum([self.level.Width ** 2, self.level.Height ** 2, self.level.Length ** 2])) def toolSelected(self): box = self.selectionBox() if box is None: self.editor.toolbar.selectTool(-1) return if box.volume > self.maxBlocks: self.editor.mouseLookOff() alert(_("Selection exceeds {0:n} blocks. Increase the block buffer setting and try again.").format( self.maxBlocks)) self.editor.toolbar.selectTool(-1) return self.rotation = 0 self.repeatCount = 1 self._scaleFactor = 1.0 if self.placeImmediately: self.destPoint = box.origin else: self.destPoint = None self.updateSchematic() self.cloneCameraDistance = max(self.cloneCameraDistance, self.safeToolDistance()) self.showPanel() cloneCameraDistance = 0 @property def cameraDistance(self): return self.cloneCameraDistance @alertException def rescaleLevel(self, factor): if factor == 1: self.level = self.originalLevel self.setupPreview() return oldshape = self.originalLevel.Blocks.shape blocks = self.originalLevel.Blocks data = self.originalLevel.Data roundedShape = oldshape newshape = map(lambda x: int(x * factor), oldshape) for i, part in enumerate(newshape): if part == 0: newshape[i] = 1 xyzshape = newshape[0], newshape[2], newshape[1] newlevel = pymclevel.MCSchematic(xyzshape, mats=self.editor.level.materials) srcgrid = numpy.mgrid[0:roundedShape[0]:1.0 / factor, 0:roundedShape[1]:1.0 / factor, 0:roundedShape[2]:1.0 / factor].astype('uint') dstgrid = numpy.mgrid[0:newshape[0], 0:newshape[1], 0:newshape[2]].astype('uint') srcgrid = srcgrid[map(slice, dstgrid.shape)] dstgrid = dstgrid[map(slice, srcgrid.shape)] def copyArray(dest, src): dest[dstgrid[0], dstgrid[1], dstgrid[2]] = src[srcgrid[0], srcgrid[1], srcgrid[2]] copyArray(newlevel.Blocks, blocks) copyArray(newlevel.Data, data) self.level = newlevel self.setupPreview() @alertException def updateSchematic(self): # extract blocks with setWindowCaption("COPYING - "): self.editor.freezeStatus("Copying to clone buffer...") box = self.selectionBox() self.level = self.editor.level.extractSchematic(box) self.originalLevel = self.level # self.level.cloneToolScaleFactor = 1.0 self.rescaleLevel(self.scaleFactor) self.setupPreview() def showPanel(self): if self.panel: self.panel.set_parent(None) self.panel = self.panelClass(self, self.editor) self.panel.centery = (self.editor.mainViewport.height - self.editor.toolbar.height) / 2 + self.editor.subwidgets[0].height self.panel.left = self.editor.left self.editor.add(self.panel) def setupPreview(self, alpha=1.0): self.discardPreviewer() if self.level: self.previewRenderer = PreviewRenderer(self.level, alpha) self.previewRenderer.position = self.editor.renderer.position self.editor.addWorker(self.previewRenderer) else: self.editor.toolbar.selectTool(-1) @property def canRotateLevel(self): return not isinstance(self.level, (pymclevel.MCInfdevOldLevel, PocketWorld, PocketLeveldbWorld)) def rotatedSelectionSize(self): if self.canRotateLevel: sizes = self.level.Blocks.shape return sizes[0], sizes[2], sizes[1] else: return self.level.size # =========================================================================== # def getSelectionRanges(self): # return self.editor.selectionTool.selectionBox() # # =========================================================================== @staticmethod def getBlockAt(): return None # use level's blockAt def getReticleOrigin(self): # returns a new origin for the current selection, where the old origin is at the new selection's center. pos, direction = self.editor.blockFaceUnderCursor lev = self.editor.level size = self.rotatedSelectionSize() if not size: return if size[1] >= self.editor.level.Height: direction = ( 0, 1, 0) # always use the upward face whenever we're splicing full-height pieces, to avoid "jitter" # print size; raise SystemExit if any(direction) and pos[1] >= 0: x, y, z = map(lambda p, s, d: p - s / 2 + s * d / 2 + (d > 0), pos, size, direction) else: x, y, z = map(lambda p, s: p - s / 2, pos, size) if self.chunkAlign: x &= ~0xf z &= ~0xf sy = size[1] if sy > lev.Height: # don't snap really tall stuff to the height return Vector(x, y, z) if y + sy > lev.Height: y = lev.Height - sy if y < 0: y = 0 if not lev.Width == 0 and lev.Length == 0: sx = size[0] if x + sx > lev.Width: x = lev.Width - sx if x < 0: x = 0 sz = size[2] if z + sz > lev.Length: z = lev.Length - sz if z < 0: z = 0 return Vector(x, y, z) def getReticleBox(self): pos = self.getReticleOrigin() sizes = self.rotatedSelectionSize() if sizes is None: return return BoundingBox(pos, sizes) def getDestBox(self): selectionSize = self.rotatedSelectionSize() return BoundingBox(self.destPoint, selectionSize) def drawTerrainReticle(self): if self.level is None: return if self.destPoint is not None: destPoint = self.destPoint if self.draggingFace is not None: # debugDrawPoint() destPoint = self.draggingOrigin() self.drawTerrainPreview(destPoint) else: self.drawTerrainPreview(self.getReticleBox().origin) draggingColor = (0.77, 1.0, 0.55, 0.05) def drawToolReticle(self): if self.level is None: return GL.glPolygonOffset(DepthOffset.CloneMarkers, DepthOffset.CloneMarkers) color = self.color if self.destPoint is not None: color = (self.color[0], self.color[1], self.color[2], 0.06) box = self.getDestBox() if self.draggingFace is not None: o = list(self.draggingOrigin()) s = list(box.size) for i in xrange(3): if i == self.draggingFace >> 1: continue o[i] -= 1000 s[i] += 2000 guideBox = BoundingBox(o, s) color = self.draggingColor GL.glColor(1.0, 1.0, 1.0, 0.33) with gl.glEnable(GL.GL_BLEND, GL.GL_TEXTURE_2D, GL.GL_DEPTH_TEST): self.editor.sixteenBlockTex.bind() drawFace(guideBox, self.draggingFace ^ 1) else: box = self.getReticleBox() if box is None: return self.drawRepeatedCube(box, color) GL.glPolygonOffset(DepthOffset.CloneReticle, DepthOffset.CloneReticle) if self.destPoint: box = self.getDestBox() if self.draggingFace is not None: box = BoundingBox(self.draggingOrigin(), box.size) face, point = self.boxFaceUnderCursor(box) if face is not None: GL.glEnable(GL.GL_BLEND) GL.glDisable(GL.GL_DEPTH_TEST) GL.glColor(*self.color) drawFace(box, face) GL.glDisable(GL.GL_BLEND) GL.glEnable(GL.GL_DEPTH_TEST) def drawRepeatedCube(self, box, color): # draw several cubes according to the repeat count # it's not really sensible to repeat a crane because the origin point is literally out of this world. delta = box.origin - self.selectionBox().origin for i in xrange(self.repeatCount): self.editor.drawConstructionCube(box, color) box = BoundingBox(box.origin + delta, box.size) def drawToolMarkers(self): selectionBox = self.selectionBox() if selectionBox: widg = self.editor.find_widget(pygame.mouse.get_pos()) try: if self.panel and (widg is self.panel.nudgeButton or widg.parent is self.panel.nudgeButton): color = self.color except: try: if self.panel and (widg is self.panel.offsetInput.nudgeButton or widg.parent is self.panel.offsetInput.nudgeButton): color = self.color except: pass finally: try: self.editor.drawConstructionCube(self.getDestBox(), color) except: pass def sourceLevel(self): return self.level @alertException def rotate(self, amount=1, blocksOnly=False): if self.canRotateLevel: self.rotation += amount self.rotation &= 0x3 for i in xrange(amount & 0x3): if blocksOnly: self.level.rotateLeftBlocks() else: self.level.rotateLeft() self.previewRenderer.level = self.level @alertException def roll(self, amount=1, blocksOnly=False): if self.canRotateLevel: for i in xrange(amount & 0x3): if blocksOnly: self.level.rollBlocks() else: self.level.roll() self.previewRenderer.level = self.level @alertException def flip(self, amount=1, blocksOnly=False): if self.canRotateLevel: for i in xrange(amount & 0x1): if blocksOnly: self.level.flipVerticalBlocks() else: self.level.flipVertical() self.previewRenderer.level = self.level @alertException def mirror(self, blocksOnly=False): if self.canRotateLevel: yaw = int(self.editor.mainViewport.yaw) % 360 if (45 <= yaw < 135) or (225 < yaw <= 315): if blocksOnly: self.level.flipEastWestBlocks() else: self.level.flipEastWest() else: if blocksOnly: self.level.flipNorthSouthBlocks() else: self.level.flipNorthSouth() self.previewRenderer.level = self.level def option1(self): self.copyAir = not self.copyAir def option2(self): self.copyWater = not self.copyWater def option3(self): self.copyBiomes = not self.copyBiomes def option4(self): self.staticCommands = not self.staticCommands def option5(self): self.moveSpawnerPos = not self.moveSpawnerPos draggingFace = None draggingStartPoint = None def draggingOrigin(self): p = self._draggingOrigin() return p def _draggingOrigin(self): dragPos = map(int, map(numpy.floor, self.positionOnDraggingPlane())) delta = map(lambda s, e: e - int(numpy.floor(s)), self.draggingStartPoint, dragPos) if self.snapCloneKey == 1: ad = map(abs, delta) midx = ad.index(max(ad)) d = [0, 0, 0] d[midx] = delta[midx] dragY = self.draggingFace >> 1 d[dragY] = delta[dragY] delta = d p = self.destPoint + delta if self.chunkAlign: p = [i // 16 * 16 for i in p] return Vector(*p) def positionOnDraggingPlane(self): pos = self.editor.mainViewport.cameraPosition dim = self.draggingFace >> 1 # if key.get_mods() & KMOD_SHIFT: # dim = self.findBestTrackingPlane(self.draggingFace) # distance = self.draggingStartPoint[dim] - pos[dim] distance += self.draggingY mouseVector = self.editor.mainViewport.mouseVector scale = distance / (mouseVector[dim] or 1) point = map(lambda a, b: a * scale + b, mouseVector, pos) return point draggingY = 0 @alertException def mouseDown(self, evt, pos, direction): box = self.selectionBox() if not box: return self.draggingY = 0 if self.destPoint is not None: if evt.num_clicks == 2: self.pickUp() return face, point = self.boxFaceUnderCursor(self.getDestBox()) if face is not None: self.draggingFace = face self.draggingStartPoint = point else: self.destPoint = self.getReticleOrigin() if self.panel and self.panel.useOffsetInput: self.panel.offsetInput.setCoords(self.destPoint - box.origin) print "Destination: ", self.destPoint @alertException def mouseUp(self, evt, pos, direction): if self.draggingFace is not None: self.destPoint = self.draggingOrigin() self.updateOffsets() self.draggingFace = None self.draggingStartPoint = None def keyDown(self,evt): keyname = evt.dict.get('keyname', None) or self.root.getKey(evt) if keyname == config.keys.snapCloneToAxis.get(): self.snapCloneKey = 1 def keyUp(self, evt): keyname = evt.dict.get('keyname', None) or self.root.getKey(evt) if keyname == config.keys.snapCloneToAxis.get(): self.snapCloneKey = 0 def increaseToolReach(self): if self.draggingFace is not None: d = (1, -1)[self.draggingFace & 1] if self.draggingFace >> 1 != 1: # xxxxx y d = -d self.draggingY += d x, y, z = self.editor.mainViewport.cameraPosition pos = [x, y, z] pos[self.draggingFace >> 1] += d self.editor.mainViewport.cameraPosition = tuple(pos) else: self.cloneCameraDistance = self.editor._incrementReach(self.cloneCameraDistance) return True def decreaseToolReach(self): if self.draggingFace is not None: d = (1, -1)[self.draggingFace & 1] if self.draggingFace >> 1 != 1: # xxxxx y d = -d self.draggingY -= d x, y, z = self.editor.mainViewport.cameraPosition pos = [x, y, z] pos[self.draggingFace >> 1] -= d self.editor.mainViewport.cameraPosition = tuple(pos) else: self.cloneCameraDistance = self.editor._decrementReach(self.cloneCameraDistance) return True def resetToolReach(self): if self.draggingFace is not None: x, y, z = self.editor.mainViewport.cameraPosition pos = [x, y, z] pos[self.draggingFace >> 1] += (1, -1)[self.draggingFace & 1] * -self.draggingY self.editor.mainViewport.cameraPosition = tuple(pos) self.draggingY = 0 else: self.cloneCameraDistance = max(self.editor.defaultCameraToolDistance, self.safeToolDistance()) return True def pickUp(self): if self.destPoint is None: return box = self.selectionBox() # pick up the object. reset the tool distance to the object's distance from the camera d = map(lambda a, b, c: abs(a - b - c / 2), self.editor.mainViewport.cameraPosition, self.destPoint, box.size) self.cloneCameraDistance = numpy.sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]) self.destPoint = None # self.panel.performButton.enabled = False print "Picked up" @alertException def confirm(self): destPoint = self.destPoint if destPoint is None: return sourceLevel = self.sourceLevel() sourceBox = sourceLevel.bounds destLevel = self.editor.level op = CloneOperation(editor=self.editor, sourceLevel=sourceLevel, sourceBox=sourceBox, originSourceBox=self.selectionBox(), destLevel=destLevel, destPoint=self.destPoint, copyAir=self.copyAir, copyWater=self.copyWater, copyBiomes=self.copyBiomes, staticCommands=self.staticCommands, moveSpawnerPos=self.moveSpawnerPos, regenerateUUID=self.regenerateUUID, repeatCount=self.repeatCount) self.editor.toolbar.selectTool( -1) # deselect tool so that the clone tool's selection change doesn't update its schematic self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() dirtyBox = op.dirtyBox() if dirtyBox: self.editor.invalidateBox(dirtyBox) self.editor.renderer.invalidateChunkMarkers() self.editor.currentOperation = None self.destPoint = None self.level = None def discardPreviewer(self): if self.previewRenderer is None: return self.previewRenderer.stopWork() self.previewRenderer.discardAllChunks() self.editor.removeWorker(self.previewRenderer) self.previewRenderer = None class ConstructionToolPanel(CloneToolPanel): useOffsetInput = False class ConstructionToolOptions(ToolOptions): def __init__(self, tool): ToolOptions.__init__(self, name='Panel.ConstructionToolOptions') self.tool = tool importNudgeLabel = Label("Import Fast Nudge Settings:") importNudgeCheckBox = CheckBoxLabel("Move by the width of schematic ", ref=config.fastNudgeSettings.importWidth, tooltipText="Moves selection by his width") importNudgeNumber = IntInputRow("Width of import movement: ", ref=config.fastNudgeSettings.importWidthNumber, width=100, min=2, max=50) col = Column((Label("Import Options"), importNudgeLabel, importNudgeCheckBox, importNudgeNumber, Button("OK", action=self.dismiss))) self.add(col) self.shrink_wrap() class ConstructionTool(CloneTool): surfaceBuild = True toolIconName = "crane" tooltipText = "Import\nRight-click for options" panelClass = ConstructionToolPanel def toolEnabled(self): return True def selectionChanged(self): pass def updateSchematic(self): self.originalLevel = self.level self.scaleFactor = 1.0 def quickNudge(self, nudge): if config.fastNudgeSettings.importWidth.get(): return map(int.__mul__, nudge, self.selectionBox().size) nudgeWidth = config.fastNudgeSettings.importWidthNumber.get() return map(lambda x: x * nudgeWidth, nudge) def __init__(self, *args): CloneTool.__init__(self, *args) self.level = None self.optionsPanel = ConstructionToolOptions(self) self.testBoardKey = 0 @property def statusText(self): if self.destPoint is None: return "Click to set this item down." return "Click and drag to reposition the item. Double-click to pick it up. Click Import or press Enter to confirm." def showPanel(self): CloneTool.showPanel(self) self.panel.performButton.text = "Import" self.updateSchematic() def toolReselected(self): self.toolSelected() # def cancel(self): # print "Cancelled Clone" # self.level = None # super(ConstructionTool, self).cancel(self) # def createTestBoard(self, anyBlock=True): if anyBlock: allBlocks = [self.editor.level.materials[a, b] for a in xrange(256) for b in xrange(16)] blockWidth = 64 else: allBlocks = self.editor.level.materials.allBlocks blockWidth = 16 blockCount = len(allBlocks) width = blockWidth * 3 + 1 rows = blockCount // blockWidth + 1 length = rows * 3 + 1 height = 3 schematic = pymclevel.MCSchematic((width, height, length), mats=self.editor.level.materials) schematic.Blocks[:, :, 0] = 1 for i, block in enumerate(allBlocks): col = (i % blockWidth) * 3 + 1 row = (i // blockWidth) * 3 schematic.Blocks[col:col + 2, row:row + 2, 2] = block.ID schematic.Data[col:col + 2, row:row + 2, 2] = block.blockData return schematic 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) # CloneTool.toolSelected(self) originalLevelSize = (0, 0, 0) def loadSchematic(self, filename): """ actually loads a schematic or a level """ try: level = pymclevel.fromFile(filename, readonly=True) self.loadLevel(level) except Exception as e: logging.warn(u"Unable to import file %s : %s", filename, e) traceback.print_exc() if filename: # self.editor.toolbar.selectTool(-1) alert( _(u"I don't know how to import this file: {0}.\n\nError: {1!r}").format(os.path.basename(filename), e)) return @alertException def loadLevel(self, level): if level: self.level = level self.repeatCount = 1 self.destPoint = None self.editor.currentTool = self # because save window triggers loseFocus, which triggers tool.cancel... hmmmmmm self.cloneCameraDistance = self.safeToolDistance() self.chunkAlign = isinstance(self.level, pymclevel.MCInfdevOldLevel) and all( b % 16 == 0 for b in self.level.bounds.size) self.setupPreview() self.originalLevelSize = (self.level.Width, self.level.Height, self.level.Length) self.showPanel() return def selectionSize(self): if not self.level: return None return self.originalLevelSize def selectionBox(self): if not self.level: return None return BoundingBox((0, 0, 0), self.selectionSize()) def sourceLevel(self): return self.level def mouseDown(self, evt, pos, direction): # x,y,z = pos box = self.selectionBox() if not box: return CloneTool.mouseDown(self, evt, pos, direction)
45,041
34.861465
203
py
MCEdit-Unified
MCEdit-Unified-master/editortools/__init__.py
"""Copyright (c) 2010-2012 David Rio Vierra Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.""" from select import SelectionTool from brush import BrushTool from fill import FillTool from clone import CloneTool, ConstructionTool from filter import FilterTool from player import PlayerPositionTool, PlayerSpawnPositionTool from chunk import ChunkTool from nbtexplorer import NBTExplorerTool from tooloptions import ToolOptions
1,076
43.875
72
py
MCEdit-Unified
MCEdit-Unified-master/editortools/blockview.py
from OpenGL import GL from numpy import array from albow import ButtonBase, ValueDisplay, AttrRef, Row from albow.openglwidgets import GLOrtho import thumbview import blockpicker from glbackground import Panel, GLBackground from glutils import DisplayList #&# Prototype for blocks/items names import mclangres #&# class BlockView(GLOrtho): def __init__(self, materials, blockInfo=None): GLOrtho.__init__(self) self.list = DisplayList(self._gl_draw) self.blockInfo = blockInfo or materials.Air self.materials = materials listBlockInfo = None def gl_draw(self): if self.listBlockInfo != self.blockInfo: self.list.invalidate() self.listBlockInfo = self.blockInfo self.list.call() def _gl_draw(self): blockInfo = self.blockInfo if blockInfo.ID is 0: return GL.glColor(1.0, 1.0, 1.0, 1.0) GL.glEnable(GL.GL_TEXTURE_2D) GL.glEnable(GL.GL_ALPHA_TEST) self.materials.terrainTexture.bind() pixelScale = 0.5 if self.materials.name in ("Pocket", "Alpha") else 1.0 texSize = 16 * pixelScale GL.glEnableClientState(GL.GL_TEXTURE_COORD_ARRAY) GL.glVertexPointer(2, GL.GL_FLOAT, 0, array([-1, -1, - 1, 1, 1, 1, 1, -1, ], dtype='float32')) # hack to get end rod to render properly # we really should use json models? if blockInfo.ID == 198: texOrigin = array([17*16, 20*16]) else: texOrigin = array(self.materials.blockTextures[blockInfo.ID, blockInfo.blockData, 0]) texOrigin = texOrigin.astype(float) * pixelScale GL.glTexCoordPointer(2, GL.GL_FLOAT, 0, array([texOrigin[0], texOrigin[1] + texSize, texOrigin[0], texOrigin[1], texOrigin[0] + texSize, texOrigin[1], texOrigin[0] + texSize, texOrigin[1] + texSize], dtype='float32')) GL.glDrawArrays(GL.GL_QUADS, 0, 4) GL.glDisableClientState(GL.GL_TEXTURE_COORD_ARRAY) GL.glDisable(GL.GL_ALPHA_TEST) GL.glDisable(GL.GL_TEXTURE_2D) @property def tooltipText(self): #&# Prototype for blocks/items names #return str(self.blockInfo.name) return mclangres.translate(self.blockInfo.name) #&# class BlockButton(ButtonBase, Panel): _ref = None def __init__(self, materials, blockInfo=None, ref=None, recentBlocks=None, *a, **kw): self.allowWildcards = False if 'name' not in kw.keys(): kw['name'] = 'Panel.BlockButton' Panel.__init__(self, *a, **kw) self.bg_color = (1, 1, 1, 0.25) self._ref = ref if blockInfo is None and ref is not None: blockInfo = ref.get() blockInfo = blockInfo or materials["Air"] if recentBlocks is not None: self.recentBlocks = recentBlocks else: self.recentBlocks = [] self.blockView = thumbview.BlockThumbView(materials, blockInfo, size=(48, 48)) self.blockLabel = ValueDisplay(ref=AttrRef(self, 'labelText'), width=180, align="l") row = Row((self.blockView, self.blockLabel), align="b") # col = Column( (self.blockButton, self.blockNameLabel) ) self.add(row) self.shrink_wrap() # self.blockLabel.bottom = self.blockButton.bottom # self.blockLabel.centerx = self.blockButton.centerx # self.add(self.blockLabel) self.materials = materials self.blockInfo = blockInfo # self._ref = ref self.updateRecentBlockView() recentBlockLimit = 7 @property def blockInfo(self): if self._ref: return self._ref.get() else: return self._blockInfo @blockInfo.setter def blockInfo(self, bi): if self._ref: self._ref.set(bi) else: self._blockInfo = bi self.blockView.blockInfo = bi if bi not in self.recentBlocks: self.recentBlocks.append(bi) if len(self.recentBlocks) > self.recentBlockLimit: self.recentBlocks.pop(0) self.updateRecentBlockView() @property def labelText(self): #&# Prototype for blocks/items names #labelText = self.blockInfo.name labelText = mclangres.translate(self.blockInfo.name) #&# if len(labelText) > 24: labelText = labelText[:23] + "..." return labelText # self.blockNameLabel.text = def createRecentBlockView(self): def makeBlockView(bi): bv = BlockView(self.materials, bi) bv.size = (16, 16) def action(evt): self.blockInfo = bi bv.mouse_up = action return bv row = [makeBlockView(bi) for bi in self.recentBlocks] row = Row(row) widget = GLBackground() widget.bg_color = (0.8, 0.8, 0.8, 0.8) widget.add(row) widget.shrink_wrap() widget.anchor = "whtr" return widget def updateRecentBlockView(self): if self.recentBlockView: self.recentBlockView.set_parent(None) self.recentBlockView = self.createRecentBlockView() self.recentBlockView.right = self.width self.add(self.recentBlockView) # print self.rect, self.recentBlockView.rect recentBlockView = None @property def tooltipText(self): #&# Prototype for blocks/items names #return str(self.blockInfo.name) return mclangres.translate(self.blockInfo.name) #&# def action(self): blockPicker = blockpicker.BlockPicker(self.blockInfo, self.materials, allowWildcards=self.allowWildcards) if blockPicker.present(): self.blockInfo = blockPicker.blockInfo def draw_all(self, s): #-# Looks like a bad stuf... Be aware of the 'spacing' member of the widgets parent. Panel.gl_draw_all(self, self.get_root(), (self.local_to_global_offset()[0], self.local_to_global_offset()[1] - self.height + self.parent.spacing))
6,436
32.010256
154
py
MCEdit-Unified
MCEdit-Unified-master/editortools/operation.py
#-# Modified by D.C.-G. for translation purpose import atexit import os import shutil import tempfile import albow from albow.translate import _ from pymclevel import BoundingBox import numpy from albow.root import Cancel import pymclevel from albow import showProgress from pymclevel.mclevelbase import exhaust undo_folder = os.path.join(tempfile.gettempdir(), "mcedit_undo", str(os.getpid())) def mkundotemp(): if not os.path.exists(undo_folder): os.makedirs(undo_folder) return tempfile.mkdtemp("mceditundo", dir=undo_folder) atexit.register(shutil.rmtree, undo_folder, True) class Operation(object): changedLevel = True undoLevel = None redoLevel = None def __init__(self, editor, level): self.editor = editor self.level = level def extractUndo(self, level, box): if isinstance(level, pymclevel.MCInfdevOldLevel): return self.extractUndoChunks(level, box.chunkPositions, box.chunkCount) else: return self.extractUndoSchematic(level, box) def extractUndoChunks(self, level, chunks, chunkCount=None): if not isinstance(level, pymclevel.MCInfdevOldLevel): chunks = numpy.array(list(chunks)) mincx, mincz = numpy.min(chunks, 0) maxcx, maxcz = numpy.max(chunks, 0) box = BoundingBox((mincx << 4, 0, mincz << 4), ((maxcx << 4) - (mincx << 4), level.Height, (maxcz << 4) - (mincz << 4))) return self.extractUndoSchematic(level, box) undoLevel = pymclevel.MCInfdevOldLevel(mkundotemp(), create=True) if not chunkCount: try: chunkCount = len(chunks) except TypeError: chunkCount = -1 def _extractUndo(): yield 0, 0, "Recording undo..." for i, (cx, cz) in enumerate(chunks): undoLevel.copyChunkFrom(level, cx, cz) yield i, chunkCount, _("Copying chunk %s...") % ((cx, cz),) undoLevel.saveInPlace() if chunkCount > 25 or chunkCount < 1: if "Canceled" == showProgress("Recording undo...", _extractUndo(), cancel=True): if albow.ask("Continue with undo disabled?", ["Continue", "Cancel"]) == "Cancel": raise Cancel else: return None else: exhaust(_extractUndo()) return undoLevel @staticmethod def extractUndoSchematic(level, box): if box.volume > 131072: sch = showProgress("Recording undo...", level.extractZipSchematicIter(box), cancel=True) else: sch = level.extractZipSchematic(box) if sch == "Cancel" or sch == "Canceled": raise Cancel if sch: sch.sourcePoint = box.origin return sch # represents a single undoable operation def perform(self, recordUndo=True): " Perform the operation. Record undo information if recordUndo" def undo(self): """ Undo the operation. Ought to leave the Operation in a state where it can be performed again. Default implementation copies all chunks in undoLevel back into level. Non-chunk-based operations should override this.""" if self.undoLevel: self.redoLevel = self.extractUndo(self.level, self.dirtyBox()) def _undo(): yield 0, 0, "Undoing..." if hasattr(self.level, 'copyChunkFrom'): for i, (cx, cz) in enumerate(self.undoLevel.allChunks): self.level.copyChunkFrom(self.undoLevel, cx, cz) yield i, self.undoLevel.chunkCount, "Copying chunk %s..." % ((cx, cz),) else: for i in self.level.copyBlocksFromIter(self.undoLevel, self.undoLevel.bounds, self.undoLevel.sourcePoint, biomes=True): yield i, self.undoLevel.chunkCount, "Copying..." if self.undoLevel.chunkCount > 25: showProgress("Undoing...", _undo()) else: exhaust(_undo()) self.editor.invalidateChunks(self.undoLevel.allChunks) def redo(self): if self.redoLevel: def _redo(): yield 0, 0, "Redoing..." if hasattr(self.level, 'copyChunkFrom'): for i, (cx, cz) in enumerate(self.redoLevel.allChunks): self.level.copyChunkFrom(self.redoLevel, cx, cz) yield i, self.redoLevel.chunkCount, "Copying chunk %s..." % ((cx, cz),) else: for i in self.level.copyBlocksFromIter(self.redoLevel, self.redoLevel.bounds, self.redoLevel.sourcePoint, biomes=True): yield i, self.undoLevel.chunkCount, "Copying..." if self.redoLevel.chunkCount > 25: showProgress("Redoing...", _redo()) else: exhaust(_redo()) def dirtyBox(self): """ The region modified by the operation. Return None to indicate no blocks were changed. """ return None
5,267
35.839161
132
py
MCEdit-Unified
MCEdit-Unified-master/editortools/blockpicker.py
from albow import Label, TextFieldWrapped, Row, TableView, TableColumn, Column, Widget, Button, AttrRef, CheckBoxLabel from albow.dialogs import Dialog from editortools import thumbview from editortools import blockview from glbackground import GLBackground from pymclevel import materials from albow.root import get_root from pymclevel.materials import Block from albow.translate import getLang #&# Prototype for blocks/items names import mclangres #&# def anySubtype(self): bl = Block(self.materials, self.ID, self.blockData) bl.wildcard = True return bl Block.anySubtype = anySubtype Block.wildcard = False # True if class BlockPicker(Dialog): is_gl_container = True def __init__old(self, blockInfo, materials, *a, **kw): self.root = get_root() self.allowWildcards = False Dialog.__init__(self, *a, **kw) panelWidth = 518 self.click_outside_response = 0 self.materials = materials self.anySubtype = blockInfo.wildcard self.matchingBlocks = materials.allBlocks try: self.selectedBlockIndex = self.matchingBlocks.index(blockInfo) except ValueError: self.selectedBlockIndex = 0 for i, b in enumerate(self.matchingBlocks): if blockInfo.ID == b.ID and blockInfo.blockData == b.blockData: self.selectedBlockIndex = i break lbl = Label("Search") # lbl.rect.topleft = (0,0) fld = TextFieldWrapped(300) # fld.rect.topleft = (100, 10) # fld.centery = lbl.centery # fld.left = lbl.right fld.change_action = self.textEntered fld.enter_action = self.ok fld.escape_action = self.cancel self.awesomeField = fld searchRow = Row((lbl, fld)) def formatBlockName(x): block = self.matchingBlocks[x] r = "{name}".format(name=block.name) if block.aka: r += " [{0}]".format(block.aka) return r def formatBlockID(x): block = self.matchingBlocks[x] ident = "({id}:{data})".format(id=block.ID, data=block.blockData) return ident tableview = TableView(columns=[TableColumn(" ", 24, "l", lambda x: ""), TableColumn("Name", 415, "l", formatBlockName), TableColumn("ID", 45, "l", formatBlockID) ]) tableicons = [blockview.BlockView(materials) for i in xrange(tableview.rows.num_rows())] for t in tableicons: t.size = (16, 16) t.margin = 0 icons = Column(tableicons, spacing=2) # tableview.margin = 5 tableview.num_rows = lambda: len(self.matchingBlocks) tableview.row_data = lambda x: (self.matchingBlocks[x], x, x) tableview.row_is_selected = lambda x: x == self.selectedBlockIndex tableview.click_row = self.selectTableRow draw_table_cell = tableview.draw_table_cell def draw_block_table_cell(surf, i, data, cell_rect, column): if isinstance(data, Block): tableicons[i - tableview.rows.scroll].blockInfo = data else: draw_table_cell(surf, i, data, cell_rect, column) tableview.draw_table_cell = draw_block_table_cell tableview.width = panelWidth tableview.anchor = "lrbt" # self.add(tableview) self.tableview = tableview tableWidget = Widget() tableWidget.add(tableview) tableWidget.shrink_wrap() def wdraw(*args): for t in tableicons: t.blockInfo = materials.Air tableWidget.draw = wdraw self.blockButton = blockView = thumbview.BlockThumbView(materials, self.blockInfo) blockView.centerx = self.centerx blockView.top = tableview.bottom # self.add(blockview) but = Button("OK") but.action = self.ok but.top = blockView.bottom but.centerx = self.centerx but.align = "c" but.height = 30 if self.allowWildcards: # self.add(but) anyRow = CheckBoxLabel("Any Subtype", ref=AttrRef(self, 'anySubtype'), tooltipText="Replace blocks with any data value. Only useful for Replace operations.") col = Column((searchRow, tableWidget, anyRow, blockView, but)) else: col = Column((searchRow, tableWidget, blockView, but)) col.anchor = "wh" self.anchor = "wh" panel = GLBackground() panel.bg_color = [i / 255. for i in self.bg_color] panel.anchor = "tlbr" self.add(panel) self.add(col) self.add(icons) icons.topleft = tableWidget.topleft icons.top += tableWidget.margin + 30 icons.left += tableWidget.margin + 4 self.shrink_wrap() panel.size = self.size try: self.tableview.rows.scroll_to_item(self.selectedBlockIndex) except: pass def __init__(self, blockInfo, materials, *a, **kw): self.root = get_root() self.allowWildcards = False Dialog.__init__(self, *a, **kw) panelWidth = 518 self.click_outside_response = 0 self.materials = materials self.anySubtype = blockInfo.wildcard self.matchingBlocks = sorted(list(set(materials.allBlocks))) #&# self.searchNames = [mclangres.translate(a.name).lower() for a in self.matchingBlocks] #&# try: self.selectedBlockIndex = self.matchingBlocks.index(blockInfo) except ValueError: self.selectedBlockIndex = 0 for i, b in enumerate(self.matchingBlocks): if blockInfo.ID == b.ID and blockInfo.blockData == b.blockData: self.selectedBlockIndex = i break lbl = Label("Search") # lbl.rect.topleft = (0,0) fld = TextFieldWrapped(300) # fld.rect.topleft = (100, 10) # fld.centery = lbl.centery # fld.left = lbl.right fld.change_action = self.textEntered fld.enter_action = self.ok fld.escape_action = self.cancel fld.attention_lost = fld.commit self.awesomeField = fld searchRow = Row((lbl, fld)) def formatBlockName(x): block = self.matchingBlocks[x] #&# #r = "{name}".format(name=block.name) r = u"{name}".format(name=mclangres.translate(block.name)) #&# if block.aka: #&# #r += " [{0}]".format(block.aka) r += u" [{0}]".format(mclangres.translate(block.aka)) #&# return r def formatBlockID(x): block = self.matchingBlocks[x] ident = "({id}:{data})".format(id=block.ID, data=block.blockData) return ident tableview = TableView(columns=[TableColumn(" ", 24, "l", lambda x: ""), TableColumn("Name", 415, "l", formatBlockName), TableColumn("ID", 45, "l", formatBlockID) ]) tableicons = [blockview.BlockView(materials) for i in xrange(tableview.rows.num_rows())] for t in tableicons: t.size = (16, 16) t.margin = 0 spacing = max(tableview.font.get_linesize() - 16, 2) icons = Column(tableicons, spacing=spacing) # tableview.margin = 5 tableview.num_rows = lambda: len(self.matchingBlocks) tableview.row_data = lambda x: (self.matchingBlocks[x], x, x) tableview.row_is_selected = lambda x: x == self.selectedBlockIndex tableview.click_row = self.selectTableRow draw_table_cell = tableview.draw_table_cell def draw_block_table_cell(surf, i, data, cell_rect, column): if isinstance(data, Block): tableicons[i - tableview.rows.scroll].blockInfo = data else: draw_table_cell(surf, i, data, cell_rect, column) tableview.draw_table_cell = draw_block_table_cell tableview.width = panelWidth tableview.anchor = "lrbt" # self.add(tableview) self.tableview = tableview tableWidget = Widget() tableWidget.add(tableview) tableWidget.shrink_wrap() def wdraw(*args): for t in tableicons: t.blockInfo = materials.Air tableWidget.draw = wdraw self.blockButton = blockView = thumbview.BlockThumbView(materials, self.blockInfo) blockView.centerx = self.centerx blockView.top = tableview.bottom # self.add(blockview) but = Button("OK") but.action = self.ok but.top = blockView.bottom but.centerx = self.centerx but.align = "c" but.height = 30 if self.allowWildcards: # self.add(but) anyRow = CheckBoxLabel("Any Subtype", ref=AttrRef(self, 'anySubtype'), tooltipText="Replace blocks with any data value. Only useful for Replace operations.") col = Column((searchRow, tableWidget, anyRow, blockView, but)) else: col = Column((searchRow, tableWidget, blockView, but)) col.anchor = "wh" self.anchor = "wh" panel = GLBackground() panel.bg_color = [i / 255. for i in self.bg_color] panel.anchor = "tlbr" self.add(panel) self.add(col) self.add(icons) icons.left += tableview.margin + tableWidget.margin + col.margin icons.top = tableWidget.top + tableview.top + tableview.header_height + tableview.header_spacing + tableWidget.margin + tableview.margin + tableview.subwidgets[1].margin + (spacing / 2) self.shrink_wrap() panel.size = self.size try: self.tableview.rows.scroll_to_item(self.selectedBlockIndex) except: pass @property def blockInfo(self): if len(self.matchingBlocks): bl = self.matchingBlocks[self.selectedBlockIndex] if self.anySubtype: return bl.anySubtype() else: return bl else: return self.materials.Air def selectTableRow(self, i, e): oldIndex = self.selectedBlockIndex self.selectedBlockIndex = i self.blockButton.blockInfo = self.blockInfo if e.num_clicks > 1 and oldIndex == i: self.ok() def textEntered(self): text = self.awesomeField.text blockData = 0 try: if ":" in text: text, num = text.split(":", 1) blockData = int(num) & 0xf blockID = int(text) % materials.id_limit else: blockID = int(text) % materials.id_limit block = self.materials.blockWithID(blockID, blockData) self.matchingBlocks = [block] self.selectedBlockIndex = 0 self.tableview.rows.scroll_to_item(self.selectedBlockIndex) self.blockButton.blockInfo = self.blockInfo return except ValueError: pass except Exception as e: print repr(e) blocks = self.materials.allBlocks if len(text): if getLang() == 'en_US': matches = self.materials.blocksMatching(text) else: matches = self.materials.blocksMatching(text, self.searchNames) if blockData: ids = set(b.ID for b in matches) matches = sorted([self.materials.blockWithID(id, blockData) for id in ids]) self.matchingBlocks = matches else: self.matchingBlocks = blocks self.matchingBlocks = sorted(list(set(self.matchingBlocks))) self.selectedBlockIndex = 0 self.tableview.rows.scroll_to_item(self.selectedBlockIndex) self.blockButton.blockInfo = self.blockInfo def dispatch_key(self, name, evt): super(BlockPicker, self).dispatch_key(name, evt) if name == "key_down": keyname = self.root.getKey(evt) if keyname == "Up" and self.selectedBlockIndex > 0: self.selectedBlockIndex -= 1 self.tableview.rows.scroll_to_item(self.selectedBlockIndex) self.blockButton.blockInfo = self.blockInfo elif keyname == "Down" and self.selectedBlockIndex < len(self.matchingBlocks) - 1: self.selectedBlockIndex += 1 self.tableview.rows.scroll_to_item(self.selectedBlockIndex) self.blockButton.blockInfo = self.blockInfo elif keyname == 'Page down': self.selectedBlockIndex = min(len(self.matchingBlocks) - 1, self.selectedBlockIndex + self.tableview.rows.num_rows()) self.tableview.rows.scroll_to_item(self.selectedBlockIndex) self.blockButton.blockInfo = self.blockInfo elif keyname == 'Page up': self.selectedBlockIndex = max(0, self.selectedBlockIndex - self.tableview.rows.num_rows()) self.tableview.rows.scroll_to_item(self.selectedBlockIndex) self.blockButton.blockInfo = self.blockInfo if self.tableview.rows.cell_to_item_no(0, 0) != None and (self.tableview.rows.cell_to_item_no(0, 0) + self.tableview.rows.num_rows() -1 > self.selectedBlockIndex or self.tableview.rows.cell_to_item_no(0, 0) + self.tableview.rows.num_rows() -1 < self.selectedBlockIndex): self.tableview.rows.scroll_to_item(self.selectedBlockIndex)
13,869
34.747423
282
py
MCEdit-Unified
MCEdit-Unified-master/editortools/nbtexplorer.py
# -*- coding: utf-8 -*- # # nbtexplorer.py # # D.C.-G. (LaChal) 2014 # # Display NBT structure # # # TODO: # * add local undo/redo for loaded NBT files # * change/optimize the undo/redo when edit level NBT data # * add a style editor and an image wrapper for the bullets from pygame import key, draw, image, Rect, event, MOUSEBUTTONDOWN from albow import Column, Row, Label, Tree, TableView, TableColumn, Button, \ FloatField, IntField, TextFieldWrapped, AttrRef, ItemRef, CheckBox, Widget, \ ScrollPanel, ask, alert, input_text_buttons, CheckBoxLabel, ChoiceButton, Menu, Frame from albow.dialogs import Dialog from albow.tree import TreeRow, setup_map_types_item from albow.utils import blit_in_rect from albow.translate import _, getLang from glbackground import Panel from pymclevel.nbt import load, TAG_Byte, TAG_Short, TAG_Int, TAG_Long, TAG_Float, \ TAG_Double, TAG_String, TAG_Byte_Array, TAG_List, TAG_Compound, TAG_Int_Array, \ TAG_Short_Array, littleEndianNBT, NBTFormatError, TAG_BYTE, TAG_SHORT, TAG_INT, \ TAG_LONG, TAG_FLOAT, TAG_DOUBLE, TAG_STRING, TAG_BYTE_ARRAY, TAG_LIST, TAG_COMPOUND, \ TAG_INT_ARRAY, TAG_SHORT_ARRAY from numpy import array from albow.theme import root scroll_button_size = 0 + root.PaletteView.scroll_button_size bullet_color_active = root.Tree.bullet_color_active fg_color = root.fg_color disabled_color = root.Label.disabled_color del root from editortools.editortool import EditorTool from editortools.operation import Operation from editortools.tooloptions import ToolOptions import copy from directories import getDataDir, getDataFile import os import mcplatform from config import config, DEF_ENC from albow.resource import resource_path # &# Protoype for blocks/items names from pymclevel.materials import alphaMaterials map_block = {} def build_map_block(): from pymclevel.materials import block_map global map_block for k, v in block_map.items(): map_block[v] = k from pymclevel.items import items as mcitems map_items = {} for k, v in mcitems.items.items(): if isinstance(v, dict): names = [] if isinstance(v['name'], list): names = v['name'] else: names = [v['name']] for name in names: if name is not None and name not in map_items.keys(): map_items[name] = (k, names.index(name)) # # DEBUG # #keys = map_items.keys() # #keys.sort() # #f = open('map_items.txt', 'w') # #for k in keys: # # f.write('%s: %s\n'%(k, map_items[k])) # #f.close() # #f = open('mcitems.txt', 'w') # #keys = mcitems.items.keys() # #for k in keys: # # f.write('%s: %s\n'%(k, mcitems.items[k])) # #f.close() import mclangres # &# import struct # ----------------------------------------------------------------------------- bullet_image = None #default_bullet_images = os.path.join(getDataDir(), "Nbtsheet.png") default_bullet_images = getDataFile('Nbtsheet.png') def get_bullet_image(index, w=16, h=16): global bullet_image if not bullet_image: # # Debug for MacOS try: if config.nbtTreeSettings.defaultBulletImages.get(): bullet_image = image.load(default_bullet_images) else: bullet_image = image.load(resource_path(config.nbtTreeSettings.bulletFileName.get())) except Exception, e: print "*** MCEDIT DEBUG: bullets image could not be loaded." print "*** MCEDIT DEBUG:", e print "*** MCEDIT DEBUG: bullets image file:", resource_path(config.nbtTreeSettings.bulletFileName.get()) print "*** MCEDIT DEBUG: current directory:", os.getcwd() from pygame import Surface, draw, SRCALPHA bullet_image = Surface((64, 64), SRCALPHA) bullet_image.fill((0, 0, 0, 0)) for i in xrange(4): for j in xrange(4): bullet_image.fill((255/(i or 1), 255/(j or 1), 255, 255), [16*i, 16*j, 16*i+16, 16*j+16]) r = Rect(0, 0, w, h) line_length = int(bullet_image.get_width() / w) line = int(index / line_length) r.top = line * h r.left = (index - (line * line_length)) * w return bullet_image.subsurface(r) default_bullet_styles = {TAG_Byte: ((20, 20, 200), None, 'circle', 'b'), TAG_Double: ((20, 200, 20), None, 'circle', 'd'), TAG_Float: ((200, 20, 20), None, 'circle', 'f'), TAG_Int: ((16, 160, 160), None, 'circle', 'i'), TAG_Long: ((200, 20, 200), None, 'circle', 'l'), TAG_Short: ((200, 200, 20), (0, 0, 0), 'circle', 's'), TAG_String: ((60, 60, 60), None, 'circle', 's'), TAG_Compound: (bullet_color_active, None, '', ''), TAG_Byte_Array: ((20, 20, 200), None, 'square', 'B'), TAG_Int_Array: ((16, 160, 160), None, 'square', 'I'), TAG_List: ((200, 200, 200), (0, 0, 0), 'square', 'L'), TAG_Short_Array: ((200, 200, 20), None, 'square', 'S'), } default_bullet_styles[dict] = default_bullet_styles[TAG_List] bullet_styles = copy.deepcopy(default_bullet_styles) def change_styles(): global default_bullet_styles global bullet_styles if config.nbtTreeSettings.useBulletStyles.get() and \ ((config.nbtTreeSettings.useBulletImages.get() and \ os.path.exists(config.nbtTreeSettings.bulletFileName.get())) \ or config.nbtTreeSettings.defaultBulletImages.get()): i = 0 for key in ( TAG_Byte, TAG_Double, TAG_Float, TAG_Int, TAG_Long, TAG_Short, TAG_String, TAG_Compound, TAG_Byte_Array, TAG_Int_Array, TAG_List): bullet_styles[key] = (get_bullet_image(i), None, 'image', '') i += 1 bullet_styles[TAG_Short_Array] = bullet_styles[TAG_Int_Array] bullet_styles[dict] = bullet_styles[TAG_List] else: bullet_styles = copy.deepcopy(default_bullet_styles) return bullet_styles change_styles() # ----------------------------------------------------------------------------- field_types = {TAG_Byte: (IntField, (0, 256)), TAG_Double: (FloatField, None), TAG_Float: (FloatField, None), TAG_Int: (IntField, (-2147483647, +2147483647)), TAG_Long: (IntField, (-9223372036854775807, +9223372036854775807)), TAG_Short: (IntField, (-65535, 65536)), TAG_String: (TextFieldWrapped, None), } array_types = {TAG_Byte_Array: field_types[TAG_Byte], TAG_Int_Array: field_types[TAG_Int], TAG_Short_Array: field_types[TAG_Short], } # ----------------------------------------------------------------------------- class TAG_List_Type(Widget): choices = [] def __init__(self, value=None): Widget.__init__(self) self.choiceButton = ChoiceButton(self.choices) self.add(self.choiceButton) self.shrink_wrap() @property def value(self): return self.choiceButton.selectedChoice item_types_map = {TAG_Byte: ("Byte", IntField, 0), TAG_Double: ("Floating point", FloatField, 0.0), TAG_Float: ("Floating point", FloatField, 0.0), TAG_Int: ("Integral", IntField, 0), TAG_Long: ("Long", IntField, 0), TAG_Short: ("Short", IntField, 0), TAG_String: ("String", TextFieldWrapped, ""), TAG_List: ("List", TAG_List_Type, None), TAG_Compound: ("Compound", None, None), TAG_Byte_Array: ("Byte Array", TextFieldWrapped, ""), TAG_Int_Array: ("Int Array", TextFieldWrapped, ""), TAG_Short_Array: ("Short Array", TextFieldWrapped, ""), } map_types_item = setup_map_types_item(item_types_map) TAG_List_Type.choices = map_types_item.keys() # ----------------------------------------------------------------------------- def create_base_item(self, i_type, i_name, i_value): return i_name, i_type(type(item_types_map[i_type][2])(i_value), i_name) create_TAG_Byte = create_TAG_Int = create_TAG_Short = create_TAG_Long = \ create_TAG_String = create_TAG_Double = create_TAG_Float = create_base_item def create_TAG_Compound(self, i_type, i_name, i_value): return i_name, i_type([], i_name) def create_TAG_List(self, i_type, i_name, i_value): return i_name, i_type([], i_name, globals()[map_types_item[i_value][0].__name__.upper()]) def create_array_item(self, i_type, i_name, i_value): value = i_value.strip().strip('[]').strip() if value != "": value = [int(a.strip()) for a in value.split(",") if a.strip().isdigit()] else: value = None return i_name, i_type(array(value, i_type.dtype), i_name) create_TAG_Byte_Array = create_TAG_Int_Array = create_TAG_Short_Array = create_array_item # ----------------------------------------------------------------------------- class NBTTree(Tree): def __init__(self, *args, **kwargs): styles = kwargs.get('styles', {}) self.update_draw_bullets_methods(styles) global map_types_item self.map_types_item = setup_map_types_item(item_types_map) Tree.__init__(self, *args, **kwargs) for t in self.item_types: if 'create_%s' % t.__name__ in globals().keys(): setattr(self, 'create_%s' % t.__name__, globals()['create_%s' % t.__name__]) def _draw_opened_bullet(self, *args, **kwargs): return Tree.draw_opened_bullet(self, *args, **kwargs) def _draw_closed_bullet(self, *args, **kwargs): return Tree.draw_closed_bullet(self, *args, **kwargs) def update_draw_bullets_methods(self, styles): if config.nbtTreeSettings.useBulletStyles.get() and bullet_styles.get(TAG_Compound, [''] * 4)[2] != '': self.draw_opened_bullet = self.draw_closed_bullet = self.draw_TAG_bullet else: self.draw_opened_bullet = self._draw_opened_bullet self.draw_closed_bullet = self._draw_closed_bullet for key in styles.keys(): if hasattr(key, '__name__'): name = key.__name__ elif isinstance(key, (str, unicode)): name = key else: name = repr(key) setattr(self, 'draw_%s_bullet' % name, self.draw_TAG_bullet) @staticmethod def add_item_to_TAG_Compound(parent, name, item): parent[name] = item def add_item_to_TAG_List(self, parent, name, item): if parent == self.selected_item[9]: idx = len(parent.value) else: idx = parent.value.index(self.selected_item[9]) parent.insert(idx, item) def add_item(self, types_item=None): if types_item is None: parent = self.get_item_parent(self.selected_item) if parent: p_type = parent[7] if p_type == TAG_List: k = parent[9].list_type v = None for key, value in item_types_map.items(): if globals().get(key.__name__.upper(), -1) == k: v = value break if v is None: return types_item = {v[0]: (key, v[1], v[2])} Tree.add_item(self, types_item) def add_child(self, types_item=None): if types_item is None: parent = self.selected_item p_type = parent[7] if p_type == TAG_List: k = parent[9].list_type v = None for key, value in item_types_map.items(): if globals().get(key.__name__.upper(), -1) == k: v = value break if v is None: return types_item = {v[0]: (key, v[1], v[2])} Tree.add_child(self, types_item) def delete_item(self): parent = self.get_item_parent(self.selected_item) if parent: if parent[7] == TAG_List: del parent[9][parent[9].value.index(self.selected_item[9])] else: del parent[9][self.selected_item[9].name] else: del self.data[self.selected_item[9].name] self.selected_item_index = None self.selected_item = None self.build_layout() def rename_item(self): result = input_text_buttons("Choose a name", 300, self.selected_item[3]) if isinstance(result, (str, unicode)): self.selected_item[3] = result self.selected_item[9].name = result self.build_layout() def click_item(self, *args, **kwargs): Tree.click_item(self, *args, **kwargs) if self._parent and self.selected_item: self._parent.update_side_panel(self.selected_item) @staticmethod def draw_image(surf, bg, r): blit_in_rect(surf, bg, r, 'c') @staticmethod def draw_square(surf, bg, r): draw.polygon(surf, bg, [r.topleft, r.topright, r.bottomright, r.bottomleft]) @staticmethod def draw_circle(surf, bg, r): draw.circle(surf, bg, ((r.left + r.right) / 2, (r.top + r.bottom) / 2), min(r.height / 2, r.width / 2)) def draw_TAG_bullet(self, surf, bg, fg, shape, text, item_text, lvl): r = self.get_bullet_rect(surf, lvl) meth = getattr(self, 'draw_%s' % shape, None) if meth and config.nbtTreeSettings.useBulletStyles.get(): meth(surf, bg, r) self.draw_item_text(surf, r, item_text) else: self.draw_deadend_bullet(surf, self.bullet_color_inactive, fg, shape, text, item_text, lvl) if text and config.nbtTreeSettings.useBulletStyles.get() and config.nbtTreeSettings.useBulletText.get(): buf = self.font.render(text, True, fg or self.fg_color) blit_in_rect(surf, buf, r, 'c') if config.nbtTreeSettings.useBulletImages.get(): self.draw_item_text(surf, r, item_text) def parse_TAG_List(self, name, data): values = {} i = 0 for value in data: if hasattr(value, 'get'): value_name = value.get('Name', None) if value_name: value_name = value_name.value else: value_name = value.name values[value_name or u"%s #%03d" % (name, i)] = value i += 1 return values # ----------------------------------------------------------------------------- class NBTExplorerOptions(ToolOptions): def __init__(self, tool): ToolOptions.__init__(self, name='Panel.NBTExplorerOptions') self.tool = tool useStyleBox = CheckBoxLabel(title="Use Bullet Styles", ref=config.nbtTreeSettings.useBulletStyles) self.useStyleBox = useStyleBox useTextBox = CheckBoxLabel(title="Use Bullet Text", ref=config.nbtTreeSettings.useBulletText) self.useTextBox = useTextBox useImagesBox = CheckBoxLabel(title="Use Bullet Images", ref=config.nbtTreeSettings.useBulletImages) self.useImagesBox = useImagesBox bulletFilePath = Row((Button("Bullet Images File", action=self.open_bullet_file), TextFieldWrapped(ref=config.nbtTreeSettings.bulletFileName, width=300)), margin=0) defaultBulletImagesBox = CheckBoxLabel(title="Reset to default", ref=config.nbtTreeSettings.defaultBulletImages) self.defaultBulletImagesBox = defaultBulletImagesBox def mouse_down(e): CheckBox.mouse_down(defaultBulletImagesBox.subwidgets[1], e) self.defaultBulletImagesBox_click(e) defaultBulletImagesBox.subwidgets[1].mouse_down = mouse_down frameContent = Column((defaultBulletImagesBox, bulletFilePath)) color = self.bg_color if len(color) == 4: color = (max(color[0] + 200, 255), max(color[1] + 200, 255), max(color[2] + 200, 255), max(color[3] + 100,255)) else: color = tuple([max([i] * 2, 255) for i in color]) bulletFilePathFrame = Frame(frameContent, border_width=1, border_color=color) bulletFilePathFrame.add_centered(frameContent) def mouse_down(e): if self.bulletFilePath.subwidgets[1].enabled: TextFieldWrapped.mouse_down(self.bulletFilePath.subwidgets[1], e) bulletFilePath.subwidgets[1].mouse_down = mouse_down self.bulletFilePath = bulletFilePath def mouse_down(e): CheckBox.mouse_down(useImagesBox.subwidgets[1], e) for sub in defaultBulletImagesBox.subwidgets: sub.enabled = config.nbtTreeSettings.useBulletImages.get() if isinstance(sub, (CheckBox, TextFieldWrapped)): if config.nbtTreeSettings.useBulletImages.get(): sub.fg_color = fg_color else: sub.fg_color = disabled_color if isinstance(sub, CheckBox): sub.set_enabled(config.nbtTreeSettings.useBulletImages.get()) self.defaultBulletImagesBox_click(None) useImagesBox.subwidgets[0].mouse_down = useImagesBox.subwidgets[1].mouse_down = mouse_down def mouse_down(e): CheckBox.mouse_down(useStyleBox.subwidgets[1], e) useImagesBox.mouse_down(e) self.useStyleBox_click(e) useStyleBox.subwidgets[0].mouse_down = useStyleBox.subwidgets[1].mouse_down = mouse_down showAllTags = CheckBoxLabel(title="Show all the tags in the tree", ref=config.nbtTreeSettings.showAllTags) col = Column(( Label("NBT Tree Settings"), Row((useStyleBox, useTextBox, useImagesBox)), bulletFilePathFrame, showAllTags, Button("OK", action=self.dismiss), )) self.add(col) self.shrink_wrap() self.useStyleBox_click(None) self.defaultBulletImagesBox_click(None) def defaultBulletImagesBox_click(self, e): enabled = not config.nbtTreeSettings.defaultBulletImages.get() \ and config.nbtTreeSettings.useBulletImages.get() \ and config.nbtTreeSettings.useBulletStyles.get() for sub in self.bulletFilePath.subwidgets: sub.enabled = enabled if isinstance(sub, TextFieldWrapped): if enabled: sub.fg_color = fg_color else: sub.fg_color = disabled_color global bullet_image bullet_image = None def useStyleBox_click(self, e): for widget in (self.useTextBox, self.useImagesBox): for sub in widget.subwidgets: sub.enabled = config.nbtTreeSettings.useBulletStyles.get() if isinstance(sub, (CheckBox, TextFieldWrapped)): if config.nbtTreeSettings.useBulletStyles.get(): sub.fg_color = fg_color else: sub.fg_color = disabled_color if isinstance(sub, CheckBox): sub.set_enabled(config.nbtTreeSettings.useBulletStyles.get()) for sub in self.defaultBulletImagesBox.subwidgets: sub.enabled = config.nbtTreeSettings.useBulletImages.get() if isinstance(sub, (CheckBox, TextFieldWrapped)): if config.nbtTreeSettings.useBulletImages.get(): sub.fg_color = fg_color else: sub.fg_color = disabled_color if isinstance(sub, CheckBox): sub.set_enabled(config.nbtTreeSettings.useBulletImages.get()) self.defaultBulletImagesBox_click(None) 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 dismiss(self, *args, **kwargs): bullet_styles = change_styles() if hasattr(self.tool, 'panel') and self.tool.panel is not None: self.tool.panel.tree.styles = bullet_styles self.tool.panel.tree.update_draw_bullets_methods(bullet_styles) self.tool.panel.tree.build_layout() ToolOptions.dismiss(self, *args, **kwargs) # ----------------------------------------------------------------------------- # &# Prototype for blocks/items names class SlotEditor(Dialog): def __init__(self, inventory, data, *args, **kwargs): Dialog.__init__(self, *args, **kwargs) self.inventory = inventory slot, id, count, damage = data self.former_id_text = id self.slot = slot self.id = TextFieldWrapped(text=str(id), doNotTranslate=True, width=300) self.id.change_action = self.text_entered self.id.escape_action = self.cancel self.id.enter_action = self.ok self.count = IntField(text="%s" % count, min=0, max=64) self.damage = IntField(text="%s" % damage, min=0, max=os.sys.maxint) header = Label(_("Inventory Slot #%s") % slot, doNotTranslate=True) row = Row([Label("id"), self.id, Label("Count"), self.count, Label("Damage"), self.damage, ]) self.matching_items = [mclangres.translate(k) for k in map_items.keys()] self.matching_items.sort() self.selected_item_index = None if id in self.matching_items: self.selected_item_index = self.matching_items.index(id) self.tableview = tableview = TableView(columns=[TableColumn("", 415, 'l')]) tableview.num_rows = lambda: len(self.matching_items) tableview.row_data = lambda x: (self.matching_items[x],) tableview.row_is_selected = lambda x: x == self.selected_item_index tableview.click_row = self.select_tablerow buttons = Row([Button("Save", action=self.dismiss), Button("Cancel", action=self.cancel)]) col = Column([header, row, tableview, buttons], spacing=2) self.add(col) self.shrink_wrap() try: self.tableview.rows.scroll_to_item(self.selected_item_index) except Exception, e: print e pass def ok(self, *args, **kwargs): self.id.set_text(self.matching_items[self.selected_item_index]) kwargs['save'] = True self.dismiss(*args, **kwargs) def select_tablerow(self, i, e): old_index = self.selected_item_index self.selected_item_index = i if e.num_clicks > 1 and old_index == i: self.id.set_text(self.matching_items[self.selected_item_index]) self.dismiss(save=True) def cancel(self, *args, **kwargs): kwargs['save'] = False self.dismiss(*args, **kwargs) def dismiss(self, *args, **kwargs): if kwargs.pop('save', True): data = [self.slot, self.id.text, self.count.text, self.damage.text] self.inventory.change_value(data) Dialog.dismiss(self, *args, **kwargs) def text_entered(self): text = self.id.get_text() if self.former_id_text == text: return results = [] for k in map_items.keys(): k = mclangres.translate(k) if text.lower() in k.lower(): results.append(k) results.sort() self.matching_items = results self.selected_item_index = 0 self.tableview.rows.scroll_to_item(self.selected_item_index) def dispatch_key(self, name, evt): super(SlotEditor, self).dispatch_key(name, evt) if name == "key_down": keyname = self.root.getKey(evt) if keyname == "Up" and self.selected_item_index > 0: self.selected_item_index -= 1 elif keyname == "Down" and self.selected_item_index < len(self.matching_items) - 1: self.selected_item_index += 1 elif keyname == 'Page down': self.selected_item_index = min(len(self.matching_items) - 1, self.selected_item_index + self.tableview.rows.num_rows()) elif keyname == 'Page up': self.selected_item_index = max(0, self.selected_item_index - self.tableview.rows.num_rows()) if self.tableview.rows.cell_to_item_no(0, 0) != None and (self.tableview.rows.cell_to_item_no(0, 0) + self.tableview.rows.num_rows() - 1 > self.selected_item_index or self.tableview.rows.cell_to_item_no( 0, 0) + self.tableview.rows.num_rows() - 1 < self.selected_item_index): self.tableview.rows.scroll_to_item(self.selected_item_index) # &# # ----------------------------------------------------------------------------- class NBTExplorerOperation(Operation): def __init__(self, toolPanel): super(NBTExplorerOperation, self).__init__(toolPanel.editor, toolPanel.editor.level) self.toolPanel = toolPanel self.tool = self.editor.nbtTool self.canUndo = False def extractUndo(self): if self.toolPanel.nbtObject.get(self.toolPanel.dataKeyName): return copy.deepcopy(self.toolPanel.nbtObject[self.toolPanel.dataKeyName]) else: return copy.deepcopy(self.toolPanel.nbtObject) def perform(self, recordUndo=True): if self.toolPanel.nbtObject: if self.toolPanel.nbtObject.get(self.toolPanel.dataKeyName): orgNBT = self.toolPanel.nbtObject[self.toolPanel.dataKeyName] else: orgNBT = self.toolPanel.nbtObject newNBT = self.toolPanel.data if "%s" % orgNBT != "%s" % newNBT: if self.level.saving: alert(_("Cannot perform action while saving is taking place")) return if recordUndo: self.canUndo = True self.undoLevel = self.extractUndo() if self.toolPanel.nbtObject.get(self.toolPanel.dataKeyName): self.toolPanel.nbtObject[self.toolPanel.dataKeyName] = self.toolPanel.data else: self.toolPanel.bntObject = self.toolPanel.data def undo(self): if self.undoLevel: self.redoLevel = self.extractUndo() self.toolPanel.data.update(self.undoLevel) if self.toolPanel.nbtObject.get(self.toolPanel.dataKeyName): self.toolPanel.nbtObject[self.toolPanel.dataKeyName] = self.undoLevel else: self.toolPanel.nbtObject = self.undoLevel self.update_tool() def redo(self): if self.redoLevel: self.toolPanel.data.update(self.redoLevel) if self.toolPanel.nbtObject.get(self.toolPanel.dataKeyName): self.toolPanel.nbtObject[self.toolPanel.dataKeyName] = self.redoLevel else: self.toolPanel.nbtObject = self.redoLevel self.update_tool() def update_tool(self): toolPanel = self.tool.panel if toolPanel: index = toolPanel.tree.selected_item_index toolPanel.tree.build_layout() toolPanel.tree.selected_item_index = index if index is not None: item = toolPanel.tree.rows[index] toolPanel.tree.selected_item = item toolPanel.displayed_item = None toolPanel.update_side_panel(item) # ----------------------------------------------------------------------------- class NBTExplorerToolPanel(Panel): """...""" def __init__(self, editor, nbtObject=None, fileName=None, savePolicy=0, dataKeyName='Data', close_text="Close", load_text="Open", magic=None, **kwargs): """...""" Panel.__init__(self, name='Panel.NBTExplorerToolPanel') self.editor = editor self.nbtObject = nbtObject self.fileName = fileName self.savePolicy = savePolicy self.displayed_item = None self.dataKeyName = dataKeyName self.magic = magic self.copy_data = kwargs.get('copy_data', True) self.init_data() btns = [] if load_text: btns.append(Button(load_text, action=self.editor.nbtTool.loadFile)) btns += [ Button({True: "Save", False: "OK"}[fileName != None], action=kwargs.get('ok_action', self.save_NBT), tooltipText="Save your change in the NBT data."), Button("Reset", action=kwargs.get('reset_action', self.reset), tooltipText="Reset ALL your changes in the NBT data."), ] if close_text: btns.append(Button(close_text, action=kwargs.get('close_action', self.close))) btnRow = Row(btns, margin=1, spacing=4) btnRow.shrink_wrap() self.btnRow = btnRow if kwargs.get('no_header', False): self.max_height = max_height = kwargs.get('height', editor.mainViewport.height - editor.toolbar.height - editor.subwidgets[0].height) - ( self.margin * 2) - btnRow.height - 2 else: title = _("NBT Explorer") if fileName: title += " - %s" % os.path.split(fileName)[-1] header = Label(title, doNotTranslate=True) self.max_height = max_height = kwargs.get('height', editor.mainViewport.height - editor.toolbar.height - editor.subwidgets[0].height) - header.height - ( self.margin * 2) - btnRow.height - 2 self.setCompounds() self.tree = NBTTree(height=max_height - btnRow.height - 2, inner_width=250, data=self.data, compound_types=self.compounds, copyBuffer=editor.nbtCopyBuffer, draw_zebra=False, _parent=self, styles=bullet_styles) self.tree.update_side_panel = self.update_side_panel self.side_panel_width = 350 row = [self.tree, Column([Label("", width=self.side_panel_width), ], margin=0)] self.displayRow = Row(row, height=max_height, margin=0, spacing=0) if kwargs.get('no_header', False): self.add(Column([self.displayRow, btnRow], margin=0)) else: self.add(Column([header, self.displayRow, btnRow], margin=0)) self.shrink_wrap() self.side_panel = None # &# Prototype for Blocks/item names mclangres.buildResources(lang=getLang()) def set_update_ui(self, v): Panel.set_update_ui(self, v) if v: mclangres.buildResources(lang=getLang()) # &# def key_down(self, e): self.dispatch_key('key_down', e) def dispatch_key(self, event_name, e): if not hasattr(e, 'key'): return if event_name == 'key_down': caught = True keyname = self.root.getKey(e) if keyname == 'Escape': if not self.tree.has_focus(): self.tree.focus() else: self.editor.key_down(e) elif self.side_panel and self.side_panel.has_focus(): self.side_panel.dispatch_key(event_name, e) elif keyname == 'Return': self.tree.dispatch_key(event_name, e) else: caught = False if not caught: self.tree.dispatch_key(event_name, e) def setCompounds(self): if config.nbtTreeSettings.showAllTags.get(): compounds = [TAG_Compound, TAG_List] else: compounds = [TAG_Compound, ] self.compounds = compounds def save_NBT(self): if self.fileName: self.editor.nbtTool.saveFile(self.fileName, self.data, self.savePolicy, self.magic) else: op = NBTExplorerOperation(self) self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() def init_data(self): data = {} if self.nbtObject is None and hasattr(self.editor.level, 'root_tag'): self.nbtObject = self.editor.level.root_tag self.copy_data = False if self.nbtObject: if self.nbtObject.get('Data'): if self.copy_data: data = copy.deepcopy(self.nbtObject[self.dataKeyName]) else: data = self.nbtObject[self.dataKeyName] else: if self.copy_data: data = copy.deepcopy(self.nbtObject) else: data = self.nbtObject self.data = data self.setCompounds() if hasattr(self, 'tree'): self.tree.set_parent(None) self.tree = NBTTree(height=self.max_height - self.btnRow.height - 2, inner_width=250, data=self.data, compound_types=self.compounds, copyBuffer=self.editor.nbtCopyBuffer, draw_zebra=False, _parent=self, styles=bullet_styles) self.displayRow.subwidgets[0].subwidgets.insert(0, self.tree) self.tree.set_parent(self.displayRow.subwidgets[0]) def reset(self): self.editor.nbtTool.hidePanel() self.editor.nbtTool.showPanel() def close(self): self.editor.toolbar.selectTool(0) self.editor.nbtTool.hidePanel() def update_side_panel(self, item): if item == self.displayed_item: return self.displayed_item = item if self.side_panel: self.side_panel.set_parent(None) items = [a for a in item[1]] rows = [] if config.nbtTreeSettings.showAllTags.get(): meth = None else: meth = getattr(self, 'build_%s' % item[3].lower(), None) col = True if meth and len(items) == 1: rows = meth(items) else: height = 0 for itm in items: t = itm.__class__.__name__ rows.append(Row([Label("Data Type:"), Label(t)], margin=1)) fields = self.build_field(itm) for field in fields: if isinstance(field, TextFieldWrapped): field.set_size_for_text(self.side_panel_width) row = Row([field, ], margin=1) rows.append(row) height += row.height if height > self.displayRow.height: col = False if rows: if col: col = Column(rows, align='l', spacing=0, height=self.displayRow.height) else: col = ScrollPanel(rows=rows, align='l', spacing=0, height=self.displayRow.height, draw_zebra=False, inner_width=self.side_panel_width - scroll_button_size) col.set_parent(self.displayRow) col.top = self.displayRow.top col.left = self.displayRow.subwidgets[0].right col.bottom = self.displayRow.subwidgets[0].bottom col.shrink_wrap() self.side_panel = col @staticmethod def build_field(itm): fields = [] if type(itm) in field_types.keys(): f, bounds = field_types[type(itm)] if bounds: fields = [f(ref=AttrRef(itm, 'value'), min=bounds[0], max=bounds[1]), ] else: fields = [f(ref=AttrRef(itm, 'value')), ] elif type(itm) in array_types.keys(): idx = 0 for _itm in itm.value.tolist(): f, bounds = array_types[type(itm)] fields.append(f(ref=ItemRef(itm.value, idx))) idx += 1 elif isinstance(itm, (TAG_Compound, TAG_List)): for _itm in itm.value: fields.append( Label("%s" % (_itm.name or "%s #%03d" % (itm.name or _("Item"), itm.value.index(_itm))), align='l', doNotTranslate=True)) fields += NBTExplorerToolPanel.build_field(_itm) elif not isinstance(itm, (str, unicode)): if not isinstance(getattr(itm, 'value', itm), (str, unicode, int, float)): fld = Label kw = {'align': 'l'} else: fld = TextFieldWrapped kw = {} fields = [fld("%s" % getattr(itm, 'value', itm), doNotTranslate=True, **kw), ] else: fields = [TextFieldWrapped("%s" % itm, doNotTranslata=True), ] return fields @staticmethod def build_attributes(items): rows = [] attributes = items[0] names = [a['Name'].value for a in attributes] indexes = [] + names names.sort() for name in names: item = attributes[indexes.index(name)] rows.append(Row([Label(name.split('.')[-1], align='l')] + NBTExplorerToolPanel.build_field(item['Base']), margin=0)) mods = item.get('Modifiers', []) for mod in mods: keys = mod.keys() keys.remove('Name') rows.append(Row([Label("-> Name", align='l')] + NBTExplorerToolPanel.build_field(mod['Name']), margin=0)) keys.sort() for key in keys: rows.append(Row( [Label(' %s' % key, align='l', doNotTranslate=True, tooltipText=mod[key].__class__.__name__)] \ + NBTExplorerToolPanel.build_field(mod[key]), margin=0)) return rows def build_motion(self, items): return self.build_pos(items) @staticmethod def build_pos(items): rows = [] pos = items[0] rows.append(Row([Label("X", align='l'), FloatField(ref=AttrRef(pos[0], 'value'))])) rows.append(Row([Label("Y", align='l'), FloatField(ref=AttrRef(pos[1], 'value'))])) rows.append(Row([Label("Z", align='l'), FloatField(ref=AttrRef(pos[2], 'value'))])) return rows @staticmethod def build_rotation(items): rows = [] rotation = items[0] rows.append(Row([Label("Y", align='l'), FloatField(ref=AttrRef(rotation[0], 'value'))])) rows.append(Row([Label("X", align='l'), FloatField(ref=AttrRef(rotation[1], 'value'))])) return rows def build_inventory(self, items): if not map_block: build_map_block() parent = self.tree.get_item_parent(self.displayed_item) if parent: parent = parent[9] else: parent = self.data if 'playerGameType' in parent.keys(): player = True else: player = False inventory = parent.get('Inventory', TAG_List()) rows = [] items = items[0] slots = [["%s" % i, "", "0", "0"] for i in xrange(36)] slots += [["%s" % i, "", "0", "0"] for i in xrange(100, 104)] slots_set = [] for item, i in zip(items, xrange(len(items))): # &# Prototype for blocks/items names item_dict = mcitems.items.get(item['id'].value, None) if item_dict is None: item_name = item['id'].value else: if isinstance(item_dict['name'], list): if int(item['Damage'].value) >= len(item_dict['name']): block_id = map_block.get(item['id'].value, None) item_name = alphaMaterials.get((int(block_id), int(item['Damage'].value))).name.rsplit('(', 1)[ 0].strip() else: item_name = item_dict['name'][int(item['Damage'].value)] else: item_name = item_dict['name'] s = i _s = 0 + i if player: s = int(item['Slot'].value) _s = 0 + s slots_set.append(s) if s >= 100: s = s - 100 + 36 if isinstance(item_name, (unicode, str)): translated_item_name = mclangres.translate(item_name) else: translated_item_name = item_name slots[s] = _s, translated_item_name, item['Count'].value, item['Damage'].value # slots[s] = item['Slot'].value, item['id'].value.split(':')[-1], item['Count'].value, item['Damage'].value # &# width = self.side_panel_width - self.margin * 5 c0w = max(15, self.font.size("000")[0]) + 4 c2w = max(15, self.font.size("00")[0]) + 4 c3w = max(15, self.font.size("000")[0]) + 4 c1w = width - c0w - c2w - c3w font_height = self.font.size("qd")[1] tableCols = [TableColumn("#", c0w), TableColumn("ID", c1w), TableColumn("C", c2w), TableColumn("D", c3w), ] height = self.displayRow.subwidgets[0].height table = TableView(height=height - (self.margin * 2), width=width, nrows=((height - (self.margin * 2) - font_height / 2) / font_height), columns=tableCols, row_height=font_height, header_height=font_height / 2) table.rows.tooltipText = "Double-click to edit" table.selected_row = None table.slots = slots def num_rows(): return len(slots) table.num_rows = num_rows def row_data(n): return slots[n] table.row_data = row_data def click_row(n, e): table.focus() table.selected_row = n if e.num_clicks > 1: SlotEditor(table, row_data(n)).present() table.click_row = click_row def row_is_selected(n): return n == table.selected_row table.row_is_selected = row_is_selected def change_value(data): s, i, c, d = data s = int(s) s_idx = 0 # &# Prototype for blocks/items names name, state = map_items.get(mclangres.untranslate(i), (i, '0')) if ':' not in name: name = 'minecraft:%s' % name # &# if s in slots_set: for slot in inventory: ok1 = False if player: ok1 = slot['Slot'].value == s else: ok1 = inventory.index(slot) == s if ok1: if not i or int(c) < 1: del inventory[s_idx] i = "" c = u'0' d = u'0' else: # &# Prototype for blocks/items names # slot['id'].value = 'minecraft:%s'%i slot['id'].value = name # &# slot['Count'].value = int(c) slot['Damage'].value = int(state) break s_idx += 1 else: new_slot = TAG_Compound() if player: new_slot['Slot'] = TAG_Byte(s) # &# Prototype for blocka/items names # new_slot['id'] = TAG_String('minecraft:%s'%i) new_slot['id'] = TAG_String(name) # &# new_slot['Count'] = TAG_Byte(int(c)) new_slot['Damage'] = TAG_Short(int(state)) idx = s for slot in inventory: ok2 = False if player: ok2 = slot['Slot'].value >= s else: ok2 = inventory.index(slot) >= s if ok2: idx = slot['Slot'].value break inventory.insert(s, new_slot) slots_set.append(s) # &# Prototype for blocks/items names # if i == name: # i = name # &# if s >= 100: n = s - 100 + 36 else: n = s table.slots[n] = slots[n] = s, i, c, state table.change_value = change_value def dispatch_key(name, evt): keyname = self.root.getKey(evt) if keyname == 'Return': SlotEditor(table, row_data(table.selected_row)).present() elif keyname == "Up" and table.selected_row > 0: table.selected_row -= 1 table.rows.scroll_to_item(table.selected_row) elif keyname == "Down" and table.selected_row < len(slots) - 1: table.selected_row += 1 table.rows.scroll_to_item(table.selected_row) elif keyname == 'Page down': table.selected_row = min(len(slots) - 1, table.selected_row + table.rows.num_rows()) elif keyname == 'Page up': table.selected_row = max(0, table.selected_row - table.rows.num_rows()) someRowBool = table.rows.cell_to_item_no(0, 0) + table.rows.num_rows() - 1 != table.selected_row if table.rows.cell_to_item_no(0, 0) is not None and someRowBool: table.rows.scroll_to_item(table.selected_row) table.dispatch_key = dispatch_key rows.append(table) return rows # ----------------------------------------------------------------------------- class NBTExplorerTool(EditorTool): """...""" tooltipText = "NBT Explorer\nDive into level NBT structure.\nRight-click for options" _alreadyHidden = False @property def alreadyHidden(self): return NBTExplorerTool._alreadyHidden @alreadyHidden.setter def alreadyHidden(self, v): NBTExplorerTool._alreadyHidden = v def __init__(self, editor): """...""" self.optionsPanel = NBTExplorerOptions(self) self.toolIconName = 'nbtexplorer' self.editor = editor self.editor.nbtTool = self def toolSelected(self): self.showPanel() def toolReselected(self): self.showPanel() def showPanel(self, fName=None, nbtObject=None, savePolicy=0, dataKeyName='Data', magic=None): """...""" if self.panel is None and self.editor.currentTool in (self, None): # or nbtObject: # !# BAD HACK try: class fakeStdErr: def __init__(self, *args, **kwargs): pass def write(self, *args, **kwargs): pass stderr = os.sys.stderr os.sys.stderr = fakeStdErr() os.sys.stderr = stderr except: alert("Unattended data. File not loaded") return # !# self.panel = NBTExplorerToolPanel(self.editor, nbtObject=nbtObject, fileName=fName, savePolicy=savePolicy, dataKeyName=dataKeyName, magic=magic) self.panel.centery = (self.editor.mainViewport.height - self.editor.toolbar.height) / 2 + \ self.editor.subwidgets[0].height self.panel.left = self.editor.left self.editor.add(self.panel) def loadFile(self, fName=None): nbtObject, dataKeyName, savePolicy, fName, magic = loadFile(fName) if nbtObject is not None: self.editor.toolbar.removeToolPanels() self.editor.currentTool = self self.showPanel(fName, nbtObject, savePolicy, dataKeyName, magic) self.optionsPanel.dismiss() def saveFile(self, fName, data, savePolicy, magic): saveFile(fName, data, savePolicy, magic) def keyDown(self, *args, **kwargs): if self.panel: self.panel.key_down(*args, **kwargs) # ------------------------------------------------------------------------------ def loadFile(fName): """Loads a NBT file. :fName: str/unicode: full file path to load. Returns a 5 element tuple: (object nbtObject, string dataKeyName, int savePolicy, int/None magic). 'magic' is used for PE support.""" if not fName: fName = mcplatform.askOpenFile(title=_("Select a NBT (.dat) file..."), suffixes=['dat', 'nbt']) if fName: if not os.path.isfile(fName): alert("The selected object is not a file.\nCan't load it.") return savePolicy = 0 magic = None fp = open(fName) data = fp.read() fp.close() _magic = struct.Struct('<i').unpack(data[:4])[0] if 2 < _magic < 6: # We have a PE world. magic = _magic 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'): t = TAG_Compound(name='Data') t.add(nbtObject) nbtObject = t 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, magic return [None] * 5 def saveFile(fName, data, savePolicy, magic): """Saves the NBT data to the disk. :fName: str/unicode: full file path to save data to. :data: object: NBT data to be saved. :savePolicy: int (-1, 0 or 1): special bit to handle different data types. :magic: int/None: 'magic' number for PE worlds.""" if fName is None: return if os.path.exists(fName): r = ask("File already exists.\nClick 'OK' to choose one.") if r == "OK": folder, name = os.path.split(fName) suffix = os.path.splitext(name)[-1][1:] file_types = _("Levels and Schematics") + "\0*.dat;*.nbt" if "*.%s"%suffix not in file_types: file_types += "\0*.{0}\0*.{0}".format(suffix) file_types += "\0\0" fName = mcplatform.askSaveFile(folder, "Choose a NBT file...", name, file_types, suffix) else: return if fName: if savePolicy in (-1, 1): if data.get('Schematic'): data = data['Schematic'] elif hasattr(data, 'name'): data.name = "" if not os.path.isdir(fName): if savePolicy <= 0: data.save(fName) elif savePolicy == 1: with littleEndianNBT(): # Here we have a PE data file. Just strip out the toSave = data.save(compressed=False) toSave = struct.Struct('<i').pack(magic) + struct.Struct('<i').pack(len(toSave)) + toSave with open(fName, 'wb') as f: f.write(toSave) else: alert("The selected object is not a file.\nCan't save it.")
52,719
39.616333
212
py
MCEdit-Unified
MCEdit-Unified-master/albow/file_dialogs.py
# -*- coding: utf-8 -*- # # Albow - File Dialogs # #-# Modified by D.C.-G. for translation purpose """ TODO: * Implement Windows support. """ import os, sys from pygame import event, image from pygame.transform import scale from pygame.locals import * from albow.widget import Widget from albow.dialogs import Dialog, ask, alert from albow.controls import Label, Button, Image from albow.extended_widgets import ChoiceButton from albow.fields import TextFieldWrapped from albow.layout import Row, Column from albow.scrollpanel import ScrollPanel from albow.theme import ThemeProperty from translate import _ from tree import Tree import logging log = logging.getLogger(__name__) DEBUG = True if DEBUG: from albow.resource import get_image def get_imgs(): """Load an return the images used as file and folder icons.""" print "*** MCEDIT DEBUG: file_dialog:", __file__ print "*** MCEDIT DEBUG: directory:", os.path.dirname(__file__) print "*** MCEDIT DEBUG: current directory:", os.getcwd() try: file_image = get_image('file.png', prefix='') folder_image = get_image('folder.png', prefix='') except Exception as e: print "MCEDIT DEBUG: Could not load file dialog images." print e from pygame import draw, Surface from pygame.locals import SRCALPHA from math import pi file_image = Surface((16, 16), SRCALPHA) file_image.fill((0,0,0,0)) draw.lines(file_image, (255, 255, 255, 255), False, [[3, 15], [3, 1], [13, 1]], 2) draw.line(file_image, (255, 255, 255, 255), [3, 7], [10, 7], 2) folder_image = Surface((16, 16), SRCALPHA) folder_image.fill((0,0,0,0)) draw.line(folder_image, (255, 255, 255, 255), [3, 15], [3, 1], 2) draw.arc(folder_image, (255, 255, 255, 255), [0, 1, 13, 15], 0, pi/1.9, 2) draw.arc(folder_image, (255, 255, 255, 255), [0, 1, 13, 15], 3*pi/2, 2*pi, 2) return file_image, folder_image else: from directories import getDataDir, getDataFile if sys.platform in ('darwin', 'linux2'): print "*** MCEDIT DEBUG: file_dialog:", __file__ print "*** MCEDIT DEBUG: directory:", os.path.dirname(__file__) print "*** MCEDIT DEBUG: current directory:", os.getcwd() try: file_image = image.load('file.png') folder_image = image.load('folder.png') except Exception as e: print "MCEDIT DEBUG: Could not load file dialog images." print e from pygame import draw, Surface from pygame.locals import SRCALPHA from math import pi file_image = Surface((16, 16), SRCALPHA) file_image.fill((0,0,0,0)) draw.lines(file_image, (255, 255, 255, 255), False, [[3, 15], [3, 1], [13, 1]], 2) draw.line(file_image, (255, 255, 255, 255), [3, 7], [10, 7], 2) folder_image = Surface((16, 16), SRCALPHA) folder_image.fill((0,0,0,0)) draw.line(folder_image, (255, 255, 255, 255), [3, 15], [3, 1], 2) draw.arc(folder_image, (255, 255, 255, 255), [0, 1, 13, 15], 0, pi/1.9, 2) draw.arc(folder_image, (255, 255, 255, 255), [0, 1, 13, 15], 3*pi/2, 2*pi, 2) else: # windows #file_image = image.load(os.path.join(getDataDir(), 'file.png')) #folder_image = image.load(os.path.join(getDataDir(), 'folder.png')) file_image = image.load(getDataFile('file.png')) folder_image = image.load(getDataFile('folder.png')) class DirPathView(Widget): def __init__(self, width, client, **kwds): Widget.__init__(self, **kwds) self.set_size_for_text(width) self.client = client def draw(self, surf): frame = self.get_margin_rect() image = self.font.render(self.client.directory, True, self.fg_color) tw = image.get_width() mw = frame.width if tw <= mw: x = 0 else: x = mw - tw surf.blit(image, (frame.left + x, frame.top)) class FileListView(ScrollPanel): def __init__(self, width, client, **kwds): kwds['align'] = kwds.get('align', 'l') ScrollPanel.__init__(self, inner_width=width, **kwds) if DEBUG: file_image, folder_image = get_imgs() self.icons = {True: scale(folder_image, (self.row_height, self.row_height)), False: scale(file_image, (self.row_height, self.row_height))} self.client = client self.names = [] def update(self): client = self.client dir = client.directory def filter(name): path = os.path.join(dir, name) return os.path.isdir(path) or self.client.filter(path) try: content = os.walk(dir) for a, dirnames, filenames in content: dirnames.sort() filenames.sort() break try: self.names = [unicode(name, 'utf-8') for name in dirnames + filenames if filter(name)] except: self.names = [name for name in dirnames + filenames if filter(name)] except EnvironmentError as e: alert(u"%s: %s" % (dir, e)) self.names = [] self.rows = [Row([Image(self.icons[os.path.isdir(os.path.join(dir, a))]), Label(a, margin=0)], margin=0, spacing=2) for a in self.names] self.selected_item_index = None self.scroll_to_item(0) def scroll_to_item(self, *args, **kwargs): self.scrollRow.scroll_to_item(*args, **kwargs) def num_items(self): return len(self.names) def click_item(self, item_no, e): self.selected_item_index = item_no ScrollPanel.click_item(self, item_no, e) if e.num_clicks == 2: self.client.dir_box_click(True) def item_is_selected(self, item_no): return item_no == self.selected_item_index def get_selected_name(self): sel = self.selected_item_index if sel is not None: return self.names[sel] else: return "" def get_platform_root_dir(): #-# Rework this in order to mimic the OSs file chooser behaviour. #-# Need platform/version specific code... return '/' class FSTree(Tree): def __init__(self, client, *args, **kwargs): kwargs['draw_zebra'] = False self.client = client self.directory = get_platform_root_dir() self.content = content = os.walk(self.directory) if client is not None and hasattr(client, 'directory'): self.directory = client.directory self.directory = kwargs.pop('directory', self.directory) self.data = data = {} d = {} for dirpath, dirnames, filenames in content: for name in dirnames: d[name] = self.parse_path(name, os.path.join(dirpath, name)) data[dirpath] = d break kwargs['data'] = data Tree.__init__(self, *args, **kwargs) del self.menu self.set_directory(self.directory) def show_menu(self, *args, **kwargs): return def set_directory(self, directory): self.diretory = directory self.deployed = [] splitted_path = directory.split(os.sep) while '' in splitted_path: splitted_path.remove('') splitted_path.insert(0, '/') d = self.data path = "" while splitted_path: name = splitted_path.pop(0) path = os.path.join(path, name) d[name] = self.parse_path(name, path) rows = self.build_layout() i = 0 for row in rows: if row[3] == name and self.get_item_path(row) in directory: self.deployed.append(row[6]) self.clicked_item = row rows[i + 1:] = self.build_layout()[i + 1:] if directory == self.get_item_path(row): self.treeRow.scroll_to_item(rows.index(row)) self.selected_item_index = rows.index(row) self.selected_item = row break i += 1 d = d[name] def parse_path(self, name, path): #!# The log.debug() and print stuff in there are intended to fix some OSX issues. #!# Please do not strip them out. -- D.C.-G. # log.debug('FSTree.parse_path') # log.debug(' path: %s\n length: %d'%(repr(path), len(path))) # print ' path: %s\n length: %d'%(repr(path), len(path)) # log.debug(' path: %s\n length: %d'%(repr(path), len(path))) # if len(path) < 1: print ' ! ! ! ^ ^ ^ ! ! !' # if len(path) < 1: log.debug(' ! ! ! ^ ^ ^ ! ! !') content = os.walk(path) data = {} d = data for a, folders, b in content: # log.debug(' a: %s\n length: %d'%(repr(a), len(a))) # print ' a: %s\n length: %d'%(repr(a), len(a)) # log.debug(' a: %s\n length: %d'%(repr(a), len(a))) # if len(a) < 1: print ' ! ! ! ^ ^ ^ ! ! !' # if len(a) < 1: log.debug(' ! ! ! ^ ^ ^ ! ! !') d = {} for folder in folders: # log.debug(' folder: %s\n length: %d'%(repr(folder), len(folder))) # print ' folder: %s\n length: %d'%(repr(folder), len(folder)) # log.debug(' folder: %s\n length: %d'%(repr(folder), len(folder))) # if len(folder) < 1: print ' ! ! ! ^ ^ ^ ! ! !' # if len(folder) < 1: log.debug(' ! ! ! ^ ^ ^ ! ! !') if isinstance(folder, str): folder = unicode(folder, 'utf-8') d[folder] = {} if isinstance(a, str): a = unicode(a,'utf-8') cont = os.walk(os.path.join(a, folder)) for _a, fs, _b in cont: for f in fs: # log.debug(' f: %s\n length: %d'%(repr(f), len(f))) # print ' f: %s\n length: %d'%(repr(f), len(f)) # log.debug(' f: %s\n length: %d'%(repr(f), len(f))) # if len(f) < 1: print ' ! ! ! ^ ^ ^ ! ! !' # if len(f) < 1: log.debug(' ! ! ! ^ ^ ^ ! ! !') if isinstance(f, str): d[folder][unicode(f, 'utf-8')] = {} else: d[folder][f] = {} break break return d def get_item_path(self, item): path_list = [] if item is not None: id = item[6] parents = [item] while id != 1: item = self.get_item_parent(parents[-1]) if item is None: break id = item[6] parents.append(item) parents.reverse() path_list = [a[3] for a in parents] path = '/' for name in path_list: path = os.path.join(path, name) return path def deploy(self, id): path = self.get_item_path(self.clicked_item) self.clicked_item[9] = self.parse_path(self.clicked_item[3], path) Tree.deploy(self, id) def select_item(self, n): Tree.select_item(self, n) self.client.directory = self.get_item_path(self.selected_item) class FileDialog(Dialog): box_width = 450 default_prompt = None up_button_text = ThemeProperty("up_button_text") def __init__(self, prompt=None, suffixes=None, default_suffix=None, **kwds): Dialog.__init__(self, **kwds) label = None d = self.margin self.suffixes = suffixes or ("",) self.file_type = self.suffixes[0] # To be removed self.compute_file_types() self.default_suffix = default_suffix # The default file extension. Will be searched in 'suffixes'. up_button = Button(self.up_button_text, action=self.go_up) dir_box = DirPathView(self.box_width + 250, self) self.dir_box = dir_box top_row = Row([dir_box, up_button]) list_box = FileListView(self.box_width - 16, self) self.list_box = list_box tree = FSTree(self, inner_width=250, directory='/') self.tree = tree row = Row((tree, list_box), margin=0) ctrls = [top_row, row] prompt = prompt or self.default_prompt if prompt: label = Label(prompt) if suffixes: filetype_label = Label("File type", width=250) def set_file_type(): self.file_type = self.filetype_button.get_value() # To be removed self.compute_file_types(self.filetype_button.get_value()) self.list_box.update() filetype_button = ChoiceButton(choices=self.suffixes, width=250, choose=set_file_type) if default_suffix: v = next((s for s in self.suffixes if ("*.%s;"%default_suffix in s or "*.%s)"%default_suffix in s)), None) if v: filetype_button.selectedChoice = v self.compute_file_types(v) self.filetype_button = filetype_button if self.saving: filename_box = TextFieldWrapped(self.box_width) filename_box.change_action = self.update_filename filename_box._enter_action = filename_box.enter_action filename_box.enter_action = self.enter_action self.filename_box = filename_box if suffixes: ctrls.append(Row([Column([label, filename_box], align='l', spacing=0), Column([filetype_label, filetype_button], align='l', spacing=0) ], ) ) else: ctrls.append(Column([label, filename_box], align='l', spacing=0)) else: if label: ctrls.insert(0, label) if suffixes: ctrls.append(Column([filetype_label, filetype_button], align='l', spacing=0)) ok_button = Button(self.ok_label, action=self.ok, enable=self.ok_enable) self.ok_button = ok_button cancel_button = Button("Cancel", action=self.cancel) vbox = Column(ctrls, align='l', spacing=d) vbox.topleft = (d, d) y = vbox.bottom + d ok_button.topleft = (vbox.left, y) cancel_button.topright = (vbox.right, y) self.add(vbox) self.add(ok_button) self.add(cancel_button) self.shrink_wrap() self._directory = None self.directory = os.getcwdu() #print "FileDialog: cwd =", repr(self.directory) ### if self.saving: filename_box.focus() def compute_file_types(self, suffix=None): if suffix is None: suffix = self.suffixes[0] if suffix: self.file_types = [a.replace('*.', '.') for a in suffix.split('(')[-1].split(')')[0].split(';')] else: self.file_types = [".*"] def get_directory(self): return self._directory def set_directory(self, x): x = os.path.abspath(x) while not os.path.exists(x): y = os.path.dirname(x) if y == x: x = os.getcwdu() break x = y if os.path.isfile(x): x = os.path.dirname(x) if self._directory != x: self._directory = x self.list_box.update() self.update() directory = property(get_directory, set_directory) def filter(self, path): if os.path.isdir(path) or os.path.splitext(path)[1] in self.file_types or self.file_types == ['.*']: return True if os.path.isdir(path) or path.endswith(self.file_type.lower()) or self.file_type == '.*': return True def update(self): self.tree.set_directory(self.directory) def update_filename(self): if self.filename_box.text in self.list_box.names: self.directory = os.path.join(self.directory, self.filename_box.text) def go_up(self): self.directory = os.path.dirname(self.directory) self.list_box.scroll_to_item(0) def dir_box_click(self, double): if double: name = self.list_box.get_selected_name() path = os.path.join(self.directory, name) suffix = os.path.splitext(name)[1] if suffix not in self.suffixes and os.path.isdir(path): self.directory = path else: self.double_click_file(name) self.update() def enter_action(self): self.filename_box._enter_action() self.ok() def ok(self): self.dir_box_click(True) #self.dismiss(True) def cancel(self): self.dismiss(False) def key_down(self, evt): k = evt.key if k == K_RETURN or k == K_KP_ENTER: self.dir_box_click(True) if k == K_ESCAPE: self.cancel() class FileSaveDialog(FileDialog): saving = True default_prompt = "Save as:" ok_label = "Save" def get_filename(self): return self.filename_box.text def set_filename(self, x): self.filename_box.text = x filename = property(get_filename, set_filename) def get_pathname(self): name = self.filename if name: return os.path.join(self.directory, name) else: return None pathname = property(get_pathname) def double_click_file(self, name): self.filename_box.text = name def ok(self): path = self.pathname if path: if os.path.exists(path): answer = ask(_("Replace existing '%s'?") % os.path.basename(path)) if answer != "OK": return #FileDialog.ok(self) self.dismiss(True) def update(self): FileDialog.update(self) def ok_enable(self): return self.filename_box.text != "" class FileOpenDialog(FileDialog): saving = False ok_label = "Open" def get_pathname(self): name = self.list_box.get_selected_name() if name: return os.path.join(self.directory, name) else: return None pathname = property(get_pathname) #def update(self): # FileDialog.update(self) def ok_enable(self): path = self.pathname enabled = self.item_is_choosable(path) return enabled def item_is_choosable(self, path): return bool(path) and self.filter(path) def double_click_file(self, name): self.dismiss(True) class LookForFileDialog(FileOpenDialog): target = None def __init__(self, target, **kwds): FileOpenDialog.__init__(self, **kwds) self.target = target def item_is_choosable(self, path): return path and os.path.basename(path) == self.target def filter(self, name): return name and os.path.basename(name) == self.target def request_new_filename(prompt=None, suffix=None, extra_suffixes=None, directory=None, filename=None, pathname=None): if pathname: directory, filename = os.path.split(pathname) if extra_suffixes: suffixes = extra_suffixes else: suffixes = [] dlog = FileSaveDialog(prompt=prompt, suffixes=suffixes, default_suffix=suffix) if directory: dlog.directory = directory if filename: dlog.filename = filename if dlog.present(): return dlog.pathname else: return None def request_old_filename(suffixes=None, directory=None): dlog = FileOpenDialog(suffixes=suffixes) if directory: dlog.directory = directory if dlog.present(): return dlog.pathname else: return None def look_for_file_or_directory(target, prompt=None, directory=None): dlog = LookForFileDialog(target=target, prompt=prompt) if directory: dlog.directory = directory if dlog.present(): return dlog.pathname else: return None
20,467
34.473137
146
py
MCEdit-Unified
MCEdit-Unified-master/albow/theme.py
# # Albow - Themes # import resource debug_theme = False class ThemeProperty(object): def __init__(self, name): self.name = name self.cache_name = intern("_" + name) def __get__(self, obj, owner): if debug_theme: print "%s(%r).__get__(%r)" % (self.__class__.__name__, self.name, obj) try: ### cache_name = self.cache_name try: return getattr(obj, cache_name) except AttributeError as e: if debug_theme: print e value = self.get_from_theme(obj.__class__, self.name) obj.__dict__[cache_name] = value return value except: ### if debug_theme: import traceback traceback.print_exc() print "-------------------------------------------------------" raise ### def __set__(self, obj, value): if debug_theme: print "Setting %r.%s = %r" % (obj, self.cache_name, value) ### obj.__dict__[self.cache_name] = value def get_from_theme(self, cls, name): return root.get(cls, name) class FontProperty(ThemeProperty): def get_from_theme(self, cls, name): return root.get_font(cls, name) class ThemeError(Exception): pass class Theme(object): # name string Name of theme, for debugging # base Theme or None Theme on which this theme is based def __init__(self, name, base=None): self.name = name self.base = base def get(self, cls, name): try: return self.lookup(cls, name) except ThemeError: raise AttributeError("No value found in theme %s for '%s' of %s.%s" % (self.name, name, cls.__module__, cls.__name__)) def lookup(self, cls, name): if debug_theme: print "Theme(%r).lookup(%r, %r)" % (self.name, cls, name) for base_class in cls.__mro__: class_theme = getattr(self, base_class.__name__, None) if class_theme: try: return class_theme.lookup(cls, name) except ThemeError: pass else: try: return getattr(self, name) except AttributeError: base_theme = self.base if base_theme: return base_theme.lookup(cls, name) else: raise ThemeError def get_font(self, cls, name): if debug_theme: print "Theme.get_font(%r, %r)" % (cls, name) spec = self.get(cls, name) if spec: if debug_theme: print "font spec =", spec return resource.get_font(*spec) root = Theme('root') root.margin = 3 root.font = (15, "DejaVuSans-Regular.ttf") root.fg_color = (255, 255, 255) root.bg_color = None root.bg_image = None root.scale_bg = False root.border_width = 0 root.border_color = (0, 0, 0) root.tab_bg_color = None root.sel_color = (112, 112, 112) root.highlight_color = None root.hover_color = None root.disabled_color = None root.highlight_bg_color = None root.hover_bg_color = None root.enabled_bg_color = None root.disabled_bg_color = None root.RootWidget = Theme('RootWidget') root.RootWidget.bg_color = (0, 0, 0) root.Button = Theme('Button') root.Button.font = (17, "DejaVuSans-Bold.ttf") root.Button.fg_color = (255, 255, 0) root.Button.highlight_color = (16, 255, 16) root.Button.disabled_color = (64, 64, 64) root.Button.hover_color = (255, 255, 225) root.Button.default_choice_color = (144, 133, 255) root.Button.default_choice_bg_color = None root.Button.highlight_bg_color = None root.Button.enabled_bg_color = (48, 48, 48) root.Button.disabled_bg_color = None root.Button.margin = 7 root.Button.border_width = 1 root.Button.border_color = (64, 64, 64) root.ValueButton = Theme('ValueButton', base=root.Button) root.Label = Theme('Label') root.Label.margin = 4 #-# root.Label.disabled_color = (64, 64, 64) #-# root.SmallLabel = Theme('SmallLabel') root.SmallLabel.font = (10, 'DejaVuSans-Regular.ttf') root.ValueDisplay = Theme('ValueDisplay') root.ValueDisplay.margin = 4 root.SmallValueDisplay = Theme('SmallValueDisplay') root.SmallValueDisplay.font = (10, 'DejaVuSans-Regular.ttf') root.ValueDisplay.margin = 2 root.ImageButton = Theme('ImageButton') root.ImageButton.highlight_color = (0, 128, 255) framed = Theme('framed') framed.border_width = 1 framed.margin = 3 root.Field = Theme('Field', base=framed) root.Field.border_color = (128, 128, 128) root.CheckWidget = Theme('CheckWidget') root.CheckWidget.smooth = False root.CheckWidget.border_color = root.Field.border_color root.CheckWidget.highlight_color = (0, 128, 255) root.CheckBox = Theme("CheckBox)") # Let use the same highlight color as for buttons root.CheckBox.highlight_color = root.Button.highlight_color root.Dialog = Theme('Dialog') root.Dialog.bg_color = (40, 40, 40) root.Dialog.border_width = 1 root.Dialog.margin = 15 root.DirPathView = Theme('DirPathView', base=framed) root.FileListView = Theme('FileListView', base=framed) root.FileListView.scroll_button_color = (255, 255, 0) root.FileDialog = Theme("FileDialog") root.FileDialog.up_button_text = "<-" root.PaletteView = Theme('PaletteView') root.PaletteView.sel_width = 2 root.PaletteView.scroll_button_size = 16 root.PaletteView.scroll_button_color = (0, 128, 255) root.PaletteView.highlight_style = 'frame' root.PaletteView.zebra_color = (48, 48, 48) root.TextScreen = Theme('TextScreen') root.TextScreen.heading_font = (24, "DejaVuSans-Bold.ttf") root.TextScreen.button_font = (18, "DejaVuSans-Bold.ttf") root.TextScreen.margin = 20 root.TabPanel = Theme('TabPanel') root.TabPanel.tab_font = (18, "DejaVuSans-Regular.ttf") root.TabPanel.tab_height = 24 root.TabPanel.tab_border_width = 0 root.TabPanel.tab_spacing = 4 root.TabPanel.tab_margin = 0 root.TabPanel.tab_fg_color = root.fg_color root.TabPanel.default_tab_bg_color = (128, 128, 128) root.TabPanel.tab_area_bg_color = None root.TabPanel.tab_dimming = 0.75 #root.TabPanel.use_page_bg_color_for_tabs = True menu = Theme('menu') menu.bg_color = (64, 64, 64) menu.fg_color = (255, 255, 255) menu.disabled_color = (0, 0, 0) menu.margin = 8 menu.border_color = (192, 192, 192) menu.scroll_button_size = 16 menu.scroll_button_color = (255, 255, 0) root.MenuBar = Theme('MenuBar', base=menu) root.MenuBar.border_width = 0 root.Menu = Theme('Menu', base=menu) root.Menu.border_width = 1 root.MusicVolumeControl = Theme('MusicVolumeControl', base=framed) root.MusicVolumeControl.fg_color = (0x40, 0x40, 0x40) root.Tree = Theme('Tree') root.Tree.bullet_size = 16 root.Tree.bullet_color_active = (0, 128, 255) root.Tree.bullet_color_inactive = (128, 128, 128)
6,859
28.44206
82
py