def generateSingleDep(self): if not self.dependfilename in self.filedeps.keys(): self.invalid = True if self.verbose: log().error("file not found in the dependency tree: %s !" % self.dependfilename) return tree = self.getSingleDepRecursive(self.dependfilename) #print tree if self.verbose: for t in tree: t['fullpath'] = self.getFullPath(t['filename']) t['md5sum'] = self.md5Sum(t['fullpath']) infostr = "%-30s %-30s" % ("+"*t['depth']+t['filename'], t['md5sum']) log().info(infostr) #self.removeOriginalFilesFromSingleDep #for t in tree: # f = t['filename'] # print str(self.filedeps[f][REQUIRES]) # print str(self.filedeps[f][REQUIREDBY]) # print "---------------------------------" self.dstree = tree if self.verbose and len(tree) > 1: self.tryGraph(tree)
def previewObject(self, filename): try: if self.actualPerspective == 0: self.MapPreview.loadFile(filename) self.MapPreview.Show(True) except: log().debug("previewobject: failed to preview %s" % filename)
def startApp(MainApp): rorSettings().stopOnExceptions = False myFrame = MainFrame(None, -1, "") MainApp.SetTopWindow(myFrame) rorSettings().rorDebug = False # if rorSettings().rorDebug: # myFrame.SetDimensions(0,0,1900,1000) # myFrame.lastFilenameUsed = "C:\Documents and Settings\Administrador\Mis documentos\Rigs of Rods\terrains\TERRENO1\Terreno1.terrn" myFrame.SetFocus() myFrame.Show() log().info("starting MainFrame.MainLoop") autoMap = rorSettings().getSetting(TOOLKIT, "autoopen") if autoMap != "": myFrame.openTerrain(autoMap) if bool(rorSettings().getSetting(TOOLKIT, "autoopeniszip")) == False: myFrame.lastFilenameUsed = autoMap else: # Open Tree window and update toolbar button state myFrame.ObjectTree.Show(True) idx = list_has_value(myFrame.tbbuttons, 'label', 'Tree') if idx != -1: item = myFrame.terraintoolbar.FindTool(myFrame.tbbuttons[idx]['id'])._tbItem.Toggle() else: print "idx not found" log().debug('starting rendering loop') # getOgreManager().startRendering() MainApp.MainLoop()
def OnStartRoRClick(self, doc=" "): if self.terrainOgreWin: if self.terrainOgreWin.terrain: # self.Preview.clear() self.OnSaveTerrain(None) log().info(" ************** STARTING ROR **************") self.ToggleRenderAll() truck = rorSettings().getSetting(TOOLKIT, "usetruck") #RORBUG: launching RoR with a truck that doesn't have UID, ror doesn't load the truck # if parameter "-enter" is used, RoR crash if truck != "": truck = " -truck " + truck log().info("command line: " + rorSettings().rorFile + " -map " + self.terrainOgreWin.terrain.name + truck) # Popen(rorSettings().rorFile + " -map " + self.terrainOgreWin.terrain.name, 1024, cwd = rorSettings().rorFolder ) call(rorSettings().rorFile + " -map " + self.terrainOgreWin.terrain.name, 1024, cwd=rorSettings().rorFolder) log().info(" ************** ROR FINISHED **************") self.ToggleRenderAll() sleep(2)#wait a bit for x in self.tbbuttons: x['window'].restorePosition() else: log().warning("trying to execute RoR without a loaded terrain") else: log().warning("trying to execute RoR without created the Ogrewindow")
def __init__(self, parent, title="ShapeW", skinOnlyFilename=None, **kwargs): wx_styles = wx.DEFAULT_FRAME_STYLE | wx.FRAME_TOOL_WINDOW | wx.FRAME_NO_TASKBAR | wx.FRAME_FLOAT_ON_PARENT rorFrame.__init__(self, parent, title, style=wx_styles, **kwargs) log().debug("%s is initialising..." % title) # perspective is the Perspective menu index (1, 2 or 3) self.perspective = 1 self.skinSize = (0, 0) self.SetAutoLayout(True) self.hasShape = False self.skinFile = skinOnlyFilename self.title = title # min height when you click on the window self.smallHeight = 100 self.delta = (0, 20) self.moving = False self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown) self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp) self.Bind(wx.EVT_MOTION, self.OnMouseMove) self.isMouseDownHere = False self.grid = wx.GridBagSizer(2, 2) # self.SetSizer(self.grid) self.updateSkin() log().debug("%s created" % title)
def RenderAll(self): for ogrewin in self.renderWindows.keys(): try: ogrewin.OnFrameStarted() except ogre.OgreException, e: log().debug('fail to render targetwindow %s' % ogrewin.renderWindowName) log().debug(str(e)) continue
def ToggleRenderAll(self): self.activeRenders(not self.ogreTimer.IsRunning()) if self.ogreTimer.IsRunning(): self.ogreTimer.Stop() log().debug("Toolkit Render Stopped") else: self.ogreTimer.Start(-1) # use previous milliseconds. log().debug("Toolkit Render re-started")
def tryGraph(self, tree = None): try: import pydot log().info("pydot found, drawing graphs! beware this can take some time with big graphs!") self.drawGraph(tree) except ImportError: log().error("pydot not found, not drawing graphs") pass
def loadReadme(self): if os.path.isfile(HELPFILENAME): try: f = open(HELPFILENAME,'r') content = f.read() f.close() return content except Exception, err: log().error(str(err)) return None
def tryDetectRenderer(self): for rs in self.ogreRoot.getAvailableRenderers(): try : rs.setConfigOption("Full Screen", "No") rs.setConfigOption("Video Mode", "800 x 600 @ 32-bit colour") self.ogreRoot.setRenderSystem(rs) log().info("successfully autodeteced renderer : %s" % rs.getName()) return True except: log().info("not able to auto-detect renderer! showing ogre config dialog instead") return False
def saveCamera(self, terrnFile=None): if self.cameraList and (len(self.cameraList) > 0): log().debug("saving %d cameras" % len(self.cameraList)) if terrnFile is not None: barename, self.ext = os.path.splitext(os.path.basename(terrnFile)) self._file = rorSettings().concatToToolkitHomeFolder(['cameras', '%s.txt' % barename], True) output = open(self._file, 'wb') if output: pickle.dump(self.cameraList, output, 0) output.close() log().debug("cameras saved to %s" % self._file)
def getFiles(top): fl = {} for root, dirs, files in os.walk(top): for f in files: fn = os.path.join(root, f) fl[fn] = {} for fk in fl.keys(): log().info("%10s %s" % ("", os.path.basename(fk))) log().info("found %d files!" % (len(fl.keys()))) return fl
def loadFile(self, filename): try: self.error("Loading ...") # self.objectPreviewWindow.Destroy() # # self.objectPreviewWindow = ObjectPreviewOgreWindow(self, "PreviewToolwindow", size=wx.Size(250, 250)) self.objectPreviewWindow.loadFile(filename) except Exception, err: self.error(" Loaded with errors, maybe you can not use this object") log().error("RoRPreviewCtrl exception") log().error(str(err))
def resolveProperty(self, name): """ create a new property RTTI rules !! ;-) """ if not hasattr(self, name): if name in dicty.keys(): setattr(self, name, dicty[name]) else : log().error('the word %s is not a valid toolkitClass token' % name) self.properties.append(name) # record the property name to free memory return getattr(self, name)
def createDeps(self): tree = self.filedeps unused = [] if self.verbose: log().info("### dependency checker log following") for filename in self.files.keys(): onlyfilename, extension = os.path.splitext(filename) basefilename = os.path.basename(filename) dependencies = self.getDependencies(extension, filename) if dependencies is None: unused.append(filename) #print "DEP "+ basefilename +" / "+str(dependencies) if not dependencies is None: for relation in dependencies.keys(): deps = dependencies[relation] tree[basefilename] = {} tree[basefilename][relation] = {} for type in deps.keys(): tree[basefilename] = self.newRelation(dependencies) if self.verbose: log().info("### file dependency check finished") if len(unused) > 0: log().info("### unused files: %s" % str(unused)) else: log().info("### all files used")
def OnExit(self, event): log().debug("closing MainFrame...") self.tbbuttons = [] #dec ref count # getOgreManager().ogreRoot.shutdown() self.ogreTimer.Stop() log().debug("Rendering Timer stopped") del self.ogreTimer p = self.GetPosition() rorSettings().setSetting("MainFrame", "left", p.x) rorSettings().setSetting("MainFrame", "top", p.y) p = self.GetSize() rorSettings().setSetting("MainFrame", "width", p.width) rorSettings().setSetting("MainFrame", "height", p.height) # this event is not triggered for Child windows :F if self.truckEditorOgreWin: self.truckEditorOgreWin.close() #save settings try: all_panes = self._mgr.GetAllPanes() for ii in xrange(len(all_panes)): if not all_panes[ii].IsToolbar(): all_panes[ii].Hide() self._mgr.UnInit() # del self._mgr log().debug("Destroying MainFrame") self.Destroy() # self.Close() except Exception, err: log().debug("exception while freeing MainFrame %s" % str(err))
def getfiles(self, md5 = False): fl = {} for root, dirs, files in os.walk(os.path.abspath(self.dir)): for f in files: fn = os.path.join(root, f) fl[fn] = {} if md5: fl[fn]['md5'] = self.md5Sum(fn) if self.verbose: for fk in fl.keys(): infostr = "%10s %s" % ("", os.path.basename(fk)) log().info(infostr) log().info("found %d files!" % (len(fl.keys()))) self.files = fl
def parseEvent(self, value): self.event = value.split(" ") for i in range(0, len(self.event)): self.event[i] = self.event[i].strip() if len(self.event) > 1: self.isSpawnZone = self.event[1].lower() == "spawnzone" if self.isSpawnZone: self._main.isSpawnZone = True if hardcoded['odef']['event'].has_key(self.event[1].lower()): self._main.event = self.event[1].lower() if len(self.event) > 2: if not self.event[2].lower() in hardcoded['odef']['trigger']: if self._main: fn = self._main.filename else: fn = 'unknown file' log().error("Odefbox has a bad trigger name.\nFilename %s\n Actual value: '%s' Allowed values: %s" % (fn, self.event[1], " / ".join(hardcoded['odef']['trigger']))) " ".join(self.event)
def main(): # check for valid RoR Directory! import ror.rorcommon if not ror.rorcommon.checkRoRDirectory(): import ror.starter ror.starter.startApp() if len(sys.argv) < 2: usage() mode = sys.argv[1] if not mode in ['list', 'listall', 'install', 'installall', 'listinstalled','uninstall', 'installrepo', 'uniqueid', 'createmod']: usage() if len(sys.argv) < 4 and mode in ['install']: usage() if mode in ['list', 'listall', 'install', 'installall']: targetfile = sys.argv[2] if not os.path.isfile(targetfile): log().error("%s is not a valid target filename!" % targetfile) usage() elif mode in ['listinstalled']: targetfile = rorpath elif mode in ['installrepo']: targetfile = sys.argv[2] elif mode == 'uninstall': targetfile = sys.argv[2] elif mode == 'createmod': targetfile = sys.argv[2] elif mode == 'uniqueid': targetfile = '' # get optional flags verbose = False dryrun = False for option in sys.argv: if option == "--verbose": verbose = True if option == "--dryrun": dryrun = True if len(sys.argv) == 4: installtarget = sys.argv[3] else: installtarget = None import ror.modtool result = ror.modtool.ModTool().work(mode, targetfile, verbose, dryrun, installtarget)
def loadFromFile(self, toolkitFilename): if toolkitFilename[ - 8:] != ".toolkit": toolkitFilename += ".toolkit" self.filename = toolkitFilename content = loadResourceFile(toolkitFilename) values = [] uid = '' for line in content: try: if len(line.strip()) == 0: continue values = line.strip().split(',') if len(values) == 0 or values[:1]==';' or values[:2] == '//' : continue str = [z.strip() for z in values[0].split(' ') if z.strip() !=''] propname = str[0] if len(str) > 1: values[0]= str[1] if propname == 'splines': uid = values[0] continue elif propname == 'end_splines': uid = '' continue elif propname == 'splineName': self.splineNames[uid] = line[11:] continue x = positionClass() x.asStrList= values except Exception, err: log().info('error procesing file %s. Ignoring line "%s"' % (toolkitFilename, line)) log().info(err) continue if len(uid) > 0 and propname == 'point': if not self.splines.has_key(uid): self.splines[uid] = [] self.splines[uid].append(x) continue prop = self.resolveProperty(propname) prop.append(x)
def getConfigPath(self, filename): """Return the absolute path to a valid config file.""" import sys import os import os.path paths = [os.path.join(os.getcwd(), filename), os.path.join(os.path.dirname(os.path.abspath(__file__)), filename)] for path in paths: if os.path.exists(path): print path return path log().warning("\n" "** Unable to locate a suitable " + filename + " file.\n" "** Please check your ogre installation and copy a\n" "** working plugins.cfg file to the current directory.\n\n")
def loadCamera(self, terrnFile): self.cameraList = [] self.list.Set([]) barename, self.ext = os.path.splitext(os.path.basename(terrnFile)) self._file = rorSettings().concatToToolkitHomeFolder(['cameras', '%s.txt' % barename], True) try: if os.path.isfile(self._file): input = open(self._file, 'rb') if input: self.cameraList = pickle.load(input) input.close() log().info("loaded %d camera Bookmarks" % len(self.cameraList)) except: self.cameraList = [] log().info("cameraBookmark couldn't be loaded") self.lastcount = len(self.cameraList) self.list.Set(self.getValues())
def removeRoRDeps(self, notfound): rortree = self.loadTree(RORDEPSFILE) newfound = {MATERIAL:[], FILE:[]} for category in notfound.keys(): for searchitem in notfound[category]: found = False for filenameA in rortree.keys(): if found: break fileA = rortree[filenameA] if PROVIDES in fileA.keys() and category in fileA[PROVIDES].keys(): for provide in fileA[PROVIDES][category]: if provide == searchitem: if self.verbose: log().info("found missing item in original ror: %s, %s" % (category, provide)) found = True break if not found: newfound[category].append(searchitem) return newfound
def saveToFile(self, fn = None): #BUG: after launching ror, I only get the latest spline in combobox if fn is not None: if fn[ - 8:] != ".toolkit": fn += ".toolkit" content = [] try: for k in dicty.keys(): # property name prop = getattr(self, k) if type(prop) is DictType: for s in prop.keys(): # each Spline points content.append("%s %s\n" % (k, s) ) if self.splineNames.has_key(s): content.append('splineName %s\n' % self.splineNames[s]) for i in range(len(prop[s])): # each point content.append(prop[s][i].leftAlign("point") + '\n') content.append("end_%s\n" % k) elif type(prop) is ListType: for i in range(len(prop)): content.append(prop[i].leftAlign(k) + "\n") except Exception, err: log().error('error in file "%s". The file has been truncated to previous line of the error' % fn) log().error(str(err)) f = open(fn,'w') f.writelines(content) f.close() log().debug('saved SplineLines in %s' % fn)
def update_renderer_configfile(rend_index, rend_list): log().debug("update_renderer_configfile(): retrieving plugins_windows.cfg") filename = os.path.join(os.getcwd(), "plugins_windows.cfg") f = open(filename, "r") content = f.readlines() f.close() log().info("selected rendersystem: %s" % rend_list[rend_index]) for i in range(0, len(content)): if content[i].find(DIRECTXLINE) >= 0: if rend_index == 1: content[i] = DIRECTXLINE + "\n" else: content[i] = "#" + DIRECTXLINE + "\n" elif content[i].find(OPENGLLINE) >= 0: if rend_index == 0: content[i] = OPENGLLINE + "\n" else: content[i] = "#" + OPENGLLINE + "\n" f = open(filename, "w") f.writelines(content) f.close()
def createUVPlane(self): self.imgwidth = 600 self.imgheight = 480 matname = None if self.trucktree: log().info("truck editor len(trucktree) = " +str(len(self.trucktree) )) matname = self.trucktree['globals'][0]['data'][2] mat = ogre.MaterialManager.getSingleton().getByName(matname) if mat is not None: texturename = mat.getTechnique(0).getPass(0).getTextureUnitState(0).getTextureName() pair = mat.getTechnique(0).getPass(0).getTextureUnitState(0).getTextureDimensions() texture = Ogre.TextureManager.getSingleton().getByName(texturename) self.imgwidth = texture.getSrcWidth() self.imgheight = texture.getSrcHeight() log().debug("texture name %s, image Width %d, image Height %d " %( texturename, int(self.imgwidth), int(self.imgheight))) plane = ogre.Plane() plane.normal = ogre.Vector3(0, 1, 0) plane.d = 20 # see http://www.ogre3d.org/docs/api/html/classOgre_1_1MeshManager.html#Ogre_1_1MeshManagera5 uuid = randomID() mesh = ogre.MeshManager.getSingleton().createPlane(uuid + 'UVPlane', "General", plane, self.imgwidth/IMGSCALE, self.imgheight/IMGSCALE, 1, 1, True, 1, 1, 1, ogre.Vector3(0, 0, 1), ogre.HardwareBuffer.HBU_STATIC_WRITE_ONLY, ogre.HardwareBuffer.HBU_STATIC_WRITE_ONLY, True, True) entity = self.sceneManager.createEntity(uuid+'uvent', uuid+'UVPlane') #it = ogre.ResourceGroupManager.getSingleton().getResourceManagerIterator() #rm = it.getNext() #print rm #texture = rm.getByName(texturename) #print "texture: ", texturename, texture.getWidth(), texture.getHeight() if matname: entity.setMaterialName(matname) self.uvplanenode = self.sceneManager.getRootSceneNode().createChildSceneNode() self.uvplanenode.attachObject(entity)
def ConfigureSkin(self): theTheme = rorSettings().getSetting(TOOLKIT, "theme") if theTheme != '': try: path = os.path.join(rorSettings().toolkitMainFolder, 'media', 'gui', 'skins', theTheme) if os.path.isdir(path): cfg = ConfigParser.ConfigParser() cfg.read(os.path.join(path, "config.txt")) read = (cfg.get('skin', 'SkinBackgroundColor')).split(',') theSkinBackColor = wx.Color(int(read[0]), int(read[1]), int(read[2])) #arggggg read = cfg.get('skin', 'SkinTransparentColor').split(',') theTransparentColor = wx.Color(int(read[0]), int(read[1]), int(read[2])) #arggggg del cfg ShapedControls.skinBackColor = theSkinBackColor ShapedControls.skinTransparentColor = theTransparentColor ShapedControls.skinTheme = theTheme except: ShapedControls.skinTheme = 'RoR theme' ShapedControls.skinBackColor = wx.Color(254, 184, 0) ShapedControls.skinTransparentColor = wx.Color(0, 0, 0) log().error('skin %s is not valid, using default' % theTheme) log().debug('using skin %s' % ShapedControls.skinTheme)
def main(): log().info("modgui started") import wx app = wx.PySimpleApp(0) wx.InitAllImageHandlers() #you may or may not need this # check for valid RoR Directory! import ror.rorcommon if not ror.rorcommon.checkRoRDirectory(): import ror.starter ror.starter.startApp() return if len(sys.argv) == 1: log().error("missing arguments") return mode = sys.argv[1] if mode in ["uninstall"]: frame_1 = ror.modgui.ModGUI(None, -1, "") app.SetTopWindow(frame_1) frame_1.Show() app.MainLoop() elif mode in ['installrepo']: if len(sys.argv) != 3: return targetfile = sys.argv[2] import ror.modtool result = ror.modtool.ModTool().work(mode, targetfile, False, False) if result == False or result is None: msg = "Installation failed! :( Please have a look at the file editorlog.log" else: msg = "Installation successfull! Mods installed:\n %s" % ", ".join(result) dlg = wx.MessageDialog(None, msg, "Info", wx.OK | wx.ICON_INFORMATION) dlg.ShowModal() dlg.Destroy() else: log().error("function %s not implemented in gui version!" % mode) return
def generateCrossDep(self, removeRoRDeps=False): crossdep = 0 notfound = {MATERIAL:[], FILE:[]} newtree = copy.deepcopy(self.filedeps) for filenameA in self.filedeps.keys(): fileA = self.filedeps[filenameA] for relation in [REQUIRES, OPTIONAL]: for type in TYPES: if not relation in fileA.keys() or len(fileA[relation]) == 0: continue for reqfile in fileA[relation][type]: found = False for filenameB in self.filedeps.keys(): fileB = self.filedeps[filenameB] if filenameA == filenameB: continue #print filenameA, relation, type, reqfile, fileB[PROVIDES][type] if len(fileB[PROVIDES]) == 0: continue if reqfile in fileB[PROVIDES][type]: crossdep += 1 newtree[filenameB][REQUIREDBY][FILE].append(filenameA) if not filenameB in fileA[REQUIRES][FILE]: # found new newtree[filenameA][REQUIRES][FILE].append(filenameB) found = True break if not found and relation != OPTIONAL: if not reqfile in notfound[type]: notfound[type].append(reqfile) self.filedeps = newtree #print newtree self.everythingfound = False if len(notfound[MATERIAL]) == 0 and len(notfound[FILE]) == 0: self.everythingfound = True if self.verbose: log().info("### nothing missing, great!") else: if removeRoRDeps: notfound = self.removeRoRDeps(notfound) self.notfound = notfound if len(notfound[MATERIAL]) == 0 and len(notfound[FILE]) == 0: self.everythingfound = True if self.verbose: log().info("### no files missing, all prior missing files found in RoR") if self.verbose: if len(notfound[FILE]) > 0: log().info("### we are missing the following files:") log().info(" "+str(notfound[FILE])) if len(notfound[MATERIAL]) > 0: log().info("### we are missing the following materials:") log().info(" "+str(notfound[MATERIAL])) if self.verbose: log().info("### found %d files, of which %d have dependencies." % (len(self.files), len(self.filedeps))) nodeps = 0 for filename in self.filedeps.keys(): file = self.filedeps[filename] line = " %-30s " % filename linesub = "" sublines = [] if REQUIRES in file.keys() and FILE in file[REQUIRES].keys(): linesub = "requires: %s" % (str(file[REQUIRES][FILE])) if linesub != "": sublines.append("%-50s" % linesub) linesub = "" if REQUIREDBY in file.keys() and FILE in file[REQUIRES].keys(): linesub = "required by: %s" % (str(file[REQUIREDBY][FILE])) if linesub != "": sublines.append("%-50s" % linesub) if len(sublines) > 0: line += ", ".join(sublines) else: line += "NO DEPENDENCIES" nodeps += 1 log().info(line) log().info("### %d files depends on each other" % (crossdep)) log().info("### %d files with no dependencies" % (nodeps)) log().info("### advanced file dependency check finished")
vert.Add(self.htmlctrl, 2, wx.EXPAND, 0) self.SetSizer(vert) self.GetSizer().SetSizeHints(self) def loadReadme(self): if os.path.isfile(HELPFILENAME): try: f = open(HELPFILENAME,'r') content = f.read() f.close() return content except Exception, err: log().error(str(err)) return None else: log().error("TerrainEditor Readme not found: %s" % HELPFILENAME) return None ID_PaneBorderSize = wx.ID_HIGHEST + 1 ID_SashSize = ID_PaneBorderSize + 1 ID_CaptionSize = ID_PaneBorderSize + 2 ID_BackgroundColor = ID_PaneBorderSize + 3 ID_SashColor = ID_PaneBorderSize + 4 ID_InactiveCaptionColor = ID_PaneBorderSize + 5 ID_InactiveCaptionGradientColor = ID_PaneBorderSize + 6 ID_InactiveCaptionTextColor = ID_PaneBorderSize + 7 ID_ActiveCaptionColor = ID_PaneBorderSize + 8 ID_ActiveCaptionGradientColor = ID_PaneBorderSize + 9 ID_ActiveCaptionTextColor = ID_PaneBorderSize + 10 ID_BorderColor = ID_PaneBorderSize + 11 ID_GripperColor = ID_PaneBorderSize + 12