diff --git a/contrib/src/panda3dtoolsgui/Panda3DToolsGUI.py b/contrib/src/panda3dtoolsgui/Panda3DToolsGUI.py index 8a42ed8131..0c8b3f3ccd 100644 --- a/contrib/src/panda3dtoolsgui/Panda3DToolsGUI.py +++ b/contrib/src/panda3dtoolsgui/Panda3DToolsGUI.py @@ -62,7 +62,7 @@ UNIT_TYPES = ["mm", "cm", "m", "in", - "ft", + "ft", "yd"] @@ -229,7 +229,7 @@ class OutputDialogPaths(wx.Dialog): self.Bind(wx.EVT_BUTTON, self.RunPaths, self.paths_done) # end wxGlade - + def setCallback(self, callback): self.callback = callback @@ -286,7 +286,7 @@ class main(wx.Frame): self._setupUI() #Show the welcome message and the initial panda path #NOTE this shoudl eventually check for an install of Panda somewhere - + self.ShowInitialEnv() def _setupUI(self): @@ -379,7 +379,7 @@ class main(wx.Frame): self.pandaPathTxt = wx.TextCtrl(self.console_panel, -1, "", style=wx.TE_READONLY) self.loadPandaPathBtn = wx.Button(self.console_panel, ID_CHOOSEPANDA, "Choose..") self.ignoreModDates = wx.CheckBox(self.console_panel, -1, "Override export changed maya scene files") - + # Maya2Egg Tool self.maya2egg_panel = wx.Panel(self.tool_options_panel, -1, style=wx.NO_BORDER|wx.TAB_TRAVERSAL) @@ -694,7 +694,7 @@ class main(wx.Frame): self.m2e_exportDestBtn.SetMinSize((-1, 23)) self.m2e_copyTexPathBtn.SetMinSize((-1, 23)) self.m2e_pathReplaceBtn.SetMinSize((-1, 23)) - + self.m2e_startFrameSpin.SetMinSize((-1, 21)) self.m2e_endFrameSpin.SetMinSize((-1, 21)) self.m2e_frameRateInSpin.SetMinSize((-1, 21)) @@ -745,7 +745,7 @@ class main(wx.Frame): self.e2b_eggFileTxt.SetMinSize((230, 21)) self.e2b_exportDestTxt.SetMinSize((230, 21)) self.egg2bam_panel.SetBackgroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE)) - + self.e2b_eggFileBtn.SetMinSize((-1, 23)) self.e2b_exportDestBtn.SetMinSize((-1, 23)) self.e2b_bamBatchOutputBtn.SetMinSize((-1, 23)) @@ -771,7 +771,7 @@ class main(wx.Frame): self.rename_exportDirTxt.SetMinSize((230, 21)) self.rename_exportFileTxt.SetMinSize((230, 21)) self.rename_stripPrefixTxt.SetMinSize((260, 21)) - + self.rename_addEggBtn.SetMinSize((-1, 23)) self.rename_addFromBatchBtn.SetMinSize((-1, 23)) self.rename_removeEggBtn.SetMinSize((-1, 23)) @@ -791,7 +791,7 @@ class main(wx.Frame): self.optchar_dropJointsTxt.SetMinSize((245, 21)) self.optchar_exposeJointsTxt.SetMinSize((245, 21)) self.optchar_flagGeometryTxt.SetMinSize((245, 21)) - + self.optchar_addEggBtn.SetMinSize((-1, 23)) self.optchar_addFromBatchBtn.SetMinSize((-1, 23)) self.optchar_removeEggBtn.SetMinSize((-1, 23)) @@ -1394,7 +1394,7 @@ class main(wx.Frame): # Simple Export Panel Functions ################################ - + def OnSimpleExport(self,e): #This is essentially the same behavior as a batch export #build up the dictionary that gets passed to Run Export @@ -1441,7 +1441,7 @@ class main(wx.Frame): # Maya2Egg Panel Functions ########################### - + def OnMaya2EggMayaFile(self, event): #choose input maya scene for maya2egg filename = '' @@ -1458,7 +1458,7 @@ class main(wx.Frame): self.m2e_mayaFileTxt.SetValue(os.path.join(self.srcProjectFolder + os.sep , filename)) #this is for a text control dlg.Destroy() #otherwise just kill the file dialog self.statusBar.SetStatusText("Current Scene File is: " + self.srcProjectFolder + os.sep + filename) - + def OnMaya2EggExportDest(self, event): #choose output egg for maya2egg filename = '' @@ -1501,7 +1501,7 @@ class main(wx.Frame): self.m2e_copyTexPathTxt.SetValue(dlg.GetPath()) dlg.Destroy() #otherwise just kill the file dialog #self.statusBar.SetStatusText("Current Egg File is: " + dirname + '\\' + filename) - + def OnMaya2EggPathReplace(self,event): batchList = self.GetSelectedBatchList() for batchItem in batchList: @@ -1533,7 +1533,7 @@ class main(wx.Frame): dlg = wx.FileDialog(self, "Choose an Egg file to load", dirname, "", "*.bam", wx.SAVE) if dlg.ShowModal() == wx.ID_OK: #if the user clicked ok then we grabbed a file so load it self.filename = dlg.GetFilename() - dirname = dlg.GetDirectory() + dirname = dlg.GetDirectory() self.e2b_exportDestTxt.SetValue(os.path.join(dirname + os.sep , self.filename)) #this is for a text control duh dlg.Destroy() #otherwise just kill the file dialog @@ -1545,7 +1545,7 @@ class main(wx.Frame): else: self.e2b_eggFileTxt.Disable() self.e2b_eggFileBtn.Disable() - + def OnEgg2BamBatchOutput(self, event): for eggInfo in self.GetOutputFromBatch(): batchItemInfo = {} @@ -1622,7 +1622,7 @@ class main(wx.Frame): self.rename_eggFilesTree.AppendItem(self.rename_eggFilesRoot, str(index) + ' ' + str(treeitem)) self.rename_eggFilesTree.ExpandAll() self.OnRenameInPlace(None) - + def OnRenameInPlace(self, event): #check if we want to use a custom egg file or not for egg-rename panel if (self.rename_exportInPlaceChk.GetValue()): @@ -1671,7 +1671,7 @@ class main(wx.Frame): dlg.Destroy() - + # Egg-Optchar Panel Functions ############################## @@ -1692,7 +1692,7 @@ class main(wx.Frame): dlg.Destroy() #otherwise just kill the file dialog self.statusBar.SetStatusText("The input egg File is: " + dirname + os.sep + filename) self.OnOptcharInPlace(None) - + def OnOptcharAddFromBatch(self, event): for eggInfo in self.GetOutputFromBatch(): self.optchar_eggList.append(eggInfo) @@ -1710,7 +1710,7 @@ class main(wx.Frame): self.optchar_eggFilesTree.Delete(item) self.UpdateEggOptcharDisplay() self.OnOptcharInPlace(None) - + def OnOptcharRemoveAllEggs(self, event): #remove all input egg files from eggs list in egg-optchar panel self.optchar_eggFilesTree.DeleteAllItems() @@ -1768,7 +1768,7 @@ class main(wx.Frame): if dlg.ShowModal() == wx.ID_OK: #if the user clicked ok then we grabbed a file so load it self.optchar_exportDirTxt.SetValue(dlg.GetPath()) dlg.Destroy() - + # Egg-Palettize Panel Functions ################################ @@ -1789,14 +1789,14 @@ class main(wx.Frame): dlg.Destroy() #otherwise just kill the file dialog self.OnPalettizeInPlace(None) - + def OnPalettizeAddFromBatch(self, event): for eggInfo in self.GetOutputFromBatch(): self.palettize_eggList.append(eggInfo) self.palettize_eggFilesTree.AppendItem(self.palettize_eggFilesRoot, str(len(self.palettize_eggList)) + ' ' + eggInfo) self.palettize_eggFilesTree.ExpandAll() self.OnPalettizeInPlace(None) - + def OnPalettizeRemoveEgg(self,e): #remove selected input egg file from multiple eggs panel in egg-palettize panel item = self.palettize_eggFilesTree.GetSelection() @@ -1872,7 +1872,7 @@ class main(wx.Frame): if dlg.ShowModal() == wx.ID_OK: #if the user clicked ok then we grabbed a file so load it self.palettize_exportTexTxt.SetValue(dlg.GetPath()) dlg.Destroy() - + def OnPalettizeLoadTxa(self, event): dirname = '' dlg = wx.FileDialog(self, "Choose a .txa file to use", dirname, "", "*.txa", wx.OPEN) @@ -1954,7 +1954,7 @@ class main(wx.Frame): # Batch Related Functions ########################## - + def GetSelectedBatchList(self): batchList = [] selectedItems = self.batchTree.GetSelections() @@ -1963,7 +1963,7 @@ class main(wx.Frame): batchList.append(self.batchList[selectedItemIndex]) if not len(batchList): batchList = self.batchList - + return batchList def GetOutputFromBatch(self, index=-1): @@ -2226,7 +2226,7 @@ class main(wx.Frame): return args def BuildEgg2BamArgs(self): - #Build up all the command line arguments present in the egg2bam panel + #Build up all the command line arguments present in the egg2bam panel args = {} if (self.e2b_flattenChk.GetValue()): @@ -2271,7 +2271,7 @@ class main(wx.Frame): args['dart'] = self.optchar_dartChoice.GetStringSelection() return args - + def BuildEggPalettizeArgs(self): args = {} @@ -2355,7 +2355,7 @@ class main(wx.Frame): def UpdateBatchDisplay(self): #update the display of the batch list - + #For now just re calculate the entire list order self.batchTree.DeleteAllItems() self.treeRoot = self.batchTree.AddRoot('Batch Files') @@ -2372,21 +2372,21 @@ class main(wx.Frame): if self.batchList != []: self.batchList = [] self.treeRoot = self.batchTree.AddRoot('Batch Files') #rather than loop through it re-add the root - + def OnClearOutput(self, event): #clear the console output content self.consoleOutputTxt.Clear() - + def OnExit(self, e): #exit the GUI self.Close(True) - + def OnLoadPview(self, event): #load pview path = self.pandaPathTxt.GetValue() + os.sep + 'bin' + os.sep self.outpview = OutputDialogpview(self) self.outpview.Show() - + def OnSortBatch(self, event): maya2eggCommands = [] egg2bamCommands = [] @@ -2435,9 +2435,9 @@ class main(wx.Frame): if batchItem['finput'].count(inPrefix): pass - + def OnSaveBatch(self,event): - #save current batch list + #save current batch list newdoc = Document() top_element = newdoc.createElement('batch') newdoc.appendChild(top_element) @@ -2795,7 +2795,7 @@ class main(wx.Frame): self.optchar_flagGeometryChk.SetValue(batchItem['args'].has_key('flag')) self.optchar_flagGeometryTxt.SetValue('' if not batchItem['args'].has_key('flag') else batchItem['args']['flag']) self.optchar_dartChoice.SetStringSelection(batchItem['args']['dart']) - + elif (batchItem['cmd'].count('egg-palettize')): self.toolComboBox.SetStringSelection('egg-palettize') self.OnTool(None) @@ -2891,7 +2891,7 @@ class main(wx.Frame): top_element.appendChild(texitem) top_element.appendChild(overitem) top_element.appendChild(attributeitem) - + pandadir = newdoc.createTextNode(str(self.pandaPathTxt.GetValue())) mayaver = newdoc.createTextNode(str(self.m2e_mayaVerComboBox.GetSelection())) pandadirElem = newdoc.createElement('pandadir') @@ -2900,7 +2900,7 @@ class main(wx.Frame): mayaverElem.appendChild(mayaver) envitem.appendChild(pandadirElem) envitem.appendChild(mayaverElem) - + inunits = newdoc.createTextNode(str(self.m2e_mayaUnitsComboBox.GetValue())) outunits = newdoc.createTextNode(str(self.m2e_pandaUnitsComboBox.GetValue())) bface = newdoc.createTextNode(str(int(self.m2e_backfaceChk.GetValue()))) @@ -2909,7 +2909,7 @@ class main(wx.Frame): subsetsval = newdoc.createTextNode(str(self.m2e_subsetsTxt.GetValue())) excludes = newdoc.createTextNode(str(int(self.m2e_excludesChk.GetValue()))) excludesval = newdoc.createTextNode(str(self.m2e_excludesTxt.GetValue())) - + inunitsElem = newdoc.createElement('inunits') outunitsElem = newdoc.createElement('outunits') bfaceElem = newdoc.createElement('bface') @@ -2918,7 +2918,7 @@ class main(wx.Frame): subnamesElem = newdoc.createElement('subnames') excludesElem = newdoc.createElement('excludes') exnamesElem = newdoc.createElement('excludesval') - + inunitsElem.appendChild(inunits) outunitsElem.appendChild(outunits) bfaceElem.appendChild(bface) @@ -2927,7 +2927,7 @@ class main(wx.Frame): subnamesElem.appendChild(subsetsval) excludesElem.appendChild(excludes) exnamesElem.appendChild(exnamesElem) - + genitem.appendChild(inunitsElem) genitem.appendChild(outunitsElem) genitem.appendChild(bfaceElem) @@ -2937,7 +2937,7 @@ class main(wx.Frame): genitem.appendChild(excludesElem) genitem.appendChild(exnamesElem) - + modeloptsElem = newdoc.createElement('modelopts') cnElem = newdoc.createElement('cn') charnameElem = newdoc.createElement('charname') @@ -2960,7 +2960,7 @@ class main(wx.Frame): framerangeElem.appendChild(frivalElem) framerangeElem.appendChild(froElem) framerangeElem.appendChild(frovalElem) - + modelopts = newdoc.createTextNode(str(self.m2e_animOptChoice.GetSelection())) cn = newdoc.createTextNode(str(int(self.m2e_charNameChk.GetValue()))) charname = newdoc.createTextNode(str(self.m2e_charNameTxt.GetValue())) @@ -2968,7 +2968,7 @@ class main(wx.Frame): modeloptsElem.appendChild(modelopts) cnElem.appendChild(cn) charnameElem.appendChild(charname) - + sf = newdoc.createTextNode(str(int(self.m2e_startFrameChk.GetValue()))) sfval = newdoc.createTextNode(str(self.m2e_startFrameSpin.GetValue())) ef = newdoc.createTextNode(str(int(self.m2e_endFrameChk.GetValue()))) @@ -2977,7 +2977,7 @@ class main(wx.Frame): frival = newdoc.createTextNode(str(self.m2e_frameRateInSpin.GetValue())) fro = newdoc.createTextNode(str(int(self.m2e_frameRateOutChk.GetValue()))) froval = newdoc.createTextNode(str(self.m2e_frameRateOutSpin.GetValue())) - + sfElem.appendChild(sf) sfvalElem.appendChild(sfval) efElem.appendChild(ef) @@ -2986,30 +2986,30 @@ class main(wx.Frame): frivalElem.appendChild(frival) froElem.appendChild(fro) frovalElem.appendChild(froval) - + subroots = newdoc.createTextNode(str(int(self.m2e_subrootsChk.GetValue()))) subrnames = newdoc.createTextNode(str(self.m2e_subrootsTxt.GetValue())) subrootsElem.appendChild(subroots) subrnamesElem.appendChild(subrnames) - + animitem.appendChild(modeloptsElem) animitem.appendChild(cnElem) animitem.appendChild(charnameElem) animitem.appendChild(framerangeElem) animitem.appendChild(subrootsElem) animitem.appendChild(subrnamesElem) - + legacy_shaderElem = newdoc.createElement('legacy-shader') copytexElem = newdoc.createElement('copytex') destpathElem = newdoc.createElement('path') legacy_shader = newdoc.createTextNode(str(int(self.m2e_legacyShaderChk.GetValue()))) copytex = newdoc.createTextNode(str(int(self.m2e_copyTexChk.GetValue()))) destpath = newdoc.createTextNode(str(self.m2e_copyTexPathTxt.GetValue())) - + legacy_shaderElem.appendChild(legacy_shader) copytexElem.appendChild(copytex) destpathElem.appendChild(destpath) - + texitem.appendChild(legacy_shaderElem) texitem.appendChild(copytexElem) texitem.appendChild(destpathElem) @@ -3033,7 +3033,7 @@ class main(wx.Frame): AElem = newdoc.createElement('A') marginElem = newdoc.createElement('margin') coverageElem = newdoc.createElement('coverage') - + imagetypeElem.appendChild(imagetype) powertwoElem.appendChild(powertwo) RElem.appendChild(R) @@ -3042,7 +3042,7 @@ class main(wx.Frame): AElem.appendChild(A) marginElem.appendChild(margin) coverageElem.appendChild(coverage) - + attributeitem.appendChild(imagetypeElem) attributeitem.appendChild(powertwoElem) attributeitem.appendChild(RElem) @@ -3051,7 +3051,7 @@ class main(wx.Frame): attributeitem.appendChild(AElem) attributeitem.appendChild(marginElem) attributeitem.appendChild(coverageElem) - + filename = '' dirname = '' dlg = wx.FileDialog(self, "Choose a location and filename", dirname, "", "*.xml", wx.SAVE) @@ -3065,7 +3065,7 @@ class main(wx.Frame): for line in out: f.writelines(line) f.close() - + def OnLoadPrefs(self, event): # wxGlade: main. #load preferences dirname = '' @@ -3083,14 +3083,14 @@ class main(wx.Frame): #parse the file of preferences prefsDict = {} for list in doc.getElementsByTagName('preferences'): - + envlist = list.getElementsByTagName('environment') genlist = list.getElementsByTagName('genoptions') animlist = list.getElementsByTagName('animoptions') texlist = list.getElementsByTagName('textureoptions') overlist = list.getElementsByTagName('overridemod') attributelist = list.getElementsByTagName('attribute') - + for elem in envlist: for nodes in elem.childNodes: for val in nodes.childNodes: @@ -3112,7 +3112,7 @@ class main(wx.Frame): for elem in animlist: for elem2 in elem.childNodes: for elem3 in elem2.childNodes: - data = elem3 + data = elem3 parent = str(elem3.parentNode.nodeName) if parent == 'framerange': list = data.childNodes @@ -3134,15 +3134,15 @@ class main(wx.Frame): for val in nodes.childNodes: key = val.parentNode.nodeName data = str(val.data) - prefsDict[str(key)] = data.strip() - + prefsDict[str(key)] = data.strip() + return prefsDict - + def updateOptions(self,prefs): #lots of type conversions since I think XML only stores strings #I'm not sure I have to cast the ints to bools - #but I don't want to chance it with wxPython - #other than that all we're doing here is + #but I don't want to chance it with wxPython + #other than that all we're doing here is #setting all the options to the saved ones in the dictionary self.pandaPathTxt.SetValue(prefs['pandadir']) self.m2e_mayaVerComboBox.SetSelection(int(prefs['mayaver'])) @@ -3180,7 +3180,7 @@ class main(wx.Frame): self.palettize_marginTxt.SetValue(int(prefs['margin'])) self.palettize_coverageTxt.SetValue(prefs['coverage']) - + if __name__ == "__main__": app = wx.App(0) wx.InitAllImageHandlers() diff --git a/contrib/src/sceneeditor/AlignTool.py b/contrib/src/sceneeditor/AlignTool.py index 5bdd566079..6ad0b11b4c 100644 --- a/contrib/src/sceneeditor/AlignTool.py +++ b/contrib/src/sceneeditor/AlignTool.py @@ -19,7 +19,7 @@ class AlignTool(AppShell): padx = 0 pady = 0 - + def __init__(self, list = [], parent = None, nodePath = None, **kw): # Keep nodePath Data self.nodePath = nodePath @@ -36,14 +36,14 @@ class AlignTool(AppShell): self.parent = Toplevel() AppShell.__init__(self, self.parent) self.parent.geometry('%dx%d+%d+%d' % (self.frameWidth, self.frameHeight,self.frameIniPosX,self.frameIniPosY)) - + self.initialiseoptions(AlignTool) - + self.parent.resizable(False,False) ## Disable the ability to resize for this Window. - + def appInit(self): return - + def createInterface(self): # The interior of the toplevel panel interior = self.interior() @@ -77,14 +77,14 @@ class AlignTool(AppShell): variable = self.alignHVar) self.alignHButton.pack(side=RIGHT, expand=False) frame.pack(side=TOP, fill = X, expand = 1,pady=5) - + groupFrame.pack(side=TOP, fill = 'both', expand = 1,padx=5,pady=5) - + frame = Frame(mainFrame) Button(frame, text='Align', width = 13, command=self.Align_press).pack(side=LEFT) Button(frame, text='OK', width = 13, command=self.ok_press).pack(side=RIGHT) frame.pack(side=BOTTOM, fill = X, expand = 1,pady=5) - + # Y and P checkbox frame = Frame(groupFrame) self.alignYVar = IntVar() @@ -149,14 +149,14 @@ class AlignTool(AppShell): variable = self.alignSZVar) self.alignSZButton.pack(side=LEFT, expand=False) frame.pack(side=TOP, fill = X, expand = 1,pady=5) - - + + mainFrame.pack(fill = 'both', expand = 1,padx=7,pady=7) - + def createMenuBar(self): self.menuBar.destroy() - + def onDestroy(self, event): messenger.send('ALW_close', [self.nodePath.getName()]) ''' @@ -165,7 +165,7 @@ class AlignTool(AppShell): pass ############################### - + def ok_press(self): ################################################################# # ok_press(self) diff --git a/contrib/src/sceneeditor/MetadataPanel.py b/contrib/src/sceneeditor/MetadataPanel.py index cfe13bef2a..7510f3d7fc 100644 --- a/contrib/src/sceneeditor/MetadataPanel.py +++ b/contrib/src/sceneeditor/MetadataPanel.py @@ -12,13 +12,13 @@ class MetadataPanel(AppShell,Pmw.MegaWidget): usecommandarea = 0 usestatusarea = 0 Metatag="" - Metanode=None + Metanode=None tag_text=None def __init__(self,nodePath,parent=None,**kw): # Initialise superclass Pmw.MegaWidget.__init__(self, parent) - + # Define the megawidget options. optiondefs = ( ('title', self.appname, None), @@ -31,10 +31,10 @@ class MetadataPanel(AppShell,Pmw.MegaWidget): if parent == None: self.parent = Toplevel() AppShell.__init__(self, self.parent) - + self.parent.resizable(False,False) - + def appInit(self): print "Metadata Panel" @@ -55,5 +55,5 @@ class MetadataPanel(AppShell,Pmw.MegaWidget): def SetIt(self): self.Metanode.setTag("Metadata",self.tag_text.get()) - - + + diff --git a/contrib/src/sceneeditor/SideWindow.py b/contrib/src/sceneeditor/SideWindow.py index f934391dba..58a41a05be 100644 --- a/contrib/src/sceneeditor/SideWindow.py +++ b/contrib/src/sceneeditor/SideWindow.py @@ -31,9 +31,9 @@ class sideWindow(AppShell): backface = 0 texture = 1 wireframe = 0 - + enableBaseUseDrive = 0 - + def __init__(self, worldColor,lightEnable,ParticleEnable, basedriveEnable,collision, backface, texture, wireframe, grid, widgetVis, enableAutoCamera, parent = None, nodePath = render, **kw): self.worldColor = worldColor @@ -58,15 +58,15 @@ class sideWindow(AppShell): self.parent = Toplevel() else: self.parent = parent - + AppShell.__init__(self, self.parent) self.parent.geometry('%dx%d+%d+%d' % (self.frameWidth, self.frameHeight,self.frameIniPosX,self.frameIniPosY)) self.parent.resizable(False,False) ## Disable the ability to resize for this Window. - + def appInit(self): print '----SideWindow is Initialized!!' - + def createInterface(self): # The interior of the toplevel panel interior = self.interior() @@ -212,11 +212,11 @@ class sideWindow(AppShell): self.notebookFrame.setnaturalsize() mainFrame.pack(fill = 'both', expand = 1) - + def createMenuBar(self): # We don't need menu bar here. self.menuBar.destroy() - + def onDestroy(self, event): ################################################################# # onDestroy(self, event) @@ -352,7 +352,7 @@ class sideWindow(AppShell): self.backface = (self.backface+1)%2 self.backfaceButton.toggle() return - + def toggleTexture(self): ################################################################# # toggleTexture(self) @@ -361,7 +361,7 @@ class sideWindow(AppShell): base.toggleTexture() self.texture = (self.texture+1)%2 return - + def toggleTextureFromMainW(self): ################################################################# # toggleTextureFromMainW(self) @@ -373,7 +373,7 @@ class sideWindow(AppShell): self.texture = (self.texture+1)%2 self.textureButton.toggle() return - + def toggleWireframe(self): ################################################################# # toggleWireframe(self) @@ -428,7 +428,7 @@ class sideWindow(AppShell): self.widgetVis = (self.widgetVis+1)%2 self.widgetVisButton.toggle() return - + def setBackgroundColorVec(self,color): ################################################################# # setBackgroundColorVec(self,color) diff --git a/contrib/src/sceneeditor/collisionWindow.py b/contrib/src/sceneeditor/collisionWindow.py index 1832d33fcb..7122e801bb 100644 --- a/contrib/src/sceneeditor/collisionWindow.py +++ b/contrib/src/sceneeditor/collisionWindow.py @@ -32,12 +32,12 @@ class collisionWindow(AppShell): 'collisionSphere', 'collisionSegment', 'collisionRay'] - + def __init__(self, nodePath, parent = None, **kw): - + self.nodePath = nodePath self.objType = 'collisionSphere' # set default type to Collision Sphere - + INITOPT = Pmw.INITOPT optiondefs = ( ('title', self.appname, None), @@ -77,7 +77,7 @@ class collisionWindow(AppShell): frame.pack(side=TOP, fill=X, expand=True, padx=3) self.collisionTypeEntry.selectitem('collisionSphere', setentry=True) - + self.inputZone = Pmw.Group(mainFrame, tag_pyclass = None) self.inputZone.pack(fill='both',expand=1) settingFrame = self.inputZone.interior() @@ -101,7 +101,7 @@ class collisionWindow(AppShell): label = Label(Interior, text='Attention! All Coordinates Are Related To Its Parent Node!') label.pack(side=LEFT,expand=0,fill=X, padx=1) Interior.pack(side=TOP, expand=0,fill=X) - + self.createPosEntry(PolygonPage, catagory='Polygon', id='Point A') self.createPosEntry(PolygonPage, catagory='Polygon', id='Point B') self.createPosEntry(PolygonPage, catagory='Polygon', id='Point C') @@ -112,7 +112,7 @@ class collisionWindow(AppShell): label = Label(Interior, text='Attention! All Coordinates Are Related To Its Parent Node!') label.pack(side=LEFT,expand=0,fill=X, padx=1) Interior.pack(side=TOP, expand=0,fill=X) - + self.createPosEntry(SpherePage, catagory='Sphere', id='Center Point') self.createEntryField(SpherePage,catagory='Sphere', id='Size', @@ -127,7 +127,7 @@ class collisionWindow(AppShell): label = Label(Interior, text='Attention! All Coordinates Are Related To Its Parent Node!') label.pack(side=LEFT,expand=0,fill=X, padx=1) Interior.pack(side=TOP, expand=0,fill=X) - + self.createPosEntry(SegmentPage, catagory='Segment', id='Point A') self.createPosEntry(SegmentPage, catagory='Segment', id='Point B') @@ -137,12 +137,12 @@ class collisionWindow(AppShell): label = Label(Interior, text='Attention! All Coordinates Are Related To Its Parent Node!') label.pack(side=LEFT,expand=0,fill=X, padx=1) Interior.pack(side=TOP, expand=0,fill=X) - + self.createPosEntry(RayPage, catagory='Ray', id='Origin') self.createPosEntry(RayPage, catagory='Ray', id='Direction') - + self.objNotebook.setnaturalsize() self.objNotebook.pack(expand = 1, fill = BOTH) @@ -175,7 +175,7 @@ class collisionWindow(AppShell): self.objNotebook.selectpage('Segment') elif self.objType=='collisionRay': self.objNotebook.selectpage('Ray') - + return def updateObjInfo(self, page=None): @@ -207,13 +207,13 @@ class collisionWindow(AppShell): float(self.widgetDict['PolygonPoint C'][1]._entry.get()), float(self.widgetDict['PolygonPoint C'][2]._entry.get())) collisionObject = CollisionPolygon(pointA, pointB, pointC) - + elif self.objType=='collisionSphere': collisionObject = CollisionSphere(float(self.widgetDict['SphereCenter Point'][0]._entry.get()), float(self.widgetDict['SphereCenter Point'][1]._entry.get()), float(self.widgetDict['SphereCenter Point'][2]._entry.get()), float(self.widgetDict['SphereSize'].getvalue())) - + elif self.objType=='collisionSegment': pointA = Point3(float(self.widgetDict['SegmentPoint A'][0]._entry.get()), float(self.widgetDict['SegmentPoint A'][1]._entry.get()), @@ -221,35 +221,35 @@ class collisionWindow(AppShell): pointB = Point3(float(self.widgetDict['SegmentPoint B'][0]._entry.get()), float(self.widgetDict['SegmentPoint B'][1]._entry.get()), float(self.widgetDict['SegmentPoint B'][2]._entry.get())) - + collisionObject = CollisionSegment() collisionObject.setPointA(pointA) collisionObject.setFromLens(base.cam.node(), Point2( -1, 1 )) ## You must set up the camera lensNode before you set point B.... collisionObject.setPointB(pointB) - + elif self.objType=='collisionRay': point = Point3(float(self.widgetDict['RayOrigin'][0]._entry.get()), float(self.widgetDict['RayOrigin'][1]._entry.get()), float(self.widgetDict['RayOrigin'][2]._entry.get())) - + vector = Vec3(float(self.widgetDict['RayDirection'][0]._entry.get()), float(self.widgetDict['RayDirection'][1]._entry.get()), float(self.widgetDict['RayDirection'][2]._entry.get())) print vector, point - + collisionObject = CollisionRay() collisionObject.setOrigin(point) collisionObject.setDirection(vector) #collisionObject.setFromLens(base.cam.node(), Point2( -1, 1 )) ## You must set up the camera lensNode before you set up others... - + if self.objType=='collisionPolygon': messenger.send('CW_addCollisionObj', [collisionObject, self.nodePath, pointA, pointB, pointC]) else: messenger.send('CW_addCollisionObj', [collisionObject, self.nodePath]) self.quit() - + return def createPosEntry(self, contentFrame, catagory, id): @@ -261,16 +261,16 @@ class collisionWindow(AppShell): text = 'X', relief = FLAT, value = 0.0, entry_width = 6) - + self.posX.pack(side=LEFT,expand=0,fill=X, padx=1) - + self.posY = self.createcomponent('posY'+catagory+id, (), None, Floater.Floater, (posInterior,), text = 'Y', relief = FLAT, value = 0.0, entry_width = 6) self.posY.pack(side=LEFT, expand=0,fill=X, padx=1) - + self.posZ = self.createcomponent('posZ'+catagory+id, (), None, Floater.Floater, (posInterior,), text = 'Z', relief = FLAT, @@ -298,5 +298,5 @@ class collisionWindow(AppShell): widget = Button(frame, text=buttonText, font=('MSSansSerif', 10), command = defaultFunction) widget.pack(side=LEFT, padx=3) self.widgetDict[catagory+id+'-'+'DefaultButton']=widget - + frame.pack(side = side, fill = fill, expand = expand,pady=3) diff --git a/contrib/src/sceneeditor/controllerWindow.py b/contrib/src/sceneeditor/controllerWindow.py index 7365152dfb..b66e390c73 100644 --- a/contrib/src/sceneeditor/controllerWindow.py +++ b/contrib/src/sceneeditor/controllerWindow.py @@ -16,7 +16,7 @@ class controllerWindow(AppShell): # This will open a talk window for user to set the control mechanism # In here, user can choose to control what object by keyboard or other inputs. ################################################################# - + # Override class variables appname = 'Controller Panel' frameWidth = 500 @@ -27,11 +27,11 @@ class controllerWindow(AppShell): # setup the type of controller we handle here. controllerList = ['Keyboard', 'Tracker'] - + # Default Keyboard setting keyboardMapDict = {} keyboardSpeedDict = {} - + def __init__(self, listOfObj, controlType , dataList, parent = None, **kw): if controlType == 'Keyboard': self.nodePath = dataList[0] # Default setting -> mainly used for Keyboard control now. @@ -41,10 +41,10 @@ class controllerWindow(AppShell): self.keyboardMapDict = dataList[1] self.keyboardSpeedDict.clear() self.keyboardSpeedDict = dataList[2] - + self.listOfObj = listOfObj self.keepControl = False - + INITOPT = Pmw.INITOPT optiondefs = ( ('title', self.appname, None), @@ -63,9 +63,9 @@ class controllerWindow(AppShell): # Handle to the toplevels interior interior = self.interior() menuBar = self.menuBar - + # We don't need menu bar here - self.menuBar.destroy() + self.menuBar.destroy() # Create a frame to hold all stuff mainFrame = Frame(interior) @@ -81,7 +81,7 @@ class controllerWindow(AppShell): self.cotrollerTypeEntry.pack(side=Tkinter.LEFT) frame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=False, pady = 3) self.cotrollerTypeEntry.selectitem('Keyboard', setentry=True) - + self.inputZone = Pmw.Group(mainFrame, tag_pyclass = None) self.inputZone.pack(fill='both',expand=1) settingFrame = self.inputZone.interior() @@ -124,11 +124,11 @@ class controllerWindow(AppShell): inputZone = Pmw.Group(assignFrame, tag_pyclass = None) inputZone.pack(fill='both',expand=1) settingFrame = inputZone.interior() - + Interior = Frame(settingFrame) widget = Label(Interior, text = 'Assign a Key For:').pack(side=Tkinter.LEFT, expand = False) Interior.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True,pady = 6 ) - + Interior = Frame(settingFrame) widget = Label(Interior, text = 'Forward :', width = 20, anchor = Tkinter.W).pack(side=Tkinter.LEFT, expand = False) widget = self.createcomponent( @@ -531,7 +531,7 @@ class controllerWindow(AppShell): assignFrame.pack(side=Tkinter.TOP, expand=True, fill = Tkinter.X) keyboardPage.pack(side=Tkinter.TOP, expand=True, fill = Tkinter.X) - + #################################################################### #################################################################### # End of Keyboard control page @@ -613,7 +613,7 @@ class controllerWindow(AppShell): self.objNotebook.selectpage('Keyboard') elif self.controllType=='Tracker': self.objNotebook.selectpage('Tracker') - + return def updateControlInfo(self, page=None): @@ -692,4 +692,4 @@ class controllerWindow(AppShell): messenger.send('ControlW_saveSetting', ['Keyboard', [self.nodePath, self.keyboardMapDict, self.keyboardSpeedDict]]) return - + diff --git a/contrib/src/sceneeditor/dataHolder.py b/contrib/src/sceneeditor/dataHolder.py index b591cd52e8..0981df643d 100644 --- a/contrib/src/sceneeditor/dataHolder.py +++ b/contrib/src/sceneeditor/dataHolder.py @@ -117,10 +117,10 @@ class dataHolder: # Initialize the basic message formate from CollisionHandler self.CollisionHandler.setInPattern("%fnenter%in") self.CollisionHandler.setOutPattern("%fnexit%in") - + pass - + def resetAll(self): ################################################################# # resetAll(self) @@ -149,7 +149,7 @@ class dataHolder: self.blendAnimDict.clear() self.particleDict.clear() self.particleNodes.clear() - + self.ModelNum=0 self.ActorNum=0 self.theScene=None @@ -167,8 +167,8 @@ class dataHolder: ## Check if there is any child node, if so, remove it. childrenList = nodePath.getChildren() - - + + if self.ModelDic.has_key(name): del self.ModelDic[name] del self.ModelRefDic[name] @@ -214,7 +214,7 @@ class dataHolder: else: print 'You cannot remove this NodePath' return - + messenger.send('SGE_Update Explorer',[render]) return @@ -247,11 +247,11 @@ class dataHolder: else: print '---- DataHolder: Target Obj is not a legal object could be duplicate!' return - + FilePath = holderRef[name] oPos = holder[name].getPos()+cPos oHpr = holder[name].getHpr()+cHpr - + for i in range(num): if isModel: ### copy model node from modelpool @@ -268,7 +268,7 @@ class dataHolder: holder[newName].setName(newName) oPos = oPos + cPos oHpr = oHpr + cHpr - + else: ### copy the actor- not includ its animations ''' @@ -289,7 +289,7 @@ class dataHolder: holder[newName].setName(newName) oPos = oPos + cPos oHpr = oHpr + cHpr - + messenger.send('SGE_Update Explorer',[render]) return @@ -434,7 +434,7 @@ class dataHolder: ########################################################################### self.lightManager.toggle() return - + def isLight(self,name): ########################################################################### # isLight(self, name) @@ -519,10 +519,10 @@ class dataHolder: if oName == nName: # If the new name is the same with old name, do nothing. return - + while self.isInScene(nName): nName = nName + '_1' - + if self.isActor(oName): self.ActorDic[nName]= self.ActorDic[oName] self.ActorRefDic[nName]= self.ActorRefDic[oName] @@ -548,7 +548,7 @@ class dataHolder: self.collisionDict[nName]= self.collisionDict[oName] self.collisionDict[nName].setName(nName) del self.collisionDict[oName] - + elif self.particleNodes.has_key(oName): self.particleNodes[nName]= self.particleNodes[oName] self.particleDict[nName]= self.particleDict[oName] @@ -588,7 +588,7 @@ class dataHolder: return True return False - + def bindCurveToNode(self,node,curveCollection): ########################################################################### # bindCurveToNode(self,node,curveCollection) @@ -664,7 +664,7 @@ class dataHolder: info['vFov'] = lens.getVfov() info['focalLength'] = lens.getFocalLength() - + elif name == 'SEditor': type = 'Special' elif self.isActor(name): @@ -684,7 +684,7 @@ class dataHolder: info['collisionNode'] = self.collisionDict[name] if self.curveDict.has_key(name): info['curveList'] = self.getCurveList(nodePath) - + return type, info def getAnimationDictFromActor(self, actorName): @@ -754,7 +754,7 @@ class dataHolder: base.cTrav.addCollider( self.collisionDict[name], self.CollisionHandler) messenger.send('SGE_Update Explorer',[render]) - + return def toggleCollisionVisable(self, visable): @@ -888,7 +888,7 @@ class dataHolder: return self.particleNodes[name] elif self.lightManager.isLight(name): return self.lightManager.getLightNode(name) - + return None def getControlSetting(self): @@ -923,7 +923,7 @@ class dataHolder: self.keyboardSpeedDict.clear() self.keyboardSpeedDict = data[2].copy() return - + def loadScene(self): ########################################################################### # loadScene(self) @@ -934,9 +934,9 @@ class dataHolder: # in the scene file hence reviving the state for the scene ########################################################################### - ### Ask for a filename + ### Ask for a filename OpenFilename = tkFileDialog.askopenfilename(filetypes = [("PY","py")],title = "Load Scene") - if(not OpenFilename): + if(not OpenFilename): return None f=Filename.fromOsSpecific(OpenFilename) fileName=f.getBasenameWoExtension() @@ -953,7 +953,7 @@ class dataHolder: ############################################################################ self.theScene=__import__(fileName) self.Scene=self.theScene.SavedScene(0,seParticleEffect,seParticles,dirName) # Specify load mode of 0 which will allow us to pass seParticle and seParticleEffect - messenger.send('SGE_Update Explorer',[render]) + messenger.send('SGE_Update Explorer',[render]) # Lets call some important initialization methods on our scene: @@ -989,7 +989,7 @@ class dataHolder: for light in self.Scene.LightDict: #print light alight=self.Scene.LightDict[light] - type=self.Scene.LightTypes[light] + type=self.Scene.LightTypes[light] thenode=self.Scene.LightNodes[light] #print type if type == 'ambient': @@ -1032,7 +1032,7 @@ class dataHolder: nodeP.removeNode() thenode=render.find("**/"+str(node)) self.bindCurveToNode(thenode,curveColl) - + ############################################################################ # Populate Particle related Dictionaries ############################################################################ @@ -1049,9 +1049,9 @@ class dataHolder: theeffect.enable() self.particleDict[effect]=theeffect self.particleNodes[effect]=emitter - - - + + + # Clean up things added to scene graph by saved file's code execution for light in self.Scene.LightDict: vestige=render.find('**/'+light) @@ -1061,11 +1061,11 @@ class dataHolder: ############################################################################ # return the filename and update the scenegraph explorer window ############################################################################ - messenger.send('SGE_Update Explorer',[render]) + messenger.send('SGE_Update Explorer',[render]) if(OpenFilename): return OpenFilename else: return None def getList(self): - return self.lightManager.getList() + return self.lightManager.getList() diff --git a/contrib/src/sceneeditor/duplicateWindow.py b/contrib/src/sceneeditor/duplicateWindow.py index 6ae4400c08..24f20b7d09 100644 --- a/contrib/src/sceneeditor/duplicateWindow.py +++ b/contrib/src/sceneeditor/duplicateWindow.py @@ -27,7 +27,7 @@ class duplicateWindow(AppShell): padx = 0 pady = 0 - + def __init__(self, parent = None, nodePath = None, **kw): # Define the megawidget options. optiondefs = ( @@ -43,10 +43,10 @@ class duplicateWindow(AppShell): self.nodePath = nodePath self.parent.resizable(False,False) ## Disable the ability to resize for this Window. - + def appInit(self): print '----SideWindow is Initialized!!' - + def createInterface(self): # The interior of the toplevel panel interior = self.interior() @@ -90,18 +90,18 @@ class duplicateWindow(AppShell): self.numberOfCopy = Pmw.EntryField(settingFrame,label_text='Number of Copy :',labelpos='w',value='1', validate=Pmw.integervalidator) self.numberOfCopy.component('entry').config(width=15) self.numberOfCopy.place(anchor=NW,x=52,y=150) - + settingFrame.pack(fill=BOTH,expand=1,padx=7,pady=7) self.button_ok = Button(mainFrame, text="OK", command=self.ok_press,width=10) self.button_ok.pack(fill=BOTH,expand=0,side=RIGHT) - + mainFrame.pack(fill = 'both', expand = 1,padx=7,pady=7) - + def createMenuBar(self): self.menuBar.destroy() - + def onDestroy(self, event): messenger.send('DW_close') ''' @@ -110,7 +110,7 @@ class duplicateWindow(AppShell): pass ############################### - + def ok_press(self): ################################################################# # ok_press(self) diff --git a/contrib/src/sceneeditor/lightingPanel.py b/contrib/src/sceneeditor/lightingPanel.py index f422215c0d..edca358d61 100644 --- a/contrib/src/sceneeditor/lightingPanel.py +++ b/contrib/src/sceneeditor/lightingPanel.py @@ -22,7 +22,7 @@ class lightingPanel(AppShell): frameWidth = 400 frameHeight = 400 currentLight = None - + def __init__(self, lightList, parent = None, **kw): self.lightList = lightList self.lightColor = [0.3*255,0.3*255,0.3*255] @@ -53,14 +53,14 @@ class lightingPanel(AppShell): self.listZone = Pmw.Group(mainFrame,tag_pyclass = None) self.listZone.pack(expand=0, fill=Tkinter.X,padx=3,pady=3) listFrame = self.listZone.interior() - + self.lightEntry = self.createcomponent( 'Lights List', (), None, Pmw.ComboBox, (listFrame,),label_text='Light :', labelpos = Tkinter.W, entry_width = 25, selectioncommand = self.selectLight, scrolledlist_items = self.lightList) self.lightEntry.pack(side=Tkinter.LEFT) - + self.renameButton = self.createcomponent( 'Rename Light', (), None, Button, (listFrame,), @@ -82,7 +82,7 @@ class lightingPanel(AppShell): command = self.addPoint) lightsMenu.add_command(label = 'Add Spotlight', command = self.addSpot) - + self.lightsButton.pack(expand=0) self.lightsButton['menu'] = lightsMenu @@ -155,7 +155,7 @@ class lightingPanel(AppShell): self.pConstantAttenuation.pack(fill = Tkinter.X, expand = 0) self.bind(self.pConstantAttenuation, 'Set point light constant attenuation') - + self.pLinearAttenuation = Slider( pointPage, text = 'Linear Attenuation', @@ -166,7 +166,7 @@ class lightingPanel(AppShell): self.pLinearAttenuation.pack(fill = Tkinter.X, expand = 0) self.bind(self.pLinearAttenuation, 'Set point light linear attenuation') - + self.pQuadraticAttenuation = Slider( pointPage, text = 'Quadratic Attenuation', @@ -177,7 +177,7 @@ class lightingPanel(AppShell): self.pQuadraticAttenuation.pack(fill = Tkinter.X, expand = 0) self.bind(self.pQuadraticAttenuation, 'Set point light quadratic attenuation') - + # Spot light controls self.sSpecularColor = seColorEntry( spotPage, text = 'Specular Color') @@ -196,7 +196,7 @@ class lightingPanel(AppShell): self.sConstantAttenuation.pack(fill = Tkinter.X, expand = 0) self.bind(self.sConstantAttenuation, 'Set spot light constant attenuation') - + self.sLinearAttenuation = Slider( spotPage, text = 'Linear Attenuation', @@ -207,7 +207,7 @@ class lightingPanel(AppShell): self.sLinearAttenuation.pack(fill = Tkinter.X, expand = 0) self.bind(self.sLinearAttenuation, 'Set spot light linear attenuation') - + self.sQuadraticAttenuation = Slider( spotPage, text = 'Quadratic Attenuation', @@ -218,7 +218,7 @@ class lightingPanel(AppShell): self.sQuadraticAttenuation.pack(fill = Tkinter.X, expand = 0) self.bind(self.sQuadraticAttenuation, 'Set spot light quadratic attenuation') - + self.sExponent = Slider( spotPage, text = 'Exponent', @@ -231,7 +231,7 @@ class lightingPanel(AppShell): 'Set spot light exponent') # MRM: Add frustum controls - + self.lightNotebook.setnaturalsize() self.lightNotebook.pack(expand = 1, fill = Tkinter.BOTH) @@ -329,7 +329,7 @@ class lightingPanel(AppShell): self.lightColor.set([255*0.3,255*0.3,255*0.3]) oldType = self.type self.type = 'ambient' - + if self.type=='ambient': self.lightNotebook.selectpage('Ambient') elif self.type =='directional': @@ -384,7 +384,7 @@ class lightingPanel(AppShell): ################################################################# messenger.send('LP_addLight',['ambient']) return - + def addDirectional(self): ################################################################# # addDirectional(self) @@ -393,7 +393,7 @@ class lightingPanel(AppShell): ################################################################# messenger.send('LP_addLight',['directional']) return - + def addPoint(self): ################################################################# # addPoint(self) @@ -402,7 +402,7 @@ class lightingPanel(AppShell): ################################################################# messenger.send('LP_addLight',['point']) return - + def addSpot(self): ################################################################# # addSpot(self) @@ -455,7 +455,7 @@ class lightingPanel(AppShell): return self.currentLight.setOrientation(Vec3(orient[0],orient[1],orient[2])) return - + def setConstantAttenuation(self, value): ################################################################# # setConstantAttenuation(self, value) @@ -464,7 +464,7 @@ class lightingPanel(AppShell): ################################################################# self.currentLight.setConstantAttenuation(value) return - + def setLinearAttenuation(self, value): ################################################################# # setLinearAttenuation(self, value) @@ -473,7 +473,7 @@ class lightingPanel(AppShell): ################################################################# self.currentLight.setLinearAttenuation(value) return - + def setQuadraticAttenuation(self, value): ################################################################# # setQuadraticAttenuation(self, value) @@ -482,7 +482,7 @@ class lightingPanel(AppShell): ################################################################# self.currentLight.setQuadraticAttenuation(value) return - + def setExponent(self, value): ################################################################# # setExponent(self, value) diff --git a/contrib/src/sceneeditor/propertyWindow.py b/contrib/src/sceneeditor/propertyWindow.py index 80bcef1d7e..35f239eee5 100644 --- a/contrib/src/sceneeditor/propertyWindow.py +++ b/contrib/src/sceneeditor/propertyWindow.py @@ -31,17 +31,17 @@ class propertyWindow(AppShell,Pmw.MegaWidget): usestatusarea = 0 widgetsDict = {} - + def __init__(self, target, type, info, parent = None, nodePath = render, **kw): self.nodePath = target self.name = target.getName() self.type = type self.info = info - + # Initialise superclass Pmw.MegaWidget.__init__(self, parent) - + # Define the megawidget options. optiondefs = ( ('title', self.appname, None), @@ -51,12 +51,12 @@ class propertyWindow(AppShell,Pmw.MegaWidget): if parent == None: self.parent = Toplevel() AppShell.__init__(self, self.parent) - + self.parent.resizable(False,False) ## Disable the ability to resize for this Window. - + def appInit(self): return - + def createInterface(self): # The interior of the toplevel panel interior = self.interior() @@ -110,15 +110,15 @@ class propertyWindow(AppShell,Pmw.MegaWidget): #### If nodePath has been binded with any curves if self.info.has_key('curveList'): self.createCurveFrame(self.contentFrame) - + ## Set all stuff done mainFrame.pack(fill = 'both', expand = 1) - + def createMenuBar(self): # we don't need menu bar here. self.menuBar.destroy() - + def onDestroy(self, event): self.ignore('forPorpertyWindow'+self.name) messenger.send('PW_close', [self.name]) @@ -154,7 +154,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): widget = Button(frame, text=buttonText, font=('MSSansSerif', 10), command = defaultFunction) widget.pack(side=LEFT, padx=3) self.widgetsDict[text+'-'+'DefaultButton']=widget - + frame.pack(side = side, fill = fill, expand = expand,pady=3) @@ -175,7 +175,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): self.posX['commandData'] = ['x'] self.posX['command'] = self.setNodePathPosHprScale self.posX.pack(side=LEFT,expand=0,fill=X, padx=1) - + self.posY = self.createcomponent('posY', (), None, Floater.Floater, (posInterior,), text = 'Y', relief = FLAT, @@ -185,7 +185,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): self.posY['commandData'] = ['y'] self.posY['command'] = self.setNodePathPosHprScale self.posY.pack(side=LEFT, expand=0,fill=X, padx=1) - + self.posZ = self.createcomponent('posZ', (), None, Floater.Floater, (posInterior,), text = 'Z', relief = FLAT, @@ -215,7 +215,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): self.hprH['commandData'] = ['h'] self.hprH['command'] = self.setNodePathPosHprScale self.hprH.pack(side = LEFT, expand=0,fill=X) - + self.hprP = self.createcomponent('hprP', (), None, Dial.AngleDial, (hprInterior,), style = 'mini', @@ -226,7 +226,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): self.hprP['commandData'] = ['p'] self.hprP['command'] = self.setNodePathPosHprScale self.hprP.pack(side = LEFT, expand=0,fill=X) - + self.hprR = self.createcomponent('hprR', (), None, Dial.AngleDial, (hprInterior,), style = 'mini', @@ -249,7 +249,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): # And, it will set the call back function to setNodePathPosHprScale() ################################################################# scaleInterior = Frame(contentFrame) - + self.scale = self.createcomponent('scale', (), None, Floater.Floater, (scaleInterior,), text = 'Scale', @@ -280,10 +280,10 @@ class propertyWindow(AppShell,Pmw.MegaWidget): self.nodeColor['command'] = self.setNodeColorVec self.nodeColor['resetValue'] = [255,255,255,255] self.nodeColor.place(anchor=NW,y=235) - self.bind(self.nodeColor, 'Set nodePath color') + self.bind(self.nodeColor, 'Set nodePath color') self.nodeColor.pack(side=TOP,expand=0,fill=X, padx=3, pady=3) return - + def setNodeColorVec(self, color): ################################################################# # setNodeColorVec(self, color) @@ -295,7 +295,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): color[3]/255.0) return - + def setNodePathPosHprScale(self, data, axis): ################################################################# # setNodePathPosHprScale(self, data, axis) @@ -345,9 +345,9 @@ class propertyWindow(AppShell,Pmw.MegaWidget): defaultFunction = lambda a = n, b = self : b.deleteCurve(a)) group.pack(side = TOP, fill = X, expand = 0,pady=3, padx=3) self.curveFrame.pack(side = TOP, fill = X, expand = 0,pady=3, padx=3) - + return - + def deleteCurve(self, number = 0): ################################################################# # deleteCurve(self, number = 0) @@ -374,7 +374,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): return else: self.ignore('curveRemovedFromNode') - + if curveList!= None: del self.info['curveList'] self.info['curveList'] = curveList @@ -397,7 +397,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): # cameraInterface(self, interior, mainFrame) # Create the interface for camera node. ################################################################# - + ## Type entry : unchageable widget = self.createEntryField(contentFrame,'Type:', value = self.type, @@ -423,7 +423,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): tag_font=('MSSansSerif', 10)) self.createHprEntry(group.interior()) group.pack(side=TOP,fill = X, expand = 0, pady=3) - + ## near entry group = Pmw.Group(contentFrame,tag_text='Lens Property', tag_font=('MSSansSerif', 10)) @@ -471,7 +471,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): widget = Label(frame, text = "Film Size:", font=('MSSansSerif', 10),width=12) widget.pack(side=LEFT) frame.pack(side = TOP, fill = X, expand = 0, pady=3) - + frame = Frame(lensFrame) widget = Pmw.EntryField(frame, labelpos='w', label_text = ' ', value = self.info['FilmSize'].getX(), @@ -490,7 +490,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): widget.pack(side=LEFT, padx=3) widget = Button(frame, text='Default', font=('MSSansSerif', 10), command = self.defaultCameraFilmSize) widget.pack(side=LEFT, padx=3) - self.widgetsDict['FilmSize'+'-'+'DefaultButton']=widget + self.widgetsDict['FilmSize'+'-'+'DefaultButton']=widget frame.pack(side = TOP, fill = X, expand = 0,pady=0) ## Focal Length entry @@ -504,7 +504,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): defaultFunction = self.defaultCameraFocalLength) group.pack(side = TOP, fill = X, expand = 0,pady=2) - + def defaultCameraFar(self): ################################################################# # defaultCameraFar(self) @@ -655,7 +655,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): tag_font=('MSSansSerif', 10)) self.createPosEntry(group.interior()) group.pack(side=TOP,fill = X, expand = 0, pady=3) - + group = Pmw.Group(contentFrame,tag_text='Orientation', tag_font=('MSSansSerif', 10)) self.createHprEntry(group.interior()) @@ -689,7 +689,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): self.nodePath.setTransparency(True) self.nodePath.setBin("fixed", 1) return - + def actorInterface(self, contentFrame): ################################################################# # actorInterface(self, contentFrame) @@ -744,7 +744,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): return else: self.ignore('animRemovedFromNode') - + if len(animDict)!= 0: del self.info['animDict'] self.info['animDict'] = animDict @@ -784,14 +784,14 @@ class propertyWindow(AppShell,Pmw.MegaWidget): self.lightColor['resetValue'] = [0.3*255,0.3*255,0.3*255,0] self.lightColor.pack(side=TOP, fill=X,expand=1, padx = 2, pady =2) self.bind(self.lightColor, 'Set light color') - + self.varActive = IntVar() self.varActive.set(self.lightNode.active) checkButton = Checkbutton(frame, text='Enable This Light', variable=self.varActive, command=self.toggleLight) checkButton.pack(side=RIGHT,pady=3) lightingGroup.pack(side=TOP, fill = X, expand =1) - + # Directional light controls if self.lightNode.type == 'directional': lightingGroup = Pmw.Group(contentFrame,tag_pyclass=None) @@ -815,10 +815,10 @@ class propertyWindow(AppShell,Pmw.MegaWidget): self.dOrientation['resetValue'] = [0,0,0,0] self.dOrientation.pack(fill = X, expand = 1) self.bind(self.dOrientation, 'Set directional light orientation') - + lightingGroup.pack(side=TOP, fill = X, expand =1) - + elif self.lightNode.type == 'point': # Point light controls lightingGroup = Pmw.Group(contentFrame,tag_pyclass=None) @@ -830,7 +830,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): self.pSpecularColor.pack(fill = X, expand = 1) self.bind(self.pSpecularColor, 'Set point light specular color') - + self.pPosition = VectorWidgets.Vector3Entry( pointPage, text = 'Position', label_font=('MSSansSerif', 10), value = [self.lightNode.getPosition().getX(),self.lightNode.getPosition().getY(),self.lightNode.getPosition().getZ(),0]) @@ -848,7 +848,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): self.pConstantAttenuation.pack(fill = X, expand = 1) self.bind(self.pConstantAttenuation, 'Set point light constant attenuation') - + self.pLinearAttenuation = Slider.Slider( pointPage, text = 'Linear Attenuation', label_font=('MSSansSerif', 10), @@ -858,7 +858,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): self.pLinearAttenuation.pack(fill = X, expand = 1) self.bind(self.pLinearAttenuation, 'Set point light linear attenuation') - + self.pQuadraticAttenuation = Slider.Slider( pointPage, text = 'Quadratic Attenuation', label_font=('MSSansSerif', 10), @@ -871,8 +871,8 @@ class propertyWindow(AppShell,Pmw.MegaWidget): lightingGroup.pack(side=TOP, fill = X, expand =1) - - elif self.lightNode.type == 'spot': + + elif self.lightNode.type == 'spot': # Spot light controls lightingGroup = Pmw.Group(contentFrame,tag_pyclass=None) spotPage = lightingGroup.interior() @@ -893,7 +893,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): self.sConstantAttenuation.pack(fill = X, expand = 1) self.bind(self.sConstantAttenuation, 'Set spot light constant attenuation') - + self.sLinearAttenuation = Slider.Slider( spotPage, text = 'Linear Attenuation', label_font=('MSSansSerif', 10), @@ -903,7 +903,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): self.sLinearAttenuation.pack(fill = X, expand = 1) self.bind(self.sLinearAttenuation, 'Set spot light linear attenuation') - + self.sQuadraticAttenuation = Slider.Slider( spotPage, text = 'Quadratic Attenuation', label_font=('MSSansSerif', 10), @@ -913,7 +913,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): self.sQuadraticAttenuation.pack(fill = X, expand = 1) self.bind(self.sQuadraticAttenuation, 'Set spot light quadratic attenuation') - + self.sExponent = Slider.Slider( spotPage, text = 'Exponent', label_font=('MSSansSerif', 10), @@ -924,7 +924,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): self.bind(self.sExponent, 'Set spot light exponent') lightingGroup.pack(side=TOP, fill = X, expand =1) - + return def setLightingColorVec(self,color): @@ -950,19 +950,19 @@ class propertyWindow(AppShell,Pmw.MegaWidget): return self.lightNode.setOrientation(Vec3(orient[0],orient[1],orient[2])) return - + def setConstantAttenuation(self, value): self.lightNode.setConstantAttenuation(value) return - + def setLinearAttenuation(self, value): self.lightNode.setLinearAttenuation(value) return - + def setQuadraticAttenuation(self, value): self.lightNode.setQuadraticAttenuation(value) return - + def setExponent(self, value): self.lightNode.setExponent(value) return @@ -988,12 +988,12 @@ class propertyWindow(AppShell,Pmw.MegaWidget): command = None, initialState='disabled', side = 'top') - + group = Pmw.Group(contentFrame,tag_text='Position', tag_font=('MSSansSerif', 10)) self.createPosEntry(group.interior()) group.pack(side=TOP,fill = X, expand = 0, pady=3) - + group = Pmw.Group(contentFrame,tag_text='Orientation', tag_font=('MSSansSerif', 10)) self.createHprEntry(group.interior()) @@ -1027,7 +1027,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): group.pack(side=TOP,fill = X, expand = 0, padx = 3, pady=3) gridPage = group.interior() - + self.xyzSnap = BooleanVar() self.xyzSnapButton = Checkbutton( gridPage, @@ -1056,7 +1056,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): value = SEditor.grid.getGridSpacing()) self.gridSpacing['command'] = SEditor.grid.setGridSpacing self.gridSpacing.pack(fill = X, expand = 0, pady=3) - + self.gridSize = Floater.Floater( gridPage, text = 'Grid Size', @@ -1072,7 +1072,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): value = SEditor.grid.getSnapAngle()) self.gridSnapAngle['command'] = SEditor.grid.setSnapAngle self.gridSnapAngle.pack(fill = X, expand = 0, pady=3) - + return def toggleXyzSnap(self): @@ -1108,14 +1108,14 @@ class propertyWindow(AppShell,Pmw.MegaWidget): tag_font=('MSSansSerif', 10)) self.createPosEntry(group.interior()) group.pack(side=TOP,fill = X, expand = 0, pady=3) - + group = Pmw.Group(contentFrame,tag_text='Orientation', tag_font=('MSSansSerif', 10)) self.createHprEntry(group.interior()) group.pack(side=TOP,fill = X, expand = 0, pady=3) self.createScaleEntry(contentFrame) - + collisionGroup = Pmw.Group(contentFrame,tag_text='Collision Object Properties', tag_font=('MSSansSerif', 10)) cObjFrame = collisionGroup.interior() @@ -1139,7 +1139,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): self.cPosX['commandData'] = ['sphere-o'] self.cPosX['command'] = self.setCollisionPosHprScale self.cPosX.pack(side=LEFT,expand=0,fill=X, padx=1) - + self.cPosY = self.createcomponent('originY', (), None, Floater.Floater, (posInterior,), text = 'Y', relief = FLAT, @@ -1149,7 +1149,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): self.cPosY['commandData'] = ['sphere-o'] self.cPosY['command'] = self.setCollisionPosHprScale self.cPosY.pack(side=LEFT, expand=0,fill=X, padx=1) - + self.cPosZ = self.createcomponent('originZ', (), None, Floater.Floater, (posInterior,), text = 'Z', relief = FLAT, @@ -1164,7 +1164,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): group.pack(side=TOP,fill = X, expand = 0, pady=3) scaleInterior = Frame(cObjFrame) - + self.scaleS = self.createcomponent('radius', (), None, Floater.Floater, (scaleInterior,), text = 'Radius', @@ -1178,7 +1178,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): scaleInterior.pack(side=TOP,expand=0,fill=X, padx=3, pady=3) pass - + elif cType == 'CollisionPolygon': frame = Frame(cObjFrame) label = Label(frame, text= "Sorry!",font=('MSSansSerif', 10), @@ -1199,9 +1199,9 @@ class propertyWindow(AppShell,Pmw.MegaWidget): label = Label(frame, text= "If you really need to change, recreate one...",font=('MSSansSerif', 10), borderwidth=5) label.pack(side=LEFT) - frame.pack(side=TOP, fill=X, expand=True) + frame.pack(side=TOP, fill=X, expand=True) pass - + elif cType == 'CollisionSegment': pointA = self.collisionObj.getPointA() pointB = self.collisionObj.getPointB() @@ -1217,7 +1217,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): self.cPosX['commandData'] = ['segment-A'] self.cPosX['command'] = self.setCollisionPosHprScale self.cPosX.pack(side=LEFT,expand=0,fill=X, padx=1) - + self.cPosY = self.createcomponent('pointA-Y', (), None, Floater.Floater, (posInterior,), text = 'Y', relief = FLAT, @@ -1227,7 +1227,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): self.cPosY['commandData'] = ['segment-A'] self.cPosY['command'] = self.setCollisionPosHprScale self.cPosY.pack(side=LEFT, expand=0,fill=X, padx=1) - + self.cPosZ = self.createcomponent('pointA-Z', (), None, Floater.Floater, (posInterior,), text = 'Z', relief = FLAT, @@ -1251,7 +1251,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): self.cPosXB['commandData'] = ['segment-B'] self.cPosXB['command'] = self.setCollisionPosHprScale self.cPosXB.pack(side=LEFT,expand=0,fill=X, padx=1) - + self.cPosYB = self.createcomponent('pointB-Y', (), None, Floater.Floater, (posInterior,), text = 'Y', relief = FLAT, @@ -1261,7 +1261,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): self.cPosYB['commandData'] = ['segment-B'] self.cPosYB['command'] = self.setCollisionPosHprScale self.cPosYB.pack(side=LEFT, expand=0,fill=X, padx=1) - + self.cPosZB = self.createcomponent('pointB-Z', (), None, Floater.Floater, (posInterior,), text = 'Z', relief = FLAT, @@ -1289,7 +1289,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): self.cPosX['commandData'] = ['ray-A'] self.cPosX['command'] = self.setCollisionPosHprScale self.cPosX.pack(side=LEFT,expand=0,fill=X, padx=1) - + self.cPosY = self.createcomponent('origin-Y', (), None, Floater.Floater, (posInterior,), text = 'Y', relief = FLAT, @@ -1299,7 +1299,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): self.cPosY['commandData'] = ['ray-A'] self.cPosY['command'] = self.setCollisionPosHprScale self.cPosY.pack(side=LEFT, expand=0,fill=X, padx=1) - + self.cPosZ = self.createcomponent('origin-Z', (), None, Floater.Floater, (posInterior,), text = 'Z', relief = FLAT, @@ -1323,7 +1323,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): self.cPosXB['commandData'] = ['ray-B'] self.cPosXB['command'] = self.setCollisionPosHprScale self.cPosXB.pack(side=LEFT,expand=0,fill=X, padx=1) - + self.cPosYB = self.createcomponent('direction-Y', (), None, Floater.Floater, (posInterior,), text = 'Y', relief = FLAT, @@ -1333,7 +1333,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): self.cPosYB['commandData'] = ['ray-B'] self.cPosYB['command'] = self.setCollisionPosHprScale self.cPosYB.pack(side=LEFT, expand=0,fill=X, padx=1) - + self.cPosZB = self.createcomponent('direction-Z', (), None, Floater.Floater, (posInterior,), text = 'Z', relief = FLAT, @@ -1346,7 +1346,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): posInterior.pack(side=TOP, expand=0,fill=X, padx=3, pady=3) group.pack(side=TOP,fill = X, expand = 0, pady=3) pass - + collisionGroup.pack(side=TOP,fill = X, expand = 0, pady=3) return @@ -1422,18 +1422,18 @@ class propertyWindow(AppShell,Pmw.MegaWidget): self.hprR.set(hpr.getZ()) self.scale.set(scale.getX()) return - + def trackDataFromSceneLight(self, pos=Point3(0,0,0), hpr=Vec3(0,0,0), scale=Point3(0,0,0)): if self.lightNode.type == 'directional': self.dPosition.set([pos.getX(),pos.getY(),pos.getZ()]) self.dOrientation.set([hpr.getX(),hpr.getY(),hpr.getZ()]) pass - + elif self.lightNode.type == 'point': self.pPosition.set([pos.getX(),pos.getY(),pos.getZ()]) - pass + pass return - + def trackDataFromSceneDummy(self, pos=Point3(0,0,0), hpr=Vec3(0,0,0), scale=Point3(0,0,0)): self.posX.set(pos.getX()) self.posY.set(pos.getY()) @@ -1443,7 +1443,7 @@ class propertyWindow(AppShell,Pmw.MegaWidget): self.hprR.set(hpr.getZ()) self.scale.set(scale.getX()) return - + def trackDataFromSceneCollision(self, pos=Point3(0,0,0), hpr=Vec3(0,0,0), scale=Point3(0,0,0)): self.posX.set(pos.getX()) self.posY.set(pos.getY()) @@ -1453,4 +1453,4 @@ class propertyWindow(AppShell,Pmw.MegaWidget): self.hprR.set(hpr.getZ()) self.scale.set(scale.getX()) return - + diff --git a/contrib/src/sceneeditor/quad.py b/contrib/src/sceneeditor/quad.py index 3b6948afce..47524739ae 100644 --- a/contrib/src/sceneeditor/quad.py +++ b/contrib/src/sceneeditor/quad.py @@ -12,15 +12,15 @@ from direct.showbase.DirectObject import DirectObject from pandac.PandaModules import * import math #Manakel 2/12/2005: replace from pandac import by from pandac.PandaModules import -from pandac.PandaModules import MouseWatcher +from pandac.PandaModules import MouseWatcher class ViewPort: ######################################################################################################################################### # The ViewPort class has the camera and associated display region set up for actually rendering the four sub-views # The constructor needs the bounds, window layer, camera, color, projection type, name and scene for the view -######################################################################################################################################### - +######################################################################################################################################### + def __init__(self,X1,X2,Y1,Y2,layer,cam,background=Vec4(0.3,0.3,0.3,1),projection="perspective",type="top",scene=render): self.VPType=type self.VP_X1=X1 @@ -29,14 +29,14 @@ class ViewPort: self.VP_Y2=Y2 self.VP_width=self.VP_X2 - self.VP_X1 self.VP_height=self.VP_Y2 - self.VP_Y1 - + self.the_viewport=layer.makeDisplayRegion(self.VP_X1, self.VP_X2,self.VP_Y1, self.VP_Y2) self.the_viewport.setCamera(cam) self.the_viewport.setClearDepthActive(1) self.the_viewport.setClearColorActive(1) self.the_viewport.setClearColor(background) - self.cam=cam - + self.cam=cam + # Set up the cameras to look in the right place. if(type=="top"): @@ -46,13 +46,13 @@ class ViewPort: self.cam.setH(-90) self.cam.setX(10) elif(type=="front"): - self.cam.setY(-10) + self.cam.setY(-10) elif(type=="perspective"): cam.setY(-100) #cam.setX(10) #cam.setZ(-10) #cam.setH(45) - #cam.setP(-45) + #cam.setP(-45) #print "aa" @@ -89,9 +89,9 @@ class ViewPort: y=1 self.lens.setAspectRatio(x/y) self.cam.node().setLens(self.lens) - + def resize(self,x,y): - + if(self.VPType=="left"): self.the_viewport.setDimensions(0,x,0,y) w=abs(x-self.VP_X1) @@ -127,7 +127,7 @@ class ViewPort: def setScene(self,scene): self.cam.node().setScene(scene) - + def setDR(self,mouseWatcher): #mouseWatcher.setDisplayRegion(self.the_viewport) pass @@ -141,7 +141,7 @@ class ViewPort: def getCam(self): return self.cam - + class QuadView(DirectObject): ######################################################################################################################################### @@ -157,7 +157,7 @@ class QuadView(DirectObject): self.AltPressed=0 self.PanConstantX=50 self.PanConstantY=50 - self.ZoomConstant=1 + self.ZoomConstant=1 self.FrontWidth=100 self.FrontHeight=100 self.TopWidth=100 @@ -186,9 +186,9 @@ class QuadView(DirectObject): self.PerspectiveWire=0 self.TopWire=0 - # Keep track of the currently selected window... values are 1-4 for four quadrants of a standard + # Keep track of the currently selected window... values are 1-4 for four quadrants of a standard # Cartesian coordinate system - + # These are the orthographic cameras # They will be restricted to panning and zooming i.e. no rotation # Top could be flipped to back, left to right and front to back @@ -198,7 +198,7 @@ class QuadView(DirectObject): # This camera will have a trackball control since its perspective self.perspectiveCam = render.attachNewNode(Camera('perspectiveCam')) - + #self.toplens=OrthographicLens() #self.leftLens=OrthographicLens() #self.frontLens=OrthographicLens() @@ -210,7 +210,7 @@ class QuadView(DirectObject): #self.leftCamLens= base.cam.node().getLens() #self.perspectiveCamLens= base.cam.node().getLens() - # Manipulate lenses here if need be + # Manipulate lenses here if need be #self.topCamLens.setFilmSize(250) # Set the Lenses @@ -239,17 +239,17 @@ class QuadView(DirectObject): #self.FrontScene=render.copyTo(self.SceneParent) #self.TopScene=render.copyTo(self.SceneParent) #self.LeftScene=render.copyTo(self.SceneParent) - + self.PerspectiveScene=render self.FrontScene=render self.TopScene=render self.LeftScene=render - + #self.PerspectiveScene.reparentTo(self.SceneParent) #self.FrontScene.reparentTo(self.SceneParent) #self.TopScene.reparentTo(self.SceneParent) #self.LeftScene.reparentTo(self.SceneParent) - + self.Perspective=ViewPort(0.5,1.0,0.0,0.5,self.newLayer,self.perspectiveCam,Vec4(0.75,0.75,0.75,1),"perspective","perspective",self.PerspectiveScene) self.Top=ViewPort(0.0,0.5,0.5,1.0,self.newLayer,self.topCam,Vec4(0.80,0.80,0.80,1),"ortho","top",self.TopScene) self.Left=ViewPort(0.0,0.5,0.0,0.5,self.newLayer,self.leftCam,Vec4(0.85,0.85,0.85,1),"ortho","left",self.LeftScene) @@ -263,7 +263,7 @@ class QuadView(DirectObject): #self.lastPickPoint = None #base.useTrackball() - + #self.dataRoot = NodePath('dataRoot') # Cache the node so we do not ask for it every frame #self.dataRootNode = self.dataRoot.node() @@ -272,7 +272,7 @@ class QuadView(DirectObject): #self.mak = self.dataRoot.attachNewNode(MouseAndKeyboard(base.win, 0, 'mak')) #self.mak.node().setSource(base.win, 0) self.mouseWatcherNode = MouseWatcher('mouseWatcher') - + self.mouseWatcher = base.mak.attachNewNode(self.mouseWatcherNode) #self.Perspective.setDR(self.mouseWatcherNode) @@ -282,7 +282,7 @@ class QuadView(DirectObject): #ddr=DisplayRegionContext(self.Perspective.getCam()) #base.setMouseOnNode(self.smiley.node()) # Let Mouse Control Perspective View for now #base.enableSoftwareMousePointer() - + # Message Handlers self.accept("a",self.setLeft) self.accept("q",self.setTop) @@ -302,7 +302,7 @@ class QuadView(DirectObject): self.accept("alt-mouse1-up",self.AltUp) self.accept("control-mouse1",self.CtlDown) self.accept("control-mouse1-up",self.CtlUp) - + # Methods #def setLastPickPoint( self ): @@ -407,7 +407,7 @@ class QuadView(DirectObject): self.PerspectiveScene.clearTexture() self.PerspectiveTexture=1 - + def reparenter(self): #self.FrontScene.reparentTo(render) @@ -437,10 +437,10 @@ class QuadView(DirectObject): if(self.oldY<-1 or self.oldY>1): return taskMgr.add(self.DragAction,'DragAction') - + def AltUpHandler(self): - taskMgr.remove('DragAction') - + taskMgr.remove('DragAction') + def gridtoggle(self): #grid=DirectGrid() #grid.enable() @@ -467,11 +467,11 @@ class QuadView(DirectObject): self.setPerspective() else: self.setFront() - + def MouseTell(self,buttonCode): self.MouseButton=buttonCode self.setAppropriateViewPort(self.mouseWatcherNode.getMouseX(),self.mouseWatcherNode.getMouseY()) - + x=base.mouseWatcherNode.getMouseX() y=base.mouseWatcherNode.getMouseY() @@ -509,12 +509,12 @@ class QuadView(DirectObject): print "Sent X:%f Sent Y:%f"%(ansX,ansY) #SEditor.iRay.pick(render,self.xy) SEditor.manipulationControl.manipulationStop(self.xy) - #print "MouseX " + str(base.mouseWatcherNode.getMouseX()) + "MouseY " + str(base.mouseWatcherNode.getMouseY()) + "\n" - #print "MouseX " + str(self.mouseWatcherNode.getMouseX()) + "MouseY " + str(self.mouseWatcherNode.getMouseY()) + "\n" - + #print "MouseX " + str(base.mouseWatcherNode.getMouseX()) + "MouseY " + str(base.mouseWatcherNode.getMouseY()) + "\n" + #print "MouseX " + str(self.mouseWatcherNode.getMouseX()) + "MouseY " + str(self.mouseWatcherNode.getMouseY()) + "\n" + base.mouseWatcherNode=self.mouseWatcherNode - + self.oldX=self.mouseWatcherNode.getMouseX() if(self.oldX<-1 or self.oldX>1): return @@ -533,11 +533,11 @@ class QuadView(DirectObject): taskMgr.remove('DragAction') self.Mouse_Draggin=0 #print "Mouse Up" - + def Max_Style_Mouse_View(self,buttoncode): pass - + def ChangeBaseDR(self): dr=base.win.getDisplayRegion(0) if(self.CurrentQuad==1): #Front @@ -569,7 +569,7 @@ class QuadView(DirectObject): self.ChangeBaseDR() self.Perspective.setCam() #self.Perspective.setDR(self.mouseWatcherNode) - + def setFront(self): print "FRONT" self.CurrentQuad=1 @@ -577,7 +577,7 @@ class QuadView(DirectObject): self.Front.setCam() #self.Front.setDR(self.mouseWatcherNode) - + def DragAction(self,task): #if(self.MouseDragging==1): self.currX= self.mouseWatcherNode.getMouseX() @@ -598,7 +598,7 @@ class QuadView(DirectObject): if(self.HorizontalAxis<-1 or self.HorizontalAxis>1 or self.VerticalAxis<-1 or self.VerticalAxis>1): return self.resizedr(self.VerticalAxis,self.HorizontalAxis) - + #if(self.AltPressed): # View Camera Transforms -> Maya style elif(1): #print "ALTPRESSED" @@ -618,7 +618,7 @@ class QuadView(DirectObject): self.MoveCamera(0,self.diffX*self.PanConstantX,-self.diffY*self.PanConstantY,self.CurrentQuad) elif(self.CurrentQuad==4): pass - elif(self.MouseButton==3): # Do Zoom + elif(self.MouseButton==3): # Do Zoom if(self.CurrentQuad==1): # Y and Z values change meanings for different cameras #lens = OrthographicLens() #lens.setFilmSize(l,self.VP_height*200) @@ -634,26 +634,26 @@ class QuadView(DirectObject): if(self.FrontHeight<=0): FrontHeight=1 self.frontCam.node().getLens().setFilmSize(self.FrontWidth,self.FrontHeight) - self.resizedr(self.VerticalAxis,self.HorizontalAxis) + self.resizedr(self.VerticalAxis,self.HorizontalAxis) elif(self.CurrentQuad==2): self.TopWidth= self.TopWidth + self.diffX self.TopHeight= self.TopHeight + self.diffX self.TopWidth= self.TopWidth + self.diffY self.TopHeight= self.TopHeight + self.diffY self.topCam.node().getLens().setFilmSize(self.TopWidth,self.TopHeight) - self.resizedr(self.VerticalAxis,self.HorizontalAxis) + self.resizedr(self.VerticalAxis,self.HorizontalAxis) elif(self.CurrentQuad==3): self.LeftWidth= self.LeftWidth + self.diffX self.LeftHeight= self.LeftHeight + self.diffX self.LeftWidth= self.LeftWidth + self.diffY self.LeftHeight= self.LeftHeight + self.diffY self.leftCam.node().getLens().setFilmSize(self.LeftWidth,self.LeftHeight) - self.resizedr(self.VerticalAxis,self.HorizontalAxis) + self.resizedr(self.VerticalAxis,self.HorizontalAxis) elif(self.CurrentQuad==4): pass else: pass - + self.oldX=self.currX self.oldY=self.currY return Task.cont @@ -669,8 +669,8 @@ class QuadView(DirectObject): self.leftCam.setPos(self.leftCam.getX()+X_amt,self.leftCam.getY()+Y_amt,self.leftCam.getZ()+Z_amt) elif(quad==4): self.perspectiveCam.setPos(self.perspectiveCam.getX()+X_amt,self.perspectiveCam.getY()+Y_amt,self.perspectiveCam.getZ()+Z_amt) - - + + #View=QuadView() #run() diff --git a/contrib/src/sceneeditor/sceneEditor.py b/contrib/src/sceneeditor/sceneEditor.py index e47df9ddcb..ca35baa92b 100644 --- a/contrib/src/sceneeditor/sceneEditor.py +++ b/contrib/src/sceneeditor/sceneEditor.py @@ -87,7 +87,7 @@ class myLevelEditor(AppShell): controlType = 'Keyboard' keyboardMapDict = {} keyboardSpeedDict = {} - + Scene=None isSelect = False nodeSelected = None @@ -99,9 +99,9 @@ class myLevelEditor(AppShell): CurrentFileName=None #Holds the current scene file name CurrentDirName=None # Holds the current file name without extension which is the path where file's data gets saved Dirty=0 # Keeps track of whether there are any modifications that should be saved - - - + + + def __init__(self, parent = None, **kw): base.setBackgroundColor(0,0,0) @@ -149,12 +149,12 @@ class myLevelEditor(AppShell): text_scale = 0.05, text_align = TextNode.ALeft ) - + self.initialiseoptions(myLevelEditor) self.parent.resizable(False,False) ## Disable the ability to resize for this Window. - + ######### Set the event handler ########## self.dataFlowEvents = [ ## Event from Side Window @@ -213,7 +213,7 @@ class myLevelEditor(AppShell): ['f11',self.loadFromBam], ['f12',self.saveAsBam], ] - + ################################# ### Collision detection @@ -223,7 +223,7 @@ class myLevelEditor(AppShell): for event in self.dataFlowEvents: self.accept(event[0], event[1], extraArgs = event[2:]) - + self.actionEvents = [ # Scene graph explorer functions ['SGE_changeName', self.changeName], @@ -247,7 +247,7 @@ class myLevelEditor(AppShell): ['se_deselectedAll',self.deselectFromScene], ] ''' All messages starting with "SGE_" are generated in seSceneGraphExplorer''' - + for event in self.actionEvents: self.accept(event[0], event[1], extraArgs = event[2:]) @@ -260,7 +260,7 @@ class myLevelEditor(AppShell): # Initialize the application. # This function will be called when you call AppShell's constructor ################################################################# - + ### Create SceneEditor Ver. DirectSession self.seSession = SeSession() self.seSession.enable() @@ -270,7 +270,7 @@ class myLevelEditor(AppShell): self.MopathPanel = None self.alignPanelDict = {} #self.quadview=QuadView() - + self.lightingPanel = None self.controllerPanel = None @@ -291,9 +291,9 @@ class myLevelEditor(AppShell): self.sideWindowCount = 1 self.sideWindow.selectPage() messenger.send('SGE_Update Explorer',[render]) ## Update the Scene Graph - + pass - + def getPhotoImage(self,name): modpath = ConfigVariableSearchPath("model-path") path = modpath.findFile(Filename(name)) @@ -338,11 +338,11 @@ class myLevelEditor(AppShell): i += 1 button = Button(buttonFrame, image = element, command=lambda n=i : self.buttonPushed(n)) button.pack(fill=X, side = LEFT) - + buttonFrame.pack(fill=X, side=LEFT,expand=True) - - + + def buttonPushed(self, buttonIndex): ################################################################# # buttonPushed(self, buttonNum) @@ -379,7 +379,7 @@ class myLevelEditor(AppShell): elif buttonIndex==9: # Open Particle Panel self.openParticlePanel() return - elif buttonIndex==10: + elif buttonIndex==10: self.openInputPanel() return elif buttonIndex==11: # Help @@ -412,14 +412,14 @@ class myLevelEditor(AppShell): elif buttonIndex==20: print "You haven't defined the function for this Button, Number %d."%buttonIndex return - + return def createMenuBar(self): # Creates default menus. Can be overridden or simply augmented # Using button Add below self.menuBar.addmenuitem('Help', 'command', - 'Get information on application', + 'Get information on application', label='About...', command=self.showAbout) ## Creat stuff inside the "File" self.menuBar.addmenuitem('File', 'command', 'Creat New Scene', @@ -447,7 +447,7 @@ class myLevelEditor(AppShell): self.menuBar.addmenuitem('File', 'command', 'Load Actor', label='Load Actor', command=self.loadActor) - + self.menuBar.addmenuitem('File', 'separator') self.menuBar.addmenuitem('File', 'command', 'Import a Scene', @@ -455,7 +455,7 @@ class myLevelEditor(AppShell): command=self.importScene) self.menuBar.addmenuitem('File', 'separator') - + self.menuBar.addmenuitem('File', 'command', 'Quit this application', label='Exit', command=self.quit) @@ -535,7 +535,7 @@ class myLevelEditor(AppShell): self.menuPanel.entryconfig('Animation Panel', state=DISABLED) self.menuPanel.entryconfig('Side Window', state=DISABLED) - + def onDestroy(self, event): ################################################################# # If you have open any thing, please rewrite here! @@ -599,7 +599,7 @@ class myLevelEditor(AppShell): if self.lightingPanel != None: self.lightingPanel.updateList(list) return - + def lightRename(self,oName, nName): ################################################################# # lightRename(self,oName, nName) @@ -613,7 +613,7 @@ class myLevelEditor(AppShell): if self.lightingPanel != None: self.lightingPanel.updateList(list,lightNode) return - + def lightSelect(self,lightName): ################################################################# # lightSelect(self,lightName) @@ -627,7 +627,7 @@ class myLevelEditor(AppShell): if self.lightingPanel != None: self.lightingPanel.updateDisplay(lightNode) return - + def addLight(self, type): ################################################################# # addLight(self, type) @@ -643,7 +643,7 @@ class myLevelEditor(AppShell): self.lightingPanel.updateList(list,lightNode) self.makeDirty() return - + def lightingPanelClose(self): ################################################################# # lightingPanelClose(self) @@ -654,7 +654,7 @@ class myLevelEditor(AppShell): self.menuPanel.entryconfig('Lighting Panel', state=NORMAL) self.lightingPanel = None return - + def openPropertyPanel(self, nodePath = None): ################################################################# # openPropertyPanel(self, nodePath = None) @@ -714,7 +714,7 @@ class myLevelEditor(AppShell): ################################################################# # addDummyNode(self, nodepath = None) # This function will be called when user try to create a dummy node into scene - # + # # Here we will call dataHolder to create a dummy node # and reparent it to the nodePath that user has assigned. # @@ -727,7 +727,7 @@ class myLevelEditor(AppShell): ################################################################# # addCollisionObj(self, nodepath = None) # This function will be called when user try to create a collision object into the scene - # + # # Here we will call collisionWindow to ask user what kind of collision objects they want to have. # Then, send the information and generated collision object to dataHolder to finish the whole process # and reparent it to the nodePath that user has assigned. @@ -757,7 +757,7 @@ class myLevelEditor(AppShell): ################################################################# SEditor.reparent(nodepath, fWrt = 1) return - + def openPlacerPanel(self, nodePath = None): ################################################################# # openPlacerPanel(self, nodePath = None) @@ -766,7 +766,7 @@ class myLevelEditor(AppShell): ################################################################# if(self.placer==None): self.placer = Placer() - self.menuPanel.entryconfig('Placer Panel', state=DISABLED) + self.menuPanel.entryconfig('Placer Panel', state=DISABLED) return def closePlacerPanel(self): @@ -779,7 +779,7 @@ class myLevelEditor(AppShell): self.placer = None self.menuPanel.entryconfig('Placer Panel', state=NORMAL) return - + def openAnimPanel(self, nodePath = None): ################################################################# # openAnimPanel(self, nodePath = None) @@ -819,7 +819,7 @@ class myLevelEditor(AppShell): ################################################################# oName = nodePath.getName() # I need this line in order to check the obj name in the control panel. AllScene.rename(nodePath,nName) - + # reset the list in the controller panel if it has been opened. if (self.controllerPanel) != None: list = AllScene.getAllObjNameAsList() @@ -841,7 +841,7 @@ class myLevelEditor(AppShell): currentModName=currentF.getBasenameWoExtension() # Let us actually remove the scene from sys modules... this is done because every scene is loaded as a module # And if we reload a scene python wont reload since its already in sys.modules... and hence we delete it - # If there is ever a garbage colleciton bug..this might be a point to look at + # If there is ever a garbage colleciton bug..this might be a point to look at if sys.modules.has_key(currentModName): del sys.modules[currentModName] print sys.getrefcount(AllScene.theScene) @@ -856,14 +856,14 @@ class myLevelEditor(AppShell): # openScene(self) ################################################################# # In the future try and provide merging of two scenes - + if(self.CurrentFileName or self.Dirty): saveScene = tkMessageBox._show("Load scene","Save the current scene?",icon = tkMessageBox.QUESTION,type = tkMessageBox.YESNOCANCEL) if (saveScene == "yes"): self.saveScene() elif (saveScene == "cancel"): return - + self.closeAllSubWindows() ## Close all sub window if(self.CurrentFileName): currentF=Filename(self.CurrentFileName) @@ -871,7 +871,7 @@ class myLevelEditor(AppShell): currentModName=currentF.getBasenameWoExtension() # Let us actually remove the scene from sys modules... this is done because every scene is loaded as a module # And if we reload a scene python wont reload since its already in sys.modules... and hence we delete it - # If there is ever a garbage colleciton bug..this might be a point to look at + # If there is ever a garbage colleciton bug..this might be a point to look at if sys.modules.has_key(currentModName): del sys.modules[currentModName] print sys.getrefcount(AllScene.theScene) @@ -880,7 +880,7 @@ class myLevelEditor(AppShell): AllScene.resetAll() self.CurrentFileName = AllScene.loadScene() - + if(self.CurrentFileName==None): return @@ -894,7 +894,7 @@ class myLevelEditor(AppShell): lightList=AllScene.getList() self.lightingPanel.updateList(lightList) messenger.send('SGE_Update Explorer',[render]) - + # Close the side window in order to reset all world settings to fit the scene we have loaded. self.sideWindow.quit() @@ -920,7 +920,7 @@ class myLevelEditor(AppShell): ################################################################# if(self.CurrentFileName): - f=FileSaver() + f=FileSaver() f.SaveFile(AllScene,self.CurrentFileName,self.CurrentDirName,1) self.Dirty=0 else: @@ -1012,7 +1012,7 @@ class myLevelEditor(AppShell): title = 'Load New Actor', parent = self.parent) - + if ActorFilename: self.makeDirty() if not AllScene.loadActor(ActorFilename, Filename.fromOsSpecific(ActorFilename)): @@ -1028,7 +1028,7 @@ class myLevelEditor(AppShell): ## Take care those things under Edit nemu def unDo(self): pass - + def reDo(self): pass @@ -1064,7 +1064,7 @@ class myLevelEditor(AppShell): # This function will do nothing but call other function # to add a dummy into the scene. # - # Ok... this is really redundancy... + # Ok... this is really redundancy... # ################################################################# self.addDummyNode(self.nodeSelected) @@ -1076,7 +1076,7 @@ class myLevelEditor(AppShell): # This function will do nothing but call other function # to open the duplication window. # - # Ok... this is really redundancy... + # Ok... this is really redundancy... # ################################################################# if self.nodeSelected!=None: @@ -1089,7 +1089,7 @@ class myLevelEditor(AppShell): # This function will do nothing but call other function # to remove the current selected node.. # - # Ok... this is really redundancy... + # Ok... this is really redundancy... # ################################################################ self.remove(self.nodeSelected) @@ -1101,11 +1101,11 @@ class myLevelEditor(AppShell): # This function will do nothing but call other function # to open the property window of current selected node.. # - # Ok... this is really redundancy... + # Ok... this is really redundancy... # ################################################################ self.openPropertyPanel(self.nodeSelected) - pass + pass def showCameraSetting(self): ################################################################ @@ -1113,7 +1113,7 @@ class myLevelEditor(AppShell): # This function will do nothing but call other function # to open the property window of camera.. # - # Ok... this is really redundancy... + # Ok... this is really redundancy... # ################################################################ self.openPropertyPanel(camera) @@ -1145,20 +1145,20 @@ class myLevelEditor(AppShell): self.sideWindowCount = 1 self.menuPanel.entryconfig('Side Window', state=DISABLED) return - + def openAnimationPanel(self): ################################################################ # openAnimationPanel(self) # This function will do nothing but call other function # to open the animation window for selected node(if it is an Actor).. # - # Ok... this is really redundancy... + # Ok... this is really redundancy... # ################################################################ if AllScene.isActor(self.nodeSelected): self.openAnimPanel(self.nodeSelected) pass - + def openMopathPanel(self): ################################################################ # openMopathPanel(self) @@ -1178,7 +1178,7 @@ class myLevelEditor(AppShell): self.ParticleEnable = visable AllScene.toggleParticleVisable(visable) return - + def openLightingPanel(self): ################################################################ # openLightingPanel(self) @@ -1189,7 +1189,7 @@ class myLevelEditor(AppShell): self.lightingPanel = lightingPanel(AllScene.getLightList()) self.menuPanel.entryconfig('Lighting Panel', state=DISABLED) return - + def addParticleEffect(self,effect_name,effect,node): AllScene.particleDict[effect_name]=effect AllScene.particleNodes[effect_name]=node @@ -1215,7 +1215,7 @@ class myLevelEditor(AppShell): def closeParticlePanel(self): self.particlePanel = None return - + def openInputPanel(self): if self.controllerPanel==None: list = AllScene.getAllObjNameAsList() @@ -1237,10 +1237,10 @@ class myLevelEditor(AppShell): # set it back into controller panel ################################################################ node = AllScene.getObjFromSceneByName(name) - + if (self.controllerPanel) != None and (node!=None): self.controllerPanel.setNodePathIn(node) - + return def setControlSet(self, controlType, dataList): @@ -1260,7 +1260,7 @@ class myLevelEditor(AppShell): # Also this will make sure we won't catch wrong keyboard message self.stopControl(controlType) self.enableControl = True - + self.setControlSet(controlType, dataList) self.lastContorlTimer = globalClock.getFrameTime() if controlType == 'Keyboard': @@ -1327,7 +1327,7 @@ class myLevelEditor(AppShell): self.controlTarget.setScale(newScale.getX(),newScale.getY(),newScale.getZ()) self.transNodeKeyboard.setPosHpr(0,0,0,0,0,0) return Task.cont - + ## Misc ##### This one get the event from SGE (Scene Graph Explorer) and Picking def selectNode(self, nodePath=None, callBack = True): @@ -1428,7 +1428,7 @@ class myLevelEditor(AppShell): # This function will do nothing but call other function # to delete selected node... # - # Ok... this is really redundancy... + # Ok... this is really redundancy... # ################################################################ self.deSelectNode(self.nodeSelected) @@ -1444,7 +1444,7 @@ class myLevelEditor(AppShell): self.makeDirty() AllScene.toggleLight() return - + def sideWindowClose(self,worldColor,lightEnable,ParticleEnable, basedriveEnable,collision, backface, texture, wireframe, grid, widgetVis, enableAutoCamera): ################################################################ @@ -1478,7 +1478,7 @@ class myLevelEditor(AppShell): # This function will do nothing but call other function # to duplicate selected node... # - # Ok... this is really redundancy... + # Ok... this is really redundancy... # ################################################################ AllScene.duplicateObj(nodePath, pos, hpr, scale, num) @@ -1685,11 +1685,11 @@ class myLevelEditor(AppShell): t.doneColor = doneColor # This really does all the work t.uponDeath = self.flashDone - + def flashDummy(self, state): # Real work is done in upon death function return Task.done - + def flashDone(self,state): # Return node Path to original state if state.nodePath.isEmpty(): @@ -1701,7 +1701,7 @@ class myLevelEditor(AppShell): state.nodePath.clearColor() - + editor = myLevelEditor(parent = base.tkRoot) diff --git a/contrib/src/sceneeditor/seAnimPanel.py b/contrib/src/sceneeditor/seAnimPanel.py index 95833bc51d..86c245a3ef 100644 --- a/contrib/src/sceneeditor/seAnimPanel.py +++ b/contrib/src/sceneeditor/seAnimPanel.py @@ -31,7 +31,7 @@ class AnimPanel(AppShell): dragMode = False rateList= ['1/24.0', '0.1', '0.5', '1.0', '2.0', '5.0' , '10.0'] - + def __init__(self, aNode = None, parent = None, **kw): INITOPT = Pmw.INITOPT self.id = 'AnimPanel '+ aNode.getName() @@ -63,7 +63,7 @@ class AnimPanel(AppShell): menuBar = self.menuBar menuBar.addmenu('Anim', 'Anim Panel Operations') - + # Reset all actor controls menuBar.addmenuitem('File', 'command', 'Load Animation', @@ -102,7 +102,7 @@ class AnimPanel(AppShell): scrolledlist_items = self['animList']) self.AnimEntry.place(x=240,y=10,anchor=NW) - + self.playRateEntry = self.createcomponent( 'playRateMenu', (), None, Pmw.ComboBox, (actorFrame,), @@ -133,7 +133,7 @@ class AnimPanel(AppShell): command = self.updateDisplay, variable = self.unitsVar) self.displayButton.place(x=120,y=77,anchor=NW) - + ## scale control frameFrame = Frame(actorFrame, relief = SUNKEN, bd = 1) self.minLabel = self.createcomponent( @@ -158,7 +158,7 @@ class AnimPanel(AppShell): text = 24) self.maxLabel.pack(side = LEFT) frameFrame.pack(side = LEFT, expand = 1, fill = X) - + ## button contorl ButtomFrame = Frame(actorFrame, relief = SUNKEN, bd = 1,borderwidth=5) self.toStartButton = self.createcomponent( @@ -168,7 +168,7 @@ class AnimPanel(AppShell): width = 8, command = self.resetAllToZero) self.toStartButton.pack(side = LEFT, expand = 1, fill = X) - + self.playButton = self.createcomponent( 'playButton', (), None, Button, (ButtomFrame,), @@ -214,14 +214,14 @@ class AnimPanel(AppShell): ################################################################# # updateList(self) # This function will update the list of animations that the Actor - # currently has into the combo box widget. + # currently has into the combo box widget. ################################################################# self.ignore('DataH_loadFinish'+self.nodeName) del self.loaderWindow self['animList'] = self['actor'].getAnimNames() animL = self['actor'].getAnimNames() self.AnimEntry.setlist(animL) - + def removeAnim(self): ################################################################# @@ -308,7 +308,7 @@ class AnimPanel(AppShell): self.stopButton.config(state=DISABLED) return Task.done else: - self.gotoT(self.currTime) + self.gotoT(self.currTime) return Task.cont def stop(self): @@ -329,7 +329,7 @@ class AnimPanel(AppShell): # the current animation. Most important thing this function do is # to recalculate all variables to fit the selected animation ################################################################# - self.animName = self.AnimEntry.get() + self.animName = self.AnimEntry.get() playRate = '%0.1f' % self['actor'].getPlayRate(self.animName) if playRate not in self.rateList: def strCmp(a, b): @@ -376,7 +376,7 @@ class AnimPanel(AppShell): else: self.minLabel['text'] = '0.0' self.maxLabel['text'] = "%.2f" % self.duration - self.frameControl.configure(from_ = 0.0, + self.frameControl.configure(from_ = 0.0, to = self.duration, resolution = 0.01) @@ -429,7 +429,7 @@ class AnimPanel(AppShell): ################################################################# self.dragMode = True return - + def resetAllToZero(self): ################################################################# # resetAllToZero(self) @@ -536,8 +536,8 @@ class LoadAnimPanel(AppShell): mainFrame.pack(expand = 1, fill = BOTH) - - + + def onDestroy(self, event): messenger.send('AWL_close',[self.nodeName]) ''' diff --git a/contrib/src/sceneeditor/seBlendAnimPanel.py b/contrib/src/sceneeditor/seBlendAnimPanel.py index 035bd9451a..6895b81417 100644 --- a/contrib/src/sceneeditor/seBlendAnimPanel.py +++ b/contrib/src/sceneeditor/seBlendAnimPanel.py @@ -36,7 +36,7 @@ class BlendAnimPanel(AppShell): enableBlend = False currentBlendName = None - + def __init__(self, aNode = None, blendDict={}, parent = None, **kw): INITOPT = Pmw.INITOPT self.id = 'BlendAnimPanel '+ aNode.getName() @@ -95,7 +95,7 @@ class BlendAnimPanel(AppShell): self.blendAnimEntry.pack(side=LEFT) Label(actorFrame, text= " ", font=('MSSansSerif', 10)).pack(side=LEFT) - + button = Button(actorFrame, text="Save", font=('MSSansSerif', 10),width = 12, command = self.saveButtonPushed).pack(side=LEFT) button = Button(actorFrame, text="Remove", font=('MSSansSerif', 10),width = 12, @@ -130,7 +130,7 @@ class BlendAnimPanel(AppShell): scrolledlist_items = self['animList']) self.AnimEntryB.pack(side=LEFT) actorFrame.pack(side = TOP, expand = False, fill = X) - + ### Blend Enable checkbox actorFrame = Frame(interior, relief = SUNKEN, bd = 1) Label(actorFrame, text= "Enable Blending:", font=('MSSansSerif', 10)).pack(side=LEFT,) @@ -182,7 +182,7 @@ class BlendAnimPanel(AppShell): self.playRateEntry.pack(side=LEFT) self.playRateEntry.selectitem('1.0') - ### Loop checkbox + ### Loop checkbox Label(actorFrame, text= " ", font=('MSSansSerif', 10)).pack(side=LEFT,) Label(actorFrame, text= "Loop:", font=('MSSansSerif', 10)).pack(side=LEFT,) @@ -193,14 +193,14 @@ class BlendAnimPanel(AppShell): Checkbutton, (actorFrame,), variable = self.loopVar) self.loopButton.pack(side=LEFT) - + actorFrame.pack(side = TOP, expand = True, fill = X) - - + + ### Display Frames/Seconds actorFrame = Frame(interior) - + Label(actorFrame, text= "Frame/Second:", font=('MSSansSerif', 10)).pack(side=LEFT) self.unitsVar = IntVar() @@ -213,7 +213,7 @@ class BlendAnimPanel(AppShell): self.displayButton.pack(side=LEFT) actorFrame.pack(side = TOP, expand = True, fill = X) - + ## scale control actorFrame = Frame(interior) frameFrame = Frame(actorFrame, relief = SUNKEN, bd = 1) @@ -240,7 +240,7 @@ class BlendAnimPanel(AppShell): self.maxLabel.pack(side = LEFT) frameFrame.pack(side = LEFT, expand = 1, fill = X) actorFrame.pack(side = TOP, expand = True, fill = X) - + ## button contorl actorFrame = Frame(interior) ButtomFrame = Frame(actorFrame, relief = SUNKEN, bd = 1,borderwidth=5) @@ -251,7 +251,7 @@ class BlendAnimPanel(AppShell): width = 8, command = self.resetAllToZero) self.toStartButton.pack(side = LEFT, expand = 1, fill = X) - + self.playButton = self.createcomponent( 'playButton', (), None, Button, (ButtomFrame,), @@ -287,7 +287,7 @@ class BlendAnimPanel(AppShell): animL = self['actor'].getAnimNames() self.AnimEntryA.setlist(animL) self.AnimEntryB.setlist(animL) - + def play(self): ################################################################# # play(self) @@ -330,7 +330,7 @@ class BlendAnimPanel(AppShell): self.stopButton.config(state=DISABLED) return Task.done else: - self.gotoT(self.currTime) + self.gotoT(self.currTime) return Task.cont def stop(self): @@ -405,7 +405,7 @@ class BlendAnimPanel(AppShell): else: self.minLabel['text'] = '0.0' self.maxLabel['text'] = "%.2f" % self.duration - self.frameControl.configure(from_ = 0.0, + self.frameControl.configure(from_ = 0.0, to = self.duration, resolution = 0.01) @@ -454,7 +454,7 @@ class BlendAnimPanel(AppShell): ################################################################# self.dragMode = True return - + def resetAllToZero(self): ################################################################# # resetAllToZero(self) @@ -559,7 +559,7 @@ class BlendAnimPanel(AppShell): self.blendAnimEntry.clear() self.currentBlendName = None return - + def saveButtonPushed(self): ################################################################# # saveButtonPushed(self) diff --git a/contrib/src/sceneeditor/seCameraControl.py b/contrib/src/sceneeditor/seCameraControl.py index 1842837c6f..31ab30ee9f 100644 --- a/contrib/src/sceneeditor/seCameraControl.py +++ b/contrib/src/sceneeditor/seCameraControl.py @@ -290,7 +290,7 @@ class DirectCameraControl(DirectObject): def lockCOA(self): self.fLockCOA = 1 SEditor.message('COA Lock On') - + def unlockCOA(self): self.fLockCOA = 0 SEditor.message('COA Lock Off') @@ -456,7 +456,7 @@ class DirectCameraControl(DirectObject): def centerCam(self): self.centerCamIn(1.0) - + def centerCamNow(self): self.centerCamIn(0.) @@ -493,7 +493,7 @@ class DirectCameraControl(DirectObject): blendType = 'easeInOut', task = 'manipulateCamera') t.uponDeath = self.updateCoaMarkerSizeOnDeath - + def spawnMoveToView(self, view): # Kill any existing tasks taskMgr.remove('manipulateCamera') @@ -527,7 +527,7 @@ class DirectCameraControl(DirectObject): self.camManipRef.setPosHpr(self.coaMarker, ZERO_VEC, hprOffset) # Scale center vec by current distance to target - offsetDistance = Vec3(SEditor.camera.getPos(self.camManipRef) - + offsetDistance = Vec3(SEditor.camera.getPos(self.camManipRef) - ZERO_POINT).length() scaledCenterVec = Y_AXIS * (-1.0 * offsetDistance) # Now put the camManipRef at that point @@ -543,15 +543,15 @@ class DirectCameraControl(DirectObject): blendType = 'easeInOut', task = 'manipulateCamera') t.uponDeath = self.updateCoaMarkerSizeOnDeath - - + + def swingCamAboutWidget(self, degrees, t): # Remove existing camera manipulation task taskMgr.remove('manipulateCamera') # Record undo point SEditor.pushUndo([SEditor.camera]) - + # Coincident with widget self.camManipRef.setPos(self.coaMarker, ZERO_POINT) # But aligned with render space @@ -584,16 +584,16 @@ class DirectCameraControl(DirectObject): # At what distance does the object fill 30% of the screen? # Assuming radius of 1 on widget camY = SEditor.dr.near * (2.0 * maxScale)/(0.3 * maxDim) - + # What is the vector through the center of the screen? centerVec = Y_AXIS * camY - + # Where is the node relative to the viewpoint vWidget2Camera = SEditor.widget.getPos(SEditor.camera) - + # How far do you move the camera to be this distance from the node? deltaMove = vWidget2Camera - centerVec - + # Move a target there self.camManipRef.setPos(SEditor.camera, deltaMove) @@ -605,7 +605,7 @@ class DirectCameraControl(DirectObject): task = 'manipulateCamera') # Upon death, reparent Cam to parent fitTask.parent = parent - fitTask.uponDeath = self.reparentCam + fitTask.uponDeath = self.reparentCam def moveToFit(self): # How bit is the active widget? @@ -629,7 +629,7 @@ class DirectCameraControl(DirectObject): # Spawn a task to move the widget t = SEditor.widget.lerpPos(Point3(centerVec), CAM_MOVE_DURATION, - other = SEditor.camera, + other = SEditor.camera, blendType = 'easeInOut', task = 'moveToFitTask') t.uponDeath = lambda state: taskMgr.remove('stickToWidget') diff --git a/contrib/src/sceneeditor/seFileSaver.py b/contrib/src/sceneeditor/seFileSaver.py index 2c817a46d4..73c71f5901 100644 --- a/contrib/src/sceneeditor/seFileSaver.py +++ b/contrib/src/sceneeditor/seFileSaver.py @@ -1,7 +1,7 @@ -#################################################################################################################################################### -# File Saving +#################################################################################################################################################### +# File Saving # This code saves the scene out as python code... the scene is stored in the various dictionaries in "dataHolder.py" ...the class "AllScene" -# +# #################################################################################################################################################### from pandac.PandaModules import * @@ -21,12 +21,12 @@ import seForceGroup class FileSaver: - #################################################################################################################################################### + #################################################################################################################################################### # This class saves out the scene built with the scene editor as python code # There are dictionaries saved out to save the state of the scene for reloading it with the editor # Currently saving is supported for Models, Animations, Lights, Dummy Nodes # Attributes like parenting are also saved out - # This class is actually instantiated in sceneEditor.py in the saveScene() method + # This class is actually instantiated in sceneEditor.py in the saveScene() method #################################################################################################################################################### def __init(self): @@ -34,11 +34,11 @@ class FileSaver: def SaveFile(self,AllScene,filename,dirname,reSaveFlag=0): - ################################################################################################################################################ + ################################################################################################################################################ # This function takes the "dataHolder" instance "AllScene" which has dictionaries containing scene information # The filename is where the scene will be written to ################################################################################################################################################ - + i1=" " # indentation i2=i1+i1 # double indentation out_file = open(filename,"w") @@ -57,7 +57,7 @@ class FileSaver: out_file.write("# theScene=SavedScene() #instantiate the class\n") out_file.write("# IMPORTANT: All the documentation below refers to \"theScene\" as the instance of SavedScene()\n") out_file.write("##########################################################################################################\n\n") - + out_file.write("##########################################################################################################\n") out_file.write("# Import Panda Modules\n") out_file.write("##########################################################################################################\n") @@ -146,7 +146,7 @@ class FileSaver: for model in AllScene.ModelDic: out_file.write("\n") modelS=str(model) - + if(1): # This is kept for now... perhaps later some sort of check might have to be enforced based on loadMode #Loading Code out_file.write(i2+"# Loading model's egg file\n") @@ -165,33 +165,33 @@ class FileSaver: for index in range(textures.getNumTextures()): texture=textures.getTexture(index) texfilename=texture.getFilename() - fnamelist.append(texfilename.getFullpath()) + fnamelist.append(texfilename.getFullpath()) oldFilename=Filename(Filename(AllScene.ModelRefDic[model].getDirname()),texfilename) if(not oldFilename.isRegularFile()): if(texfilename.resolveFilename(getTexturePath(),"")): oldFilename=texfilename oldtexpath=oldFilename.toOsSpecific() - + newtexpath=dirname + "/" + texfilename.getBasename() newtexpathF=Filename(newtexpath) newtexpathSpecific=newtexpathF.toOsSpecific() - + print "TEXTURE SAVER:: copying" + oldtexpath + " to " + newtexpathSpecific if(oldtexpath != newtexpathSpecific): shutil.copyfile(oldtexpath,newtexpathSpecific) - - - - + + + + # Copy the file over to the relative directory oldModelpath=AllScene.ModelRefDic[model].toOsSpecific() - print "FILESAVER:: copying from " + AllScene.ModelRefDic[model].toOsSpecific() + "to" + newpathSpecific + print "FILESAVER:: copying from " + AllScene.ModelRefDic[model].toOsSpecific() + "to" + newpathSpecific if(oldModelpath!=newpathSpecific): shutil.copyfile(oldModelpath,newpathSpecific) - + e=EggData() e.read(AllScene.ModelRefDic[model]) etc=EggTextureCollection() @@ -203,10 +203,10 @@ class FileSaver: fn.setDirname("") tex.setFilename(fn) e.writeEgg(Filename.fromOsSpecific(newpathSpecific)) - - out_file.write(i2+"if(self.loadmode==1):\n") + + out_file.write(i2+"if(self.loadmode==1):\n") out_file.write(i2+i1+ "self."+ modelS + "=loader.loadModel(\'" + self.savepath + "/" + AllScene.ModelRefDic[model].getBasename() + "')\n")#Relative Path out_file.write(i2+"else:\n") out_file.write(i2+i1+ "self."+ modelS + "=loader.loadModel(self.executionpath + \'/" + AllScene.ModelRefDic[model].getBasename() + "')\n")#Relative Path with execution point specified by the invoking-level-editor @@ -221,7 +221,7 @@ class FileSaver: out_file.write(i2+"# Alpha\n") out_file.write(i2+ "self."+ modelS + ".setTransparency(1)\n") clr=AllScene.ModelDic[model].getColor() - out_file.write(i2+ "self."+ modelS + ".setColor(%.4f,%.4f,%.4f,%.4f)\n"%(clr.getX(),clr.getY(),clr.getZ(),clr.getW())) + out_file.write(i2+ "self."+ modelS + ".setColor(%.4f,%.4f,%.4f,%.4f)\n"%(clr.getX(),clr.getY(),clr.getZ(),clr.getW())) out_file.write("\n") out_file.write(i2+ "# Reparent To Render for now and later we update all the parentings\n") @@ -234,7 +234,7 @@ class FileSaver: out_file.write(i2+ "self.ModelDic[\'" + modelS + "\']=self." + AllScene.ModelDic[model].getName()+"\n") #out_file.write(i2+ "self.ModelRefDic[\'" + modelS + "\']=Filename(\'"+ AllScene.ModelRefDic[model].getFullpath() +"\')\n")# The old Absolute Path way out_file.write(i2+ "self.ModelRefDic[\'" + modelS + "\']=\'"+ AllScene.ModelRefDic[model].getBasename() +"\'\n")# Relative paths - out_file.write(i2+ "self.ModelDic[\'"+ modelS + "\'].setName(\'"+ modelS +"\')\n") + out_file.write(i2+ "self.ModelDic[\'"+ modelS + "\'].setName(\'"+ modelS +"\')\n") out_file.write("\n") #################################################################################################################################################### @@ -248,7 +248,7 @@ class FileSaver: for dummy in AllScene.dummyDict: out_file.write("\n") dummyS=str(dummy) - + if(1): # This is kept for now... perhaps later some sort of check might have to be enforced based on loadMode out_file.write(i2+ "self."+ dummyS + "=loader.loadModel(\"models/misc/sphere\")\n") #Transformation Code @@ -259,13 +259,13 @@ class FileSaver: out_file.write(i2+ "self.dummyDict[\'" + dummyS + "\']=self." + AllScene.dummyDict[dummy].getName()+"\n") out_file.write(i2+ "self.dummyDict[\'"+ dummyS + "\'].setName(\'"+ dummyS +"\')\n") out_file.write("\n") - out_file.write(i2+ "# Save Metadata...can be retrieved by doing theScene.dummyDict[\"Dummy_Name\"].getTag(\"Metadata\")\n") + out_file.write(i2+ "# Save Metadata...can be retrieved by doing theScene.dummyDict[\"Dummy_Name\"].getTag(\"Metadata\")\n") out_file.write(i2+ "self."+ dummyS + ".setTag(\"Metadata\",\"" + AllScene.dummyDict[dummy].getTag("Metadata") + "\")\n") out_file.write("\n") #################################################################################################################################################### # Saving Actors and their animations - #################################################################################################################################################### + #################################################################################################################################################### out_file.write(i2+"##########################################################################################################\n") out_file.write(i2+"# Code for all the Actors and animations\n") out_file.write(i2+"# To access the Actors\n") @@ -275,7 +275,7 @@ class FileSaver: for actor in AllScene.ActorDic: out_file.write("\n") actorS=str(actor) - + if(1): # This is kept for now... perhaps later some sort of check might have to be enforced based on loadMode #out_file.write(i2+ "self."+ actorS + "=Actor.Actor(\'"+ AllScene.ActorRefDic[actor].getFullpath() + "\')\n")# The old way with absolute paths @@ -293,7 +293,7 @@ class FileSaver: for index in range(textures.getNumTextures()): texture=textures.getTexture(index) texfilename=texture.getFilename() - actorfnamelist.append(texfilename.getFullpath()) + actorfnamelist.append(texfilename.getFullpath()) oldFilename=Filename(Filename(AllScene.ActorRefDic[actor].getDirname()),texfilename) if(not oldFilename.isRegularFile()): @@ -312,10 +312,10 @@ class FileSaver: # Copy the file over to the relative directory oldActorpath=AllScene.ActorRefDic[actor].toOsSpecific() - print "FILESAVER:: copying from " + AllScene.ActorRefDic[actor].toOsSpecific() + "to" + newpathSpecific + print "FILESAVER:: copying from " + AllScene.ActorRefDic[actor].toOsSpecific() + "to" + newpathSpecific if(oldActorpath!=newpathSpecific): shutil.copyfile(oldActorpath,newpathSpecific) - + e=EggData() e.read(AllScene.ActorRefDic[actor]) @@ -328,10 +328,10 @@ class FileSaver: fn.setDirname("") tex.setFilename(fn) e.writeEgg(Filename.fromOsSpecific(newpathSpecific)) - - out_file.write(i2+"if(self.loadmode==1):\n") + + out_file.write(i2+"if(self.loadmode==1):\n") out_file.write(i2+i1+ "self."+ actorS + "=Actor.Actor(\'" + self.savepath + "/" + AllScene.ActorRefDic[actor].getBasename() + "')\n")#Relative Path out_file.write(i2+"else:\n") out_file.write(i2+i1+ "self."+ actorS + "=Actor.Actor(self.executionpath + \'/" + AllScene.ActorRefDic[actor].getBasename() + "')\n")#Relative Path with execution point specified by the invoking-level-editor @@ -347,7 +347,7 @@ class FileSaver: out_file.write(i2+ "self."+ actorS + ".setColor(%.4f,%.4f,%.4f,%.4f)\n"%(clr.getX(),clr.getY(),clr.getZ(),clr.getW())) out_file.write(i2+ "self."+ actorS + ".reparentTo(render)\n") - + out_file.write("\n") out_file.write(i2+ "# Save Metadata...can be retrieved by doing theScene.ActorDic[\"Actor_Name\"].getTag(\"Metadata\")\n") out_file.write(i2+ "self."+ actorS + ".setTag(\"Metadata\",\"" + AllScene.ActorDic[actor].getTag("Metadata") + "\")\n") @@ -362,7 +362,7 @@ class FileSaver: #out_file.write(i2+ "self."+ actorS + ".loadAnims(" + str(ActorAnimations) +")\n") # Old way with absolute paths #Manakel 2/12/2004: solve the not empty but not defined animation case if not animation is None: - print "ACTOR ANIMATIONS:" + ActorAnimations[animation] + print "ACTOR ANIMATIONS:" + ActorAnimations[animation] oldAnimPath=Filename(ActorAnimations[animation]) oldAnim=oldAnimPath.toOsSpecific() dirOS=Filename(dirname) @@ -380,24 +380,24 @@ class FileSaver: out_file.write(i2+"else:\n") theloadAnimString=str(ActorAnimationsInvoke)# We hack the "self.executionpath" part into the dictionary as a variable using string replace print "LOAD ANIM STRING BEFORE" + theloadAnimString - theloadAnimString=theloadAnimString.replace('\'self.executionpath +','self.executionpath + \'') + theloadAnimString=theloadAnimString.replace('\'self.executionpath +','self.executionpath + \'') print "LOAD ANIM STRING AFTER" + theloadAnimString out_file.write(i2+ i1+"self."+ actorS + ".loadAnims(" + theloadAnimString +")\n") # Now with new relative paths based on editor invocation out_file.write(i2+ "self.ActorDic[\'" + actorS + "\']=self." + AllScene.ActorDic[actor].getName()+"\n") #out_file.write(i2+ "self.ActorRefDic[\'" + actorS + "\']=Filename(\'"+AllScene.ActorRefDic[actor].getFullpath() +"\')\n") # Old way with absolute paths out_file.write(i2+ "self.ActorRefDic[\'" + actorS + "\']=\'"+ AllScene.ActorRefDic[actor].getBasename() +"\'\n")# Relative paths - out_file.write(i2+ "self.ActorDic[\'"+ actorS + "\'].setName(\'"+ actorS +"\')\n") + out_file.write(i2+ "self.ActorDic[\'"+ actorS + "\'].setName(\'"+ actorS +"\')\n") if(AllScene.blendAnimDict.has_key(actor)): # Check if a dictionary of blended animations exists out_file.write(i2+ "self.blendAnimDict[\"" + actorS +"\"]=" + str(AllScene.blendAnimDict[actor]) + "\n") - - + + out_file.write("\n") - + #################################################################################################################################################### # Collsion Node Saving #################################################################################################################################################### - + out_file.write(i2+"##########################################################################################################\n") out_file.write(i2+"# Code for setting up Collision Nodes\n") out_file.write(i2+"# To use collision detection:\n") @@ -410,7 +410,7 @@ class FileSaver: nodetype=solid.getType().getName() if(nodetype=="CollisionSphere"): #Save Collison Sphere - out_file.write(i2+"collSolid=CollisionSphere(%.3f,%.3f,%.3f,%.3f)\n"%(solid.getCenter().getX(),solid.getCenter().getY(),solid.getCenter().getZ(),solid.getRadius())) + out_file.write(i2+"collSolid=CollisionSphere(%.3f,%.3f,%.3f,%.3f)\n"%(solid.getCenter().getX(),solid.getCenter().getY(),solid.getCenter().getZ(),solid.getRadius())) pass elif(nodetype=="CollisionPolygon"): #Save Collison Polygon @@ -430,13 +430,13 @@ class FileSaver: out_file.write(i2+"pointB = Point3(" + bx + "," + by + "," + bz + ")\n") out_file.write(i2+"pointC = Point3(" + cx + "," + cy + "," + cz + ")\n") out_file.write(i2+"collSolid=CollisionPolygon(pointA, pointB, pointC)\n") - + pass elif(nodetype=="CollisionSegment"): #Save Collison Segment A=AllScene.collisionDict[collnode].node().getSolid(0).getPointA() B=AllScene.collisionDict[collnode].node().getSolid(0).getPointB() - + out_file.write(i2+"pointA = Point3(%.3f,%.3f,%.3f)\n"%(A.getX(),A.getY(),A.getZ())) out_file.write(i2+"pointB = Point3(%.3f,%.3f,%.3f)\n"%(B.getX(),B.getY(),B.getZ())) out_file.write(i2+"collSolid=CollisionSegment()\n") @@ -455,7 +455,7 @@ class FileSaver: out_file.write(i2+"collSolid=CollisionRay()\n") out_file.write(i2+"collSolid.setOrigin(point)\n") out_file.write(i2+"collSolid.setDirection(vector)\n") - + pass else: print "Invalid Collision Node: " + nodetype @@ -466,7 +466,7 @@ class FileSaver: out_file.write(i2+"self." + collnodeS + "_Node" + ".addSolid(collSolid)\n") out_file.write(i2+"base.cTrav.addCollider(self." + collnodeS + "_Node,self.CollisionHandler)\n") out_file.write("\n") - + @@ -488,8 +488,8 @@ class FileSaver: out_file.write (i2+ "alight = AmbientLight(\'"+ light.getName() +"\')\n") out_file.write (i2+ "alight.setColor(VBase4("+ str(light.getLightColor().getX())+ "," + str(light.getLightColor().getY())+ "," + str(light.getLightColor().getZ()) + "," + str(light.getLightColor().getW()) + "))\n") out_file.write (i2+ "self.lightAttrib=self.lightAttrib.addLight(alight)\n") - out_file.write (i2+ "self."+light.getName()+"= render.attachNewNode(alight.upcastToPandaNode())\n") - out_file.write (i2+ "self."+light.getName()+".setTag(\"Metadata\",\"" + light.getTag("Metadata") + "\")\n") + out_file.write (i2+ "self."+light.getName()+"= render.attachNewNode(alight.upcastToPandaNode())\n") + out_file.write (i2+ "self."+light.getName()+".setTag(\"Metadata\",\"" + light.getTag("Metadata") + "\")\n") out_file.write (i2+ "self.LightDict[\'" + light.getName() + "\']=alight\n") out_file.write (i2+ "self.LightTypes[\'" + light.getName() + "\']=\'" + type + "\'\n") out_file.write (i2+ "self.LightNodes[\'" + light.getName() + "\']=self." + light.getName() + "\n") @@ -503,10 +503,10 @@ class FileSaver: #out_file.write (i2+ "alight.setPoint(Point3(" + str(light.getX()) + "," + str(light.getY()) + "," + str(light.getZ()) + "))\n") out_file.write (i2+ "alight.setSpecularColor(Vec4(" + str(light.getSpecColor().getX()) + "," + str(light.getSpecColor().getY()) + "," + str(light.getSpecColor().getZ()) + "," + str(light.getSpecColor().getW()) + "))\n") out_file.write (i2+ "self.lightAttrib=self.lightAttrib.addLight(alight)\n") - out_file.write (i2+ "self."+light.getName()+ "= render.attachNewNode(alight.upcastToPandaNode())\n") + out_file.write (i2+ "self."+light.getName()+ "= render.attachNewNode(alight.upcastToPandaNode())\n") out_file.write (i2+ "self."+light.getName()+ ".setPos(Point3(" + str(light.getX()) + "," + str(light.getY()) + "," + str(light.getZ()) + "))\n") out_file.write (i2+ "self."+light.getName()+ ".setHpr(Vec3("+ str(light.getH())+ "," + str(light.getP())+ "," + str(light.getR()) + "))\n") - out_file.write (i2+ "self."+light.getName()+ ".setTag(\"Metadata\",\"" + light.getTag("Metadata") + "\")\n") + out_file.write (i2+ "self."+light.getName()+ ".setTag(\"Metadata\",\"" + light.getTag("Metadata") + "\")\n") #out_file.write (i2+ "alight.setPos out_file.write (i2+ "self.LightDict[\'" + light.getName() + "\']=alight\n") out_file.write (i2+ "self.LightTypes[\'" + light.getName() + "\']=\'" + type + "\'\n") @@ -521,8 +521,8 @@ class FileSaver: out_file.write (i2+ "alight.setSpecularColor(Vec4(" + str(light.getSpecColor().getX()) + "," + str(light.getSpecColor().getY()) + "," + str(light.getSpecColor().getZ()) + "," + str(light.getSpecColor().getW()) + "))\n") out_file.write (i2+ "alight.setAttenuation(Vec3("+ str(light.getAttenuation().getX()) + "," + str(light.getAttenuation().getY()) + "," + str(light.getAttenuation().getZ()) + "))\n") out_file.write (i2+ "self.lightAttrib=self.lightAttrib.addLight(alight)\n") - out_file.write (i2+ "self."+light.getName()+ "= render.attachNewNode(alight.upcastToPandaNode())\n") - out_file.write (i2+ "self."+light.getName()+ ".setTag(\"Metadata\",\"" + light.getTag("Metadata") + "\")\n") + out_file.write (i2+ "self."+light.getName()+ "= render.attachNewNode(alight.upcastToPandaNode())\n") + out_file.write (i2+ "self."+light.getName()+ ".setTag(\"Metadata\",\"" + light.getTag("Metadata") + "\")\n") out_file.write (i2+ "self."+light.getName()+ ".setPos(Point3(" + str(light.getX()) + "," + str(light.getY()) + "," + str(light.getZ()) + "))\n") out_file.write (i2+ "self.LightDict[\'" + light.getName() + "\']=alight\n") out_file.write (i2+ "self.LightTypes[\'" + light.getName() + "\']=\'" + type + "\'\n") @@ -539,8 +539,8 @@ class FileSaver: out_file.write (i2+ "alight.setAttenuation(Vec3("+ str(light.getAttenuation().getX()) + "," + str(light.getAttenuation().getY()) + "," + str(light.getAttenuation().getZ()) + "))\n") out_file.write (i2+ "alight.setExponent(" +str(light.getExponent()) +")\n") out_file.write (i2+ "self.lightAttrib=self.lightAttrib.addLight(alight)\n") - out_file.write (i2+ "self."+light.getName()+ "= render.attachNewNode(alight.upcastToLensNode())\n") - out_file.write (i2+ "self."+light.getName()+ ".setTag(\"Metadata\",\"" + light.getTag("Metadata") + "\")\n") + out_file.write (i2+ "self."+light.getName()+ "= render.attachNewNode(alight.upcastToLensNode())\n") + out_file.write (i2+ "self."+light.getName()+ ".setTag(\"Metadata\",\"" + light.getTag("Metadata") + "\")\n") out_file.write (i2+ "self."+light.getName()+ ".setPos(Point3(" + str(light.getX()) + "," + str(light.getY()) + "," + str(light.getZ()) + "))\n") out_file.write (i2+ "self."+light.getName()+ ".setHpr(Vec3("+ str(light.getH())+ "," + str(light.getP())+ "," + str(light.getR()) + "))\n") out_file.write (i2+ "self.LightDict[\'" + light.getName() + "\']=alight\n") @@ -552,7 +552,7 @@ class FileSaver: out_file.write (i2+ "return None") out_file.write("\n") - + #################################################################################################################################################### # Enable Lighting @@ -571,32 +571,32 @@ class FileSaver: out_file.write(i2+"# Load Particle Effects. The parameters to this function are to allow us to use our modified versions of the Particle Effects modules when loading this file with the level editor\n") out_file.write(i2+"self.starteffects(self.loadmode,self.seParticleEffect,self.seParticles)\n") out_file.write("\n") - + #################################################################################################################################################### # Save Camera Settings #################################################################################################################################################### out_file.write("\n") out_file.write(i2+ "# Save Camera Settings\n") - out_file.write(i2+ "camera.setX(" + str(camera.getX()) + ")\n") - out_file.write(i2+ "camera.setY(" + str(camera.getY()) + ")\n") - out_file.write(i2+ "camera.setZ(" + str(camera.getZ()) + ")\n") - out_file.write(i2+ "camera.setH(" + str(camera.getH()) + ")\n") - out_file.write(i2+ "camera.setP(" + str(camera.getP()) + ")\n") - out_file.write(i2+ "camera.setR(" + str(camera.getR()) + ")\n") - out_file.write(i2+ "camera.getChild(0).node().getLens().setNear(" + str(camera.getChild(0).node().getLens().getNear()) + ")\n") - out_file.write(i2+ "camera.getChild(0).node().getLens().setFar(" + str(camera.getChild(0).node().getLens().getFar()) + ")\n") - out_file.write(i2+ "camera.getChild(0).node().getLens().setFov(VBase2(%.5f,%.5f))\n"% (camera.getChild(0).node().getLens().getHfov(),camera.getChild(0).node().getLens().getVfov())) + out_file.write(i2+ "camera.setX(" + str(camera.getX()) + ")\n") + out_file.write(i2+ "camera.setY(" + str(camera.getY()) + ")\n") + out_file.write(i2+ "camera.setZ(" + str(camera.getZ()) + ")\n") + out_file.write(i2+ "camera.setH(" + str(camera.getH()) + ")\n") + out_file.write(i2+ "camera.setP(" + str(camera.getP()) + ")\n") + out_file.write(i2+ "camera.setR(" + str(camera.getR()) + ")\n") + out_file.write(i2+ "camera.getChild(0).node().getLens().setNear(" + str(camera.getChild(0).node().getLens().getNear()) + ")\n") + out_file.write(i2+ "camera.getChild(0).node().getLens().setFar(" + str(camera.getChild(0).node().getLens().getFar()) + ")\n") + out_file.write(i2+ "camera.getChild(0).node().getLens().setFov(VBase2(%.5f,%.5f))\n"% (camera.getChild(0).node().getLens().getHfov(),camera.getChild(0).node().getLens().getVfov())) FilmSize=camera.getChild(0).node().getLens().getFilmSize() - out_file.write(i2+ "camera.getChild(0).node().getLens().setFilmSize(%.3f,%.3f)\n"%(FilmSize.getX(),FilmSize.getY())) - out_file.write(i2+ "camera.getChild(0).node().getLens().setFocalLength(" + str(camera.getChild(0).node().getLens().getFocalLength()) + ")\n") - out_file.write(i2+ "camera.setTag(\"Metadata\",\"" + camera.getTag("Metadata") + "\")\n") + out_file.write(i2+ "camera.getChild(0).node().getLens().setFilmSize(%.3f,%.3f)\n"%(FilmSize.getX(),FilmSize.getY())) + out_file.write(i2+ "camera.getChild(0).node().getLens().setFocalLength(" + str(camera.getChild(0).node().getLens().getFocalLength()) + ")\n") + out_file.write(i2+ "camera.setTag(\"Metadata\",\"" + camera.getTag("Metadata") + "\")\n") out_file.write(i2+ "camera.reparentTo(render)\n") out_file.write(i2+ "base.disableMouse()\n") self.bgColor=base.getBackgroundColor() out_file.write(i2+ "base.setBackgroundColor(%.3f,%.3f,%.3f)\n"%(self.bgColor.getX(),self.bgColor.getY(),self.bgColor.getZ())) out_file.write("\n") - + #################################################################################################################################################### # Mopath Saving @@ -626,17 +626,17 @@ class FileSaver: out_file.write(i2+"mp=MopathInterval(m,self." + str(node) + ")\n") out_file.write(i2+"self.curveIntervals.append(mp)\n") - + out_file.write(i2+"if(self.loadmode==1):\n") out_file.write(i2+i1+"self.curveRefColl.append(\"" + self.savepath +"/"+ filestring +"\")\n") out_file.write(i2+"else:\n") out_file.write(i2+i1+"self.curveRefColl.append(self.executionpath + \"/"+ filestring +"\")\n") curvenumber=curvenumber+1 - out_file.write(i2+"self.curveIntervalsDict[\"" + str(node) + "\"]=self.curveIntervals\n") + out_file.write(i2+"self.curveIntervalsDict[\"" + str(node) + "\"]=self.curveIntervals\n") out_file.write(i2+"self.curveDict[\"" + str(node) + "\"]=self.curveRefColl\n") - + #################################################################################################################################################### # Lets do all the reparenting here so as to make sure everything that needed to load was loaded #################################################################################################################################################### @@ -665,7 +665,7 @@ class FileSaver: parent=AllScene.dummyDict[dummy].getParent().getName() if(parent=="render" or parent=="camera"): out_file.write(i2+ "self."+ dummyS + ".reparentTo(" + parent + ")\n") - else: + else: if(AllScene.particleDict.has_key(parent)): out_file.write(i2+ "self."+ dummyS + ".reparentTo(self." + parent + ".getEffect())\n") else: @@ -675,7 +675,7 @@ class FileSaver: out_file.write(i2+"\n") for actor in AllScene.ActorDic: - actorS=str(actor) + actorS=str(actor) parent=AllScene.ActorDic[actor].getParent().getName() if(parent=="render" or parent=="camera"): out_file.write(i2+ "self."+ actorS + ".reparentTo(" + parent + ")\n") @@ -687,7 +687,7 @@ class FileSaver: out_file.write(i2+ "self.ActorDic[\'" + actorS + "\']=self." + AllScene.ActorDic[actor].getName()+"\n") out_file.write(i2+"\n") - + for collnode in AllScene.collisionDict: collnodeS=str(collnode) @@ -741,7 +741,7 @@ class FileSaver: for effect in AllScene.particleDict: parent=AllScene.particleNodes[effect].getParent().getName() if(parent=="render" or parent=="camera"): - out_file.write(i2+"self.particleDict[\""+ str(effect) +"\"].reparentTo(" + parent + ")\n") + out_file.write(i2+"self.particleDict[\""+ str(effect) +"\"].reparentTo(" + parent + ")\n") else: out_file.write(i2+"self.particleDict[\""+ str(effect) +"\"].reparentTo(self." + parent + ")\n") out_file.write(i2+"\n") @@ -809,11 +809,11 @@ class FileSaver: out_file.write(i2+"blendList=blendDicts[blendName]\n") out_file.write(i2+"actor.stop(blendList[0])\n") out_file.write(i2+"actor.stop(blendList[1])\n") - out_file.write("\n") + out_file.write("\n") out_file.write(i1+"def changeBlending(self,actor,blendName,blending):\n") out_file.write(i2+"blendDicts=self.blendAnimDict[actor.getName()]\n") - out_file.write(i2+"blendList=blendDicts[blendName]\n") + out_file.write(i2+"blendList=blendDicts[blendName]\n") out_file.write(i2+"blendList[2]=blending\n") out_file.write(i2+"self.blendAnimDict[actor.getName()]={blendName:[blendList[0],blendList[1],blending]}\n") out_file.write("\n") @@ -823,21 +823,21 @@ class FileSaver: #################################################################################################################################################### # Hide and Show Methods #################################################################################################################################################### - + out_file.write("\n") out_file.write(i2+"##########################################################################################################\n") out_file.write(i2+"# Hide and Show Methods\n") out_file.write(i2+"# These will help you hide/show dummies, collision solids, effect nodes etc.\n") out_file.write(i2+"##########################################################################################################\n\n") - - + + out_file.write("\n") out_file.write(i1+"def hideDummies(self):\n") out_file.write("\n") out_file.write(i2+"for dummy in self.dummyDict:\n") out_file.write(i2+i1+"self.dummyDict[dummy].reparentTo(hidden)\n") - - + + out_file.write("\n") out_file.write(i1+"def hideCollSolids(self):\n") out_file.write("\n") @@ -857,8 +857,8 @@ class FileSaver: out_file.write("\n") out_file.write(i2+"for dummy in self.dummyDict:\n") out_file.write(i2+i1+"self.dummyDict[dummy].reparentTo(hidden)\n") - - + + out_file.write("\n") out_file.write(i1+"def showCollSolids(self):\n") out_file.write("\n") @@ -885,7 +885,7 @@ class FileSaver: out_file.write(i2+"##########################################################################################################\n\n") for effect in AllScene.particleDict: - + out_file.write("\n\n") out_file.write("class " + str(effect) + ":\n") out_file.write(i1+"def __init__(self,mode=1,seParticleEffect=None,seParticles=None):\n") @@ -911,5 +911,5 @@ class FileSaver: #out_file.write("run()\n") out_file.close() - - + + diff --git a/contrib/src/sceneeditor/seForceGroup.py b/contrib/src/sceneeditor/seForceGroup.py index c8ba2b9d4e..7d27c78ebd 100644 --- a/contrib/src/sceneeditor/seForceGroup.py +++ b/contrib/src/sceneeditor/seForceGroup.py @@ -15,7 +15,7 @@ class ForceGroup(DirectObject): """__init__(self)""" if (name == None): - self.name = 'ForceGroup-%d' % ForceGroup.id + self.name = 'ForceGroup-%d' % ForceGroup.id ForceGroup.id += 1 else: self.name = name @@ -74,7 +74,7 @@ class ForceGroup(DirectObject): def getNodePath(self): return self.nodePath - # Utility functions + # Utility functions def __getitem__(self, index): numForces = self.node.getNumForces() if ((index < 0) or (index >= numForces)): diff --git a/contrib/src/sceneeditor/seGeometry.py b/contrib/src/sceneeditor/seGeometry.py index 1d22bcb891..79115e5531 100644 --- a/contrib/src/sceneeditor/seGeometry.py +++ b/contrib/src/sceneeditor/seGeometry.py @@ -79,7 +79,7 @@ class LineNodePath(NodePath): def getVertexColor( self ): return self.lineSegs.getVertexColor() - + def drawArrow(self, sv, ev, arrowAngle, arrowLength): """ Do the work of moving the cursor around to draw an arrow from @@ -206,12 +206,12 @@ def qSlerp(startQuat, endQuat, t): destQuat = Quat.identQuat() # Calc dot product cosOmega = (startQ.getI() * endQuat.getI() + - startQ.getJ() * endQuat.getJ() + + startQ.getJ() * endQuat.getJ() + startQ.getK() * endQuat.getK() + startQ.getR() * endQuat.getR()) # If the above dot product is negative, it would be better to # go between the negative of the initial and the final, so that - # we take the shorter path. + # we take the shorter path. if ( cosOmega < 0.0 ): cosOmega *= -1 startQ.setI(-1 * startQ.getI()) @@ -227,7 +227,7 @@ def qSlerp(startQuat, endQuat, t): startScale = math.sin((1.0 - t) * omega)/sinOmega endScale = math.sin(t * omega)/sinOmega else: - # ends very close + # ends very close startScale = 1.0 - t endScale = t destQuat.setI(startScale * startQ.getI() + diff --git a/contrib/src/sceneeditor/seGrid.py b/contrib/src/sceneeditor/seGrid.py index 559bdf6cb1..b9785df261 100644 --- a/contrib/src/sceneeditor/seGrid.py +++ b/contrib/src/sceneeditor/seGrid.py @@ -90,7 +90,7 @@ class DirectGrid(NodePath,DirectObject): # Now redraw lines numLines = int(math.ceil(self.gridSize/self.gridSpacing)) scaledSize = numLines * self.gridSpacing - + center = self.centerLines minor = self.minorLines major = self.majorLines @@ -116,7 +116,7 @@ class DirectGrid(NodePath,DirectObject): minor.create() major.create() self.gridBack.setScale(scaledSize) - + def setXyzSnap(self, fSnap): self.fXyzSnap = fSnap @@ -138,7 +138,7 @@ class DirectGrid(NodePath,DirectObject): ROUND_TO(self.snapPos[0], self.gridSpacing), ROUND_TO(self.snapPos[1], self.gridSpacing), ROUND_TO(self.snapPos[2], self.gridSpacing)) - + # Move snap marker to this point self.snapMarker.setPos(self.snapPos) @@ -157,7 +157,7 @@ class DirectGrid(NodePath,DirectObject): def setGridSpacing(self, spacing): self.gridSpacing = spacing self.updateGrid() - + def getGridSpacing(self): return self.gridSpacing diff --git a/contrib/src/sceneeditor/seLights.py b/contrib/src/sceneeditor/seLights.py index 59d7b1dc72..1a42e9045a 100644 --- a/contrib/src/sceneeditor/seLights.py +++ b/contrib/src/sceneeditor/seLights.py @@ -62,7 +62,7 @@ class seLight(NodePath): self.exponent = exponent self.lence = lence self.active = True - + if isinstance(light, Spotlight): node = light.upcastToLensNode() else: @@ -75,10 +75,10 @@ class seLight(NodePath): self.LightNode.setHpr(self.orientation) self.LightNode.setPos(self.position) else: - self.LightNode.setHpr(self.orientation) + self.LightNode.setHpr(self.orientation) self.LightNode.setPos(self.position) - - + + self.assign(self.LightNode) if(self.type=='spot'): self.helpModel = loader.loadModel( "models/misc/Spotlight" ) @@ -99,7 +99,7 @@ class seLight(NodePath): # getLight(self) # This function will return the light object it contains. ################################################################# - + return self.light def getLightColor(self): @@ -108,14 +108,14 @@ class seLight(NodePath): # This function will return the color of the light color of this light node. ################################################################# return self.lightcolor - + def getName(self): ################################################################# # getName(self) # This function will return the name of this light. ################################################################# return self.light.getName() - + def rename(self,name): ################################################################# # rename(self, name) @@ -203,7 +203,7 @@ class seLight(NodePath): ################################################################# self.orientation = self.LightNode.getHpr() return self.orientation - + def setOrientation(self,orient): ################################################################# # setOrientation(self, orient) @@ -241,7 +241,7 @@ class seLight(NodePath): self.light.setAttenuation(Vec3(value, self.linear, self.quadratic)) self.constant = value return - + def setLinearAttenuation(self, value): ################################################################# # setLinearAttenuation(self, value) @@ -252,7 +252,7 @@ class seLight(NodePath): self.light.setAttenuation(Vec3(self.constant, value, self.quadratic)) self.linear = value return - + def setQuadraticAttenuation(self, value): ################################################################# # setQuadraticAttenuation(self, value) @@ -270,7 +270,7 @@ class seLight(NodePath): # This function will return the value of the Exponent Attenuation # of this light node. (float) ################################################################# - return self.exponent + return self.exponent def setExponent(self, value): ################################################################# @@ -282,7 +282,7 @@ class seLight(NodePath): self.light.setExponent(value) self.exponent = value return - + class seLightManager(NodePath): ################################################################# # seLightManager(NodePath) @@ -307,7 +307,7 @@ class seLightManager(NodePath): self.helpModel = loader.loadModel( "models/misc/sphere" ) self.helpModel.reparentTo(self) self.helpModel.hide() - + @@ -342,7 +342,7 @@ class seLightManager(NodePath): ### create the light lence = None - + if type == 'ambient': self.ambientCount += 1 if(name=='DEFAULT_NAME'): @@ -368,7 +368,7 @@ class seLightManager(NodePath): light = PointLight('point_' + `self.pointCount`) else: light = PointLight(name) - + light.setColor(lightcolor) light.setSpecularColor(specularColor) light.setAttenuation(Vec3(constant, linear, quadratic)) @@ -406,7 +406,7 @@ class seLightManager(NodePath): self.lightDict[light.getName()] = lightNode self.setOn(lightNode) - + return self.lightDict.keys(),lightNode def addLight(self, light): @@ -507,7 +507,7 @@ class seLightManager(NodePath): ################################################################# for name in self.lightDict: self.delete(name, removeEntry = False) - + self.lightDict.clear() def isLight(self,name): @@ -531,7 +531,7 @@ class seLightManager(NodePath): return self.lightDict.keys(),lightNode else: print '----Light Mnager: No such Light!' - + def getLightNodeList(self): ################################################################# # getLightNodeList(self) @@ -612,7 +612,7 @@ class seLightManager(NodePath): if render.node().hasAttrib(LightAttrib.getClassType()): render.node().setAttrib(self.lightAttrib) - + def setOff(self, lightNode): ################################################################# # setOff(self, lightNode) diff --git a/contrib/src/sceneeditor/seManipulation.py b/contrib/src/sceneeditor/seManipulation.py index d3f0b06ce8..e4d50d81dc 100644 --- a/contrib/src/sceneeditor/seManipulation.py +++ b/contrib/src/sceneeditor/seManipulation.py @@ -200,7 +200,7 @@ class DirectManipulationControl(DirectObject): # Send event to signal start of manipulation messenger.send('DIRECT_manipulateObjectStart') # Manipulate the real object with the constraint - # The constraint is passed as the name of the node + # The constraint is passed as the name of the node self.spawnManipulateObjectTask() def spawnManipulateObjectTask(self): @@ -314,7 +314,7 @@ class DirectManipulationControl(DirectObject): self.fWidgetTop = self.widgetCheck('top?') self.rotationCenter = getScreenXY(SEditor.widget) self.lastCrankAngle = getCrankAngle(self.rotationCenter) - + # Rotate widget based on how far cursor has swung around origin newAngle = getCrankAngle(self.rotationCenter) deltaAngle = self.lastCrankAngle - newAngle @@ -528,7 +528,7 @@ class ObjectHandles(NodePath,DirectObject): self.xDiscGroup = self.xHandles.find('**/x-disc-group') self.xDisc = self.xHandles.find('**/x-disc-visible') self.xDiscCollision = self.xHandles.find('**/x-disc') - + self.yHandles = self.find('**/Y') self.yPostGroup = self.yHandles.find('**/y-post-group') self.yPostCollision = self.yHandles.find('**/y-post') @@ -537,7 +537,7 @@ class ObjectHandles(NodePath,DirectObject): self.yDiscGroup = self.yHandles.find('**/y-disc-group') self.yDisc = self.yHandles.find('**/y-disc-visible') self.yDiscCollision = self.yHandles.find('**/y-disc') - + self.zHandles = self.find('**/Z') self.zPostGroup = self.zHandles.find('**/z-post-group') self.zPostCollision = self.zHandles.find('**/z-post') @@ -782,7 +782,7 @@ class ObjectHandles(NodePath,DirectObject): lines.moveTo(0,0,0) lines.drawTo(-1.5,0,0) lines.create() - + # X ring self.xRing = self.xRingGroup.attachNewNode('x-ring-visible') lines = LineNodePath(self.xRing) @@ -794,7 +794,7 @@ class ObjectHandles(NodePath,DirectObject): math.cos(deg2Rad(ang)), math.sin(deg2Rad(ang))) lines.create() - + # Y post self.yPost = self.yPostGroup.attachNewNode('y-post-visible') lines = LineNodePath(self.yPost) @@ -809,7 +809,7 @@ class ObjectHandles(NodePath,DirectObject): lines.moveTo(0,0,0) lines.drawTo(0,-1.5,0) lines.create() - + # Y ring self.yRing = self.yRingGroup.attachNewNode('y-ring-visible') lines = LineNodePath(self.yRing) @@ -836,7 +836,7 @@ class ObjectHandles(NodePath,DirectObject): lines.moveTo(0,0,0) lines.drawTo(0,0,-1.5) lines.create() - + # Z ring self.zRing = self.zRingGroup.attachNewNode('z-ring-visible') lines = LineNodePath(self.zRing) @@ -929,12 +929,12 @@ class ObjectHandles(NodePath,DirectObject): # Calc the xfrom from camera to the nodePath mCam2NodePath = SEditor.camera.getMat(nodePath) - + # And determine where the viewpoint is relative to widget lineOrigin = VBase3(0) decomposeMatrix(mCam2NodePath, VBase3(0), VBase3(0), lineOrigin, CSDefault) - + # Next we find the vector from viewpoint to the widget through # the mouse's position on near plane. # This defines the intersection ray diff --git a/contrib/src/sceneeditor/seMopathRecorder.py b/contrib/src/sceneeditor/seMopathRecorder.py index 1816bb3168..7ba2ee52d7 100644 --- a/contrib/src/sceneeditor/seMopathRecorder.py +++ b/contrib/src/sceneeditor/seMopathRecorder.py @@ -59,7 +59,7 @@ class MopathRecorder(AppShell, DirectObject): # Call superclass initialization function AppShell.__init__(self) - + self.initialiseoptions(MopathRecorder) self.selectNodePathNamed('camera') @@ -306,9 +306,9 @@ class MopathRecorder(AppShell, DirectObject): frame.pack(fill = Tkinter.X, expand = 1) - + mainFrame.pack(expand = 1, fill = Tkinter.X, pady = 3) - + # Playback controls playbackFrame = Frame(interior, relief = Tkinter.SUNKEN, borderwidth = 2) @@ -370,7 +370,7 @@ class MopathRecorder(AppShell, DirectObject): string.atof(s.speedVar.get()))) self.speedEntry.pack(side = Tkinter.LEFT, expand = 0) frame.pack(fill = Tkinter.X, expand = 1) - + playbackFrame.pack(fill = Tkinter.X, pady = 2) # Create notebook pages @@ -387,7 +387,7 @@ class MopathRecorder(AppShell, DirectObject): label = Label(self.resamplePage, text = 'RESAMPLE CURVE', font=('MSSansSerif', 12, 'bold')) label.pack(fill = Tkinter.X) - + # Resample resampleFrame = Frame( self.resamplePage, relief = Tkinter.SUNKEN, borderwidth = 2) @@ -411,7 +411,7 @@ class MopathRecorder(AppShell, DirectObject): self.faceForward, side = Tkinter.LEFT, fill = Tkinter.X, expand = 1) frame.pack(fill = Tkinter.X, expand = 0) resampleFrame.pack(fill = Tkinter.X, expand = 0, pady = 2) - + # Desample desampleFrame = Frame( self.resamplePage, relief = Tkinter.SUNKEN, borderwidth = 2) @@ -555,7 +555,7 @@ class MopathRecorder(AppShell, DirectObject): sfFrame, 'Style', 'Num Segs', 'Set number of segments used to approximate each parametric unit', min = 1.0, max = 400, resolution = 1.0, - value = 40, + value = 40, command = self.setNumSegs, side = Tkinter.TOP) widget.component('hull')['relief'] = Tkinter.RIDGE widget = self.createSlider( @@ -644,8 +644,8 @@ class MopathRecorder(AppShell, DirectObject): # Pack record frame optionsFrame.pack(fill = Tkinter.X, pady = 2) - self.mainNotebook.setnaturalsize() - + self.mainNotebook.setnaturalsize() + def pushUndo(self, fResetRedo = 1): SEditor.pushUndo([self.nodePath]) @@ -663,7 +663,7 @@ class MopathRecorder(AppShell, DirectObject): def pushRedo(self): SEditor.pushRedo([self.nodePath]) - + def redoHook(self): # Reflect new changes pass @@ -675,7 +675,7 @@ class MopathRecorder(AppShell, DirectObject): def redoListEmptyHook(self): # Make sure button is deactivated self.redoButton.configure(state = 'disabled') - + def selectedNodePathHook(self, nodePath): """ Hook called upon selection of a node path used to select playback @@ -770,11 +770,11 @@ class MopathRecorder(AppShell, DirectObject): self.manipulandumId = self.playbackMarker.id() elif SEditor.selected.last.id() == self.tangentMarker.id(): self.manipulandumId = self.tangentMarker.id() - + def manipulateObjectCleanupHook(self): # Clear flag self.manipulandumId = None - + def onDestroy(self, event): # Remove hooks for event, method in self.actionEvents: @@ -853,7 +853,7 @@ class MopathRecorder(AppShell, DirectObject): self.curveNodePath.show() else: self.curveNodePath.hide() - + def setKnotVis(self): self.nurbsCurveDrawer.setShowKnots( self.getVariable('Style', 'Knots').get()) @@ -861,11 +861,11 @@ class MopathRecorder(AppShell, DirectObject): def setCvVis(self): self.nurbsCurveDrawer.setShowCvs( self.getVariable('Style', 'CVs').get()) - + def setHullVis(self): self.nurbsCurveDrawer.setShowHull( self.getVariable('Style', 'Hull').get()) - + def setTraceVis(self): if self.getVariable('Style', 'Trace').get(): self.trace.show() @@ -881,10 +881,10 @@ class MopathRecorder(AppShell, DirectObject): def setNumSegs(self, value): self.numSegs = int(value) self.nurbsCurveDrawer.setNumSegs(self.numSegs) - + def setNumTicks(self, value): self.nurbsCurveDrawer.setNumTicks(float(value)) - + def setTickScale(self, value): self.nurbsCurveDrawer.setTickScale(float(value)) @@ -933,7 +933,7 @@ class MopathRecorder(AppShell, DirectObject): self.curveCollection = None self.curveFitter.reset() self.nurbsCurveDrawer.hide() - + def setSamplingMode(self, mode): self.samplingMode = mode @@ -950,7 +950,7 @@ class MopathRecorder(AppShell, DirectObject): def setRefineMode(self): self.setRecordingType('Refine') - + def setExtendMode(self): self.setRecordingType('Extend') @@ -1015,7 +1015,7 @@ class MopathRecorder(AppShell, DirectObject): self.recordTask, self.name + '-recordTask') t.startTime = globalClock.getFrameTime() else: - self.markingNode.removeNode() # Hide the marker in the end of recording + self.markingNode.removeNode() # Hide the marker in the end of recording if self.samplingMode == 'Continuous': # Kill old task taskMgr.remove(self.name + '-recordTask') @@ -1043,7 +1043,7 @@ class MopathRecorder(AppShell, DirectObject): self.setNewCurveMode() # Compute curve self.computeCurves() - + def recordTask(self, state): # Record raw data point time = self.recordStart + ( @@ -1324,7 +1324,7 @@ class MopathRecorder(AppShell, DirectObject): def setPlaybackSF(self, value): self.playbackSF = pow(10.0, float(value)) self.speedVar.set('%0.2f' % self.playbackSF) - + def playbackTask(self, state): time = globalClock.getFrameTime() dTime = self.playbackSF * (time - state.lastTime) @@ -1383,7 +1383,7 @@ class MopathRecorder(AppShell, DirectObject): def setDesampleFrequency(self, frequency): self.desampleFrequency = frequency - + def desampleCurve(self): if (self.curveFitter.getNumSamples() == 0): print 'MopathRecorder.desampleCurve: Must define curve first' @@ -1397,7 +1397,7 @@ class MopathRecorder(AppShell, DirectObject): def setNumSamples(self, numSamples): self.numSamples = int(numSamples) - + def sampleCurve(self, fCompute = 1, curveName = None): if self.curveCollection == None: print 'MopathRecorder.sampleCurve: Must define curve first' @@ -1429,7 +1429,7 @@ class MopathRecorder(AppShell, DirectObject): def setPathDuration(self, event): newMaxT = float(self.getWidget('Resample', 'Path Duration').get()) self.setPathDurationTo(newMaxT) - + def setPathDurationTo(self, newMaxT): # Compute scale factor sf = newMaxT/self.maxT @@ -1725,7 +1725,7 @@ class MopathRecorder(AppShell, DirectObject): ## WIDGET UTILITY FUNCTIONS ## def addWidget(self, widget, category, text): self.widgetDict[category + '-' + text] = widget - + def getWidget(self, category, text): return self.widgetDict[category + '-' + text] @@ -1763,7 +1763,7 @@ class MopathRecorder(AppShell, DirectObject): self.bind(widget, balloonHelp) self.widgetDict[category + '-' + text] = widget return widget - + def createCheckbutton(self, parent, category, text, balloonHelp, command, initialState, side = 'top', fill = Tkinter.X, expand = 0): @@ -1778,7 +1778,7 @@ class MopathRecorder(AppShell, DirectObject): self.widgetDict[category + '-' + text] = widget self.variableDict[category + '-' + text] = bool return widget - + def createRadiobutton(self, parent, side, category, text, balloonHelp, variable, value, command = None, fill = Tkinter.X, expand = 0): @@ -1790,7 +1790,7 @@ class MopathRecorder(AppShell, DirectObject): self.bind(widget, balloonHelp) self.widgetDict[category + '-' + text] = widget return widget - + def createFloater(self, parent, category, text, balloonHelp, command = None, min = 0.0, resolution = None, maxVelocity = 10.0, **kw): @@ -1948,7 +1948,7 @@ class MopathRecorder(AppShell, DirectObject): self.cCamNode.setLens(self.cLens) self.cCamNode.setScene(render) self.cCam = self.cCamera.attachNewNode(self.cCamNode) - + self.cDr.setCamera(self.cCam) def toggleWidgetVis(self): @@ -1984,8 +1984,8 @@ class MopathRecorder(AppShell, DirectObject): comboBox.selectitem(name) messenger.send('mPath_bindPathToNode',[self.playbackNodePath, self.curveCollection]) return - - + + def addCurvesFromNodepath(self,curveList): '''addCurvesFromNodepath(self,curveList) @@ -2039,7 +2039,7 @@ class namePathPanel(AppShell): label = Label(dataFrame, text='This name will be used as a reference for this Path.',font=('MSSansSerif', 10)) label.pack(side = Tkinter.TOP, expand = 0, fill = Tkinter.X) dataFrame.pack(side = Tkinter.TOP, expand = 0, fill = Tkinter.X, padx=5, pady=10) - + dataFrame = Frame(mainFrame) self.inputZone = Pmw.EntryField(dataFrame, labelpos='w', label_text = 'Name Selected Path: ', entry_font=('MSSansSerif', 10), @@ -2055,15 +2055,15 @@ class namePathPanel(AppShell): mainFrame.pack(expand = 1, fill = Tkinter.BOTH) - - + + def onDestroy(self, event): ''' If you have open any thing, please rewrite here! ''' pass - + def ok_press(self): name = self.inputZone.getvalue() messenger.send('MP_checkName',[name]) diff --git a/contrib/src/sceneeditor/seParticleEffect.py b/contrib/src/sceneeditor/seParticleEffect.py index 2292bc5856..068f8f234e 100644 --- a/contrib/src/sceneeditor/seParticleEffect.py +++ b/contrib/src/sceneeditor/seParticleEffect.py @@ -6,7 +6,7 @@ from direct.directnotify import DirectNotifyGlobal class ParticleEffect(NodePath): notify = DirectNotifyGlobal.directNotify.newCategory('ParticleEffect') - pid = 1 + pid = 1 def __init__(self, name=None, particles=None): """__init__()""" @@ -143,7 +143,7 @@ class ParticleEffect(NodePath): def getParticlesList(self): """getParticles()""" return self.particlesDict.values() - + def getParticlesNamed(self, name): """getParticlesNamed(name)""" return self.particlesDict.get(name, None) @@ -186,7 +186,7 @@ class ParticleEffect(NodePath): # Save all the particles to file num = 0 for p in self.particlesDict.values(): - target = 'p%d' % num + target = 'p%d' % num num = num + 1 f.write(target + ' = Particles.Particles(\'%s\')\n' % p.getName()) p.printParams(f, target) @@ -240,7 +240,7 @@ class ParticleEffect(NodePath): # Save all the particles to file num = 0 for p in self.particlesDict.values(): - target = 'p%d' % num + target = 'p%d' % num num = num + 1 f.write(i2+"if(mode==0):\n") f.write(i2+i1+target + ' = seParticles.Particles(\'%s\')\n' % p.getName()) diff --git a/contrib/src/sceneeditor/seParticlePanel.py b/contrib/src/sceneeditor/seParticlePanel.py index 07036567ab..099e31012d 100644 --- a/contrib/src/sceneeditor/seParticlePanel.py +++ b/contrib/src/sceneeditor/seParticlePanel.py @@ -48,16 +48,16 @@ class ParticlePanel(AppShell): pe = seParticleEffect.ParticleEffect('effect1', particles) self.particleEffect = pe self.emitter=loader.loadModel("sphere") - pe.reparentTo(self.emitter) + pe.reparentTo(self.emitter) self.emitter.setName("effect1") self.emitter.reparentTo(render) pe.enable() messenger.send('ParticlePanel_Added_Effect',['effect1',pe,self.emitter]) self.effectsDict[self.particleEffect.getName()]=self.particleEffect - + messenger.send('SGE_Update Explorer',[render]) - + # Initialize application specific info AppShell.__init__(self) diff --git a/contrib/src/sceneeditor/seParticles.py b/contrib/src/sceneeditor/seParticles.py index c2c86fad55..b062a3e00a 100644 --- a/contrib/src/sceneeditor/seParticles.py +++ b/contrib/src/sceneeditor/seParticles.py @@ -144,7 +144,7 @@ class Particles(ParticleSystem): self.renderer = SpriteParticleRenderer.SpriteParticleRenderer() if (self.renderer.getSourceType() == SpriteParticleRenderer.SpriteParticleRenderer.STTexture): - # Use current default texture + # Use current default texture # See sourceTextureName SpriteParticleRenderer-extensions.py self.renderer.setTextureFromFile() else: diff --git a/contrib/src/sceneeditor/sePlacer.py b/contrib/src/sceneeditor/sePlacer.py index f1ad920df0..108ef7fbc6 100644 --- a/contrib/src/sceneeditor/sePlacer.py +++ b/contrib/src/sceneeditor/sePlacer.py @@ -31,7 +31,7 @@ class Placer(AppShell): # Call superclass initialization function AppShell.__init__(self) - + self.initialiseoptions(Placer) # Accept the message from sceneEditor to update the information about the target nodePath @@ -44,7 +44,7 @@ class Placer(AppShell): 'placerOrbitFromCS') self.orbitToCS = SEditor.group.attachNewNode('placerOrbitToCS') self.refCS = self.tempCS - + # Dictionary keeping track of all node paths manipulated so far self.nodePathDict = {} self.nodePathDict['camera'] = SEditor.camera @@ -109,7 +109,7 @@ class Placer(AppShell): 'Toggle widget manipulation mode', label = 'Toggle Widget Mode', command = SEditor.manipulationControl.toggleObjectHandlesMode) - + # Get a handle to the menu frame menuFrame = self.menuFrame self.nodePathMenu = Pmw.ComboBox( @@ -133,7 +133,7 @@ class Placer(AppShell): menubutton_width = 8) modeMenu.pack(side = 'left', expand = 0) self.bind(modeMenu, 'Select manipulation mode') - + self.refNodePathMenu = Pmw.ComboBox( menuFrame, entry_width = 16, selectioncommand = self.selectRefNodePathNamed, @@ -190,7 +190,7 @@ class Placer(AppShell): self.posX['postCallback'] = self.xformStop self.posX['callbackData'] = ['x'] self.posX.pack(expand=1,fill='both') - + self.posY = self.createcomponent('posY', (), None, Floater, (posInterior,), text = 'Y', relief = Tkinter.FLAT, @@ -201,7 +201,7 @@ class Placer(AppShell): self.posY['postCallback'] = self.xformStop self.posY['callbackData'] = ['y'] self.posY.pack(expand=1,fill='both') - + self.posZ = self.createcomponent('posZ', (), None, Floater, (posInterior,), text = 'Z', relief = Tkinter.FLAT, @@ -228,7 +228,7 @@ class Placer(AppShell): hprMenubutton['menu'] = hprMenu hprGroup.pack(side='left',fill = 'both', expand = 1) hprInterior = hprGroup.interior() - + # Create the dials self.hprH = self.createcomponent('hprH', (), None, AngleDial, (hprInterior,), @@ -241,7 +241,7 @@ class Placer(AppShell): self.hprH['postCallback'] = self.xformStop self.hprH['callbackData'] = ['h'] self.hprH.pack(expand=1,fill='both') - + self.hprP = self.createcomponent('hprP', (), None, AngleDial, (hprInterior,), style = 'mini', @@ -253,7 +253,7 @@ class Placer(AppShell): self.hprP['postCallback'] = self.xformStop self.hprP['callbackData'] = ['p'] self.hprP.pack(expand=1,fill='both') - + self.hprR = self.createcomponent('hprR', (), None, AngleDial, (hprInterior,), style = 'mini', @@ -297,7 +297,7 @@ class Placer(AppShell): # Pack group widgets scaleGroup.pack(side='left',fill = 'both', expand = 1) scaleInterior = scaleGroup.interior() - + # Create the dials self.scaleX = self.createcomponent('scaleX', (), None, Floater, (scaleInterior,), @@ -311,7 +311,7 @@ class Placer(AppShell): self.scaleX['preCallback'] = self.xformStart self.scaleX['postCallback'] = self.xformStop self.scaleX.pack(expand=1,fill='both') - + self.scaleY = self.createcomponent('scaleY', (), None, Floater, (scaleInterior,), text = 'Y Scale', @@ -324,7 +324,7 @@ class Placer(AppShell): self.scaleY['preCallback'] = self.xformStart self.scaleY['postCallback'] = self.xformStop self.scaleY.pack(expand=1,fill='both') - + self.scaleZ = self.createcomponent('scaleZ', (), None, Floater, (scaleInterior,), text = 'Z Scale', @@ -417,7 +417,7 @@ class Placer(AppShell): else: if name == 'widget': # Record relationship between selected nodes and widget - SEditor.selected.getWrtAll() + SEditor.selected.getWrtAll() # Update active node path self.setActiveNodePath(nodePath) @@ -490,7 +490,7 @@ class Placer(AppShell): else: # Flash entry self.refNodePathMenuEntry.configure(background = 'Pink') - + def addNodePath(self, nodePath): self.addNodePathToDict(nodePath, self.nodePathNames, self.nodePathMenu, self.nodePathDict) @@ -568,7 +568,7 @@ class Placer(AppShell): else: # Move the objects with the widget SEditor.selected.moveWrtWidgetAll() - + def xformStart(self, data): # Record undo point self.pushUndo() @@ -581,7 +581,7 @@ class Placer(AppShell): self.deltaHpr = self['nodePath'].getHpr(self.refCS) # Update placer to reflect new state self.updatePlacer() - + def xformStop(self, data): # Throw event to signal manipulation done # Send nodepath as a list @@ -746,7 +746,7 @@ class Placer(AppShell): def pushRedo(self): SEditor.pushRedo([self['nodePath']]) - + def redoHook(self, nodePathList = []): # Reflect new changes self.updatePlacer() @@ -758,7 +758,7 @@ class Placer(AppShell): def redoListEmptyHook(self): # Make sure button is deactivated self.redoButton.configure(state = 'disabled') - + def printNodePathInfo(self): np = self['nodePath'] if np: @@ -787,7 +787,7 @@ class Placer(AppShell): # Also, stop accepting the updata message from sceneEditor messenger.send('Placer_close') self.ignore('placerUpdate') - + def place(nodePath): return Placer(nodePath = nodePath) diff --git a/contrib/src/sceneeditor/seSceneGraphExplorer.py b/contrib/src/sceneeditor/seSceneGraphExplorer.py index 337d16c651..a864d11e90 100644 --- a/contrib/src/sceneeditor/seSceneGraphExplorer.py +++ b/contrib/src/sceneeditor/seSceneGraphExplorer.py @@ -5,7 +5,7 @@ # # we need a customized SceneGraphExplorer. # -# Do forget to check the seTree. +# Do forget to check the seTree. # ################################################################# from direct.showbase.DirectObject import DirectObject @@ -40,25 +40,25 @@ DEFAULT_MENU_ITEMS = [ class seSceneGraphExplorer(Pmw.MegaWidget, DirectObject): "Graphical display of a scene graph" - def __init__(self, parent = None, nodePath = render, **kw): + def __init__(self, parent = None, nodePath = render, **kw): # Define the megawidget options. optiondefs = ( ('menuItems', [], Pmw.INITOPT), ) self.defineoptions(kw, optiondefs) - + # Initialise superclass Pmw.MegaWidget.__init__(self, parent) - + # Initialize some class variables self.nodePath = nodePath # Create the components. - + # Setup up container interior = self.interior() interior.configure(relief = Tkinter.GROOVE, borderwidth = 2) - + # Create a label and an entry self._scrolledCanvas = self.createcomponent( 'scrolledCanvas', @@ -70,14 +70,14 @@ class seSceneGraphExplorer(Pmw.MegaWidget, DirectObject): self._canvas['scrollregion'] = ('0i', '0i', '2i', '4i') self._scrolledCanvas.resizescrollregion() self._scrolledCanvas.pack(padx = 3, pady = 3, expand=1, fill = Tkinter.BOTH) - + self._canvas.bind('', self.mouse2Down) self._canvas.bind('', self.mouse2Motion) self._canvas.bind('', lambda e, sc = self._scrolledCanvas: sc.resizescrollregion()) self.interior().bind('', self.onDestroy) - + # Create the contents self._treeItem = SceneGraphExplorerItem(self.nodePath) @@ -114,7 +114,7 @@ class seSceneGraphExplorer(Pmw.MegaWidget, DirectObject): self._width = 1.0 * self._canvas.winfo_width() self._height = 1.0 * self._canvas.winfo_height() xview = self._canvas.xview() - yview = self._canvas.yview() + yview = self._canvas.yview() self._left = xview[0] self._top = yview[0] self._dxview = xview[1] - xview[0] diff --git a/contrib/src/sceneeditor/seSelection.py b/contrib/src/sceneeditor/seSelection.py index 1e9811f390..73cdb1ea46 100644 --- a/contrib/src/sceneeditor/seSelection.py +++ b/contrib/src/sceneeditor/seSelection.py @@ -35,7 +35,7 @@ class DirectNodePath(NodePath): self.mCoa2Dnp = Mat4(Mat4.identMat()) if SEditor.coaMode == COA_CENTER: self.mCoa2Dnp.setRow(3, Vec4(center[0], center[1], center[2], 1)) - + # Transform from nodePath to widget self.tDnp2Widget = TransformState.makeIdentity() @@ -72,11 +72,11 @@ class SelectedNodePaths(DirectObject): if not nodePath: print 'Nothing selected!!' return None - + # Reset selected objects and highlight if multiSelect is false if not fMultiSelect: self.deselectAll() - + # Get this pointer id = nodePath.id() # First see if its already in the selected dictionary @@ -199,7 +199,7 @@ class SelectedNodePaths(DirectObject): if selected: selected.remove() __builtins__["last"] = self.last = None - + def removeAll(self): # Remove all selected nodePaths from the Scene Graph self.forEachSelectedNodePathDo(NodePath.remove) @@ -258,7 +258,7 @@ class DirectBoundingBox: # Restore transform self.nodePath.setMat(tMat) del tMat - + def computeBounds(self): self.bounds = self.getBounds() if self.bounds.isEmpty() or self.bounds.isInfinite(): @@ -269,7 +269,7 @@ class DirectBoundingBox: self.radius = self.bounds.getRadius() self.min = Point3(self.center - Point3(self.radius)) self.max = Point3(self.center + Point3(self.radius)) - + def createBBoxLines(self): # Create a line segments object for the bbox lines = LineNodePath(hidden) @@ -283,7 +283,7 @@ class DirectBoundingBox: maxX = self.max[0] maxY = self.max[1] maxZ = self.max[2] - + # Bottom face lines.moveTo( minX, minY, minZ ) lines.drawTo( maxX, minY, minZ ) @@ -308,22 +308,22 @@ class DirectBoundingBox: # Create and return bbox lines lines.create() - + # Make sure bbox is never lit or drawn in wireframe useDirectRenderStyle(lines) - + return lines def updateBBoxLines(self): ls = self.lines.lineSegs - + minX = self.min[0] minY = self.min[1] minZ = self.min[2] maxX = self.max[0] maxY = self.max[1] maxZ = self.max[2] - + # Bottom face ls.setVertex( 0, minX, minY, minZ ) ls.setVertex( 1, maxX, minY, minZ ) @@ -359,7 +359,7 @@ class DirectBoundingBox: def hide(self): self.lines.reparentTo(hidden) - + def getCenter(self): return self.center @@ -376,7 +376,7 @@ class DirectBoundingBox: return '%.2f %.2f %.2f' % (vec[0], vec[1], vec[2]) def __repr__(self): - return (`self.__class__` + + return (`self.__class__` + '\nNodePath:\t%s\n' % self.nodePath.getName() + 'Min:\t\t%s\n' % self.vecAsString(self.min) + 'Max:\t\t%s\n' % self.vecAsString(self.max) + @@ -533,7 +533,7 @@ class SelectionRay(SelectionQueue): # Initialize the superclass SelectionQueue.__init__(self, parentNP) self.addCollider(CollisionRay()) - + def pick(self, targetNodePath, xy = None): # Determine ray direction based upon the mouse coordinates if xy: @@ -553,7 +553,7 @@ class SelectionRay(SelectionQueue): #mx = base.mouseWatcherNode.getMouseX()+1 #my = base.mouseWatcherNode.getMouseY()+1 #print base.camNode.getName() - #print "Arrived X" + str(mx) + " Arrived Y " + str(my) + #print "Arrived X" + str(mx) + " Arrived Y " + str(my) self.collider.setFromLens( base.camNode, mx, my ) self.ct.traverse( targetNodePath ) @@ -587,7 +587,7 @@ class SelectionRay(SelectionQueue): self.collider.setDirection( dir ) self.ct.traverse( targetNodePath ) self.sortEntries() - + def pickGeom3D(self, targetNodePath = render, origin = Point3(0), dir = Vec3(0,0,-1), skipFlags = SKIP_HIDDEN | SKIP_CAMERA ): @@ -616,7 +616,7 @@ class SelectionSegment(SelectionQueue): self.numColliders = 0 for i in range(numSegments): self.addCollider(CollisionSegment()) - + def addCollider(self, collider): # Record new collision object self.colliders.append(collider) @@ -659,30 +659,30 @@ class SelectionSphere(SelectionQueue): self.numColliders = 0 for i in range(numSpheres): self.addCollider(CollisionSphere(Point3(0), 1)) - + def addCollider(self, collider): # Record new collision object self.colliders.append(collider) # Add the collider to the collision Node self.collisionNode.addSolid( collider ) self.numColliders += 1 - + def setCenter(self, i, center): c = self.colliders[i] c.setCenter(center) - + def setRadius(self, i, radius): c = self.colliders[i] c.setRadius(radius) - + def setCenterRadius(self, i, center, radius): c = self.colliders[i] c.setCenter(center) c.setRadius(radius) - + def isEntryBackfacing(self, entry): # If dot product of collision point surface normal and - # ray from sphere origin to collision point is positive, + # ray from sphere origin to collision point is positive, # center is on the backside of the polygon fromNodePath = entry.getFromNodePath() v = Vec3(entry.getSurfacePoint(fromNodePath) - @@ -706,7 +706,7 @@ class SelectionSphere(SelectionQueue): skipFlags = SKIP_HIDDEN | SKIP_CAMERA ): self.collideWithGeom() return self.pick(targetNodePath, skipFlags) - + def pickBitMask(self, bitMask = BitMask32.allOff(), targetNodePath = render, skipFlags = SKIP_HIDDEN | SKIP_CAMERA ): diff --git a/contrib/src/sceneeditor/seSession.py b/contrib/src/sceneeditor/seSession.py index 7fb9325098..95f235829b 100644 --- a/contrib/src/sceneeditor/seSession.py +++ b/contrib/src/sceneeditor/seSession.py @@ -49,7 +49,7 @@ class SeSession(DirectObject): ### Customized DirectSession self.useObjectHandles() self.grid = DirectGrid() self.grid.disable() - + # Initialize the collection of selected nodePaths self.selected = SelectedNodePaths() # Ancestry of currently selected object @@ -94,19 +94,19 @@ class SeSession(DirectObject): ### Customized DirectSession # Lists for managing undo/redo operations self.undoList = [] self.redoList = [] - + # One run through the context task to init everything self.drList.updateContext() for dr in self.drList: dr.camUpdate() - + self.modifierEvents = ['control', 'control-up', 'shift', 'shift-up', 'alt', 'alt-up', ] - self.keyEvents = ['escape', 'delete', 'page_up', 'page_down', + self.keyEvents = ['escape', 'delete', 'page_up', 'page_down', '[', '{', ']', '}', 'shift-a', 'b', 'control-f', 'l', 'shift-l', 'o', 'p', 'r', @@ -124,7 +124,7 @@ class SeSession(DirectObject): ### Customized DirectSession 'control-mouse3', 'control-mouse3-up', 'alt-mouse3', 'alt-mouse3-up', ] - + def enable(self): if self.fEnabled: return @@ -361,7 +361,7 @@ class SeSession(DirectObject): ### Customized DirectSession elif (input == ']') or (input == '}'): self.redo() - + def getModifiers(self, input, base): modifiers = DIRECT_NO_MOD modifierString = input[: input.find(base)] @@ -405,7 +405,7 @@ class SeSession(DirectObject): ### Customized DirectSession self.cameraControl.updateCoa(coa) # Adjust widgets size # This uses the additional scaling factor used to grow and - # shrink the widget + # shrink the widget self.widget.setScalingFactor(dnp.getRadius()) # Spawn task to have object handles follow the selected object taskMgr.remove('followSelectedNodePath') @@ -462,7 +462,7 @@ class SeSession(DirectObject): ### Customized DirectSession 'Active Reparent Target:' + nodePath.getName()) # Alert everyone else self.activeParentReadout.show() - + def reparent(self, nodePath = None, fWrt = 0): if (nodePath and self.activeParent and self.isNotCycle(nodePath, self.activeParent)): @@ -486,7 +486,7 @@ class SeSession(DirectObject): ### Customized DirectSession return self.isNotCycle(nodePath, parent.getParent()) else: return 1 - + def fitOnNodePath(self, nodePath = 'None Given'): if nodePath == 'None Given': # If nothing specified, try selected node path @@ -553,7 +553,7 @@ class SeSession(DirectObject): ### Customized DirectSession if (name != 'render') and (name != 'renderTop')and(self.checkTypeNameForAncestry(type, ntype)): self.ancestryIndex = i self.select(np, 0, 0, True) - + def checkTypeNameForAncestry(self, type, nextType ): if (type=='ModelRoot'): if (nextType=='AmbientLight')or(nextType=='PointLight')or(nextType=='DirectionalLight')or(nextType=='Spotlight'): @@ -620,7 +620,7 @@ class SeSession(DirectObject): ### Customized DirectSession messenger.send('DIRECT_undoListEmpty') # Return last item return undoGroup - + def pushRedo(self, nodePathList): # Assemble group of changes redoGroup = [] @@ -644,7 +644,7 @@ class SeSession(DirectObject): ### Customized DirectSession messenger.send('DIRECT_redoListEmpty') # Return last item return redoGroup - + def undo(self): if self.undoList: # Get last item off of redo list @@ -736,7 +736,7 @@ class SeSession(DirectObject): ### Customized DirectSession print posE, hprE posInterval1 = base.camera.posInterval(time, posE, bakeInStart = 1) posInterval2 = base.camera.posInterval(time, posB, bakeInStart = 1) - + hprInterval1 = base.camera.hprInterval(time, hprE, bakeInStart = 1) hprInterval2 = base.camera.hprInterval(time, hprB, bakeInStart = 1) @@ -744,9 +744,9 @@ class SeSession(DirectObject): ### Customized DirectSession parallel2 = Parallel(posInterval2, hprInterval2) Sequence(Wait(7), parallel1, Wait(1), parallel2).start() - + return - + class DisplayRegionContext(DirectObject): regionCount = 0 @@ -833,14 +833,14 @@ class DisplayRegionContext(DirectObject): return prop.getXSize() else: return 640 - + def getHeight(self): prop = base.win.getProperties() if prop.hasSize(): return prop.getYSize() else: return 480 - + def camUpdate(self, lens = None): # Window Data self.near = self.camLens.getNear() @@ -885,7 +885,7 @@ class DisplayRegionList(DirectObject): else: # MRM: Doesn't properly handle multiple camera groups anymore # Assumes everything is under main camera - + # This is following the old way of setting up # display regions. A display region is set up for # each camera node in the scene graph. This was done @@ -920,11 +920,11 @@ class DisplayRegionList(DirectObject): def setNearFar(self, near, far): for dr in self.displayRegionList: dr.camLens.setNearFar(near, far) - + def setNear(self, near): for dr in self.displayRegionList: dr.camLens.setNear(near) - + def setFar(self, far): for dr in self.displayRegionList: dr.camLens.setFar(far) diff --git a/contrib/src/sceneeditor/seTree.py b/contrib/src/sceneeditor/seTree.py index 4bcf1e2db0..018d6af410 100644 --- a/contrib/src/sceneeditor/seTree.py +++ b/contrib/src/sceneeditor/seTree.py @@ -54,7 +54,7 @@ class TreeNode: value = i, indicatoron = 0, command = self.popupMenuCommand) - + def destroy(self): for key in self.kidKeys: c = self.children[key] @@ -257,7 +257,7 @@ class TreeNode: self.canvas.tag_bind(id, "<1>", self.select) self.canvas.tag_bind(id, "", self.flip) self.canvas.tag_bind(id, "<3>", self.popupMenu) - + def drawtext(self, text=None): textx = self.x+20-1 texty = self.y-1 @@ -410,7 +410,7 @@ class TreeItem: def OnSelect(self): """Called when item selected.""" - + def GetTextForEdit(self): """Called before editting the item.""" diff --git a/direct/src/actor/Actor.py b/direct/src/actor/Actor.py index 8db72857e8..1db0c859a3 100644 --- a/direct/src/actor/Actor.py +++ b/direct/src/actor/Actor.py @@ -25,7 +25,7 @@ class Actor(DirectObject, NodePath): validateSubparts = ConfigVariableBool('validate-subparts', True) mergeLODBundles = ConfigVariableBool('merge-lod-bundles', True) allowAsyncBind = ConfigVariableBool('allow-async-bind', True) - + class PartDef: """Instances of this class are stored within the @@ -34,7 +34,7 @@ class Actor(DirectObject, NodePath): model file is a different PartBundle. This can include the multiple different LOD's, as well as the multiple different pieces of a multipart Actor. """ - + def __init__(self, partBundleNP, partBundleHandle, partModel): # We also save the ModelRoot node along with the # PartBundle, so that the reference count in the ModelPool @@ -45,7 +45,7 @@ class Actor(DirectObject, NodePath): def getBundle(self): return self.partBundleHandle.getBundle() - + def __repr__(self): return 'Actor.PartDef(%s, %s)' % (repr(self.partBundleNP), repr(self.partModel)) @@ -59,7 +59,7 @@ class Actor(DirectObject, NodePath): There is a different AnimDef for each different part or sub-part, times each different animation in the AnimDict. """ - + def __init__(self, filename = None, animBundle = None): self.filename = filename self.animBundle = None @@ -86,8 +86,8 @@ class Actor(DirectObject, NodePath): def makeCopy(self): return Actor.SubpartDef(self.truePartName, PartSubset(self.subset)) - - + + def __repr__(self): return 'Actor.SubpartDef(%s, %s)' % (repr(self.truePartName), repr(self.subset)) @@ -171,7 +171,7 @@ class Actor(DirectObject, NodePath): # When this flag is true, __animControlDict has only one key, # ['common']; when it is false, __animControlDict has one key # per each LOD name. - + if mergeLODBundles is None: # If this isn't specified, it comes from the Config.prc # file. @@ -223,7 +223,7 @@ class Actor(DirectObject, NodePath): root.setPreserveTransform(1) self.assign(NodePath(root)) self.setGeomNode(self.attachNewNode(ModelNode('actorGeom'))) - + self.__hasLOD = 0 # load models @@ -340,7 +340,7 @@ class Actor(DirectObject, NodePath): def copyActor(self, other, overwrite=False): # act like a copy constructor self.gotName = other.gotName - + # copy the scene graph elements of other if (overwrite): otherCopy = other.copyTo(NodePath()) @@ -370,7 +370,7 @@ class Actor(DirectObject, NodePath): self.__copyPartBundles(other) self.__copySubpartDict(other) self.__subpartsComplete = other.__subpartsComplete - + # copy the anim dictionary from other self.__copyAnimControls(other) @@ -444,7 +444,7 @@ class Actor(DirectObject, NodePath): for lodName, partDict in self.__animControlDict.items(): if self.mergeLODBundles: lodName = self.__sortedLODNames[0] - + partInfo = [] for partName in partDict.keys(): subpartDef = self.__subpartDict.get(partName, Actor.SubpartDef(partName)) @@ -513,7 +513,7 @@ class Actor(DirectObject, NodePath): self.__subpartDict = {} self.__sortedLODNames = [] self.__animControlDict = {} - + def flush(self): """ Actor flush function @@ -527,7 +527,7 @@ class Actor(DirectObject, NodePath): # remove all its children if self.__geomNode: self.__geomNode.getChildren().detach() - + self.__hasLOD = 0 # accessing @@ -544,9 +544,9 @@ class Actor(DirectObject, NodePath): def getPartBundles(self, partName = None): """ Returns a list of PartBundle objects for the entire Actor, or for the indicated part only. """ - + bundles = [] - + for lodName, partBundleDict in self.__partBundleDict.items(): if partName == None: for partDef in partBundleDict.values(): @@ -635,7 +635,7 @@ class Actor(DirectObject, NodePath): self.__LODNode = self.__geomNode.attachNewNode(node) self.__hasLOD = 1 self.switches = {} - + def useLOD(self, lodName): """ @@ -646,7 +646,7 @@ class Actor(DirectObject, NodePath): ## sortedKeys = self.switches.keys() ## sortedKeys.sort() child = self.__LODNode.find(str(lodName)) - index = self.__LODNode.node().findChild(child.node()) + index = self.__LODNode.node().findChild(child.node()) self.__LODNode.node().forceSwitch(index) def printLOD(self): @@ -705,7 +705,7 @@ class Actor(DirectObject, NodePath): safe method (but expensive) for retrieving the child index """ return list(self.__LODNode.getChildren()).index(self.getLOD(lodName)) - + def getLOD(self, lodName): """getLOD(self, string) Get the named node under the LOD to which we parent all LOD @@ -754,7 +754,7 @@ class Actor(DirectObject, NodePath): away. """ self.__LODAnimation = (farDistance, nearDistance, delayFactor) - + for lodData in self.__partBundleDict.values(): for partData in lodData.values(): char = partData.partBundleNP @@ -781,7 +781,7 @@ class Actor(DirectObject, NodePath): If force is True, this will update every joint, even if we don't believe it's necessary. - + Returns True if any joint has changed as a result of this, False otherwise. """ @@ -907,7 +907,7 @@ class Actor(DirectObject, NodePath): """ if len(self.__animControlDict.items()) == 0: return - + lodName, animControlDict = self.__animControlDict.items()[0] if partName == None: partName, animDict = animControlDict.items()[0] @@ -1138,7 +1138,7 @@ class Actor(DirectObject, NodePath): """ Returns the list of all joints, from the named part or from all parts, that match the indicated jointName. The jointName may include pattern characters like *. """ - + joints=[] pattern = GlobPattern(jointName) @@ -1219,7 +1219,7 @@ class Actor(DirectObject, NodePath): for child in partNode.getChildren(): self.__getPartJoints(joints, pattern, child, subset, isIncluded) - + def getJointTransform(self, partName, jointName, lodName='lodRoot'): partBundleDict=self.__partBundleDict.get(lodName) if not partBundleDict: @@ -1278,7 +1278,7 @@ class Actor(DirectObject, NodePath): subpartDef = self.__subpartDict.get(partName, Actor.SubpartDef(partName)) trueName = subpartDef.truePartName anyGood = False - for bundleDict in self.__partBundleDict.values(): + for bundleDict in self.__partBundleDict.values(): bundle = bundleDict[trueName].getBundle() if node == None: node = self.attachNewNode(ModelNode(jointName)) @@ -1308,20 +1308,20 @@ class Actor(DirectObject, NodePath): subpartDef = self.__subpartDict.get(partName, Actor.SubpartDef(partName)) trueName = subpartDef.truePartName anyGood = False - for bundleDict in self.__partBundleDict.values(): + for bundleDict in self.__partBundleDict.values(): if bundleDict[trueName].getBundle().freezeJoint(jointName, transform): anyGood = True if not anyGood: self.notify.warning("Cannot freeze joint %s" % (jointName)) - + def releaseJoint(self, partName, jointName): """Undoes a previous call to controlJoint() or freezeJoint() and restores the named joint to its normal animation. """ subpartDef = self.__subpartDict.get(partName, Actor.SubpartDef(partName)) trueName = subpartDef.truePartName - for bundleDict in self.__partBundleDict.values(): + for bundleDict in self.__partBundleDict.values(): bundleDict[trueName].getBundle().releaseJoint(jointName) def instance(self, path, partName, jointName, lodName="lodRoot"): @@ -1477,8 +1477,8 @@ class Actor(DirectObject, NodePath): for geomNum in xrange(numGeoms): thisGeom = thisGeomNode.node().getGeom(geomNum) thisGeom.markBoundsStale() - thisGeomNode.node().markInternalBoundsStale() - + thisGeomNode.node().markInternalBoundsStale() + def fixBounds_old(self, part=None): """fixBounds(self, nodePath=None) Force recomputation of bounding spheres for all geoms @@ -1569,7 +1569,7 @@ class Actor(DirectObject, NodePath): is given then try to loop on all parts. NOTE: loops on all LOD's """ - + if fromFrame == None: for control in self.getAnimControls(animName, partName): control.loop(restart) @@ -1614,7 +1614,7 @@ class Actor(DirectObject, NodePath): The animBlend and frameBlend parameters are boolean flags. You may set either or both to True or False. If you do not specify them, they do not change from the previous value. - + When animBlend is True, multiple different animations may simultaneously be playing on the Actor. This means you may call play(), loop(), or pose() on multiple animations and have @@ -1683,7 +1683,7 @@ class Actor(DirectObject, NodePath): the overall pose. This controls blending of multiple animations; it only makes sense to call this after a previous call to setBlend(animBlend = True). - """ + """ for control in self.getAnimControls(animName, partName, lodName): control.getPart().setControlEffect(control, effect) @@ -1712,7 +1712,7 @@ class Actor(DirectObject, NodePath): a given anim and part. If none specified, try the first part and lod. Return the animControl if present, or None otherwise. """ - + if not partName: partName = 'modelRoot' @@ -1775,7 +1775,7 @@ class Actor(DirectObject, NodePath): # is specified, it really means to play the animation on # all subparts, not on the overall Actor. partName = self.__subpartDict.keys() - + controls = [] # build list of lodNames and corresponding animControlDicts # requested. @@ -1808,7 +1808,7 @@ class Actor(DirectObject, NodePath): partNameList = partName animDictItems = [] - + for pName in partNameList: animDict = partDict.get(pName) if animDict == None: @@ -1870,7 +1870,7 @@ class Actor(DirectObject, NodePath): # Force the animation to load if it's # not already loaded. animControl.waitPending() - + if animControl: controls.append(animControl) @@ -1900,7 +1900,7 @@ class Actor(DirectObject, NodePath): # If copy = 0, then we should always hit the disk. loaderOptions = LoaderOptions(loaderOptions) loaderOptions.setFlags(loaderOptions.getFlags() & ~LoaderOptions.LFNoRamCache) - + # Pass loaderOptions to specify that we want to # get the skeleton model. This only matters to model # files (like .mb) for which we can choose to extract @@ -1914,7 +1914,7 @@ class Actor(DirectObject, NodePath): bundleNP = model else: bundleNP = model.find("**/+Character") - + if (bundleNP.isEmpty()): Actor.notify.warning("%s is not a character!" % (modelPath)) model.reparentTo(self.__geomNode) @@ -2048,7 +2048,7 @@ class Actor(DirectObject, NodePath): joints = self.getOverlappingJoints(partName, otherPartName) if joints: raise StandardError, 'Overlapping joints: %s and %s' % (partName, otherPartName) - + def setSubpartsComplete(self, flag): """Sets the subpartsComplete flag. This affects the behavior @@ -2070,7 +2070,7 @@ class Actor(DirectObject, NodePath): It makes sense to set this True when the union of all of your subparts completely defines the entire Actor. """ - + self.__subpartsComplete = flag if __dev__ and self.__subpartsComplete and self.validateSubparts.getValue(): @@ -2078,11 +2078,11 @@ class Actor(DirectObject, NodePath): # specified all of them. if self.__subpartDict: self.verifySubpartsComplete() - + def getSubpartsComplete(self): """See setSubpartsComplete().""" - + return self.__subpartsComplete def verifySubpartsComplete(self, partName = None, lodName = None): @@ -2128,7 +2128,7 @@ class Actor(DirectObject, NodePath): lodNames[i] = str(lodNames[i]) else: lodNames = [lodName] - + assert Actor.notify.debug("in loadAnims: %s, part: %s, lod: %s" % (anims, partName, lodNames[0])) @@ -2172,7 +2172,7 @@ class Actor(DirectObject, NodePath): lodNames = ['common'] else: lodNames = self.__partBundleDict.keys() - + for lod in lodNames: for part in partNames: self.__animControlDict.setdefault(lod,{}) @@ -2183,9 +2183,9 @@ class Actor(DirectObject, NodePath): # for lod in self.__partBundleDict.keys(): # # store the file path only; we will bind it (and produce # # an AnimControl) when it is played - # + # # self.__animControlDict[lod][partName][animName] = Actor.AnimDef(filename) - + def loadAnimsOnAllLODs(self, anims,partName="modelRoot"): """loadAnims(self, string:string{}, string='modelRoot', string='lodRoot') @@ -2198,13 +2198,13 @@ class Actor(DirectObject, NodePath): lodNames = ['common'] else: lodNames = self.__partBundleDict.keys() - + for animName, filename in anims.items(): # make sure this lod is in anim control dict for lod in lodNames: # store the file path only; we will bind it (and produce # an AnimControl) when it is played - + self.__animControlDict[lod][partName][animName]= Actor.AnimDef(filename) def postFlatten(self): @@ -2213,7 +2213,7 @@ class Actor(DirectObject, NodePath): especially necessary when mergeLODBundles is true, since this kind of actor may be broken after a flatten operation; this method should restore proper Actor functionality. """ - + if self.mergeLODBundles: # Re-merge all bundles, and restore the common bundle map. self.__commonBundleHandles = {} @@ -2226,11 +2226,11 @@ class Actor(DirectObject, NodePath): partDef.partBundleHandle = loadedBundleHandle else: self.__commonBundleHandles[partName] = partDef.partBundleHandle - + # Since we may have merged together some bundles, all of # our anims are now suspect. Force them to reload. self.unloadAnims() - + def unloadAnims(self, anims=None, partName=None, lodName=None): """unloadAnims(self, string:string{}, string='modelRoot', string='lodRoot') @@ -2401,7 +2401,7 @@ class Actor(DirectObject, NodePath): for partName, partDef in other.__partBundleDict[lodName].items(): # We can really only copy from a non-flattened avatar. assert partDef.partBundleNP.node().getNumBundles() == 1 - + # find the part in our tree bundleNP = partLod.find("**/%s%s"%(Actor.partPrefix,partName)) if (bundleNP != None): @@ -2498,7 +2498,7 @@ class Actor(DirectObject, NodePath): result.append((lodName, animList)) return result - + def printAnimBlends(self, animName=None, partName=None, lodName=None): for lodName, animList in self.getAnimBlends(animName, partName, lodName): print 'LOD %s:' % (lodName) diff --git a/direct/src/actor/DistributedActor.py b/direct/src/actor/DistributedActor.py index 1c56c805cf..2e991d2043 100644 --- a/direct/src/actor/DistributedActor.py +++ b/direct/src/actor/DistributedActor.py @@ -11,11 +11,11 @@ class DistributedActor(DistributedNode.DistributedNode, Actor.Actor): try: self.DistributedActor_initialized except: - self.DistributedActor_initialized = 1 - Actor.Actor.__init__(self) + self.DistributedActor_initialized = 1 + Actor.Actor.__init__(self) DistributedNode.DistributedNode.__init__(self, cr) # Since actors are probably fairly heavyweight, we'd - # rather cache them than delete them if possible. + # rather cache them than delete them if possible. self.setCacheable(1) def disable(self): @@ -28,10 +28,10 @@ class DistributedActor(DistributedNode.DistributedNode, Actor.Actor): try: self.DistributedActor_deleted except: - self.DistributedActor_deleted = 1 + self.DistributedActor_deleted = 1 DistributedNode.DistributedNode.delete(self) Actor.Actor.delete(self) - def loop(self, animName, restart=1, partName=None, fromFrame=None, toFrame=None): + def loop(self, animName, restart=1, partName=None, fromFrame=None, toFrame=None): return Actor.Actor.loop(self, animName, restart, partName, fromFrame, toFrame) diff --git a/direct/src/cluster/ClusterClient.py b/direct/src/cluster/ClusterClient.py index 4dca3a1379..f238aca91d 100644 --- a/direct/src/cluster/ClusterClient.py +++ b/direct/src/cluster/ClusterClient.py @@ -147,7 +147,7 @@ class ClusterClient(DirectObject.DirectObject): if (serverList == None): serverList = range(len(self.serverList)) - + for server in serverList: self.serverList[server].sendNamedMovementDone() @@ -161,7 +161,7 @@ class ClusterClient(DirectObject.DirectObject): key]) self.sortedControlMappings.sort() - + def moveObject(self, nodePath, object, serverList, offset, hasColor = True): self.notify.debug('moving object '+object) xyz = nodePath.getPos(render) + offset @@ -222,7 +222,7 @@ class ClusterClient(DirectObject.DirectObject): serverList = range(len(self.serverList)) if (offset == None): offset = Vec3(0,0,0) - + self.controlMappings[objectName] = [controlledName,serverList] self.controlOffsets[objectName] = offset self.controlPriorities[objectName] = priority @@ -247,7 +247,7 @@ class ClusterClient(DirectObject.DirectObject): if (serverList == None): self.controlMappings.pop(name) - self.controlPriorities.pop(name) + self.controlPriorities.pop(name) else: list = self.controlMappings[key][1] newList = [] @@ -260,7 +260,7 @@ class ClusterClient(DirectObject.DirectObject): self.controlPriorities.pop(name) self.redoSortedPriorities() - + def getNodePathFindCmd(self, nodePath): import string pathString = repr(nodePath) @@ -288,14 +288,14 @@ class ClusterClient(DirectObject.DirectObject): newTag["selectFunction"] = selectFunction newTag["selectArgs"] = selectArgs newTag["deselectFunction"] = deselectFunction - newTag["deselectArgs"] = deselectArgs + newTag["deselectArgs"] = deselectArgs self.taggedObjects[object] = newTag def removeObjectTag(self,object): self.taggedObjects.pop(object) - + def selectNodePath(self, nodePath): name = self.getNodePathName(nodePath) @@ -308,14 +308,14 @@ class ClusterClient(DirectObject.DirectObject): function(*args) else: self(self.getNodePathFindCmd(nodePath) + '.select()', 0) - + def deselectNodePath(self, nodePath): name = self.getNodePathName(nodePath) if name in self.taggedObjects: tag = self.taggedObjects[name] function = tag["deselectFunction"] - args = tag["deselectArgs"] + args = tag["deselectArgs"] if (function != None): function(*args) self.startMoveSelectedTask() @@ -372,12 +372,12 @@ class ClusterClient(DirectObject.DirectObject): # clear the queue self.serverQueues[server] = [] - + def handleNamedMovement(self, data): """ Update cameraJig position to reflect latest position """ - - (name,x, y, z, h, p, r, sx, sy, sz,red,g,b,a, hidden) = data + + (name,x, y, z, h, p, r, sx, sy, sz,red,g,b,a, hidden) = data #print "name" #if (name == "camNode"): # print x,y,z,h,p,r, sx, sy, sz,red,g,b,a, hidden diff --git a/direct/src/cluster/ClusterMsgs.py b/direct/src/cluster/ClusterMsgs.py index e06deeb132..ba166f7c09 100644 --- a/direct/src/cluster/ClusterMsgs.py +++ b/direct/src/cluster/ClusterMsgs.py @@ -166,7 +166,7 @@ class ClusterMsgHandler: self.packetNumber = self.packetNumber + 1 datagram.addUint8(CLUSTER_NAMED_MOVEMENT_DONE) return datagram - + def makeNamedObjectMovementDatagram(self, xyz, hpr, scale, color, hidden, name): datagram = PyDatagram() @@ -186,9 +186,9 @@ class ClusterMsgHandler: datagram.addFloat32(color[0]) datagram.addFloat32(color[1]) datagram.addFloat32(color[2]) - datagram.addFloat32(color[3]) + datagram.addFloat32(color[3]) datagram.addBool(hidden) - return datagram + return datagram def parseCamMovementDatagram(self, dgi): x=dgi.getFloat32() @@ -215,7 +215,7 @@ class ClusterMsgHandler: red = dgi.getFloat32() g = dgi.getFloat32() b = dgi.getFloat32() - a = dgi.getFloat32() + a = dgi.getFloat32() hidden = dgi.getBool() return (name,x, y, z, h, p, r, sx, sy, sz, red, g, b, a, hidden) diff --git a/direct/src/cluster/ClusterServer.py b/direct/src/cluster/ClusterServer.py index 0e5cea0e0d..4ec78b0841 100644 --- a/direct/src/cluster/ClusterServer.py +++ b/direct/src/cluster/ClusterServer.py @@ -138,7 +138,7 @@ class ClusterServer(DirectObject.DirectObject): def setControlMappingOffset(self,objectName,offset): if (objectName in self.controlMappings): self.controlOffsets[objectName] = offset - + def removeControlMapping(self,name): if (name in self.controlMappings): @@ -146,7 +146,7 @@ class ClusterServer(DirectObject.DirectObject): self.controlPriorities.pop(name) self.redoSortedPriorities() - + def startControlObjectTask(self): self.notify.debug("moving control objects") taskMgr.add(self.controlObjectTask,"controlObjectTask",50) @@ -155,7 +155,7 @@ class ClusterServer(DirectObject.DirectObject): #print "running control object task" for pair in self.sortedControlPriorities: object = pair[1] - name = self.controlMappings[object] + name = self.controlMappings[object] if (object in self.objectMappings): self.moveObject(self.objectMappings[object],name,self.controlOffsets[object], self.objectHasColor[object]) @@ -169,7 +169,7 @@ class ClusterServer(DirectObject.DirectObject): self.notify.debug("named movement done") datagram = self.msgHandler.makeNamedMovementDone() self.cw.send(datagram,self.lastConnection) - + def moveObject(self, nodePath, object, offset, hasColor): self.notify.debug('moving object '+object) #print "moving object",object @@ -322,7 +322,7 @@ class ClusterServer(DirectObject.DirectObject): """ Update cameraJig position to reflect latest position """ (x, y, z, h, p, r) = self.msgHandler.parseCamMovementDatagram(dgi) self.cameraJig.setPosHpr(render, x, y, z, h, p, r) - self.fPosReceived = 1 + self.fPosReceived = 1 def handleSelectedMovement(self, dgi): """ Update cameraJig position to reflect latest position """ diff --git a/direct/src/controls/BattleWalker.py b/direct/src/controls/BattleWalker.py index 922ce7bfee..8b6e634e25 100755 --- a/direct/src/controls/BattleWalker.py +++ b/direct/src/controls/BattleWalker.py @@ -36,12 +36,12 @@ class BattleWalker(GravityWalker.GravityWalker): slideLeft = inputState.isSet("slideLeft") slideRight = inputState.isSet("slideRight") jump = inputState.isSet("jump") - + # Check for Auto-Run if base.localAvatar.getAutoRun(): forward = 1 reverse = 0 - + # Determine what the speeds are based on the buttons: self.speed=(forward and self.avatarControlForwardSpeed or reverse and -self.avatarControlReverseSpeed) @@ -58,7 +58,7 @@ class BattleWalker(GravityWalker.GravityWalker): self.speed*=base.debugRunningMultiplier self.slideSpeed*=base.debugRunningMultiplier self.rotationSpeed*=1.25 - + if self.needToDeltaPos: self.setPriorParentVector() self.needToDeltaPos = 0 diff --git a/direct/src/controls/ControlManager.py b/direct/src/controls/ControlManager.py index 13f0d6b9a9..bc3aad3ff2 100755 --- a/direct/src/controls/ControlManager.py +++ b/direct/src/controls/ControlManager.py @@ -37,9 +37,9 @@ class ControlManager: self.enable() #self.monitorTask = taskMgr.add(self.monitor, "ControlManager-%s"%(id(self)), priority=-1) self.forceAvJumpToken = None - - - + + + if self.passMessagesThrough: # for not breaking toontown ist=self.inputStateTokens ist.append(inputState.watchWithModifiers("forward", "arrow_up", inputSource=inputState.ArrowKeys)) @@ -50,7 +50,7 @@ class ControlManager: def __str__(self): return 'ControlManager: using \'%s\'' % self.currentControlsName - + def add(self, controls, name="basic"): """ controls is an avatar control system. @@ -75,7 +75,7 @@ class ControlManager: def get(self, name): return self.controls.get(name) - + def remove(self, name): """ name is any key that was used to refer to the @@ -166,7 +166,7 @@ class ControlManager: if self.currentControls: return self.currentControls.getIsAirborne() return False - + def setTag(self, key, value): assert self.notify.debugCall(id(self)) for controls in self.controls.values(): @@ -181,7 +181,7 @@ class ControlManager: assert self.notify.debugCall(id(self)) if self.currentControls: self.currentControls.setCollisionsActive(1) - + def collisionsOff(self): assert self.notify.debugCall(id(self)) if self.currentControls: @@ -198,25 +198,25 @@ class ControlManager: if self.isEnabled: assert self.notify.debug('already isEnabled') return - + self.isEnabled = 1 # keep track of what we do on the inputState so we can undo it later on #self.inputStateTokens = [] ist = self.inputStateTokens ist.append(inputState.watch("run", 'runningEvent', "running-on", "running-off")) - + ist.append(inputState.watchWithModifiers("forward", "arrow_up", inputSource=inputState.ArrowKeys)) ist.append(inputState.watch("forward", "force-forward", "force-forward-stop")) - + ist.append(inputState.watchWithModifiers("reverse", "arrow_down", inputSource=inputState.ArrowKeys)) ist.append(inputState.watchWithModifiers("reverse", "mouse4", inputSource=inputState.Mouse)) - + if self.wantWASD: ist.append(inputState.watchWithModifiers("turnLeft", "arrow_left", inputSource=inputState.ArrowKeys)) ist.append(inputState.watch("turnLeft", "mouse-look_left", "mouse-look_left-done")) ist.append(inputState.watch("turnLeft", "force-turnLeft", "force-turnLeft-stop")) - + ist.append(inputState.watchWithModifiers("turnRight", "arrow_right", inputSource=inputState.ArrowKeys)) ist.append(inputState.watch("turnRight", "mouse-look_right", "mouse-look_right-done")) ist.append(inputState.watch("turnRight", "force-turnRight", "force-turnRight-stop")) @@ -232,7 +232,7 @@ class ControlManager: ist.append(inputState.watchWithModifiers("turnLeft", "arrow_left", inputSource=inputState.ArrowKeys)) ist.append(inputState.watch("turnLeft", "mouse-look_left", "mouse-look_left-done")) ist.append(inputState.watch("turnLeft", "force-turnLeft", "force-turnLeft-stop")) - + ist.append(inputState.watchWithModifiers("turnRight", "arrow_right", inputSource=inputState.ArrowKeys)) ist.append(inputState.watch("turnRight", "mouse-look_right", "mouse-look_right-done")) ist.append(inputState.watch("turnRight", "force-turnRight", "force-turnRight-stop")) @@ -242,7 +242,7 @@ class ControlManager: ist.append(inputState.watchWithModifiers("jump", "space")) else: ist.append(inputState.watch("jump", "control", "control-up")) - + if self.currentControls: self.currentControls.enableAvatarControls() @@ -260,7 +260,7 @@ class ControlManager: if self.currentControls: self.currentControls.disableAvatarControls() - + if self.passMessagesThrough: # for not breaking toontown ist=self.inputStateTokens ist.append(inputState.watchWithModifiers("forward", "arrow_up", inputSource=inputState.ArrowKeys)) @@ -274,10 +274,10 @@ class ControlManager: self.currentControls.setCollisionsActive(0) self.currentControls.setAvatar(None) self.currentControls = None - + def disableAvatarJump(self): """ - prevent + prevent """ assert self.forceAvJumpToken is None self.forceAvJumpToken=inputState.force( @@ -310,7 +310,7 @@ class ControlManager: if not self.isEnabled: return - + turnLeftWASDSet = inputState.isSet("turnLeft", inputSource=inputState.WASD) turnRightWASDSet = inputState.isSet("turnRight", inputSource=inputState.WASD) slideLeftWASDSet = inputState.isSet("slideLeft", inputSource=inputState.WASD) @@ -339,7 +339,7 @@ class ControlManager: inputState.set("slideLeft", turnLeftWASDSet, inputSource=inputState.WASD) inputState.set("slideRight", turnRightWASDSet, inputSource=inputState.WASD) - + inputState.set("turnLeft", False, inputSource=inputState.WASD) inputState.set("turnRight", False, inputSource=inputState.WASD) - + diff --git a/direct/src/controls/DevWalker.py b/direct/src/controls/DevWalker.py index ae450bc68d..03f2f0b0ff 100755 --- a/direct/src/controls/DevWalker.py +++ b/direct/src/controls/DevWalker.py @@ -116,7 +116,7 @@ class DevWalker(DirectObject.DirectObject): if base.localAvatar.getAutoRun(): forward = 1 reverse = 0 - + # Determine what the speeds are based on the buttons: self.speed=( (forward and self.avatarControlForwardSpeed or @@ -183,7 +183,7 @@ class DevWalker(DirectObject.DirectObject): def flushEventHandlers(self): pass - + if __debug__: def debugPrint(self, message): """for debugging""" diff --git a/direct/src/controls/NonPhysicsWalker.py b/direct/src/controls/NonPhysicsWalker.py index 09b5ce77d3..02d2edae30 100755 --- a/direct/src/controls/NonPhysicsWalker.py +++ b/direct/src/controls/NonPhysicsWalker.py @@ -70,7 +70,7 @@ class NonPhysicsWalker(DirectObject.DirectObject): if self.cRayNodePath and not self.cRayNodePath.isEmpty(): self.cRayNodePath.node().setFromCollideMask(self.cRayBitMask) - + def initializeCollisions(self, collisionTraverser, avatarNodePath, avatarRadius = 1.4, floorOffset = 1.0, reach = 1.0): """ @@ -201,12 +201,12 @@ class NonPhysicsWalker(DirectObject.DirectObject): turnRight = inputState.isSet("turnRight") slide = inputState.isSet(self.slideName) or 0 #jump = inputState.isSet("jump") - + # Check for Auto-Run if base.localAvatar.getAutoRun(): forward = 1 reverse = 0 - + # Determine what the speeds are based on the buttons: self.speed=(forward and self.avatarControlForwardSpeed or reverse and -self.avatarControlReverseSpeed) @@ -218,7 +218,7 @@ class NonPhysicsWalker(DirectObject.DirectObject): self.rotationSpeed=not slide and ( (turnLeft and self.avatarControlRotateSpeed) or (turnRight and -self.avatarControlRotateSpeed)) - + def handleAvatarControls(self, task): """ Check on the arrow keys and update the avatar. @@ -311,7 +311,7 @@ class NonPhysicsWalker(DirectObject.DirectObject): if hasattr(self, 'cTrav'): self.pusher.flush() self.lifter.flush() # not currently defined or needed - + if __debug__: def debugPrint(self, message): """for debugging""" diff --git a/direct/src/controls/PhysicsWalker.py b/direct/src/controls/PhysicsWalker.py index e58c2df3f6..b0a0cdfcb8 100755 --- a/direct/src/controls/PhysicsWalker.py +++ b/direct/src/controls/PhysicsWalker.py @@ -469,12 +469,12 @@ class PhysicsWalker(DirectObject.DirectObject): slideLeft = 0#inputState.isSet("slideLeft") slideRight = 0#inputState.isSet("slideRight") jump = inputState.isSet("jump") - + # Check for Auto-Run if base.localAvatar.getAutoRun(): forward = 1 reverse = 0 - + # Determine what the speeds are based on the buttons: self.__speed=(forward and self.avatarControlForwardSpeed or reverse and -self.avatarControlReverseSpeed) diff --git a/direct/src/controls/SwimWalker.py b/direct/src/controls/SwimWalker.py index 03ba0a97ec..b52bf5e609 100755 --- a/direct/src/controls/SwimWalker.py +++ b/direct/src/controls/SwimWalker.py @@ -16,7 +16,7 @@ class SwimWalker(NonPhysicsWalker.NonPhysicsWalker): if base.localAvatar.getAutoRun(): forward = 1 reverse = 0 - + # Determine what the speeds are based on the buttons: self.speed=(forward and self.avatarControlForwardSpeed or reverse and -self.avatarControlReverseSpeed) diff --git a/direct/src/controls/TwoDWalker.py b/direct/src/controls/TwoDWalker.py index 0ca3033af9..d80f90bf4d 100644 --- a/direct/src/controls/TwoDWalker.py +++ b/direct/src/controls/TwoDWalker.py @@ -9,7 +9,7 @@ from panda3d.core import ConfigVariableBool class TwoDWalker(GravityWalker): """ The TwoDWalker is primarily for a 2D Scroller game environment. Eg - Toon Blitz minigame. - TODO: This class is still work in progress. + TODO: This class is still work in progress. Currently Toon Blitz is using this only for jumping. Moving the Toon left to right is handled by toontown/src/minigame/TwoDDrive.py. I eventually want this class to control all the 2 D movements, possibly with a @@ -26,13 +26,13 @@ class TwoDWalker(GravityWalker): assert self.notify.debugStateCall(self) self.notify.debug('Constructing TwoDWalker') GravityWalker.__init__(self) - + def handleAvatarControls(self, task): """ Check on the arrow keys and update the avatar. - """ + """ # get the button states: - jump = inputState.isSet("forward") + jump = inputState.isSet("forward") if self.lifter.isOnGround(): if self.isAirborne: self.isAirborne = 0 @@ -45,9 +45,9 @@ class TwoDWalker(GravityWalker): if self.isAirborne == 0: assert self.debugPrint("isAirborne 1 due to isOnGround() false") self.isAirborne = 1 - + return Task.cont - + def jumpPressed(self): """This function should be called from TwoDDrive when the jump key is pressed.""" if self.lifter.isOnGround(): diff --git a/direct/src/directdevices/DirectJoybox.py b/direct/src/directdevices/DirectJoybox.py index ac5518ed3e..7376154947 100644 --- a/direct/src/directdevices/DirectJoybox.py +++ b/direct/src/directdevices/DirectJoybox.py @@ -280,8 +280,8 @@ class DirectJoybox(DirectObject): self.floatingNP.setHpr(hpr) self.nodePath.wrtReparentTo(parent) hpr = Vec3(0,0,0) - - + + self.nodePath.setPosHpr(self.nodePath, pos, hpr) def joeMode(self): @@ -382,10 +382,10 @@ class DirectJoybox(DirectObject): self.nodePath.setH(self.nodePath,dh) self.nodePath.setY(self.nodePath,dy) - - - - + + + + def spaceFly(self): # Do nothing if no nodePath selected diff --git a/direct/src/directnotify/DirectNotify.py b/direct/src/directnotify/DirectNotify.py index 2d3fb5ab19..96f79f57a3 100644 --- a/direct/src/directnotify/DirectNotify.py +++ b/direct/src/directnotify/DirectNotify.py @@ -99,7 +99,7 @@ class DirectNotify: else: print ("DirectNotify: unknown notify level: " + str(level) + " for category: " + str(categoryName)) - + def setDconfigLevels(self): for categoryName in self.getCategories(): diff --git a/direct/src/directscripts/extract_docs.py b/direct/src/directscripts/extract_docs.py index a0033ff5fe..8e291f95ae 100644 --- a/direct/src/directscripts/extract_docs.py +++ b/direct/src/directscripts/extract_docs.py @@ -166,12 +166,12 @@ def processFunction(handle, function, isConstructor = False): wrapper = interrogate_function_python_wrapper(function, i_wrapper) if interrogate_wrapper_has_comment(wrapper): print >>handle, block_comment(interrogate_wrapper_comment(wrapper)) - + if not isConstructor: if interrogate_function_is_method(function): if not interrogate_wrapper_number_of_parameters(wrapper) > 0 or not interrogate_wrapper_parameter_is_this(wrapper, 0): print >>handle, "static", - + if interrogate_wrapper_has_return_value(wrapper): print >>handle, translated_type_name(interrogate_wrapper_return_type(wrapper)), else: @@ -180,7 +180,7 @@ def processFunction(handle, function, isConstructor = False): print >>handle, translateFunctionName(interrogate_function_name(function)) + "(", else: print >>handle, "__init__(", - + first = True for i_param in range(interrogate_wrapper_number_of_parameters(wrapper)): if not interrogate_wrapper_parameter_is_this(wrapper, i_param): @@ -190,16 +190,16 @@ def processFunction(handle, function, isConstructor = False): if interrogate_wrapper_parameter_has_name(wrapper, i_param): print >>handle, interrogate_wrapper_parameter_name(wrapper, i_param), first = False - + print >>handle, ");" def processType(handle, type): typename = translated_type_name(type, scoped=False) derivations = [ translated_type_name(interrogate_type_get_derivation(type, n)) for n in range(interrogate_type_number_of_derivations(type)) ] - + if interrogate_type_has_comment(type): print >>handle, block_comment(interrogate_type_comment(type)) - + if interrogate_type_is_enum(type): print >>handle, "enum %s {" % typename for i_value in range(interrogate_type_number_of_enum_values(type)): @@ -222,28 +222,28 @@ def processType(handle, type): else: print "I don't know what type %s is" % interrogate_type_true_name(type) return - + if len(derivations) > 0: print >>handle, "%s %s : public %s {" % (classtype, typename, ", public ".join(derivations)) else: print >>handle, "%s %s {" % (classtype, typename) print >>handle, "public:" - + for i_ntype in xrange(interrogate_type_number_of_nested_types(type)): processType(handle, interrogate_type_get_nested_type(type, i_ntype)) - + for i_method in xrange(interrogate_type_number_of_constructors(type)): processFunction(handle, interrogate_type_get_constructor(type, i_method), True) - + for i_method in xrange(interrogate_type_number_of_methods(type)): processFunction(handle, interrogate_type_get_method(type, i_method)) - + for i_method in xrange(interrogate_type_number_of_make_seqs(type)): print >>handle, "list", translateFunctionName(interrogate_make_seq_seq_name(interrogate_type_get_make_seq(type, i_method))), "();" for i_element in xrange(interrogate_type_number_of_elements(type)): processElement(handle, interrogate_type_get_element(type, i_element)) - + print >>handle, "};" def processModule(handle, package): @@ -277,10 +277,10 @@ def processModule(handle, package): if __name__ == "__main__": handle = open("pandadoc.hpp", "w") - + print >>handle, comment("Panda3D modules that are implemented in C++.") print >>handle, "namespace panda3d {" - + # Determine the path to the interrogatedb files interrogate_add_search_directory(os.path.join(os.path.dirname(pandac.__file__), "..", "..", "etc")) interrogate_add_search_directory(os.path.join(os.path.dirname(pandac.__file__), "input")) diff --git a/direct/src/directscripts/packpanda.py b/direct/src/directscripts/packpanda.py index 72e33c3e9b..1868b0f1cb 100755 --- a/direct/src/directscripts/packpanda.py +++ b/direct/src/directscripts/packpanda.py @@ -369,8 +369,8 @@ if (sys.platform == "win32"): CMD=CMD+'/DPPGAME="'+TMPGAME+'" ' CMD=CMD+'/DPPMAIN="'+MAIN+'" ' CMD=CMD+'/DPPICON="'+PPICON+'" ' - CMD=CMD+'"'+PSOURCE+'\\direct\\directscripts\\packpanda.nsi"' - + CMD=CMD+'"'+PSOURCE+'\\direct\\directscripts\\packpanda.nsi"' + print "" print CMD print "packing..." @@ -386,12 +386,12 @@ else: os.system("cp --recursive %s/Pmw %s/usr/share/games/%s/Pmw" % (PANDA, TMPDIR, BASENAME)) os.system("cp %s %s/usr/share/games/%s/LICENSE" % (LICENSE, TMPDIR, BASENAME)) os.system("cp --recursive /usr/lib/panda3d/* %s/usr/lib/games/%s/" % (TMPDIR, BASENAME)) - + # Make the script to run the game txt = RUN_SCRIPT[1:].replace("BASENAME",BASENAME).replace("PYTHONV",PYTHONV).replace("MAIN",MAIN) WriteFile(TMPDIR+"/usr/bin/"+BASENAME, txt) os.system("chmod +x "+TMPDIR+"/usr/bin/"+BASENAME) - + if (os.path.exists("/usr/bin/rpmbuild")): os.system("rm -rf %s/DEBIAN" % TMPDIR) os.system("rpm -E '%_target_cpu' > packpanda-TMP.txt") @@ -404,7 +404,7 @@ else: os.system("mv "+ARCH+"/"+BASENAME+"-"+VER+"-1."+ARCH+".rpm .") os.rmdir(ARCH) os.remove("packpanda-TMP.spec") - + if (os.path.exists("/usr/bin/dpkg-deb")): os.system("dpkg --print-architecture > packpanda-TMP.txt") ARCH=ReadFile("packpanda-TMP.txt").strip() @@ -415,7 +415,7 @@ else: os.system("cd %s ; (find usr -type f -exec md5sum {} \;) > DEBIAN/md5sums" % TMPDIR) WriteFile(TMPDIR+"/DEBIAN/control",txt) os.system("dpkg-deb -b "+TMPDIR+" "+BASENAME+"_"+VER+"_"+ARCH+".deb") - + if not(os.path.exists("/usr/bin/rpmbuild") or os.path.exists("/usr/bin/dpkg-deb")): exit("To build an installer, either rpmbuild or dpkg-deb must be present on your system!") diff --git a/direct/src/directtools/DirectCameraControl.py b/direct/src/directtools/DirectCameraControl.py index 2ec27e8a5a..e3fbe6c8b7 100644 --- a/direct/src/directtools/DirectCameraControl.py +++ b/direct/src/directtools/DirectCameraControl.py @@ -12,9 +12,9 @@ COA_MARKER_SF = 0.0075 Y_AXIS = Vec3(0, 1, 0) class DirectCameraControl(DirectObject): - + notify = DirectNotifyGlobal.directNotify.newCategory('DirectCameraControl') - + def __init__(self): # Create the grid self.startT = 0.0 @@ -54,7 +54,7 @@ class DirectCameraControl(DirectObject): ## ['c', self.centerCamIn, 0.5], ## ['f', self.fitOnWidget], # Note: This function doesn't work as intended ## ['h', self.homeCam], -## ['shift-v', self.toggleMarkerVis], +## ['shift-v', self.toggleMarkerVis], ## ['m', self.moveToFit], # Note: This function doesn't work as intended; the object dissappears and screen flashes ## ['n', self.pickNextCOA], ## ['u', self.orbitUprightCam], @@ -75,12 +75,12 @@ class DirectCameraControl(DirectObject): ## ['-', self.zoomCam, -2.0, t], ## ['_', self.zoomCam, -2.0, t], ## ] - + self.keyEvents = [ ['DIRECT-centerCamIn', self.centerCamIn, 0.5], ['DIRECT-fitOnWidget', self.fitOnWidget], # Note: This function doesn't work as intended ['DIRECT-homeCam', self.homeCam], - ['DIRECT-toggleMarkerVis', self.toggleMarkerVis], + ['DIRECT-toggleMarkerVis', self.toggleMarkerVis], ['DIRECT-moveToFit', self.moveToFit], # Note: This function doesn't work as intended; the object dissappears and screen flashes ['DIRECT-pickNextCOA', self.pickNextCOA], ['DIRECT-orbitUprightCam', self.orbitUprightCam], @@ -106,13 +106,13 @@ class DirectCameraControl(DirectObject): self.altDown = 0 self.perspCollPlane = None # [gjeon] used for new LE self.perspCollPlane2 = None # [gjeon] used for new LE - + def toggleMarkerVis(self): ## if base.direct.cameraControl.coaMarker.isHidden(): ## base.direct.cameraControl.coaMarker.show() ## else: ## base.direct.cameraControl.coaMarker.hide() - + if self.coaMarker.isHidden(): self.coaMarker.show() else: @@ -142,7 +142,7 @@ class DirectCameraControl(DirectObject): if self.manipulateCameraTask: taskMgr.remove(self.manipulateCameraTask) self.manipulateCameraTask = None - + if self.manipulateCameraInterval: self.manipulateCameraInterval.finish() self.manipulateCameraInterval = None @@ -157,7 +157,7 @@ class DirectCameraControl(DirectObject): if ival: ival.start() self.manipulateCameraInterval = ival - + def mouseDollyStop(self): self.__stopManipulateCamera() @@ -231,7 +231,7 @@ class DirectCameraControl(DirectObject): self.coaMarker.show() # Resize it self.updateCoaMarkerSize() - + def mouseFlyStartTopWin(self): print "Moving mouse 2 in new window" #altIsDown = base.getAlt() @@ -281,7 +281,7 @@ class DirectCameraControl(DirectObject): self.__stopManipulateCamera() # Spawn new task t = Task.Task(self.OrthoZoomTask) - self.__startManipulateCamera(task = t) + self.__startManipulateCamera(task = t) def spawnHPPan(self): # Kill any existing tasks @@ -349,7 +349,7 @@ class DirectCameraControl(DirectObject): moveDir = Vec3(Y_AXIS) if self.useMayaCamControls : # use maya controls - moveDir.assign(moveDir * ((base.direct.dr.mouseDeltaX -1.0 * base.direct.dr.mouseDeltaY) + moveDir.assign(moveDir * ((base.direct.dr.mouseDeltaX -1.0 * base.direct.dr.mouseDeltaY) * state.zoomSF)) hVal = 0.0 else: @@ -382,7 +382,7 @@ class DirectCameraControl(DirectObject): base.direct.dr.orthoFactor = 0.0001 base.direct.dr.updateFilmSize(x, y) return Task.cont - + def HPPanTask(self, state): base.direct.camera.setHpr(base.direct.camera, (0.5 * base.direct.dr.mouseDeltaX * @@ -403,7 +403,7 @@ class DirectCameraControl(DirectObject): if base.direct.camera.getPos().getZ() >=0: iRay.ct.traverse(self.perspCollPlane) else: - iRay.ct.traverse(self.perspCollPlane2) + iRay.ct.traverse(self.perspCollPlane2) if iRay.getNumEntries() > 0: entry = iRay.getEntry(0) @@ -814,7 +814,7 @@ class DirectCameraControl(DirectObject): # How far do you move the camera to be this distance from the node? deltaMove = vWidget2Camera - centerVec - + # Move a target there try: self.camManipRef.setPos(base.direct.camera, deltaMove) diff --git a/direct/src/directtools/DirectGlobals.py b/direct/src/directtools/DirectGlobals.py index 2a70697598..372d16839f 100644 --- a/direct/src/directtools/DirectGlobals.py +++ b/direct/src/directtools/DirectGlobals.py @@ -59,4 +59,4 @@ def LE_showInOneCam(nodePath, thisCamName): for camName in LE_CAM_MASKS.keys(): if camName != thisCamName: nodePath.hide(LE_CAM_MASKS[camName]) - + diff --git a/direct/src/directtools/DirectGrid.py b/direct/src/directtools/DirectGrid.py index 71fedf52c1..e7e67823a3 100644 --- a/direct/src/directtools/DirectGrid.py +++ b/direct/src/directtools/DirectGrid.py @@ -55,7 +55,7 @@ class DirectGrid(NodePath, DirectObject): self.reparentTo(parent) else: self.reparentTo(base.direct.group) - + self.updateGrid() self.fEnabled = 1 diff --git a/direct/src/directtools/DirectLights.py b/direct/src/directtools/DirectLights.py index af6dfdbc8c..1797351032 100644 --- a/direct/src/directtools/DirectLights.py +++ b/direct/src/directtools/DirectLights.py @@ -7,7 +7,7 @@ class DirectLight(NodePath): NodePath.__init__(self) # Record light and name self.light = light - + # Attach node to self self.assign(parent.attachNewNode(self.light)) diff --git a/direct/src/directtools/DirectManipulation.py b/direct/src/directtools/DirectManipulation.py index 36c2efc989..ad9a1c0e51 100644 --- a/direct/src/directtools/DirectManipulation.py +++ b/direct/src/directtools/DirectManipulation.py @@ -72,11 +72,11 @@ class DirectManipulationControl(DirectObject): base.direct.widget.multiplyScalingFactorBy(factor) else: self.objectHandles.multiplyScalingFactorBy(factor) - + def supportMultiView(self): if self.fMultiView: return - + self.objectHandles.hide(BitMask32.bit(0)) self.objectHandles.hide(BitMask32.bit(1)) self.objectHandles.hide(BitMask32.bit(2)) @@ -99,14 +99,14 @@ class DirectManipulationControl(DirectObject): self.leftViewWidget.hide(BitMask32.bit(3)) self.fMultiView = 1 - + def manipulationStart(self, modifiers): # Start out in select mode self.mode = 'select' if base.direct.cameraControl.useMayaCamControls and modifiers == 4: self.mode = 'camera' - + if self.fAllowSelectionOnly: return @@ -131,7 +131,7 @@ class DirectManipulationControl(DirectObject): return else: entry = None - + if not base.direct.gotAlt(modifiers): if entry: # Check to see if we are moving the object @@ -158,10 +158,10 @@ class DirectManipulationControl(DirectObject): def switchToWorldSpaceMode(self): self.worldSpaceManip = True - + def switchToLocalSpaceMode(self): self.worldSpaceManip = False - + def switchToMoveMode(self, state): taskMgr.remove('manip-watch-mouse') self.mode = 'move' @@ -180,7 +180,7 @@ class DirectManipulationControl(DirectObject): def watchMarqueeTask(self, state): taskMgr.remove('manip-watch-mouse') - taskMgr.remove('manip-move-wait') + taskMgr.remove('manip-move-wait') self.mode = 'select' self.drawMarquee(state.initX, state.initY) return Task.cont @@ -287,7 +287,7 @@ class DirectManipulationControl(DirectObject): nodePath = findTaggedNodePath(geom) if nodePath in selectionList: continue - + bb = geom.getBounds() bbc = bb.makeCopy() bbc.xform(geom.getParent().getNetTransform().getMat()) @@ -305,7 +305,7 @@ class DirectManipulationControl(DirectObject): max = Point3(0) geom.calcTightBounds(min, max) # Restore transform - geom.setMat(tMat) + geom.setMat(tMat) fll = Point3(min[0], max[1], min[2]) flr = Point3(max[0], max[1], min[2]) @@ -341,7 +341,7 @@ class DirectManipulationControl(DirectObject): base.direct.deselectAll() #elif self.mode == 'move': self.manipulateObjectCleanup() - + self.mode = None def manipulateObjectCleanup(self): @@ -460,7 +460,7 @@ class DirectManipulationControl(DirectObject): if hasattr(base.direct, 'widget'): base.direct.widget.coaModeColor() else: - self.objectHandles.coaModeColor() + self.objectHandles.coaModeColor() else: if hasattr(base.direct, 'widget'): base.direct.widget.manipModeColor() @@ -472,7 +472,7 @@ class DirectManipulationControl(DirectObject): if hasattr(base.direct, 'widget'): base.direct.widget.disabledModeColor() else: - self.objectHandles.disabledModeColor() + self.objectHandles.disabledModeColor() #-------------------------------------------------------------------------- # Function: get edit types list for specified objects which indicate @@ -589,7 +589,7 @@ class DirectManipulationControl(DirectObject): else: # [gjeon] uniform scaling self.fScaling3D = 1 - self.scale3D(state) + self.scale3D(state) else: if type == 'post' and not self.currEditTypes & EDIT_TYPE_UNMOVABLE: self.xlate1D(state) @@ -714,7 +714,7 @@ class DirectManipulationControl(DirectObject): if self.fGridSnap: base.direct.widget.setPos(self.gridSnapping(base.direct.widget, offset)) else: - base.direct.widget.setPos(base.direct.widget, offset) + base.direct.widget.setPos(base.direct.widget, offset) def xlate2D(self, state): # Constrained 2D (planar) translation @@ -744,7 +744,7 @@ class DirectManipulationControl(DirectObject): if self.fGridSnap: base.direct.widget.setPos(self.gridSnapping(base.direct.widget, offset)) else: - base.direct.widget.setPos(base.direct.widget, offset) + base.direct.widget.setPos(base.direct.widget, offset) def rotate1D(self, state): # Constrained 1D rotation about the widget's main axis (X, Y, or Z) @@ -940,7 +940,7 @@ class DirectManipulationControl(DirectObject): elif self.constraint[:1] == 'z': currScale = Vec3(currScale.getX(), currScale.getY(), currScale.getZ() * d1/d0) base.direct.widget.setScale(currScale) - return + return # [gjeon] Constrained 1D scale of the selected node based upon up down mouse motion if self.fScaleInit: @@ -957,7 +957,7 @@ class DirectManipulationControl(DirectObject): # Scale factor is ratio current mag with init mag if self.constraint[:1] == 'x': - currScale = Vec3(self.initScale.getX() * + currScale = Vec3(self.initScale.getX() * self.objectHandles.getAxisIntersectPt('x').length() / self.initScaleMag, self.initScale.getY(), self.initScale.getZ()) elif self.constraint[:1] == 'y': @@ -992,7 +992,7 @@ class DirectManipulationControl(DirectObject): # Scale factor is ratio current mag with init mag currScale = Vec3(currScale.getX() * d1/d0, currScale.getY() * d1/d0, currScale.getZ() * d1/d0) base.direct.widget.setScale(currScale) - return + return else: self.hitPtScale.assign(self.objectHandles.getMouseIntersectPt()) @@ -1134,29 +1134,29 @@ class ObjectHandles(NodePath, DirectObject): # tag with name so they can skipped during iRay selection self.xPostCollision.setTag('WidgetName',name) - self.yPostCollision.setTag('WidgetName',name) + self.yPostCollision.setTag('WidgetName',name) self.zPostCollision.setTag('WidgetName',name) self.xRingCollision.setTag('WidgetName',name) - self.yRingCollision.setTag('WidgetName',name) + self.yRingCollision.setTag('WidgetName',name) self.zRingCollision.setTag('WidgetName',name) self.xDiscCollision.setTag('WidgetName',name) - self.yDiscCollision.setTag('WidgetName',name) + self.yDiscCollision.setTag('WidgetName',name) self.zDiscCollision.setTag('WidgetName',name) - + self.xScaleCollision.setTag('WidgetName',name) - self.yScaleCollision.setTag('WidgetName',name) + self.yScaleCollision.setTag('WidgetName',name) self.zScaleCollision.setTag('WidgetName',name) # name disc geoms so they can be added to unpickables self.xDisc.find("**/+GeomNode").setName('x-disc-geom') self.yDisc.find("**/+GeomNode").setName('y-disc-geom') - self.zDisc.find("**/+GeomNode").setName('z-disc-geom') + self.zDisc.find("**/+GeomNode").setName('z-disc-geom') #turn scale off by default self.disableHandles('scale') - + # Start with widget handles hidden self.fActive = 1 self.toggleWidget() @@ -1172,7 +1172,7 @@ class ObjectHandles(NodePath, DirectObject): def manipModeColor(self): self.clearColor() - + def toggleWidget(self): if self.fActive: if hasattr(base.direct, "manipulationControl") and base.direct.manipulationControl.fMultiView: @@ -1187,7 +1187,7 @@ class ObjectHandles(NodePath, DirectObject): widget.showWidgetIfActive() else: self.activate() - + def activate(self): self.scalingNode.reparentTo(self) self.fActive = 1 @@ -1195,7 +1195,7 @@ class ObjectHandles(NodePath, DirectObject): def deactivate(self): self.scalingNode.reparentTo(hidden) self.fActive = 0 - + def showWidgetIfActive(self): if self.fActive: self.reparentTo(base.direct.group) @@ -1205,7 +1205,7 @@ class ObjectHandles(NodePath, DirectObject): def hideWidget(self): self.reparentTo(hidden) - + def enableHandles(self, handles): if type(handles) == types.ListType: for handle in handles: @@ -1389,7 +1389,7 @@ class ObjectHandles(NodePath, DirectObject): def multiplyScalingFactorBy(self, factor): self.ohScalingFactor = self.ohScalingFactor * factor sf = self.ohScalingFactor * self.directScalingFactor - ival = self.scalingNode.scaleInterval(0.5, (sf, sf, sf), + ival = self.scalingNode.scaleInterval(0.5, (sf, sf, sf), blendType = 'easeInOut', name = 'resizeObjectHandles') ival.start() @@ -1436,7 +1436,7 @@ class ObjectHandles(NodePath, DirectObject): lines.create() lines.setName('x-post-line') - + #X scale self.xScale = self.xScaleGroup.attachNewNode('x-scale-visible') lines = LineNodePath(self.xScale) @@ -1444,9 +1444,9 @@ class ObjectHandles(NodePath, DirectObject): lines.setThickness(5) lines.moveTo(1.3, 0, 0) lines.drawTo(-1.5, 0, 0) - + drawBox(lines, (1.3, 0, 0), 0.2) - + lines.create() lines.setName('x-scale-line') @@ -1497,12 +1497,12 @@ class ObjectHandles(NodePath, DirectObject): lines.setThickness(5) lines.moveTo(0, 1.3, 0) lines.drawTo(0, -1.5, 0) - + drawBox(lines, (0, 1.4, 0), 0.2) - + lines.create() lines.setName('y-scale-line') - + # Y ring self.yRing = self.yRingGroup.attachNewNode('y-ring-visible') lines = LineNodePath(self.yRing) @@ -1515,7 +1515,7 @@ class ObjectHandles(NodePath, DirectObject): math.sin(deg2Rad(ang))) lines.create() lines.setName('y-ring-line') - + # Z post self.zPost = self.zPostGroup.attachNewNode('z-post-visible') lines = LineNodePath(self.zPost) @@ -1551,12 +1551,12 @@ class ObjectHandles(NodePath, DirectObject): lines.setThickness(5) lines.moveTo(0, 0, 1.3) lines.drawTo(0, 0, -1.5) - + drawBox(lines, (0, 0, 1.4), 0.2) - + lines.create() lines.setName('y-scale-line') - + # Z ring self.zRing = self.zRingGroup.attachNewNode('z-ring-visible') lines = LineNodePath(self.zRing) @@ -1601,7 +1601,7 @@ class ObjectHandles(NodePath, DirectObject): def getAxisIntersectPt(self, axis): if hasattr(base.direct, "manipulationControl") and base.direct.manipulationControl.fMultiView and\ - base.direct.camera.getName() != 'persp': + base.direct.camera.getName() != 'persp': # create ray from the camera to detect 3d position iRay = SelectionRay(base.direct.camera) iRay.collider.setFromLens(base.direct.camNode, base.direct.dr.mouseX, base.direct.dr.mouseY) @@ -1622,12 +1622,12 @@ class ObjectHandles(NodePath, DirectObject): self.hitPt.setZ(0) elif axis == 'y': self.hitPt.setX(0) - self.hitPt.setZ(0) + self.hitPt.setZ(0) elif axis == 'z': self.hitPt.setX(0) - self.hitPt.setY(0) + self.hitPt.setY(0) return self.hitPt - + # Calc the xfrom from camera to widget mCam2Widget = base.direct.camera.getMat(base.direct.widget) lineDir = Vec3(mCam2Widget.xformVec(base.direct.dr.nearVec)) @@ -1683,7 +1683,7 @@ class ObjectHandles(NodePath, DirectObject): if iRay.getNumEntries() == 0: del iRay return Point3(0) - + entry = iRay.getEntry(0) hitPt = entry.getSurfacePoint(entry.getFromNodePath()) @@ -1701,7 +1701,7 @@ class ObjectHandles(NodePath, DirectObject): base.direct.camera.getName() != 'persp': self.hitPt.assign(self.getMouseIntersectPt()) return self.hitPt - + # Find out the point of interection of the ray passing though the mouse # with the plane containing the 2D xlation or 1D rotation widgets @@ -1739,31 +1739,31 @@ def drawBox(lines, center, sideLength): lines.drawTo(center[0] + l, center[1] - l, center[2] - l) lines.drawTo(center[0] + l, center[1] - l, center[2] + l) lines.drawTo(center[0] + l, center[1] + l, center[2] + l) - + lines.moveTo(center[0] - l, center[1] + l, center[2] + l) lines.drawTo(center[0] - l, center[1] + l, center[2] - l) lines.drawTo(center[0] - l, center[1] - l, center[2] - l) lines.drawTo(center[0] - l, center[1] - l, center[2] + l) lines.drawTo(center[0] - l, center[1] + l, center[2] + l) - + lines.moveTo(center[0] + l, center[1] + l, center[2] + l) lines.drawTo(center[0] + l, center[1] + l, center[2] - l) lines.drawTo(center[0] - l, center[1] + l, center[2] - l) lines.drawTo(center[0] - l, center[1] + l, center[2] + l) lines.drawTo(center[0] + l, center[1] + l, center[2] + l) - + lines.moveTo(center[0] + l, center[1] - l, center[2] + l) lines.drawTo(center[0] + l, center[1] - l, center[2] - l) lines.drawTo(center[0] - l, center[1] - l, center[2] - l) lines.drawTo(center[0] - l, center[1] - l, center[2] + l) lines.drawTo(center[0] + l, center[1] - l, center[2] + l) - + lines.moveTo(center[0] + l, center[1] + l, center[2] + l) lines.drawTo(center[0] - l, center[1] + l, center[2] + l) lines.drawTo(center[0] - l, center[1] - l, center[2] + l) lines.drawTo(center[0] + l, center[1] - l, center[2] + l) lines.drawTo(center[0] + l, center[1] + l, center[2] + l) - + lines.moveTo(center[0] + l, center[1] + l, center[2] - l) lines.drawTo(center[0] - l, center[1] + l, center[2] - l) lines.drawTo(center[0] - l, center[1] - l, center[2] - l) diff --git a/direct/src/directtools/DirectSelection.py b/direct/src/directtools/DirectSelection.py index 8adb64f6ca..2b2373ce26 100644 --- a/direct/src/directtools/DirectSelection.py +++ b/direct/src/directtools/DirectSelection.py @@ -616,7 +616,7 @@ class SelectionRay(SelectionQueue): if direct: self.collider.setFromLens(base.direct.camNode, mx, my) else: - self.collider.setFromLens(base.camNode, mx, my) + self.collider.setFromLens(base.camNode, mx, my) self.ct.traverse(targetNodePath) self.sortEntries() diff --git a/direct/src/directtools/DirectSession.py b/direct/src/directtools/DirectSession.py index 55c47a2775..2fb18b5806 100644 --- a/direct/src/directtools/DirectSession.py +++ b/direct/src/directtools/DirectSession.py @@ -186,7 +186,7 @@ class DirectSession(DirectObject): if base.wantTk: from direct.tkpanels import Placer from direct.tkwidgets import Slider - from direct.tkwidgets import SceneGraphExplorer + from direct.tkwidgets import SceneGraphExplorer self.actionEvents.extend([ ['SGE_Place', Placer.place], ['SGE_Set Color', Slider.rgbPanel], @@ -210,7 +210,7 @@ class DirectSession(DirectObject): self.keyEvents = keyList[:] self.keyEvents.extend(list(map(addCtrl, keyList))) - self.keyEvents.extend(list(map(addShift, keyList))) + self.keyEvents.extend(list(map(addShift, keyList))) self.keyEvents.extend(self.specialKeys) self.mouseEvents = ['mouse1', 'mouse1-up', @@ -291,7 +291,7 @@ class DirectSession(DirectObject): 'enter': 'DIRECT-enter', } - self.passThroughKeys = ['v','b','l','p', 'r', 'shift-r', 's', 't','shift-a', 'w'] + self.passThroughKeys = ['v','b','l','p', 'r', 'shift-r', 's', 't','shift-a', 'w'] if base.wantTk: from direct.showbase import TkGlobal @@ -403,7 +403,7 @@ class DirectSession(DirectObject): # Position a target point to lerp the oobe camera to base.direct.cameraControl.camManipRef.setPosHpr(self.trueCamera, 0, 0, 0, 0, 0, 0) ival = self.oobeCamera.posHprInterval( - 2.0, pos = Point3(0), hpr = Vec3(0), + 2.0, pos = Point3(0), hpr = Vec3(0), other = base.direct.cameraControl.camManipRef, blendType = 'easeInOut') ival = Sequence(ival, Func(self.endOOBE), name = 'oobeTransition') @@ -425,7 +425,7 @@ class DirectSession(DirectObject): self.trueCamera, Vec3(-2, -20, 5)) base.direct.cameraControl.camManipRef.lookAt(self.trueCamera) ival = self.oobeCamera.posHprInterval( - 2.0, pos = Point3(0), hpr = Vec3(0), + 2.0, pos = Point3(0), hpr = Vec3(0), other = base.direct.cameraControl.camManipRef, blendType = 'easeInOut') ival = Sequence(ival, Func(self.beginOOBE), name = 'oobeTransition') @@ -498,19 +498,19 @@ class DirectSession(DirectObject): if input.endswith('-up') or\ input not in self.modifierEvents: # to handle orphan events - return + return if (self.fMouse1 == 0 and 'mouse1-up' in input) or\ (self.fMouse2 == 0 and 'mouse2-up' in input) or\ (self.fMouse3 == 0 and 'mouse3-up' in input): # to handle orphan events - return + return if (self.fMouse1 or self.fMouse2 or self.fMouse3) and\ input[4:7] != base.direct.camera.getName()[:3] and\ input.endswith('-up'): # to handle orphan events - return + return winCtrl = None possibleWinCtrls = [] @@ -530,7 +530,7 @@ class DirectSession(DirectObject): winCtrl = cWinCtrl else: if input[4:7] != cWinCtrl.camera.getName()[:3]: - winCtrl = cWinCtrl + winCtrl = cWinCtrl if winCtrl is None: return if input not in self.modifierEvents: @@ -667,7 +667,7 @@ class DirectSession(DirectObject): taskMgr.add(self.widgetResizeTask, 'DIRECTWidgetResize') else: taskMgr.remove('DIRECTWidgetResize') - + def widgetResizeTask(self, state): if not taskMgr.hasTaskNamed('resizeObjectHandles'): dnp = self.selected.last @@ -680,7 +680,7 @@ class DirectSession(DirectObject): nodeCamDist = Vec3(dnp.getPos(base.camList[3])).length() sf = 0.075 * nodeCamDist * math.tan(deg2Rad(direct.drList[3].fovV)) self.manipulationControl.widgetList[3].setDirectScalingFactor(sf) - + else: nodeCamDist = Vec3(dnp.getPos(direct.camera)).length() sf = 0.075 * nodeCamDist * math.tan(deg2Rad(direct.drList.getCurrentDr().fovV)) @@ -757,7 +757,7 @@ class DirectSession(DirectObject): for widget in self.manipulationControl.widgetList: widget.hideWidget() else: - self.widget.hideWidget() + self.widget.hideWidget() self.selectedNPReadout.reparentTo(hidden) self.selectedNPReadout.setText(' ') taskMgr.remove('followSelectedNodePath') @@ -1311,10 +1311,10 @@ class DisplayRegionList(DirectObject): self.mouseUpdate() # hack to test movement return Task.cont - + def addDisplayRegionContext(self, cam): self.displayRegionList.append(DisplayRegionContext(cam)) - + def removeDisplayRegionContext(self, cam): for drc in self.displayRegionList: if drc.cam == cam: diff --git a/direct/src/directutil/DirectMySQLdbConnection.py b/direct/src/directutil/DirectMySQLdbConnection.py index 6174e269a0..4de1876cd4 100755 --- a/direct/src/directutil/DirectMySQLdbConnection.py +++ b/direct/src/directutil/DirectMySQLdbConnection.py @@ -36,7 +36,7 @@ class DirectMySQLdbConnection(Connection): client_flag |= CLIENT.MULTI_STATEMENTS if client_version >= (5, 0): client_flag |= CLIENT.MULTI_RESULTS - + kwargs2['client_flag'] = client_flag ### DCR: skip over the Connection __init__ @@ -45,7 +45,7 @@ class DirectMySQLdbConnection(Connection): self.encoders = dict([ (k, v) for k, v in conv.items() if type(k) is not int ]) - + self._server_version = tuple([ int(n) for n in self.get_server_info().split('.')[:2] ]) db = proxy(self) diff --git a/direct/src/directutil/Mopath.py b/direct/src/directutil/Mopath.py index c962993ba3..07d7dd63b2 100644 --- a/direct/src/directutil/Mopath.py +++ b/direct/src/directutil/Mopath.py @@ -185,6 +185,6 @@ class Mopath(DirectObject): tp = self.calcTime(t) self.xyzNurbsCurve.getPoint(tp, p) ls.drawTo(p) - + return NodePath(ls.create()) - + diff --git a/direct/src/distributed/CRDataCache.py b/direct/src/distributed/CRDataCache.py index 09a85daf97..afc86abaa1 100755 --- a/direct/src/distributed/CRDataCache.py +++ b/direct/src/distributed/CRDataCache.py @@ -112,4 +112,4 @@ if __debug__: dc._stopMemLeakCheck() dc.destroy() del dc - + diff --git a/direct/src/distributed/CachedDOData.py b/direct/src/distributed/CachedDOData.py index a780815c72..99a600c05b 100755 --- a/direct/src/distributed/CachedDOData.py +++ b/direct/src/distributed/CachedDOData.py @@ -14,7 +14,7 @@ class CachedDOData: def destroy(self): # override and handle this object being destroyed # this is destruction of this object, not the cached data (see flush) - pass + pass def flush(self): # override and destroy the cached data diff --git a/direct/src/distributed/CartesianGridBase.py b/direct/src/distributed/CartesianGridBase.py index ca16855b29..d45fb00292 100755 --- a/direct/src/distributed/CartesianGridBase.py +++ b/direct/src/distributed/CartesianGridBase.py @@ -50,7 +50,7 @@ class CartesianGridBase: xMax = abs(spherePos[0])+sphereRadius yMax = abs(spherePos[1])+sphereRadius sphereRadius = Vec3(xMax,yMax,0).length() - + # sphereRadius = max(sphereRadius, gridRadius*cellWidth) return max(2 * (sphereRadius // cellWidth), 1) diff --git a/direct/src/distributed/ClientRepository.py b/direct/src/distributed/ClientRepository.py index 4483633be5..a22c5b404c 100644 --- a/direct/src/distributed/ClientRepository.py +++ b/direct/src/distributed/ClientRepository.py @@ -23,7 +23,7 @@ class ClientRepository(ClientRepositoryBase): GameGlobalsId = 0 doNotDeallocateChannel = True - + def __init__(self, dcFileNames = None, dcSuffix = '', connectMethod = None, threadedNet = None): ClientRepositoryBase.__init__(self, dcFileNames = dcFileNames, dcSuffix = dcSuffix, connectMethod = connectMethod, threadedNet = threadedNet) @@ -168,7 +168,7 @@ class ClientRepository(ClientRepositoryBase): on the network or previously passed through createDistributedObject.) In either case, the new DistributedObject is returned from this method. - + This method will issue the appropriate network commands to make this object appear on all of the other clients. @@ -195,7 +195,7 @@ class ClientRepository(ClientRepositoryBase): doId = self.allocateDoId() elif reserveDoId: self.reserveDoId(doId) - + dclass = self.dclassesByName.get(className) if not dclass: self.notify.error("Unknown distributed class: %s" % (distObj.__class__)) @@ -288,13 +288,13 @@ class ClientRepository(ClientRepositoryBase): def isLocalId(self, doId): """ Returns true if this doId is one that we're the owner of, false otherwise. """ - + return ((doId >= self.doIdBase) and (doId < self.doIdLast)) def haveCreateAuthority(self): """ Returns true if this client has been assigned a range of doId's it may use to create objects, false otherwise. """ - + return (self.doIdLast > self.doIdBase) def getAvatarIdFromSender(self): @@ -418,7 +418,7 @@ class ClientRepository(ClientRepositoryBase): # Reformat the packed datagram to change the message type and # add the target id. dgi.getUint16() - + dg = PyDatagram() dg.addUint16(CLIENT_OBJECT_UPDATE_FIELD_TARGETED_CMU) dg.addUint32(channelId & 0xffffffff) diff --git a/direct/src/distributed/ClientRepositoryBase.py b/direct/src/distributed/ClientRepositoryBase.py index 2b0ebaa632..9f60eaac98 100644 --- a/direct/src/distributed/ClientRepositoryBase.py +++ b/direct/src/distributed/ClientRepositoryBase.py @@ -73,7 +73,7 @@ class ClientRepositoryBase(ConnectionRepository): self.lastHeartbeat = 0 self._delayDeletedDOs = {} - + self.specialNameNumber = 0 def setDeferInterval(self, deferInterval): @@ -103,7 +103,7 @@ class ClientRepositoryBase(ConnectionRepository): ## self.send(datagram) ## # Make sure the message gets there. ## self.flush() - + def specialName(self, label): name = ("SpecialName %s %s" % (self.specialNameNumber, label)) self.specialNameNumber += 1 @@ -205,7 +205,7 @@ class ClientRepositoryBase(ConnectionRepository): def doDeferredGenerate(self, task): """ This is the task that generates an object on the deferred queue. """ - + now = globalClock.getFrameTime() while self.deferredGenerates: if now - self.lastGenerate < self.deferInterval: @@ -386,7 +386,7 @@ class ClientRepositoryBase(ConnectionRepository): del self.deferredGenerates[i] if len(self.deferredGenerates) == 0: taskMgr.remove('deferredGenerate') - + else: self._logFailedDisable(doId, ownerView) @@ -422,7 +422,7 @@ class ClientRepositoryBase(ConnectionRepository): doId = di.getUint32() ovUpdated = self.__doUpdateOwner(doId, di) - + if doId in self.deferredDoIds: # This object hasn't really been generated yet. Sit on # the update. @@ -436,8 +436,8 @@ class ClientRepositoryBase(ConnectionRepository): else: # This object has been fully generated. It's OK to update. self.__doUpdate(doId, di, ovUpdated) - - + + def __doUpdate(self, doId, di, ovUpdated): # Find the DO do = self.doId2do.get(doId) @@ -445,9 +445,9 @@ class ClientRepositoryBase(ConnectionRepository): # Let the dclass finish the job do.dclass.receiveUpdate(do, di) elif not ovUpdated: - # this next bit is looking for avatar handles so that if you get an update - # for an avatar that isn't in your doId2do table but there is a - # avatar handle for that object then it's messages will be forwarded to that + # this next bit is looking for avatar handles so that if you get an update + # for an avatar that isn't in your doId2do table but there is a + # avatar handle for that object then it's messages will be forwarded to that # object. We are currently using that for whisper echoing # if you need a more general perpose system consider registering proxy objects on # a dict and adding the avatar handles to that dict when they are created @@ -458,14 +458,14 @@ class ClientRepositoryBase(ConnectionRepository): if handle: dclass = self.dclassesByName[handle.dclassName] dclass.receiveUpdate(handle, di) - + else: self.notify.warning( "Asked to update non-existent DistObj " + str(doId)) except: self.notify.warning( "Asked to update non-existent DistObj " + str(doId) + "and failed to find it") - + def __doUpdateOwner(self, doId, di): ovObj = self.doId2ownerView.get(doId) if ovObj: @@ -489,7 +489,7 @@ class ClientRepositoryBase(ConnectionRepository): self.bootedText = None self.notify.warning( "Server is booting us out with no explanation.") - + # disconnect now, don't wait for send/recv to fail self.stopReaderPollTask() self.lostConnection() @@ -504,7 +504,7 @@ class ClientRepositoryBase(ConnectionRepository): message = di.getString() self.notify.info('Message from server: %s' % (message)) return message - + def handleSystemMessageAknowledge(self, di): # Got a system message from the server. message = di.getString() diff --git a/direct/src/distributed/ClockDelta.py b/direct/src/distributed/ClockDelta.py index 21c282cb85..3a3705d5eb 100644 --- a/direct/src/distributed/ClockDelta.py +++ b/direct/src/distributed/ClockDelta.py @@ -192,7 +192,7 @@ class ClockDelta(DirectObject.DirectObject): oldUncertainty = self.getUncertainty() if oldUncertainty != None: self.notify.info( - 'previous delta at %.3f s, +/- %.3f s.' % + 'previous delta at %.3f s, +/- %.3f s.' % (self.delta, oldUncertainty)) self.notify.info( 'new delta at %.3f s, +/- %.3f s.' % diff --git a/direct/src/distributed/ConnectionRepository.py b/direct/src/distributed/ConnectionRepository.py index 48ef67c266..3ff327a5b4 100644 --- a/direct/src/distributed/ConnectionRepository.py +++ b/direct/src/distributed/ConnectionRepository.py @@ -13,7 +13,7 @@ import gc -class ConnectionRepository( +class ConnectionRepository( DoInterestManager, DoCollectionManager, CConnectionRepository): """ This is a base class for things that know how to establish a @@ -39,7 +39,7 @@ class ConnectionRepository( if threadedNet is None: # Default value. threadedNet = config.GetBool('threaded-net', False) - + # let the C connection repository know whether we're supporting # 'owner' views of distributed objects (i.e. 'receives ownrecv', # 'I own this object and have a separate view of it regardless of @@ -60,7 +60,7 @@ class ConnectionRepository( # events in the main thread, instead of within the network # thread (if there is one). self.accept(self._getLostConnectionEvent(), self.lostConnection) - + self.config = config if self.config.GetBool('verbose-repository'): @@ -103,7 +103,7 @@ class ConnectionRepository( self.notify.info("Using connect method 'net'") elif self.connectMethod == self.CM_NATIVE: self.notify.info("Using connect method 'native'") - + self.connectHttp = None self.http = None @@ -134,7 +134,7 @@ class ConnectionRepository( # periodically increase gc threshold if there is no garbage taskMgr.doMethodLater(self.config.GetFloat('garbage-threshold-adjust-delay', 5 * 60.), self._adjustGcThreshold, self.GarbageThresholdTaskName) - + self._gcDefaultThreshold = gc.get_threshold() def _getLostConnectionEvent(self): diff --git a/direct/src/distributed/DistributedCamera.py b/direct/src/distributed/DistributedCamera.py index e714db6d57..7ea07d91bb 100755 --- a/direct/src/distributed/DistributedCamera.py +++ b/direct/src/distributed/DistributedCamera.py @@ -1,5 +1,5 @@ from pandac.PandaModules import * -from direct.fsm.FSM import FSM +from direct.fsm.FSM import FSM from direct.interval.IntervalGlobal import * from direct.distributed.DistributedObject import DistributedObject @@ -10,7 +10,7 @@ class Fixture(NodePath, FSM): self.id = id self.lens = PerspectiveLens() self.lens.setFov(base.camLens.getFov()) - + model = loader.loadModel('models/misc/camera', okMissing = True) model.reparentTo(self) @@ -46,17 +46,17 @@ class Fixture(NodePath, FSM): fov = self.lens.getFov() self.lens.setFov(fov[0]+x, fov[1]+y) self.dirty = True - + def getFov(self): return self.lens.getFov() - + def setupFrustum(self): oldFrustum = self.find('frustum') if oldFrustum: oldFrustum.detachNode() - + self.attachNewNode(GeomNode('frustum')).node().addGeom(self.lens.makeGeometry()) - + def setRecordingInProgress(self, inProgress): self.recordingInProgress = inProgress if self.recordingInProgress and \ @@ -64,7 +64,7 @@ class Fixture(NodePath, FSM): self.hide() else: self.show() - + def show(self): if base.config.GetBool('aware-of-cameras',0) and \ not self.recordingInProgress: @@ -75,7 +75,7 @@ class Fixture(NodePath, FSM): self.scaleIval = Sequence(LerpScaleInterval(self.getChild(0), 0.25, 2, startScale = 1, blendType = 'easeInOut'), LerpScaleInterval(self.getChild(0), 0.25, 1, startScale = 2, blendType = 'easeInOut')) return self.scaleIval - + def setState(self, state): self.request(state) @@ -95,7 +95,7 @@ class Fixture(NodePath, FSM): self.scaleIval = None self.hide() - + def enterStandby(self): self.show() if self.id == base.config.GetInt('camera-id', -1): @@ -104,7 +104,7 @@ class Fixture(NodePath, FSM): else: self.setColorScale(3,3,0,1) self.getScaleIval().finish() - + def enterBlinking(self): self.show() self.setColorScale(0,3,0,1) @@ -150,8 +150,8 @@ class Fixture(NodePath, FSM): lodNodes = render.findAllMatches('**/+LODNode') for i in xrange(0,lodNodes.getNumPaths()): lodNodes[i].node().forceSwitch(lodNodes[i].node().getHighestSwitch()) - - + + def exitUsing(self): self.ignore('arrow_left') self.ignore('arrow_left-repeat') @@ -169,7 +169,7 @@ class Fixture(NodePath, FSM): if self.dirty: messenger.send('refresh-fixture', [self.id, self.pack()]) self.dirty = False - + class DistributedCamera(DistributedObject): def __init__(self, cr): @@ -192,17 +192,17 @@ class DistributedCamera(DistributedObject): for fixture in self.fixtures.itervalues(): out = '%s\n%s' % (out, fixture.pack()) return out[1:] - + def disable(self): self.ignore('escape') - + self.parent = None - + for fixture in self.fixtures.itervalues(): fixture.cleanup() fixture.detachNode() self.fixtures = {} - + DistributedObject.disable(self) def getOV(self): @@ -220,7 +220,7 @@ class DistributedCamera(DistributedObject): def getCamParent(self): return self.parent - + def setFixtures(self, fixtures): for x in range(len(fixtures), len(self.fixtures)): fixture = self.fixtures.pop(x) @@ -236,14 +236,14 @@ class DistributedCamera(DistributedObject): if x not in self.fixtures: self.fixtures[x] = Fixture(x, self.parent, Point3(0), hpr = Point3(0), fov = VBase2(0)) - + fix = self.fixtures.get(x) fix.setId(x) fix.setPosHpr(pos,hpr) fix.setState(state) fix.setFov(fov) recordingInProgress |= state == 'Recording' - + messenger.send('recordingInProgress', [recordingInProgress]) def testFixture(self, index): diff --git a/direct/src/distributed/DistributedCameraOV.py b/direct/src/distributed/DistributedCameraOV.py index 4ee8dfcb9f..82945de29e 100755 --- a/direct/src/distributed/DistributedCameraOV.py +++ b/direct/src/distributed/DistributedCameraOV.py @@ -12,13 +12,13 @@ class DistributedCameraOV(DistributedObjectOV): self.ignore('escape') self.ignore('refresh-fixture') DistributedObjectOV.delete(self) - + def getObject(self): return self.cr.getDo(self.getDoId()) - + def setCamParent(self, doId): self.parent = doId - + def setFixtures(self, fixtures): self.fixtures = fixtures @@ -31,7 +31,7 @@ class DistributedCameraOV(DistributedObjectOV): data = data.strip().replace('Camera','') pos,hpr,fov = eval(data) return pos,hpr,fov - + def loadFromFile(self, name): self.b_setFixtures([]) f = file('cameras-%s.txt' % name, 'r'); @@ -53,7 +53,7 @@ class DistributedCameraOV(DistributedObjectOV): # distributed only self.d_setFixtures(self.fixtures) - + def b_setFixtures(self, fixtures): self.getObject().setFixtures(fixtures) self.setFixtures(fixtures) @@ -101,7 +101,7 @@ class DistributedCameraOV(DistributedObjectOV): hpr[0], hpr[1], hpr[2], 'Standby'], index) - + def startRecording(self): self.accept('escape', self.stopRecording) for fixture in self.fixtures: diff --git a/direct/src/distributed/DistributedCartesianGrid.py b/direct/src/distributed/DistributedCartesianGrid.py index f4a645eaab..80d0bafc4e 100755 --- a/direct/src/distributed/DistributedCartesianGrid.py +++ b/direct/src/distributed/DistributedCartesianGrid.py @@ -24,7 +24,7 @@ GRID_Z_OFFSET = 0.0 class DistributedCartesianGrid(DistributedNode, CartesianGridBase): notify = directNotify.newCategory("DistributedCartesianGrid") notify.setDebug(0) - + VisualizeGrid = ConfigVariableBool("visualize-cartesian-grid", False) RuleSeparator = ":" @@ -102,14 +102,14 @@ class DistributedCartesianGrid(DistributedNode, CartesianGridBase): if child.gridParent: child.gridParent.delete() child.gridParent = None - + @report(types = ['deltaStamp', 'avLocation', 'args'], dConfigParam = ['connector','shipboard']) def startProcessVisibility(self, avatar): if not self._onOffState: # if we've been told that we're OFF, don't try # to process visibilty return - + assert not self.cr._noNewInterests if self.cr.noNewInterests(): self.notify.warning( @@ -168,7 +168,7 @@ class DistributedCartesianGrid(DistributedNode, CartesianGridBase): return Task.done if self.visAvatar.gameFSM.state == 'Cutscene': return Task.cont - + pos = self.visAvatar.getPos(self) # Check to make sure our x and y are positive dx = self.cellWidth * self.gridSize * .5 @@ -211,14 +211,14 @@ class DistributedCartesianGrid(DistributedNode, CartesianGridBase): assert self.notify.debug( "processVisibility: %s: altering interest to zoneId: %s" % (self.doId, zoneId)) - + event = None if self.visDirty: - event = self.uniqueName("visibility") + event = self.uniqueName("visibility") self.cr.alterInterest( self.gridVisContext, self.getDoId(), self.visZone, event = event) - + # If the visAvatar is parented to this grid, also do a # setLocation parentId = self.visAvatar.parentId @@ -236,7 +236,7 @@ class DistributedCartesianGrid(DistributedNode, CartesianGridBase): return Task.cont # Update our location based on our avatar's position on the grid - # Assumes our position is correct, relative to the grid + # Assumes our position is correct, relative to the grid def addObjectToGrid(self, av): assert self.notify.debug("addObjectToGrid %s" % av) # Get our pos relative to the island grid @@ -273,12 +273,12 @@ class DistributedCartesianGrid(DistributedNode, CartesianGridBase): def turnOff(self): self._onOffState = False self.stopProcessVisibility() - + def turnOn(self, av = None): self._onOffState = True if av: self.startProcessVisibility(av) - + ################################################## # Visualization Tools ################################################## @@ -416,6 +416,6 @@ class DistributedCartesianGrid(DistributedNode, CartesianGridBase): def setWorldContext(self, worldContext): pass - + def clearWorldContext(self, event = None): pass diff --git a/direct/src/distributed/DistributedCartesianGridAI.py b/direct/src/distributed/DistributedCartesianGridAI.py index ea9e12616e..e9f3b53816 100755 --- a/direct/src/distributed/DistributedCartesianGridAI.py +++ b/direct/src/distributed/DistributedCartesianGridAI.py @@ -34,7 +34,7 @@ class DistributedCartesianGridAI(DistributedNodeAI, CartesianGridBase): def getCellWidth(self): return self.cellWidth - + def getParentingRules(self): self.notify.debug("calling getter") rule = ("%i%s%i%s%i" % (self.startingZone, self.RuleSeparator, @@ -127,7 +127,7 @@ class DistributedCartesianGridAI(DistributedNodeAI, CartesianGridBase): if not self.isValidZone(zoneId): self.notify.warning( - "%s handleAvatarZoneChange %s: not a valid zone (%s) for pos %s" %(self.doId, av.doId, zoneId, pos)) + "%s handleAvatarZoneChange %s: not a valid zone (%s) for pos %s" %(self.doId, av.doId, zoneId, pos)) return # Set the location on the server. diff --git a/direct/src/distributed/DistributedObject.py b/direct/src/distributed/DistributedObject.py index f785e197e3..cfd25fda23 100644 --- a/direct/src/distributed/DistributedObject.py +++ b/direct/src/distributed/DistributedObject.py @@ -326,12 +326,12 @@ class DistributedObject(DistributedObjectBase): #This message was moved out of announce generate - #to avoid ordering issues. + #to avoid ordering issues. def postGenerateMessage(self): if self.activeState != ESGenerated: self.activeState = ESGenerated messenger.send(self.uniqueName("generate"), [self]) - + def updateRequiredFields(self, dclass, di): dclass.receiveUpdateBroadcastRequired(self, di) self.announceGenerate() @@ -341,7 +341,7 @@ class DistributedObject(DistributedObjectBase): dclass.receiveUpdateAllRequired(self, di) self.announceGenerate() self.postGenerateMessage() - + def updateRequiredOtherFields(self, dclass, di): # First, update the required fields dclass.receiveUpdateBroadcastRequired(self, di) @@ -350,7 +350,7 @@ class DistributedObject(DistributedObjectBase): # but before we update the non-required fields. self.announceGenerate() self.postGenerateMessage() - + dclass.receiveUpdateOther(self, di) def sendUpdate(self, fieldName, args = [], sendToId = None): diff --git a/direct/src/distributed/DistributedObjectAI.py b/direct/src/distributed/DistributedObjectAI.py index dd746223c6..18985e42e1 100644 --- a/direct/src/distributed/DistributedObjectAI.py +++ b/direct/src/distributed/DistributedObjectAI.py @@ -242,13 +242,13 @@ class DistributedObjectAI(DistributedObjectBase): def postGenerateMessage(self): self.__generated = True - messenger.send(self.uniqueName("generate"), [self]) + messenger.send(self.uniqueName("generate"), [self]) def updateRequiredFields(self, dclass, di): dclass.receiveUpdateBroadcastRequired(self, di) self.announceGenerate() self.postGenerateMessage() - + def updateAllRequiredFields(self, dclass, di): dclass.receiveUpdateAllRequired(self, di) self.announceGenerate() @@ -260,7 +260,7 @@ class DistributedObjectAI(DistributedObjectBase): # but before we update the non-required fields. self.announceGenerate() self.postGenerateMessage() - + dclass.receiveUpdateOther(self, di) def updateAllRequiredOtherFields(self, dclass, di): @@ -269,7 +269,7 @@ class DistributedObjectAI(DistributedObjectBase): # but before we update the non-required fields. self.announceGenerate() self.postGenerateMessage() - + dclass.receiveUpdateOther(self, di) def sendSetZone(self, zoneId): @@ -387,7 +387,7 @@ class DistributedObjectAI(DistributedObjectBase): self.generate() self.announceGenerate() self.postGenerateMessage() - + # this is a special generate used for estates, or anything else that # needs to have a hard coded doId as assigned by the server def generateWithRequiredAndId(self, doId, parentId, zoneId, optionalFields=[]): @@ -402,7 +402,7 @@ class DistributedObjectAI(DistributedObjectBase): self.generate() self.announceGenerate() self.postGenerateMessage() - + def generateOtpObject(self, parentId, zoneId, optionalFields=[], doId=None): assert self.notify.debugStateCall(self) # have we already allocated a doId? @@ -574,8 +574,8 @@ class DistributedObjectAI(DistributedObjectBase): def execCommand(self, string, mwMgrId, avId, zoneId): pass - + def _retrieveCachedData(self): """ This is a no-op on the AI. """ pass - + diff --git a/direct/src/distributed/DistributedObjectGlobalAI.py b/direct/src/distributed/DistributedObjectGlobalAI.py index cbd6c94d04..10b80be712 100755 --- a/direct/src/distributed/DistributedObjectGlobalAI.py +++ b/direct/src/distributed/DistributedObjectGlobalAI.py @@ -9,17 +9,17 @@ class DistributedObjectGlobalAI(DistributedObjectAI): doNotDeallocateChannel = 1 isGlobalDistObj = 1 - def __init__(self, air): + def __init__(self, air): DistributedObjectAI.__init__(self, air) def announceGenerate(self): DistributedObjectAI.announceGenerate(self) try: if not self.doNotListenToChannel: - self.air.registerForChannel(self.doId) + self.air.registerForChannel(self.doId) except AttributeError: - self.air.registerForChannel(self.doId) - return False + self.air.registerForChannel(self.doId) + return False def delete(self): DistributedObjectAI.delete(self) @@ -29,4 +29,4 @@ class DistributedObjectGlobalAI(DistributedObjectAI): except AttributeError: self.air.unregisterForChannel(self.doId) ## self.air.removeDOFromTables(self) - + diff --git a/direct/src/distributed/DistributedObjectGlobalUD.py b/direct/src/distributed/DistributedObjectGlobalUD.py index c53f1cdde9..191c60c685 100755 --- a/direct/src/distributed/DistributedObjectGlobalUD.py +++ b/direct/src/distributed/DistributedObjectGlobalUD.py @@ -14,11 +14,11 @@ class DistributedObjectGlobalUD(DistributedObjectUD): def __init__(self, air): DistributedObjectUD.__init__(self, air) self.ExecNamespace = {"self":self} - + def announceGenerate(self): self.air.registerForChannel(self.doId) DistributedObjectUD.announceGenerate(self) - + def delete(self): self.air.unregisterForChannel(self.doId) ## self.air.removeDOFromTables(self) @@ -26,7 +26,7 @@ class DistributedObjectGlobalUD(DistributedObjectUD): def execCommand(self, command, mwMgrId, avId, zoneId): text = str(self.__execMessage(command))[:config.GetInt("ai-debug-length",300)] - + dclass = uber.air.dclassesByName.get("PiratesMagicWordManagerAI") dg = dclass.aiFormatUpdate( "setMagicWordResponse", mwMgrId, (1<<32)+avId, uber.air.ourChannel, [text]) diff --git a/direct/src/distributed/DistributedObjectOV.py b/direct/src/distributed/DistributedObjectOV.py index 8c4e7a6760..ef3c12dd62 100755 --- a/direct/src/distributed/DistributedObjectOV.py +++ b/direct/src/distributed/DistributedObjectOV.py @@ -169,7 +169,7 @@ class DistributedObjectOV(DistributedObjectBase): # but before we update the non-required fields. self.announceGenerate() self.postGenerateMessage() - + dclass.receiveUpdateOther(self, di) def getCacheable(self): diff --git a/direct/src/distributed/DistributedObjectUD.py b/direct/src/distributed/DistributedObjectUD.py index 6d39c003c1..7642cd222b 100755 --- a/direct/src/distributed/DistributedObjectUD.py +++ b/direct/src/distributed/DistributedObjectUD.py @@ -213,7 +213,7 @@ class DistributedObjectUD(DistributedObjectBase): # but before we update the non-required fields. self.announceGenerate() self.postGenerateMessage() - + dclass.receiveUpdateOther(self, di) def updateAllRequiredOtherFields(self, dclass, di): @@ -222,7 +222,7 @@ class DistributedObjectUD(DistributedObjectBase): # but before we update the non-required fields. self.announceGenerate() self.postGenerateMessage() - + dclass.receiveUpdateOther(self, di) def sendSetZone(self, zoneId): @@ -233,7 +233,7 @@ class DistributedObjectUD(DistributedObjectBase): # arguments are newZoneId, oldZoneId # includes the quiet zone. return 'DOChangeZone-%s' % self.doId - + def getLogicalZoneChangeEvent(self): # this event is generated whenever this object changes to a # non-quiet-zone zone. @@ -324,7 +324,7 @@ class DistributedObjectUD(DistributedObjectBase): self.generate() self.announceGenerate() self.postGenerateMessage() - + def generateOtpObject(self, parentId, zoneId, optionalFields=[], doId=None): assert self.notify.debugStateCall(self) # have we already allocated a doId? diff --git a/direct/src/distributed/DistributedSmoothNode.py b/direct/src/distributed/DistributedSmoothNode.py index aff5189aba..34ad0ae52b 100644 --- a/direct/src/distributed/DistributedSmoothNode.py +++ b/direct/src/distributed/DistributedSmoothNode.py @@ -113,7 +113,7 @@ class DistributedSmoothNode(DistributedNode.DistributedNode, to specialize the behavior. """ self.smoother.computeAndApplySmoothPosHpr(self, self) - + def doSmoothTask(self, task): self.smoothPosition() return cont @@ -205,7 +205,7 @@ class DistributedSmoothNode(DistributedNode.DistributedNode, self.smoother.markPosition() self.stopped = False - + # distributed set pos and hpr functions # 'send' versions are inherited from DistributedSmoothNodeBase def setSmStop(self, timestamp=None): @@ -398,7 +398,7 @@ class DistributedSmoothNode(DistributedNode.DistributedNode, return self.getR() def getComponentT(self): return 0 - + @report(types = ['args'], dConfigParam = 'smoothnode') def clearSmoothing(self, bogus = None): # Call this to invalidate all the old position reports @@ -442,7 +442,7 @@ class DistributedSmoothNode(DistributedNode.DistributedNode, self.sendUpdate("suggestResync", [avId, timestampA, timestampB, serverTimeSec, serverTimeUSec, uncertainty]) - + def suggestResync(self, avId, timestampA, timestampB, serverTimeSec, serverTimeUSec, uncertainty): """ @@ -471,14 +471,14 @@ class DistributedSmoothNode(DistributedNode.DistributedNode, self.cr.localAvatarDoId, timestampB, serverTime, globalClockDelta.getUncertainty()) - + def d_returnResync(self, avId, timestampB, serverTime, uncertainty): serverTimeSec = math.floor(serverTime) serverTimeUSec = (serverTime - serverTimeSec) * 10000.0 self.sendUpdate("returnResync", [ avId, timestampB, serverTimeSec, serverTimeUSec, uncertainty]) - + def returnResync(self, avId, timestampB, serverTimeSec, serverTimeUSec, uncertainty): """ diff --git a/direct/src/distributed/DistributedSmoothNodeBase.py b/direct/src/distributed/DistributedSmoothNodeBase.py index c8338fa8c9..47dfbf8b4e 100755 --- a/direct/src/distributed/DistributedSmoothNodeBase.py +++ b/direct/src/distributed/DistributedSmoothNodeBase.py @@ -9,7 +9,7 @@ class DummyTaskClass: pass DummyTask = DummyTaskClass() - + class DistributedSmoothNodeBase: """common base class for DistributedSmoothNode and DistributedSmoothNodeAI """ @@ -65,7 +65,7 @@ class DistributedSmoothNodeBase: def startPosHprBroadcast(self, period=.2, stagger=0, type=None): if self.cnode == None: self.initializeCnode() - + BT = DistributedSmoothNodeBase.BroadcastTypes if type is None: type = BT.FULL @@ -79,7 +79,7 @@ class DistributedSmoothNodeBase: } # this comment is here so it will show up in a grep for 'def d_broadcastPosHpr' self.d_broadcastPosHpr = broadcastFuncs[self.broadcastType] - + # Set stagger to non-zero to randomly delay the initial task execution # over 'period' seconds, to spread out task processing over time # when a large number of SmoothNodes are created simultaneously. diff --git a/direct/src/distributed/DoCollectionManager.py b/direct/src/distributed/DoCollectionManager.py index f0f4f24233..691e84f75a 100755 --- a/direct/src/distributed/DoCollectionManager.py +++ b/direct/src/distributed/DoCollectionManager.py @@ -79,10 +79,10 @@ class DoCollectionManager: if re.search(str,repr(value)): matches.append(value) return matches - + def doFindAllOfType(self, query): """ - Useful method for searching through the Distributed Object collection + Useful method for searching through the Distributed Object collection for objects of a particular type """ matches = [] @@ -185,7 +185,7 @@ class DoCollectionManager: strToReturn = '%s\n== doId2ownerView\n' % (strToReturn) strToReturn = '%s%s' % (strToReturn, self._returnObjects(self.getDoTable(ownerView=False))) return strToReturn - + def printObjectCount(self): # print object counts by distributed object type @@ -220,7 +220,7 @@ class DoCollectionManager: def hasOwnerViewDoId(self, doId): assert self.hasOwnerView() return doId in self.doId2ownerView - + def getOwnerViewDoList(self, classType): assert self.hasOwnerView() l = [] @@ -295,7 +295,7 @@ class DoCollectionManager: (doId, parentId, zoneId)) # Let the object finish the job # calls storeObjectLocation() - obj.setLocation(parentId, zoneId) + obj.setLocation(parentId, zoneId) else: self.notify.warning( "handleObjectLocation: Asked to update non-existent obj: %s" % (doId)) @@ -322,7 +322,7 @@ class DoCollectionManager: if oldParentObj is not None: oldParentObj.handleChildLeave(object, oldZoneId) self.deleteObjectLocation(object, oldParentId, oldZoneId) - + elif (oldZoneId != zoneId): # Remove old location oldParentObj = self.doId2do.get(oldParentId) @@ -367,7 +367,7 @@ class DoCollectionManager: elif parentId not in (None, 0, self.getGameDoId()): self.notify.warning('storeObjectLocation(%s): parent %s not present' % (object.doId, parentId)) - + def deleteObjectLocation(self, object, parentId, zoneId): # Do not worry about null values if ((parentId is None) or (zoneId is None) or diff --git a/direct/src/distributed/DoInterestManager.py b/direct/src/distributed/DoInterestManager.py index f7bd1b0723..ed72de562c 100755 --- a/direct/src/distributed/DoInterestManager.py +++ b/direct/src/distributed/DoInterestManager.py @@ -173,14 +173,14 @@ class DoInterestManager(DirectObject.DirectObject): 'addInterest: no setParentingRules defined in the DC for object %s (%s)' '' % (parentId, parent.__class__.__name__)) - - + + if event: contextId = self._getNextContextId() else: contextId = 0 # event = self._getAnonymousEvent('addInterest') - + DoInterestManager._interests[handle] = InterestState( description, InterestState.StateActive, contextId, event, parentId, zoneIdList, self._completeEventCount) if self.__verbose(): @@ -273,7 +273,7 @@ class DoInterestManager(DirectObject.DirectObject): "removeInterest: handle not found: %s" % (handle)) assert self.printInterestsIfDebug() return existed - + def removeAutoInterest(self, handle): """ Stop looking in a (set of) zone(s) @@ -352,7 +352,7 @@ class DoInterestManager(DirectObject.DirectObject): contextId = self._getNextContextId() DoInterestManager._interests[handle].context = contextId - DoInterestManager._interests[handle].parentId = parentId + DoInterestManager._interests[handle].parentId = parentId DoInterestManager._interests[handle].zoneIdList = zoneIdList DoInterestManager._interests[handle].addEvent(event) @@ -421,7 +421,7 @@ class DoInterestManager(DirectObject.DirectObject): Consider whether we should cull the interest set. """ assert DoInterestManager.notify.debugCall() - + if handle in DoInterestManager._interests: if DoInterestManager._interests[handle].isPendingDelete(): # make sure there is no pending event for this interest @@ -454,12 +454,12 @@ class DoInterestManager(DirectObject.DirectObject): print format % tuple(i) print "Note: interests with a Context of 0 do not get" \ " done/finished notices." - + def printInterestSets(self): print "******************* Interest Sets **************" format = '%6s %' + str(DoInterestManager._debug_maxDescriptionLen) + 's %11s %11s %8s %8s %8s' print format % ( - "Handle", "Description", + "Handle", "Description", "ParentId", "ZoneIdList", "State", "Context", "Event") @@ -479,7 +479,7 @@ class DoInterestManager(DirectObject.DirectObject): def printInterests(self): self.printInterestHistory() self.printInterestSets() - + def _sendAddInterest(self, handle, contextId, parentId, zoneIdList, description, action=None): """ diff --git a/direct/src/distributed/GridChild.py b/direct/src/distributed/GridChild.py index 58ac9783b4..78b35f8c67 100755 --- a/direct/src/distributed/GridChild.py +++ b/direct/src/distributed/GridChild.py @@ -41,7 +41,7 @@ class GridChild: # than just one) #if self._gridInterestEnabled: self.__setGridInterest(grid, zoneId) - + def enableGridInterest(self, enabled = True): self._gridInterestEnabled = enabled if enabled and self.isOnAGrid(): @@ -72,13 +72,13 @@ class GridChild: return self._gridParent.getGridZone() else: return None - + def __setGridParent(self, gridParent): if self._gridParent and self._gridParent is not gridParent: self._gridParent.delete() self._gridParent = gridParent - + def __setGridInterest(self, grid, zoneId): assert not self.cr.noNewInterests() if self.cr.noNewInterests(): @@ -146,11 +146,11 @@ class SmoothGridChild(GridChild): @report(types = ['args'], dConfigParam = 'smoothnode') def transformTelemetry(self, x, y, z, h, p, r, e): # We don't really need to transform telemetry, but - # we do update our grid cell such that the new + # we do update our grid cell such that the new # telemetry is correct now. # We do this instead of overriding setSmPosHprE() # because we're a mixin class. if self.isOnAGrid(): - self.setGridCell(self.getGrid(), e) # causes a wrtReparent() which updates + self.setGridCell(self.getGrid(), e) # causes a wrtReparent() which updates # all previous smooth positions return x, y, z, h, p, r diff --git a/direct/src/distributed/InterestWatcher.py b/direct/src/distributed/InterestWatcher.py index c82b3b86a9..094be3a677 100755 --- a/direct/src/distributed/InterestWatcher.py +++ b/direct/src/distributed/InterestWatcher.py @@ -6,7 +6,7 @@ class InterestWatcher(DirectObject): """Object that observes all interests adds/removes over a period of time, and sends out an event when all of those interests have closed""" notify = directNotify.newCategory('InterestWatcher') - + def __init__(self, interestMgr, name, doneEvent=None, recurse=True, start=True, mustCollect=False, doCollectionMgr=None): DirectObject.__init__(self) @@ -29,7 +29,7 @@ class InterestWatcher(DirectObject): self.accept(self._interestMgr._getAddInterestEvent(), self._handleInterestOpenEvent) self.accept(self._interestMgr._getRemoveInterestEvent(), self._handleInterestCloseEvent) - + def stopCollect(self): self.ignore(self._interestMgr._getAddInterestEvent()) self.ignore(self._interestMgr._getRemoveInterestEvent()) diff --git a/direct/src/distributed/MsgTypes.py b/direct/src/distributed/MsgTypes.py index 231cf78733..b5e5d260df 100644 --- a/direct/src/distributed/MsgTypes.py +++ b/direct/src/distributed/MsgTypes.py @@ -4,7 +4,7 @@ from direct.showbase.PythonUtil import invertDictLossless MsgName2Id = { # 2 new params: passwd, char bool 0/1 1 = new account - # 2 new return values: 129 = not found, 12 = bad passwd, + # 2 new return values: 129 = not found, 12 = bad passwd, 'CLIENT_LOGIN': 1, 'CLIENT_LOGIN_RESP': 2, 'CLIENT_GET_AVATARS': 3, @@ -85,15 +85,15 @@ MsgName2Id = { 'CLIENT_GET_FRIEND_LIST_EXTENDED_RESP': 116, 'CLIENT_SET_FIELD_SENDABLE': 120, - + 'CLIENT_SYSTEMMESSAGE_AKNOWLEDGE': 123, 'CLIENT_CHANGE_GENERATE_ORDER': 124, # new toontown specific login message, adds last logged in, and if child account has parent acount 'CLIENT_LOGIN_TOONTOWN': 125, - 'CLIENT_LOGIN_TOONTOWN_RESP': 126, - - + 'CLIENT_LOGIN_TOONTOWN_RESP': 126, + + 'STATESERVER_OBJECT_GENERATE_WITH_REQUIRED': 2001, 'STATESERVER_OBJECT_GENERATE_WITH_REQUIRED_OTHER': 2003, @@ -105,7 +105,7 @@ MsgName2Id = { # create id->name table for debugging MsgId2Names = invertDictLossless(MsgName2Id) - + # put msg names in module scope, assigned to msg value globals().update(MsgName2Id) @@ -115,7 +115,7 @@ QUIET_ZONE_IGNORED_LIST = [ # We mustn't ignore updates, because some updates for localToon # are always important. #CLIENT_OBJECT_UPDATE_FIELD, - + # These are now handled. If it is a create for a class that is in the # uber zone, we should create it. #CLIENT_CREATE_OBJECT_REQUIRED, diff --git a/direct/src/distributed/MsgTypesCMU.py b/direct/src/distributed/MsgTypesCMU.py index b91a505453..c0d1ccd4ca 100644 --- a/direct/src/distributed/MsgTypesCMU.py +++ b/direct/src/distributed/MsgTypesCMU.py @@ -24,6 +24,6 @@ MsgName2Id = { # create id->name table for debugging MsgId2Names = invertDictLossless(MsgName2Id) - + # put msg names in module scope, assigned to msg value globals().update(MsgName2Id) diff --git a/direct/src/distributed/ParentMgr.py b/direct/src/distributed/ParentMgr.py index eea9d5438f..434c3cbd64 100644 --- a/direct/src/distributed/ParentMgr.py +++ b/direct/src/distributed/ParentMgr.py @@ -80,7 +80,7 @@ class ParentMgr: # there is no longer any valid place for the child in the # scenegraph; put it under hidden child.reparentTo(hidden) - + def registerParent(self, token, parent): if token in self.token2nodepath: self.notify.error( diff --git a/direct/src/distributed/PyDatagram.py b/direct/src/distributed/PyDatagram.py index f5db501b72..74e73fbf28 100755 --- a/direct/src/distributed/PyDatagram.py +++ b/direct/src/distributed/PyDatagram.py @@ -32,29 +32,29 @@ class PyDatagram(Datagram): #def addChannel(self, channelId): # ... addChannel = Datagram.addUint64 - + def addServerHeader(self, channel, sender, code): self.addInt8(1) self.addChannel(channel) self.addChannel(sender) self.addUint16(code) - - + + def addOldServerHeader(self, channel, sender, code): self.addChannel(channel) self.addChannel(sender) self.addChannel('A') self.addUint16(code) - - + + # def addServerControlHeader(self, code): # self.addInt8(1) # self.addChannel(CONTROL_MESSAGE) -# self.addUint16(code) +# self.addUint16(code) # def addOldServerControlHeader(self, code): # self.addChannel(CONTROL_MESSAGE) # self.addUint16(code) - + def putArg(self, arg, subatomicType, divisor=1): if (divisor == 1): funcSpecs = self.FuncDict.get(subatomicType) diff --git a/direct/src/distributed/PyDatagramIterator.py b/direct/src/distributed/PyDatagramIterator.py index 88ebf4021b..e97600f6b4 100755 --- a/direct/src/distributed/PyDatagramIterator.py +++ b/direct/src/distributed/PyDatagramIterator.py @@ -22,7 +22,7 @@ class PyDatagramIterator(DatagramIterator): STUint32: DatagramIterator.getUint32, STUint64: DatagramIterator.getUint64, STFloat64: DatagramIterator.getFloat64, - STString: DatagramIterator.getString, + STString: DatagramIterator.getString, STBlob: DatagramIterator.getString, STBlob32: DatagramIterator.getString32, } @@ -77,7 +77,7 @@ class PyDatagramIterator(DatagramIterator): else: raise Exception("Error: No such type as: " + str(subAtomicType)) else: - # See if it is in the handy dict + # See if it is in the handy dict getFunc = self.FuncDict.get(subatomicType) if getFunc: retVal = (getFunc(self)/float(divisor)) diff --git a/direct/src/distributed/RelatedObjectMgr.py b/direct/src/distributed/RelatedObjectMgr.py index 35eb2978b4..a2c00b2ea0 100644 --- a/direct/src/distributed/RelatedObjectMgr.py +++ b/direct/src/distributed/RelatedObjectMgr.py @@ -27,7 +27,7 @@ class RelatedObjectMgr(DirectObject.DirectObject): notify = DirectNotifyGlobal.directNotify.newCategory('RelatedObjectMgr') doLaterSequence = 1 - + def __init__(self, cr): self.cr = cr self.pendingObjects = {} @@ -64,14 +64,14 @@ class RelatedObjectMgr(DirectObject.DirectObject): The return value may be saved and passed to a future call to abortRequest(), in order to abort a pending request before the timeout expires. - + Actually, you should be careful to call abortRequest() if you have made a call to requestObjects() that has not been resolved. - To find examples, do a search for abortRequest() to find out - how other code is using it. A common idiom is to store the + To find examples, do a search for abortRequest() to find out + how other code is using it. A common idiom is to store the result from requestObjects() and call abortRequest() if delete() or destroy() is called on the requesting object. - + See Also: abortRequest() """ assert self.notify.debug("requestObjects(%s, timeout=%s)" % (doIdList, timeout)) @@ -107,7 +107,7 @@ class RelatedObjectMgr(DirectObject.DirectObject): if timeout != None: doLaterName = "RelatedObject-%s" % (RelatedObjectMgr.doLaterSequence) assert self.notify.debug("doLaterName = %s" % (doLaterName)) - + RelatedObjectMgr.doLaterSequence += 1 tuple = (allCallback, eachCallback, timeoutCallback, @@ -134,7 +134,7 @@ class RelatedObjectMgr(DirectObject.DirectObject): Aborts a previous request. The parameter is the return value from a previous call to requestObjects(). The pending request is removed from the queue and no further callbacks will be called. - + See Also: requestObjects() """ if tuple: @@ -164,14 +164,14 @@ class RelatedObjectMgr(DirectObject.DirectObject): taskMgr.remove(doLaterName) self.pendingObjects = {} - + def __timeoutExpired(self, tuple): allCallback, eachCallback, timeoutCallback, doIdsPending, doIdList, doLaterName = tuple assert self.notify.debug("timeout expired for %s (remaining: %s)" % (doIdList, doIdsPending)) self.__removePending(tuple, doIdsPending) - + if timeoutCallback: timeoutCallback(doIdList) else: @@ -191,7 +191,7 @@ class RelatedObjectMgr(DirectObject.DirectObject): if len(pendingList) == 0: del self.pendingObjects[doId] self.__noListenFor(doId) - + def __listenFor(self, doId): # Start listening for the indicated object to be generated. @@ -230,7 +230,7 @@ class RelatedObjectMgr(DirectObject.DirectObject): assert self.notify.debug("All objects generated on list: %s" % (doIdList,)) if doLaterName: taskMgr.remove(doLaterName) - + objects, doIdsPending = self.__generateObjectList(doIdList) if None in objects: assert self.notify.warning('calling %s with None.\n objects=%s\n doIdsPending=%s\n doIdList=%s\n' % (allCallback,objects,doIdsPending,doIdList)) @@ -252,6 +252,6 @@ class RelatedObjectMgr(DirectObject.DirectObject): doIdsPending.append(doId) else: objects.append(None) - + return objects, doIdsPending diff --git a/direct/src/distributed/ServerRepository.py b/direct/src/distributed/ServerRepository.py index 5a24f81299..613b88788f 100644 --- a/direct/src/distributed/ServerRepository.py +++ b/direct/src/distributed/ServerRepository.py @@ -49,7 +49,7 @@ class ServerRepository: # or moving objects between zones, might influence this # set. self.currentInterestZoneIds = set() - + # A dictionary of doId -> Object, for distributed objects # currently in existence that were created by the client. self.objectsByDoId = {} @@ -76,7 +76,7 @@ class ServerRepository: # Note that the server does not store any other data about # the distributed objects; in particular, it doesn't # record its current fields. That is left to the clients. - + def __init__(self, tcpPort, serverAddress = None, udpPort = None, dcFileNames = None, @@ -137,7 +137,7 @@ class ServerRepository: # An allocator object that assigns the next doIdBase to each # client. self.idAllocator = UniqueIdAllocator(0, 0xffffffff / self.doIdRange) - + self.dcFile = DCFile() self.dcSuffix = '' self.readDCFile(dcFileNames) @@ -168,7 +168,7 @@ class ServerRepository: """Returns the current setting of TCP header size. See setTcpHeaderSize(). """ return self.qcr.getTcpHeaderSize() - + def importModule(self, dcImports, moduleName, importSymbols): """ Imports the indicated moduleName and all of its symbols @@ -317,10 +317,10 @@ class ServerRepository: # Now we can start listening to that new connection. self.qcr.addConnection(newConnection) - + self.lastConnection = newConnection self.sendDoIdRange(client) - + return task.cont def readerPollUntilEmpty(self, task): @@ -415,7 +415,7 @@ class ServerRepository: self.notify.debug( "Creating object %s of type %s by client %s" % ( doId, dclass.getName(), client.doIdBase)) - + object = self.Object(doId, zoneId, dclass) client.objectsByDoId[doId] = object client.objectsByZoneId.setdefault(zoneId, set()).add(object) @@ -433,7 +433,7 @@ class ServerRepository: dg.addUint16(classId) dg.addUint32(doId) dg.appendData(dgi.getRemainingBytes()) - + self.sendToZoneExcept(zoneId, dg, [client]) def handleClientObjectUpdateField(self, datagram, dgi, targeted = False): @@ -454,7 +454,7 @@ class ServerRepository: "Ignoring update for unknown object %s from client %s" % ( doId, client.doIdBase)) return - + dcfield = object.dclass.getFieldByIndex(fieldId) if dcfield == None: self.notify.warning( @@ -489,16 +489,16 @@ class ServerRepository: return self.cw.send(dg, target.connection) self.needsFlush.add(target) - + elif dcfield.hasKeyword('p2p'): # p2p: to object owner only self.cw.send(dg, owner.connection) self.needsFlush.add(owner) - + elif dcfield.hasKeyword('broadcast'): # Broadcast: to everyone except orig sender self.sendToZoneExcept(object.zoneId, dg, [client]) - + elif dcfield.hasKeyword('reflect'): # Reflect: broadcast to everyone including orig sender self.sendToZoneExcept(object.zoneId, dg, []) @@ -528,7 +528,7 @@ class ServerRepository: return self.sendToZoneExcept(object.zoneId, datagram, []) - + self.objectsByZoneId[object.zoneId].remove(object) if not self.objectsByZoneId[object.zoneId]: del self.objectsByZoneId[object.zoneId] @@ -632,7 +632,7 @@ class ServerRepository: self.qcr.removeConnection(client.connection) self.qcm.closeConnection(client.connection) - + def handleClientSetInterest(self, client, dgi): """ The client is specifying a particular set of zones it is @@ -645,11 +645,11 @@ class ServerRepository: client.explicitInterestZoneIds = zoneIds self.updateClientInterestZones(client) - + def updateClientInterestZones(self, client): """ Something about the client has caused its set of interest zones to potentially change. Recompute them. """ - + origZoneIds = client.currentInterestZoneIds newZoneIds = client.explicitInterestZoneIds | set(client.objectsByZoneId.keys()) if origZoneIds == newZoneIds: @@ -683,7 +683,7 @@ class ServerRepository: self.cw.send(datagram, client.connection) self.needsFlush.add(client) - + def clientHardDisconnectTask(self, task): """ client did not tell us he was leaving but we lost connection to @@ -696,7 +696,7 @@ class ServerRepository: def sendToZoneExcept(self, zoneId, datagram, exceptionList): """sends a message to everyone who has interest in the indicated zone, except for the clients on exceptionList.""" - + if self.notify.getDebug(): self.notify.debug( "ServerRepository sending to all in zone %s except %s:" % (zoneId, [c.doIdBase for c in exceptionList])) @@ -713,7 +713,7 @@ class ServerRepository: def sendToAllExcept(self, datagram, exceptionList): """ sends a message to all connected clients, except for clients on exceptionList. """ - + if self.notify.getDebug(): self.notify.debug( "ServerRepository sending to all except %s:" % ([c.doIdBase for c in exceptionList],)) diff --git a/direct/src/distributed/StagedObject.py b/direct/src/distributed/StagedObject.py index 2bb4006023..7692dc3684 100755 --- a/direct/src/distributed/StagedObject.py +++ b/direct/src/distributed/StagedObject.py @@ -6,7 +6,7 @@ class StagedObject: The idea here is that a DistributedObject could be present and active due to simple visibility, but we want to hide or otherwise disable it for some reason. """ - + UNKNOWN = -1 OFF = 0 ON = 1 @@ -31,16 +31,16 @@ class StagedObject: self.handleOnStage(*args, **kw) pass pass - + def handleOnStage(self): """ Override this function to provide your on/off stage funcitionality. - + Don't forget to call down to this one, though. """ self.__state = StagedObject.ON pass - + def goOffStage(self, *args, **kw): """ If a stage switch is needed, the correct "handle" function @@ -53,16 +53,16 @@ class StagedObject: self.handleOffStage(*args, **kw) pass pass - + def handleOffStage(self): """ Override this function to provide your on/off stage funcitionality. - + Don't forget to call down to this one, though. """ self.__state = StagedObject.OFF pass - + def isOnStage(self): return self.__state == StagedObject.ON diff --git a/direct/src/distributed/TimeManager.py b/direct/src/distributed/TimeManager.py index 36a9027028..f74a97300b 100644 --- a/direct/src/distributed/TimeManager.py +++ b/direct/src/distributed/TimeManager.py @@ -4,7 +4,7 @@ from direct.task import Task from direct.distributed import DistributedObject from direct.directnotify import DirectNotifyGlobal from direct.distributed.ClockDelta import globalClockDelta - + class TimeManager(DistributedObject.DistributedObject): """ This DistributedObject lives on the AI and on the client side, and @@ -113,7 +113,7 @@ class TimeManager(DistributedObject.DistributedObject): self.synchronize("clock error") ### Synchronization methods ### - + def synchronize(self, description): """synchronize(self, string description) @@ -132,7 +132,7 @@ class TimeManager(DistributedObject.DistributedObject): if now - self.lastAttempt < self.minWait: self.notify.debug("Not resyncing (too soon): %s" % (description)) return 0 - + self.talkResult = 0 self.thisContext = self.nextContext self.attemptCount = 0 @@ -144,7 +144,7 @@ class TimeManager(DistributedObject.DistributedObject): return 1 - + def serverTime(self, context, timestamp): """serverTime(self, int8 context, int32 timestamp) @@ -162,7 +162,7 @@ class TimeManager(DistributedObject.DistributedObject): if context != self.thisContext: self.notify.info("Ignoring TimeManager response for old context %d" % (context)) return - + elapsed = end - self.start self.attemptCount += 1 self.notify.info("Clock sync roundtrip took %0.3f ms" % (elapsed * 1000.0)) @@ -181,7 +181,7 @@ class TimeManager(DistributedObject.DistributedObject): self.sendUpdate("requestServerTime", [self.thisContext]) return self.notify.info("Giving up on uncertainty requirement.") - + messenger.send("gotTimeSync", taskChain = 'default') messenger.send(self.cr.uniqueName("gotTimeSync"), taskChain = 'default') diff --git a/direct/src/extensions_native/HTTPChannel_extensions.py b/direct/src/extensions_native/HTTPChannel_extensions.py index e70bbd77d1..3d87a97bc9 100644 --- a/direct/src/extensions_native/HTTPChannel_extensions.py +++ b/direct/src/extensions_native/HTTPChannel_extensions.py @@ -1,5 +1,5 @@ #################################################################### -#Dtool_funcToMethod(func, class) +#Dtool_funcToMethod(func, class) #del func ##################################################################### @@ -32,7 +32,7 @@ if hasattr(core, 'HTTPChannel'): Dtool_funcToMethod(spawnTask, core.HTTPChannel) del spawnTask ##################################################################### - + def doTask(self, task): from direct.task import Task if self.run(): diff --git a/direct/src/extensions_native/Mat3_extensions.py b/direct/src/extensions_native/Mat3_extensions.py index dc47a04f04..28e862ca78 100644 --- a/direct/src/extensions_native/Mat3_extensions.py +++ b/direct/src/extensions_native/Mat3_extensions.py @@ -1,5 +1,5 @@ #################################################################### -#Dtool_funcToMethod(func, class) +#Dtool_funcToMethod(func, class) #del func ##################################################################### @@ -17,6 +17,6 @@ def pPrintValues(self): """ return "\n%s\n%s\n%s" % ( self.getRow(0).pPrintValues(), self.getRow(1).pPrintValues(), self.getRow(2).pPrintValues()) -Dtool_funcToMethod(pPrintValues, Mat3) +Dtool_funcToMethod(pPrintValues, Mat3) del pPrintValues ##################################################################### diff --git a/direct/src/filter/CommonFilters.py b/direct/src/filter/CommonFilters.py index a6f9e43520..c861561066 100644 --- a/direct/src/filter/CommonFilters.py +++ b/direct/src/filter/CommonFilters.py @@ -10,7 +10,7 @@ the composition process isn't simply a question of concatenating them: you have to somehow make them work together. I suspect that there exists some fairly simple framework that would make this automatable. However, until I write some more filters myself, I won't know what -that framework is. Until then, I'll settle for this +that framework is. Until then, I'll settle for this clunky approach. - Josh """ @@ -337,13 +337,13 @@ class CommonFilters: if ("Inverted" in configuration): text += " o_color = float4(1, 1, 1, 1) - o_color;\n" text += "}\n" - + self.finalQuad.setShader(Shader.make(text, Shader.SL_Cg)) for tex in self.textures: self.finalQuad.setShaderInput("tx"+tex, self.textures[tex]) - + self.task = taskMgr.add(self.update, "common-filters-update") - + if (changed == "CartoonInk") or fullrebuild: if ("CartoonInk" in configuration): c = configuration["CartoonInk"] @@ -363,13 +363,13 @@ class CommonFilters: self.bloom[0].setShaderInput("trigger", bloomconf.mintrigger, 1.0/(bloomconf.maxtrigger-bloomconf.mintrigger), 0.0, 0.0) self.bloom[0].setShaderInput("desat", bloomconf.desat) self.bloom[3].setShaderInput("intensity", intensity, intensity, intensity, intensity) - + if (changed == "VolumetricLighting") or fullrebuild: if ("VolumetricLighting" in configuration): config = configuration["VolumetricLighting"] tcparam = config.density / float(config.numsamples) self.finalQuad.setShaderInput("vlparams", tcparam, config.decay, config.exposure, 0.0) - + if (changed == "AmbientOcclusion") or fullrebuild: if ("AmbientOcclusion" in configuration): config = configuration["AmbientOcclusion"] diff --git a/direct/src/filter/FilterManager.py b/direct/src/filter/FilterManager.py index 432ae6fe93..bf35abf3c9 100644 --- a/direct/src/filter/FilterManager.py +++ b/direct/src/filter/FilterManager.py @@ -44,7 +44,7 @@ class FilterManager(DirectObject): FilterManager.notify = directNotify.newCategory("FilterManager") # Find the appropriate display region. - + region = None for dr in win.getDisplayRegions(): drcam = dr.getCamera() @@ -54,7 +54,7 @@ class FilterManager(DirectObject): if region is None: self.notify.error('Could not find appropriate DisplayRegion to filter') return False - + # Instance Variables. self.win = win @@ -102,7 +102,7 @@ class FilterManager(DirectObject): (self.region.getRight() == 1.0) and (self.region.getBottom() == 0.0) and (self.region.getTop() == 1.0)) - + def getScaledSize(self, mul, div, align): """ Calculate the size of the desired window. Not public. """ @@ -213,7 +213,7 @@ class FilterManager(DirectObject): lens.setNearFar(-1000, 1000) quadcamnode.setLens(lens) quadcam = quad.attachNewNode(quadcamnode) - + self.region.setCamera(quadcam) self.setStackedClears(buffer, self.rclears, self.wclears) @@ -247,7 +247,7 @@ class FilterManager(DirectObject): texgroup = (depthtex, colortex, auxtex0, auxtex1) winx, winy = self.getScaledSize(mul, div, align) - + depthbits = bool(depthtex != None) buffer = self.createBuffer("filter-stage", winx, winy, texgroup, depthbits) @@ -284,7 +284,7 @@ class FilterManager(DirectObject): self.buffers.append(buffer) self.sizes.append((mul, div, align)) - + return quad def createBuffer(self, name, xsize, ysize, texgroup, depthbits=1): diff --git a/direct/src/fsm/ClassicFSM.py b/direct/src/fsm/ClassicFSM.py index 98191166ab..a0d6045c5f 100644 --- a/direct/src/fsm/ClassicFSM.py +++ b/direct/src/fsm/ClassicFSM.py @@ -108,7 +108,7 @@ class ClassicFSM(DirectObject): assert not self.__internalStateInFlux if self.__currentState == self.__initialState: return - + assert self.__currentState == None self.__internalStateInFlux = 1 self.__enter(self.__initialState, argList) diff --git a/direct/src/fsm/FSM.py b/direct/src/fsm/FSM.py index db85ad4b00..1c0465b74d 100644 --- a/direct/src/fsm/FSM.py +++ b/direct/src/fsm/FSM.py @@ -197,7 +197,7 @@ class FSM(DirectObject): # If there's no matching filterState() function, call # defaultFilter() instead. filter = self.defaultFilter - + return filter def getCurrentOrNextState(self): @@ -394,7 +394,7 @@ class FSM(DirectObject): if request[0].isupper(): return (request,) + args return self.defaultFilter(request, args) - + def setStateArray(self, stateArray): """array of unique states to iterate through""" diff --git a/direct/src/fsm/FourState.py b/direct/src/fsm/FourState.py index 52c9549d85..790439e901 100755 --- a/direct/src/fsm/FourState.py +++ b/direct/src/fsm/FourState.py @@ -13,15 +13,15 @@ import State class FourState: """ Generic four state ClassicFSM base class. - + This is a mix-in class that expects that your derived class is a DistributedObject. - - Inherit from FourStateFSM and pass in your states. Two of - the states should be oposites of each other and the other + + Inherit from FourStateFSM and pass in your states. Two of + the states should be oposites of each other and the other two should be the transition states between the first two. E.g. - + +--------+ -->| closed | -- | +--------+ | @@ -35,10 +35,10 @@ class FourState: | +------+ | ----| open |<--- +------+ - + There is a fifth off state, but that is an implementation detail (and that's why it's not called a five state ClassicFSM). - + I found that this pattern repeated in several things I was working on, so this base class was created. """ @@ -47,22 +47,22 @@ class FourState: def __init__(self, names, durations = [0, 1, None, 1, 1]): """ names is a list of state names - + E.g. ['off', 'opening', 'open', 'closing', 'closed',] - + e.g. 2: ['off', 'locking', 'locked', 'unlocking', 'unlocked',] - + e.g. 3: ['off', 'deactivating', 'deactive', 'activating', 'activated',] - + durations is a list of time values (floats) or None values. - + Each list must have five entries. - + More Details - + Here is a diagram showing the where the names from the list are used: @@ -86,8 +86,8 @@ class FourState: Each states also has an associated on or off value. The only state that is 'on' is state 4. So, the transition states - between off and on (states 1 and 3) are also considered - off (and so is state 2 which is oposite of 4 and therefore + between off and on (states 1 and 3) are also considered + off (and so is state 2 which is oposite of 4 and therefore oposite of 'on'). """ assert self.debugPrint("FourState(names=%s)"%(names)) @@ -129,7 +129,7 @@ class FourState: names[0], ) self.fsm.enterInitialState() - + def setTrack(self, track): assert self.debugPrint("setTrack(track=%s)"%(track,)) if self.track is not None: @@ -138,18 +138,18 @@ class FourState: if track is not None: track.start(self.stateTime) self.track = track - + def enterStateN(self, stateIndex): self.stateIndex = stateIndex self.duration = self.durations[stateIndex] or 0.0 - + # The AI is the authority on setting the On value. # If the client wants the state changed it needs to # send a request to the AI. #def setIsOn(self, isOn): # assert self.debugPrint("setIsOn(isOn=%s)"%(isOn,)) # pass - + def isOn(self): assert self.debugPrint("isOn() returning %s (stateIndex=%s)"%(self.stateIndex==4, self.stateIndex)) return self.stateIndex==4 @@ -159,13 +159,13 @@ class FourState: Allow derived classes to overide this. """ assert self.debugPrint("changedOnState(isOn=%s)"%(isOn,)) - + ##### state 0 ##### - + def enterState0(self): assert self.debugPrint("enter0()") self.enterStateN(0) - + def exitState0(self): assert self.debugPrint("exit0()") # It's important for FourStates to broadcast their state @@ -173,45 +173,45 @@ class FourState: # if a door was generated and went directly to an 'open' state, # it would not broadcast its state until it closed. self.changedOnState(0) - + ##### state 1 ##### - + def enterState1(self): assert self.debugPrint("enterState1()") self.enterStateN(1) - + def exitState1(self): assert self.debugPrint("exitState1()") - + ##### state 2 ##### - + def enterState2(self): assert self.debugPrint("enterState2()") self.enterStateN(2) - + def exitState2(self): assert self.debugPrint("exitState2()") - + ##### state 3 ##### - + def enterState3(self): assert self.debugPrint("enterState3()") self.enterStateN(3) - + def exitState3(self): assert self.debugPrint("exitState3()") - + ##### state 4 ##### - + def enterState4(self): assert self.debugPrint("enterState4()") self.enterStateN(4) self.changedOnState(1) - + def exitState4(self): assert self.debugPrint("exitState4()") self.changedOnState(0) - + if __debug__: def debugPrint(self, message): """for debugging""" diff --git a/direct/src/fsm/FourStateAI.py b/direct/src/fsm/FourStateAI.py index d81d2bcf47..814d8f057a 100755 --- a/direct/src/fsm/FourStateAI.py +++ b/direct/src/fsm/FourStateAI.py @@ -14,15 +14,15 @@ from direct.task import Task class FourStateAI: """ Generic four state ClassicFSM base class. - + This is a mix-in class that expects that your derived class is a DistributedObjectAI. - - Inherit from FourStateFSM and pass in your states. Two of - the states should be oposites of each other and the other + + Inherit from FourStateFSM and pass in your states. Two of + the states should be oposites of each other and the other two should be the transition states between the first two. E.g. - + +--------+ -->| closed | -- | +--------+ | @@ -36,10 +36,10 @@ class FourStateAI: | +------+ | ----| open |<--- +------+ - + There is a fifth off state, but that is an implementation detail (and that's why it's not called a five state ClassicFSM). - + I found that this pattern repeated in several things I was working on, so this base class was created. """ @@ -56,16 +56,16 @@ class FourStateAI: e.g. 3: ['off', 'deactivating', 'deactive', 'activating', 'activated',] - + durations is a list of durations in seconds or None values. The list of duration values should be the same length as the list of state names and the lists correspond. - For each state, after n seconds, the ClassicFSM will move to + For each state, after n seconds, the ClassicFSM will move to the next state. That does not happen for any duration values of None. - + More Details - + Here is a diagram showing the where the names from the list are used: @@ -89,8 +89,8 @@ class FourStateAI: Each states also has an associated on or off value. The only state that is 'on' is state 4. So, the transition states - between off and on (states 1 and 3) are also considered - off (and so is state 2 which is oposite of state 4 and therefore + between off and on (states 1 and 3) are also considered + off (and so is state 2 which is oposite of state 4 and therefore oposite of 'on'). """ assert self.debugPrint( @@ -143,15 +143,15 @@ class FourStateAI: del self.doLaterTask del self.states del self.fsm - + def getState(self): assert self.debugPrint("getState() returning %s"%(self.stateIndex,)) return [self.stateIndex] - + def sendState(self): assert self.debugPrint("sendState()") self.sendUpdate('setState', self.getState()) - + def setIsOn(self, isOn): assert self.debugPrint("setIsOn(isOn=%s)"%(isOn,)) if isOn: @@ -168,7 +168,7 @@ class FourStateAI: # nextState = (2, 2, None, 1, 1)[self.stateIndex] #if nextState is not None: # self.fsm.request(self.states[nextState]) - + def isOn(self): assert self.debugPrint("isOn() returning %s (stateIndex=%s)"%(self.stateIndex==4, self.stateIndex)) return self.stateIndex==4 @@ -190,12 +190,12 @@ class FourStateAI: def distributeStateChange(self): """ - This function is intentionaly simple so that derived classes + This function is intentionaly simple so that derived classes may easily alter the network message. """ assert self.debugPrint("distributeStateChange()") self.sendState() - + def enterStateN(self, stateIndex, nextStateIndex): assert self.debugPrint( "enterStateN(stateIndex=%s, nextStateIndex=%s)"% @@ -209,64 +209,64 @@ class FourStateAI: self.durations[stateIndex], self.switchToNextStateTask, "enterStateN-timer-%s"%id(self)) - + def exitStateN(self): assert self.debugPrint("exitStateN()") if self.doLaterTask: taskMgr.remove(self.doLaterTask) self.doLaterTask=None - + ##### state 0 ##### - + def enterState0(self): assert self.debugPrint("enter0()") self.enterStateN(0, 0) - + def exitState0(self): assert self.debugPrint("exit0()") - + ##### state 1 ##### - + def enterState1(self): #assert self.debugPrint("enterState1()") self.enterStateN(1, 2) - + def exitState1(self): assert self.debugPrint("exitState1()") self.exitStateN() - + ##### state 2 ##### - + def enterState2(self): #assert self.debugPrint("enterState2()") self.enterStateN(2, 3) - + def exitState2(self): assert self.debugPrint("exitState2()") self.exitStateN() - + ##### state 3 ##### - + def enterState3(self): #assert self.debugPrint("enterState3()") self.enterStateN(3, 4) - + def exitState3(self): assert self.debugPrint("exitState3()") self.exitStateN() - + ##### state 4 ##### - + def enterState4(self): assert self.debugPrint("enterState4()") self.enterStateN(4, 1) self.changedOnState(1) - + def exitState4(self): assert self.debugPrint("exitState4()") self.exitStateN() self.changedOnState(0) - + if __debug__: def debugPrint(self, message): """for debugging""" diff --git a/direct/src/fsm/SampleFSM.py b/direct/src/fsm/SampleFSM.py index ba2c1de138..b3b6fa88ed 100644 --- a/direct/src/fsm/SampleFSM.py +++ b/direct/src/fsm/SampleFSM.py @@ -145,7 +145,7 @@ class ToonEyes(FSM.FSM): ## exitRed(self, 'Red', 'Green') ## enterGreen(self, 'Red', 'Green') ## ('Green',) -## >>> +## >>> #### #### Example of using NewStyle: @@ -175,7 +175,7 @@ class ToonEyes(FSM.FSM): ## exitRed(self, 'Red', 'Green') ## enterGreen(self, 'Red', 'Green') ## ('Green',) -## >>> +## >>> #### #### Example of using ToonEyes: @@ -193,4 +193,4 @@ class ToonEyes(FSM.FSM): ## swap in eyes surprised model ## ('Surprised',) ## >>> eyes.request('blink') -## >>> +## >>> diff --git a/direct/src/fsm/State.py b/direct/src/fsm/State.py index 75e8269f11..3be6501002 100644 --- a/direct/src/fsm/State.py +++ b/direct/src/fsm/State.py @@ -23,7 +23,7 @@ class State(DirectObject): @classmethod def replaceMethod(self, oldFunction, newFunction): import types - count = 0 + count = 0 for state in self.States: # Note: you can only replace methods currently enterFunc = state.getEnterFunc() @@ -99,7 +99,7 @@ class State(DirectObject): def isTransitionDefined(self, otherState): if self.transitionsToAny(): return 1 - + # if we're given a state object, get its name instead if type(otherState) != type(''): otherState = otherState.getName() diff --git a/direct/src/fsm/StateData.py b/direct/src/fsm/StateData.py index 7f3fd48b3a..82ce729d93 100644 --- a/direct/src/fsm/StateData.py +++ b/direct/src/fsm/StateData.py @@ -20,7 +20,7 @@ class StateData(DirectObject): self.doneStatus = None self.isLoaded = 0 self.isEntered = 0 - + def enter(self): """ Enters the StateData. This makes it active in whatever sense diff --git a/direct/src/fsm/StatePush.py b/direct/src/fsm/StatePush.py index 9b0dd5fbb7..0d30a8c3f8 100755 --- a/direct/src/fsm/StatePush.py +++ b/direct/src/fsm/StatePush.py @@ -249,7 +249,7 @@ class FunctionCall(ReceivesMultipleStateChanges, PushesStateChanges): if self._initialized: self._func(*self._bakedArgs, **self._bakedKargs) PushesStateChanges._handleStateChange(self) - + if __debug__: l = [] def handler(value, l=l): @@ -351,7 +351,7 @@ class Pulse(PushesStateChanges): def sendPulse(self): self._handlePotentialStateChange(True) self._handlePotentialStateChange(False) - + if __debug__: l = [] def handler(value, l=l): @@ -393,7 +393,7 @@ class EventArgument(PushesStateChanges, DirectObject): self.ignoreAll() del self._index PushesStateChanges.destroy(self) - + def _handleEvent(self, *args): self._handlePotentialStateChange(args[self._index]) diff --git a/direct/src/gui/DirectButton.py b/direct/src/gui/DirectButton.py index a40dfda94b..f5dcee7413 100644 --- a/direct/src/gui/DirectButton.py +++ b/direct/src/gui/DirectButton.py @@ -47,7 +47,7 @@ class DirectButton(DirectFrame): # Initialize superclasses DirectFrame.__init__(self, parent) - + # If specifed, add scaling to the pressed state to make it # look like the button is moving when you press it. We have # to set up the node first, before we call initialise options; @@ -57,7 +57,7 @@ class DirectButton(DirectFrame): if self['pressEffect']: pressEffectNP = self.stateNodePath[1].attachNewNode('pressEffect', 1) self.stateNodePath[1] = pressEffectNP - + # Call option initialization functions self.initialiseoptions(DirectButton) @@ -101,7 +101,7 @@ class DirectButton(DirectFrame): if self['command']: # Pass any extra args to command apply(self['command'], self['extraArgs']) - + def setClickSound(self): clickSound = self['clickSound'] # Clear out sounds diff --git a/direct/src/gui/DirectCheckBox.py b/direct/src/gui/DirectCheckBox.py index 6091f8bc31..e0e2f8dc24 100755 --- a/direct/src/gui/DirectCheckBox.py +++ b/direct/src/gui/DirectCheckBox.py @@ -34,12 +34,12 @@ class DirectCheckBox(DirectButton): ('checkedImage', None, None), ('isChecked', False, None), ) - + # Merge keyword options with default options self.defineoptions(kw, optiondefs) DirectButton.__init__(self,parent) - + self.initialiseoptions(DirectCheckBox) @@ -52,7 +52,7 @@ class DirectCheckBox(DirectButton): self['image'] = self['uncheckedImage'] self.setImage() - + if self['command']: # Pass any extra args to command apply(self['command'], [self['isChecked']] + self['extraArgs']) diff --git a/direct/src/gui/DirectEntry.py b/direct/src/gui/DirectEntry.py index 5fa8920328..fc3b153b2a 100644 --- a/direct/src/gui/DirectEntry.py +++ b/direct/src/gui/DirectEntry.py @@ -256,7 +256,7 @@ class DirectEntry(DirectFrame): """ Changes the text currently showing in the typable region; does not change the current cursor position. Also see enterText(). """ - + self.unicodeText = isinstance(text, types.UnicodeType) if self.unicodeText: self.guiItem.setWtext(text) diff --git a/direct/src/gui/DirectEntryScroll.py b/direct/src/gui/DirectEntryScroll.py index 7341671d6a..3fe1599b1b 100644 --- a/direct/src/gui/DirectEntryScroll.py +++ b/direct/src/gui/DirectEntryScroll.py @@ -13,7 +13,7 @@ class DirectEntryScroll(DirectFrame): ('relief', None, None), ('clipSize', (-1, 1, -1, 1), self.setClipSize), ) - + self.defineoptions(kw, optiondefs) DirectFrame.__init__(self, parent, **kw) self.canvas = None @@ -22,68 +22,68 @@ class DirectEntryScroll(DirectFrame): self.clipXMin = 0.0 self.clipXMax = 0.0 self.initialiseoptions(DirectEntryScroll) - + # don't set a scale on the entry - # instead make it the correct size, use something like: + # instead make it the correct size, use something like: # text_scale = 0.035, # frameSize = (-0.006, 3.2, -0.015, 0.036), # if you need to scale the entry scale it's parent instead - + self.entry = entry self.canvas = NodePath(self.guiItem.getCanvasNode()) self.entry.reparentTo(self.canvas) self.canvas.setPos(0,0,0) - + self.entry.bind(DGG.CURSORMOVE,self.cursorMove) - + self.canvas.node().setBounds(OmniBoundingVolume()) self.canvas.node().setFinal(1) self.resetCanvas() - - - + + + def cursorMove(self, cursorX, cursorY): cursorX = self.entry.guiItem.getCursorX() * self.entry['text_scale'][0] canvasX = self.canvas.getX() visXMin = self.clipXMin - canvasX visXMax = self.clipXMax - canvasX visXCenter = (visXMin + visXMax) * 0.5 - distanceToCenter = visXCenter - cursorX + distanceToCenter = visXCenter - cursorX clipExtent = self.clipXMax - self.clipXMin - + entryExtent = self.entry['text_scale'][0] * self.entry['width'] entryWiggle = entryExtent - clipExtent - + if abs(distanceToCenter) > (clipExtent * 0.5): self.moveToCenterCursor() - - + + def moveToCenterCursor(self): cursorX = self.entry.guiItem.getCursorX() * self.entry['text_scale'][0] canvasX = self.canvas.getX() visXMin = self.clipXMin - canvasX visXMax = self.clipXMax - canvasX visXCenter = (visXMin + visXMax) * 0.5 - distanceToCenter = visXCenter - cursorX + distanceToCenter = visXCenter - cursorX newX = canvasX + distanceToCenter - + clipExtent = self.clipXMax - self.clipXMin entryExtent = self.entry['text_scale'][0] * self.entry['width'] entryWiggle = entryExtent - clipExtent - + if self.entry.guiItem.getCursorPosition() <= 0: #deals with the cursor jump bug newX = 0.0 elif newX > 0.0: newX = 0.0 elif newX < (-entryWiggle): newX = -entryWiggle - + #print("CursorX %s CanvasX %s VisCenter %s Distance %s NewX %s Wiggle %s" % (cursorX, canvasX, visXCenter, distanceToCenter, newX, entryWiggle)) - + self.canvas.setX(newX) - + def destroy(self): # Destroy children of the canvas for child in self.canvas.getChildren(): @@ -98,11 +98,11 @@ class DirectEntryScroll(DirectFrame): self.entry.destroy() self.entry = None DirectFrame.destroy(self) - - + + def getCanvas(self): return self.canvas - + def setClipSize(self): self.guiItem.setClipFrame(self['clipSize']) self.clipXMin = self['clipSize'][0] @@ -111,7 +111,7 @@ class DirectEntryScroll(DirectFrame): self.visXMax = self.clipXMax if self.canvas: self.resetCanvas() - + def resetCanvas(self): self.canvas.setPos(0,0,0) diff --git a/direct/src/gui/DirectFrame.py b/direct/src/gui/DirectFrame.py index ed67b84c25..2f5ed61241 100644 --- a/direct/src/gui/DirectFrame.py +++ b/direct/src/gui/DirectFrame.py @@ -43,7 +43,7 @@ class DirectFrame(DirectGuiWidget): # Initialize superclasses DirectGuiWidget.__init__(self, parent) - + # Call option initialization functions self.initialiseoptions(DirectFrame) @@ -69,7 +69,7 @@ class DirectFrame(DirectGuiWidget): text = textList[i] except IndexError: text = textList[-1] - + if self.hascomponent(component): if text == None: # Destroy component @@ -92,7 +92,7 @@ class DirectFrame(DirectGuiWidget): def setGeom(self): # Determine argument type geom = self['geom'] - + if geom == None: # Passed in None geomList = (None,) * self['numStates'] @@ -103,7 +103,7 @@ class DirectFrame(DirectGuiWidget): else: # Otherwise, hope that the user has passed in a tuple/list geomList = geom - + # Create/destroy components for i in range(self['numStates']): component = 'geom' + repr(i) @@ -113,7 +113,7 @@ class DirectFrame(DirectGuiWidget): geom = geomList[i] except IndexError: geom = geomList[-1] - + if self.hascomponent(component): if geom == None: # Destroy component @@ -161,7 +161,7 @@ class DirectFrame(DirectGuiWidget): image = imageList[i] except IndexError: image = imageList[-1] - + if self.hascomponent(component): if image == None: # Destroy component diff --git a/direct/src/gui/DirectGuiGlobals.py b/direct/src/gui/DirectGuiGlobals.py index a84442da87..7033de54ff 100644 --- a/direct/src/gui/DirectGuiGlobals.py +++ b/direct/src/gui/DirectGuiGlobals.py @@ -65,11 +65,11 @@ WITHOUT = PGButton.getWithoutPrefix() B1CLICK = PGButton.getClickPrefix() + MouseButton.one().getName() + '-' B2CLICK = PGButton.getClickPrefix() + MouseButton.two().getName() + '-' B3CLICK = PGButton.getClickPrefix() + MouseButton.three().getName() + '-' -B1PRESS = PGButton.getPressPrefix() + MouseButton.one().getName() + '-' -B2PRESS = PGButton.getPressPrefix() + MouseButton.two().getName() + '-' +B1PRESS = PGButton.getPressPrefix() + MouseButton.one().getName() + '-' +B2PRESS = PGButton.getPressPrefix() + MouseButton.two().getName() + '-' B3PRESS = PGButton.getPressPrefix() + MouseButton.three().getName() + '-' -B1RELEASE = PGButton.getReleasePrefix() + MouseButton.one().getName() + '-' -B2RELEASE = PGButton.getReleasePrefix() + MouseButton.two().getName() + '-' +B1RELEASE = PGButton.getReleasePrefix() + MouseButton.one().getName() + '-' +B2RELEASE = PGButton.getReleasePrefix() + MouseButton.two().getName() + '-' B3RELEASE = PGButton.getReleasePrefix() + MouseButton.three().getName() + '-' # For DirectEntry widgets OVERFLOW = PGEntry.getOverflowPrefix() diff --git a/direct/src/gui/DirectLabel.py b/direct/src/gui/DirectLabel.py index 1728fdcb13..6dd31c6096 100644 --- a/direct/src/gui/DirectLabel.py +++ b/direct/src/gui/DirectLabel.py @@ -34,7 +34,7 @@ class DirectLabel(DirectFrame): # Initialize superclasses DirectFrame.__init__(self, parent) - + # Call option initialization functions self.initialiseoptions(DirectLabel) diff --git a/direct/src/gui/DirectOptionMenu.py b/direct/src/gui/DirectOptionMenu.py index bd2e45fffc..7dfc758fee 100644 --- a/direct/src/gui/DirectOptionMenu.py +++ b/direct/src/gui/DirectOptionMenu.py @@ -238,7 +238,7 @@ class DirectOptionMenu(DirectButton): """ Clear frame color, clear highlightedIndex """ item['frameColor'] = frameColor item['frameSize'] = (self.minX, self.maxX, self.minZ, self.maxZ) - item['text_scale'] = (1,1) + item['text_scale'] = (1,1) self.highlightedIndex = None def selectHighlightedIndex(self, event = None): diff --git a/direct/src/gui/DirectRadioButton.py b/direct/src/gui/DirectRadioButton.py index 775ccf5648..2b0f0473e4 100755 --- a/direct/src/gui/DirectRadioButton.py +++ b/direct/src/gui/DirectRadioButton.py @@ -190,7 +190,7 @@ class DirectRadioButton(DirectButton): def commandFunc(self, event): - if len(self['value']) == len(self['variable']) != 0: + if len(self['value']) == len(self['variable']) != 0: for i in range(len(self['value'])): self['variable'][i] = self['value'][i] self.check() diff --git a/direct/src/gui/DirectScrolledList.py b/direct/src/gui/DirectScrolledList.py index d2ac37dfef..3bd5c9fd07 100644 --- a/direct/src/gui/DirectScrolledList.py +++ b/direct/src/gui/DirectScrolledList.py @@ -149,7 +149,7 @@ class DirectScrolledList(DirectFrame): if self.decButtonCallback: self.decButtonCallback = None self.incButton.destroy() - self.decButton.destroy() + self.decButton.destroy() DirectFrame.destroy(self) def selectListItem(self, item): @@ -320,7 +320,7 @@ class DirectScrolledList(DirectFrame): messenger.send('wakeup') if self.incButtonCallback: self.incButtonCallback() - + def __decButtonDown(self, event): assert self.notify.debugStateCall(self) task = Task(self.__scrollByTask) @@ -333,14 +333,14 @@ class DirectScrolledList(DirectFrame): self.scrollBy(task.delta) messenger.send('wakeup') if self.decButtonCallback: - self.decButtonCallback() - + self.decButtonCallback() + def __buttonUp(self, event): assert self.notify.debugStateCall(self) taskName = self.taskName("scroll") #print "buttonUp: removing ", taskName taskMgr.remove(taskName) - + def addItem(self, item, refresh=1): """ Add this string and extraArg to the list @@ -376,7 +376,7 @@ class DirectScrolledList(DirectFrame): return 1 else: return 0 - + def removeAndDestroyItem(self, item, refresh = 1): """ Remove and destroy this item from the panel. @@ -411,16 +411,16 @@ class DirectScrolledList(DirectFrame): del self.currentSelected self["items"].remove(item) if type(item) != type(''): - #RAU possible leak here, let's try to do the right thing + #RAU possible leak here, let's try to do the right thing #item.reparentTo(hidden) item.removeNode() retval = 1 if (refresh): self.refresh() - + return retval - + def removeAndDestroyAllItems(self, refresh = 1): """ Remove and destroy all items from the panel. @@ -436,12 +436,12 @@ class DirectScrolledList(DirectFrame): item.destroy() self["items"].remove(item) if type(item) != type(''): - #RAU possible leak here, let's try to do the right thing + #RAU possible leak here, let's try to do the right thing #item.reparentTo(hidden) item.removeNode() retval = 1 if (refresh): - self.refresh() + self.refresh() return retval def refresh(self): @@ -471,7 +471,7 @@ class DirectScrolledList(DirectFrame): def setDecButtonCallback(self): assert self.notify.debugStateCall(self) - self.decButtonCallback = self["decButtonCallback"] + self.decButtonCallback = self["decButtonCallback"] """ diff --git a/direct/src/gui/DirectWaitBar.py b/direct/src/gui/DirectWaitBar.py index 2fe9567941..648f26cd11 100644 --- a/direct/src/gui/DirectWaitBar.py +++ b/direct/src/gui/DirectWaitBar.py @@ -15,7 +15,7 @@ d = DirectWaitBar(borderWidth=(0, 0)) class DirectWaitBar(DirectFrame): """ DirectWaitBar - A DirectWidget that shows progress completed towards a task. """ - + def __init__(self, parent = None, **kw): # Inherits from DirectFrame # A Direct Frame can have: diff --git a/direct/src/gui/OnscreenText.py b/direct/src/gui/OnscreenText.py index 9e0f2cb18b..536b1b6445 100644 --- a/direct/src/gui/OnscreenText.py +++ b/direct/src/gui/OnscreenText.py @@ -162,7 +162,7 @@ class OnscreenText(DirectObject, NodePath): self.pos = pos self.roll = roll self.wordwrap = wordwrap - + if decal: textNode.setCardDecal(1) @@ -334,7 +334,7 @@ class OnscreenText(DirectObject, NodePath): def setWordwrap(self, wordwrap): self.wordwrap = wordwrap - + if wordwrap: self.textNode.setWordwrap(wordwrap) else: @@ -342,7 +342,7 @@ class OnscreenText(DirectObject, NodePath): def getWordwrap(self): return self.wordwrap - + def setFg(self, fg): self.textNode.setTextColor(fg[0], fg[1], fg[2], fg[3]) diff --git a/direct/src/interval/ActorInterval.py b/direct/src/interval/ActorInterval.py index 2e884fcc15..ae26c4cde4 100644 --- a/direct/src/interval/ActorInterval.py +++ b/direct/src/interval/ActorInterval.py @@ -28,7 +28,7 @@ class ActorInterval(Interval.Interval): # specifying otherwise unless you also specify loop=1, which will # loop the animation over its frame range during the duration of # the interval. - + # Note: if loop == 0 and duration > anim duration then the # animation will play once and then hold its final pose for the # remainder of the interval. @@ -36,7 +36,7 @@ class ActorInterval(Interval.Interval): # loop = 1 implies a loop within the entire range of animation, # while constrainedLoop = 1 implies a loop within startFrame and # endFrame only. - + def __init__(self, actor, animName, loop=0, constrainedLoop=0, duration=None, startTime=None, endTime=None, startFrame=None, endFrame=None, @@ -134,7 +134,7 @@ class ActorInterval(Interval.Interval): frameCount = t * self.frameRate if self.constrainedLoop: frameCount = frameCount % self.numFrames - + if self.reverse: absFrame = self.endFrame - frameCount else: @@ -186,7 +186,7 @@ class ActorInterval(Interval.Interval): # Otherwise, the user-specified duration determines which # is our final frame. self.privStep(self.getDuration()) - + self.state = CInterval.SFinal self.intervalDone() @@ -225,7 +225,7 @@ class LerpAnimInterval(CLerpAnimEffectInterval): for control in controls: self.addControl(control, startAnim, 1.0 - startWeight, 1.0 - endWeight) - + if endAnim != None: controls = actor.getAnimControls( endAnim, partName = partName, lodName = lodName) diff --git a/direct/src/interval/AnimControlInterval.py b/direct/src/interval/AnimControlInterval.py index bd2acc17ff..57494b145b 100755 --- a/direct/src/interval/AnimControlInterval.py +++ b/direct/src/interval/AnimControlInterval.py @@ -31,7 +31,7 @@ class AnimControlInterval(Interval.Interval): # specifying otherwise unless you also specify loop=1, which will # loop the animation over its frame range during the duration of # the interval. - + # Note: if loop == 0 and duration > anim duration then the # animation will play once and then hold its final pose for the # remainder of the interval. @@ -39,7 +39,7 @@ class AnimControlInterval(Interval.Interval): # loop = 1 implies a loop within the entire range of animation, # while constrainedLoop = 1 implies a loop within startFrame and # endFrame only. - + def __init__(self, controls, loop=0, constrainedLoop=0, duration=None, startTime=None, endTime=None, startFrame=None, endFrame=None, @@ -49,7 +49,7 @@ class AnimControlInterval(Interval.Interval): AnimControlInterval.animNum += 1 # Record class specific variables - if(isinstance(controls, AnimControlCollection)): + if(isinstance(controls, AnimControlCollection)): self.controls = controls if(config.GetBool("strict-anim-ival",0)): checkSz = self.controls.getAnim(0).getNumFrames() @@ -61,7 +61,7 @@ class AnimControlInterval(Interval.Interval): self.controls.storeAnim(controls,"") else: self.notify.error("invalid input control(s) for AnimControlInterval") - + self.loopAnim = loop self.constrainedLoop = constrainedLoop self.playRate = playRate @@ -78,7 +78,7 @@ class AnimControlInterval(Interval.Interval): self.startFrame = startTime * self.frameRate else: self.startFrame = 0 - + if endFrame != None: self.endFrame = endFrame elif endTime != None: @@ -131,7 +131,7 @@ class AnimControlInterval(Interval.Interval): frameCount = t * self.frameRate if self.constrainedLoop: frameCount = frameCount % self.numFrames - + if self.reverse: absFrame = self.endFrame - frameCount else: @@ -152,7 +152,7 @@ class AnimControlInterval(Interval.Interval): frame = (intFrame % numFrames) + (absFrame - intFrame) else: frame = max(min(absFrame, numFrames - 1), 0) - + self.controls.poseAll(frame) self.state = CInterval.SStarted @@ -177,7 +177,7 @@ class AnimControlInterval(Interval.Interval): # Otherwise, the user-specified duration determines which # is our final frame. self.privStep(self.getDuration()) - + self.state = CInterval.SFinal self.intervalDone() diff --git a/direct/src/interval/FunctionInterval.py b/direct/src/interval/FunctionInterval.py index 815fd8b090..2dc2d7686a 100644 --- a/direct/src/interval/FunctionInterval.py +++ b/direct/src/interval/FunctionInterval.py @@ -21,7 +21,7 @@ class FunctionInterval(Interval.Interval): # Keep a list of function intervals currently in memory for # Control-C-Control-V redefining. These are just weakrefs so they - # should not cause any leaks. + # should not cause any leaks. if __debug__: import weakref FunctionIntervals = weakref.WeakKeyDictionary() @@ -29,7 +29,7 @@ class FunctionInterval(Interval.Interval): @classmethod def replaceMethod(self, oldFunction, newFunction): import types - count = 0 + count = 0 for ival in self.FunctionIntervals: # print 'testing: ', ival.function, oldFunction # Note: you can only replace methods currently @@ -55,7 +55,7 @@ class FunctionInterval(Interval.Interval): # Record instance variables self.function = function - + # Create a unique name for the interval if necessary if name is None: name = self.makeUniqueName(function) diff --git a/direct/src/interval/IndirectInterval.py b/direct/src/interval/IndirectInterval.py index c435dbc76a..991265273e 100644 --- a/direct/src/interval/IndirectInterval.py +++ b/direct/src/interval/IndirectInterval.py @@ -34,7 +34,7 @@ class IndirectInterval(Interval.Interval): self.startAtStart = (startT == 0) self.endAtEnd = (endT == None or endT == interval.getDuration()) - + if endT == None: endT = interval.getDuration() diff --git a/direct/src/interval/Interval.py b/direct/src/interval/Interval.py index c44c63cb03..d18b2defcf 100644 --- a/direct/src/interval/Interval.py +++ b/direct/src/interval/Interval.py @@ -181,7 +181,7 @@ class Interval(DirectObject): already started, this changes its speed on-the-fly. Note that since playRate is a parameter to start() and loop(), the next call to start() or loop() will reset this parameter. """ - + if self.isPlaying(): self.pause() self.__playRate = playRate diff --git a/direct/src/interval/IntervalManager.py b/direct/src/interval/IntervalManager.py index 3fa556f30c..0e909ceeb8 100644 --- a/direct/src/interval/IntervalManager.py +++ b/direct/src/interval/IntervalManager.py @@ -55,7 +55,7 @@ class IntervalManager(CIntervalManager): def getIntervalsMatching(self, pattern): ivals = [] - + count = 0 maxIndex = self.getMaxIndex() for index in range(maxIndex): diff --git a/direct/src/interval/LerpBlendHelpers.py b/direct/src/interval/LerpBlendHelpers.py index 93816555c1..fdbcc73cbb 100644 --- a/direct/src/interval/LerpBlendHelpers.py +++ b/direct/src/interval/LerpBlendHelpers.py @@ -5,7 +5,7 @@ __all__ = ['getBlend'] from panda3d.direct import * """global lerp blend types for lerp function""" - + easeIn = EaseInBlendType() easeOut = EaseOutBlendType() @@ -14,7 +14,7 @@ easeInOut = EaseInOutBlendType() noBlend = NoBlendType() - + def getBlend(blendType): """ Return the C++ blend class corresponding to blendType string diff --git a/direct/src/interval/LerpInterval.py b/direct/src/interval/LerpInterval.py index 51e9a7e61e..06271fc061 100644 --- a/direct/src/interval/LerpInterval.py +++ b/direct/src/interval/LerpInterval.py @@ -727,7 +727,7 @@ class LerpFunctionNoStateInterval(Interval.Interval): happens to get skipped over completely, it will not bother to call the function at all. """ - + # Interval counter lerpFunctionIntervalNum = 1 # create LerpFunctionInterval DirectNotify category @@ -766,7 +766,7 @@ class LerpFunctionNoStateInterval(Interval.Interval): ## Evaluate function #apply(self.function, [data] + self.extraArgs) #self.state = CInterval.SStarted - #self.currT = t + #self.currT = t def privStep(self, t): # Evaluate the function diff --git a/direct/src/interval/MetaInterval.py b/direct/src/interval/MetaInterval.py index 067414aea1..7ec7967662 100644 --- a/direct/src/interval/MetaInterval.py +++ b/direct/src/interval/MetaInterval.py @@ -50,7 +50,7 @@ class MetaInterval(CMetaInterval): # (for instance, the connection to the server being lost) when # we have to exit right away; these keywords indicate # intervals that might not be cleaned up by their owners. - + autoPause = 0 autoFinish = 0 if 'autoPause' in kw: @@ -86,7 +86,7 @@ class MetaInterval(CMetaInterval): #else: self.ivals = ivals - + self.__ivalsDirty = 1 if name == None: @@ -118,7 +118,7 @@ class MetaInterval(CMetaInterval): # Functions to make the MetaInterval object act just like a Python # list of intervals: - + def append(self, ival): # Appends a single interval to the list so far. if isinstance(self.ivals, types.TupleType): @@ -238,7 +238,7 @@ class MetaInterval(CMetaInterval): return copy # Functions to define sequence, parallel, and track behaviors: - + def addSequence(self, list, name, relTime, relTo, duration): # Adds the given list of intervals to the MetaInterval to be # played one after the other. @@ -263,7 +263,7 @@ class MetaInterval(CMetaInterval): maxDuration = 0 for ival in list: maxDuration = max(maxDuration, ival.getDuration()) - + self.pushLevel(name, relTime, relTo) for ival in list: self.addInterval(ival, maxDuration - ival.getDuration(), TRACK_START) @@ -379,7 +379,7 @@ class MetaInterval(CMetaInterval): self.__updateIvals() self.setupResumeUntil(endT) self.__manager.addInterval(self) - + def finish(self): self.__updateIvals() state = self.getState() @@ -435,7 +435,7 @@ class MetaInterval(CMetaInterval): self.clearIntervals() self.applyIvals(self, 0, TRACK_START) self.__ivalsDirty = 0 - + def clearIntervals(self): # This overrides the function defined at the C++ level to # reset the inPython flag. Clearing out the intervals list @@ -443,7 +443,7 @@ class MetaInterval(CMetaInterval): # Python interval gets added. CMetaInterval.clearIntervals(self) self.inPython = 0 - + def applyIvals(self, meta, relTime, relTo): # Add the intervals listed in this object to the given # MetaInterval object at the C++ level. This will make the @@ -466,7 +466,7 @@ class MetaInterval(CMetaInterval): already started, this changes its speed on-the-fly. Note that since playRate is a parameter to start() and loop(), the next call to start() or loop() will reset this parameter. """ - + if self.isPlaying(): self.pause() CMetaInterval.setPlayRate(self, playRate) @@ -490,7 +490,7 @@ class MetaInterval(CMetaInterval): t = self.getEventT() eventType = self.getEventType() self.popEvent() - + ival = self.pythonIvals[index] ival.privDoEvent(t, eventType) ival.privPostEvent() @@ -539,8 +539,8 @@ class MetaInterval(CMetaInterval): self.__updateIvals() return CMetaInterval.getIntervalStartTime(self, *args, **kw) - - + + def getDuration(self): # This function overrides from the parent level to force it to # update the interval list first, if necessary. @@ -548,14 +548,14 @@ class MetaInterval(CMetaInterval): self.__updateIvals() return CMetaInterval.getDuration(self) - def __repr__(self, *args, **kw): + def __repr__(self, *args, **kw): # This function overrides from the parent level to force it to # update the interval list first, if necessary. self.__updateIvals() return CMetaInterval.__repr__(self, *args, **kw) - def __str__(self, *args, **kw): + def __str__(self, *args, **kw): # This function overrides from the parent level to force it to # update the interval list first, if necessary. @@ -563,7 +563,7 @@ class MetaInterval(CMetaInterval): return CMetaInterval.__str__(self, *args, **kw) - def timeline(self, out = None): + def timeline(self, out = None): # This function overrides from the parent level to force it to # update the interval list first, if necessary. @@ -605,7 +605,7 @@ class Track(MetaInterval): isinstance(tuple, types.ListType)): # It's not a tuple. return 0 - + relTime = tuple[0] ival = tuple[1] if len(tuple) >= 3: diff --git a/direct/src/interval/MopathInterval.py b/direct/src/interval/MopathInterval.py index 4a479896f1..0764b1bc12 100644 --- a/direct/src/interval/MopathInterval.py +++ b/direct/src/interval/MopathInterval.py @@ -22,18 +22,18 @@ class MopathInterval(LerpInterval.LerpFunctionInterval): if duration == None: duration = abs(toT - fromT) - + # Generate unique name if necessary if (name == None): name = 'Mopath-%d' % MopathInterval.mopathNum - MopathInterval.mopathNum += 1 + MopathInterval.mopathNum += 1 LerpInterval.LerpFunctionInterval.__init__( self, self.__doMopath, fromData = fromT, toData = toT, duration = duration, blendType = blendType, name = name) - - self.mopath = mopath + + self.mopath = mopath self.node = node def destroy(self): diff --git a/direct/src/interval/ParticleInterval.py b/direct/src/interval/ParticleInterval.py index fec166b6ec..3682904fce 100644 --- a/direct/src/interval/ParticleInterval.py +++ b/direct/src/interval/ParticleInterval.py @@ -57,14 +57,14 @@ class ParticleInterval(Interval): name is a string: use this for unique intervals so that they can be easily found in the taskMgr """ - + # Generate unique name id = 'Particle-%d' % ParticleInterval.particleNum ParticleInterval.particleNum += 1 if name == None: name = id # Record instance variables - self.particleEffect = particleEffect + self.particleEffect = particleEffect self.cleanup = cleanup if parent != None: @@ -76,14 +76,14 @@ class ParticleInterval(Interval): particles.setRenderParent(renderParent.node()) self.__softStopped = False - + if softStopT == 0.0: self.softStopT = duration elif softStopT < 0.0: self.softStopT = duration+softStopT else: self.softStopT = softStopT - + # Initialize superclass Interval.__init__(self, name, duration) @@ -119,7 +119,7 @@ class ParticleInterval(Interval): def privInstant(self): self.privInitialize(self.getDuration()) self.privFinalize() - + def privStep(self, t): if self.state == CInterval.SPaused or t < self.currT: # Restarting from a pause. @@ -138,4 +138,4 @@ class ParticleInterval(Interval): if self.cleanup and self.particleEffect: self.particleEffect.cleanup() self.particleEffect = None - + diff --git a/direct/src/interval/ProjectileInterval.py b/direct/src/interval/ProjectileInterval.py index 3372b415af..39077bf1fe 100755 --- a/direct/src/interval/ProjectileInterval.py +++ b/direct/src/interval/ProjectileInterval.py @@ -36,7 +36,7 @@ class ProjectileInterval(Interval): (If startPos is not provided, it will be obtained from the node's position at the time that the interval is first started. Note that in this case you must provide a duration of some kind.) - + # go from startPos to endPos in duration seconds startPos, endPos, duration # given a starting velocity, go for a specific time period @@ -46,7 +46,7 @@ class ProjectileInterval(Interval): # pass through wayPoint at time 'timeToWayPoint'. Go until # you hit a given Z plane startPos, wayPoint, timeToWayPoint, endZ - + You may alter gravity by providing a multiplier in 'gravityMult'. '2.' will make gravity twice as strong, '.5' half as strong. '-1.' will reverse gravity @@ -58,7 +58,7 @@ class ProjectileInterval(Interval): be updated automatically as the interval plays. It will *not* be automatically removed from the node when the interval finishes. - + """ self.node = node self.collNode = collNode @@ -210,16 +210,16 @@ class ProjectileInterval(Interval): self.parabola = LParabola(VBase3(0, 0, 0.5 * self.zAcc), self.startVel, self.startPos) - + if not self.endPos: self.endPos = self.__calcPos(self.duration) - + # these are the parameters that we need to know: assert self.notify.debug('startPos: %s' % repr(self.startPos)) assert self.notify.debug('endPos: %s' % repr(self.endPos)) assert self.notify.debug('duration: %s' % self.duration) assert self.notify.debug('startVel: %s' % repr(self.startVel)) - assert self.notify.debug('z-accel: %s' % self.zAcc) + assert self.notify.debug('z-accel: %s' % self.zAcc) def __initialize(self): if self.implicitStartPos: @@ -232,7 +232,7 @@ class ProjectileInterval(Interval): assert self.notify.error('invalid projectile parameters') return False return True - + def privInitialize(self, t): self.__initialize() if self.collNode: @@ -268,17 +268,17 @@ class ProjectileInterval(Interval): You must provide a few of the parameters, and the others will be computed. The input parameters in question are: duration, endZ, endPos, startVel, gravityMult - + Valid sets of input parameters (AA), (trivially computed/default parameters) (BB), non-trivial computed parameters (CC): AA && BB => CC - + # one parameter duration && (startVel, gravityMult) => endZ, endPos endZ && (startVel, gravityMult) => duration, endPos endPos && (endZ, gravityMult ) => duration, startVel - + # two parameters duration, endZ && (endPos, gravityMult) => startVel duration, endPos && (endZ, gravityMult ) => startVel @@ -287,14 +287,14 @@ class ProjectileInterval(Interval): endZ, startVel && (gravityMult ) => duration, endPos endZ, gravityMult && (endPos, startVel ) => duration endPos, gravityMult && (endZ ) => duration, startVel - + # three parameters duration, endZ, startVel && ( ) => endPos, gravityMult duration, endZ, gravityMult && (endPos) => startVel duration, endPos, gravityMult && (endZ ) => startVel duration, startVel, gravityMult && ( ) => endZ, endPos endZ, startVel, gravityMult && ( ) => duration, endPos - + # four parameters duration, endZ, startVel, gravityMult && () => endPos ################################################################## diff --git a/direct/src/interval/SoundInterval.py b/direct/src/interval/SoundInterval.py index 5326f105e6..ca38af297a 100644 --- a/direct/src/interval/SoundInterval.py +++ b/direct/src/interval/SoundInterval.py @@ -61,13 +61,13 @@ class SoundInterval(Interval.Interval): duration = max(self.soundDuration - self.startTime, 0) #if (duration == 0): # self.notify.warning('zero length duration!') - + # MPG - hack for Miles bug #duration += 1.5 - + # DCR - hack for Miles bug - adding 1.5 seconds caused # problems for MG_neg_buzzer.wav - + # DCR - what this is all about: Miles is under-reporting the # length of MP3 files, and they're getting cut off too early. # This is a temporary hack. We could: @@ -79,7 +79,7 @@ class SoundInterval(Interval.Interval): # MilesAudioManager. This is no longer necessary up here, # where it pollutes SoundInterval for everyone. #duration += min(duration * 2.4, 1.5) - + # Generate unique name if necessary if (name == None): name = id @@ -108,7 +108,7 @@ class SoundInterval(Interval.Interval): ## if self._reverse: ## # Don't attempt to play the sound backwards. ## return - + if self.state == CInterval.SPaused: # Restarting from a pause. t1 = t + self.startTime @@ -120,7 +120,7 @@ class SoundInterval(Interval.Interval): self.node and not self.node.isEmpty(): base.sfxPlayer.setFinalVolume(self.sound, self.node, self.volume, self.listenerNode, self.cutOff) - + self.state = CInterval.SStarted self.currT = t diff --git a/direct/src/interval/TestInterval.py b/direct/src/interval/TestInterval.py index b7a56d1698..444ad20aaf 100755 --- a/direct/src/interval/TestInterval.py +++ b/direct/src/interval/TestInterval.py @@ -41,7 +41,7 @@ class TestInterval(Interval): self.particleEffect = particleEffect self.parent = parent self.renderParent = renderParent - + Interval.__init__(self, name, duration) def __del__(self): @@ -54,7 +54,7 @@ class TestInterval(Interval): self.particleEffect.clearToInitial() self.currT = 0 Interval.start(self,*args,**kwargs) - + def privInitialize(self, t): if self.parent != None: self.particleEffect.reparentTo(self.parent) @@ -92,7 +92,7 @@ class TestInterval(Interval): self.currT = self.getDuration() self.state = CInterval.SFinal - + def privInstant(self): """ Full jump from Initial state to Final State diff --git a/direct/src/leveleditor/ActionMgr.py b/direct/src/leveleditor/ActionMgr.py index ab4c40f4c6..041f6b4cf2 100755 --- a/direct/src/leveleditor/ActionMgr.py +++ b/direct/src/leveleditor/ActionMgr.py @@ -68,13 +68,13 @@ class ActionBase(Functor): def postCall(self): # implement post process here pass - + def undo(self): print "undo method is not defined for this action" class ActionAddNewObj(ActionBase): """ Action class for adding new object """ - + def __init__(self, editor, *args, **kargs): self.editor = editor function = self.editor.objectMgr.addNewObject @@ -88,11 +88,11 @@ class ActionAddNewObj(ActionBase): def redo(self): if self.uid is None: - print "Can't redo this add" + print "Can't redo this add" else: self.result = self._do__call__(uid=self.uid) return self.result - + def undo(self): if self.result is None: print "Can't undo this add" @@ -190,7 +190,7 @@ class ActionDeleteObj(ActionBase): self.selecteUIDs = [] self.hierarchy = {} - self.objInfos = {} + self.objInfos = {} class ActionDeleteObjById(ActionBase): """ Action class for deleting object """ @@ -209,7 +209,7 @@ class ActionDeleteObjById(ActionBase): if isUID: obj = self.editor.objectMgr.findObjectById(uid_np) else: - obj = self.editor.objectMgr.findObjectByNodePath(uid_np) + obj = self.editor.objectMgr.findObjectByNodePath(uid_np) if obj: uid = obj[OG.OBJ_UID] objNP = obj[OG.OBJ_NP] @@ -263,7 +263,7 @@ class ActionDeleteObjById(ActionBase): del self.hierarchy[uid] self.hierarchy = {} - self.objInfos = {} + self.objInfos = {} class ActionChangeHierarchy(ActionBase): """ Action class for changing Scene Graph Hierarchy """ @@ -282,7 +282,7 @@ class ActionChangeHierarchy(ActionBase): class ActionSelectObj(ActionBase): """ Action class for adding new object """ - + def __init__(self, editor, *args, **kargs): self.editor = editor function = base.direct.selectCB @@ -327,7 +327,7 @@ class ActionTransformObj(ActionBase): self.result = ActionBase._do__call__(self, *args, **kargs) obj = self.editor.objectMgr.findObjectById(self.uid) if obj: - self.editor.objectMgr.objectsLastXform[self.uid] = Mat4(obj[OG.OBJ_NP].getMat()) + self.editor.objectMgr.objectsLastXform[self.uid] = Mat4(obj[OG.OBJ_NP].getMat()) return self.result def undo(self): @@ -344,7 +344,7 @@ class ActionTransformObj(ActionBase): class ActionDeselectAll(ActionBase): """ Action class for adding new object """ - + def __init__(self, editor, *args, **kargs): self.editor = editor function = base.direct.deselectAllCB @@ -387,7 +387,7 @@ class ActionUpdateObjectProp(ActionBase): def redo(self): self.result = self._do__call__()#uid=self.uid, xformMat=self.xformMat) if self.editor and self.fSelectObject: - base.direct.select(self.obj[OG.OBJ_NP], fUndo=0) + base.direct.select(self.obj[OG.OBJ_NP], fUndo=0) return self.result def undo(self): @@ -397,4 +397,4 @@ class ActionUpdateObjectProp(ActionBase): if self.undoFunc: self.undoFunc() if self.editor and self.fSelectObject: - base.direct.select(self.obj[OG.OBJ_NP], fUndo=0) + base.direct.select(self.obj[OG.OBJ_NP], fUndo=0) diff --git a/direct/src/leveleditor/AnimControlUI.py b/direct/src/leveleditor/AnimControlUI.py index 99f9cd880a..71cf4168cf 100755 --- a/direct/src/leveleditor/AnimControlUI.py +++ b/direct/src/leveleditor/AnimControlUI.py @@ -1,936 +1,936 @@ -""" - This is the GUI for the Animation Control Panel -""" -from direct.interval.IntervalGlobal import * -from direct.actor.Actor import * -from panda3d.core import VBase3,VBase4 -import ObjectGlobals as OG -import AnimGlobals as AG - -import os,wx, time -from wx.lib.embeddedimage import PyEmbeddedImage - -#---------------------------------------------------------------------- -FirstFrame = PyEmbeddedImage( - "iVBORw0KGgoAAAANSUhEUgAAABwAAAAcCAIAAAD9b0jDAAAAA3NCSVQICAjb4U/gAAACh0lE" - "QVRIie2Uz08aQRTHd368CZzYGGNjPWkTlB7EK0QSewSSamL9R+upXmpko/LLskgqhrDGyqb4" - "Y40CB3dnd6aHMYBIjSZe2vhOk/2+93nf93Z3UOvsTHvtwK9OfIP+f1CEEKUUITRWJYQQQl4A" - "RQgBpQihVqvV6/UwflBCCGGM3XY6tm33H9JhGWPMOR9xFwhhnZzs7e21bPvL+rqu60KIe3eU" - "3tzcVCqVQqHwYW5ubW0tCIIBlDFmmmbTsjLptBoEADjnjUajWCodHx/3er2JiQklqWEdxzGr" - "1R8HB7/bbU3TotHoqFOMcfv8vFarZdJpxpjruvV6vVAs1ut1z/MopQBACAEAAGi32xXTLJfL" - "l5eXGGMAUJ3Gj88Y45w3LSu/v9+0LNd1AYAxpmlaEASE0uvr659HR+Vy2XEcla9pmpRS0zQy" - "tOsBFCEkhPi2tZXP533fD4VCqqY/iue6Xzc3r66uGGPDUr98kNw/SSkJIclE4tPKiq7rnHNl" - "QYUQIhwOp5aXF+bnlfERKKUDf3RYkFJOTk5ms9n40lJuZ6d6eOh5HgDcu5AyFoslk8liqWQY" - "xsXFxcjnOQYqhPB9PwgCzvn76emNjY3FeNzI5ZrNpjKMCQmCAACSicR8NLqfz5dLpU63q9Dk" - "sVMhRCQSmZmZQQhJKTnnCKGPsdjc7KxpmoZhtGxbCIEwVr11Xc9mMvHFxZ1crlarqfzBfp++" - "+THGlNLbTmd3d/fX6enn1dV3U1O+7ysVAIQQjUbj+/Z2bGEhlUqpXT+AKpuP0WpxjuOEw+FQ" - "KDScgxACgG63e3d3F4lEnuV0uFi1HNtVXQjq99VG3v4T8Tecij7uvsczoS+KN+g/Av0D3hpG" - "5dYDHHkAAAAASUVORK5CYII=") - - -#---------------------------------------------------------------------- -PreFrame = PyEmbeddedImage( - "iVBORw0KGgoAAAANSUhEUgAAABwAAAAcCAIAAAD9b0jDAAAAA3NCSVQICAjb4U/gAAACQ0lE" - "QVRIieWVzW4aMRSFbV+DCHTDJlkAYZMKAek2fQHYddElu/SteA+eoNk0iPA7BBBQgtQJI6Gi" - "ZoQKM2PP2F24P2RmKFGVRauenSX707nH99r4XtfRc4s8O/G/ghKMMcaHoQAAAIdxhFBKGeeM" - "MR/XDxVCrFYr0zQP4hzH0TStVqvpuk4p3d3waAEA6/W6Wq2m0ul3l5cIISmlDwcAm81mPp83" - "m827+ZwCFAoFn9NHUEXZWpZt20F3GGPLsiaTidbvz2Yzx3EQQvFkkgSy8kPVeUJ+xQIACjcc" - "DjudziddZ4ypBIQQyshh6C4OIWSa5sfZrNVqGYZh2zal9GeCUkq19KUUDsUIUUpN0xwOh71e" - "b2EYnHNCSCQSCe5EgZYKgWKMGefvr64Gt7f3i4XnebvuQhQoP7z5CSG2ZX15ePA8T2W6D+i7" - "gL1OpZQUoFwuF4vFD9fXo9HI2m6B0lA0CZuU8KJUPelM5u3Jyavz80ajMZ1OXdf9vesDUOXX" - "c10gpFAsZk5PB4NBvV5fLpdCiF1rT70oH5ozFj86en1x8fLsrN1ud7vdz6sVAKgo1UPxpJby" - "SQghhEgmk6VSKZ/PN25u+pq2tSzFCsYRMqacc9d1g2jP8xBCqVTqzfFxsVCo1+vj8Zgx9n2u" - "9kGFEIlEolKpJOJxGeg+Jdd1CSG5XC6bzbbabcMwghOFfR8fxjgajQohOOfhWfyQyvTrZgOE" - "xGKxXW5I+er5OSghBEboRSIhpfyTi9oniZAMBIr+0o/vH4d+A5itKwKTfnzPAAAAAElFTkSu" - "QmCC") - - -#---------------------------------------------------------------------- -PreKeyFrame = PyEmbeddedImage( - "iVBORw0KGgoAAAANSUhEUgAAABwAAAAcCAIAAAD9b0jDAAAAA3NCSVQICAjb4U/gAAACPUlE" - "QVRIib3Vz0/aYBgH8OfHiyTGgAsciJMl6A5j7OLO4+48eHT/qjflSDPlRweNEqPGrTF2hQwW" - "gbR9nx2Yi9Ii1bE9x7b55Pu87/Ok+PXqChZdtHDxv6FEsLS0UJQZXVcdHIBSi0OJ0HXV4aHE" - "QJmZmGOgML99BCAipZTjOPVard/vE00jT2gTEYkIEV3XbZpms9HwfP/T3l4mk9FaPwdVSmmt" - "v7uuaZqmaV5fX2utX66tEbOIPC0pIjIzANi23basRqPR7XaDIGBmRAQACImPoZNmtda2bbda" - "raZpOo4zeaiUAgARYebwgUajiJhIJPzR6Jtt12u1k5OTG8f5Y90vVgrjoIQ4Ho/Pz87ax8df" - "TLM/GABAIpGIbkckVvtE9PP2dn9//8KyiFkp9fvsogoRI99Ohw+CIJ1K7e7ulsvllZWVIAim" - "xuVBIqVinakAIFE+n8/t7LwtlarVauf0dDgaRUeeMQDRt+95HiG+3tx8lc+32m2jWr24vASA" - "yfDPCj4HBQAR8X2fmd9vbW0UCs1m8/PRkXNzowH4buUnIxW+qTnDLyKe56VSqQ/l8pti0TCM" - "Rr3+o9+fuDwjeKw1DYIAAbKZzMft7WKxaBiGZVnD4XDWHcbdfZnQiBuFwvr6eqfTqVQqAhBe" - "/Blo1Hd3b8T3fSZ6Vyrlcrler7eUTIbzhlBEmLU/92jP816srqbTaREJh8UHv2hEGI9xMJBs" - "9pG8c+thUhFIJmV5GXz/2SJE/E5E/lKMQhdR/wT9BR51CSZZ1VE7AAAAAElFTkSuQmCC") - -#---------------------------------------------------------------------- -PrePlay = PyEmbeddedImage( - "iVBORw0KGgoAAAANSUhEUgAAABwAAAAcCAIAAAD9b0jDAAAAA3NCSVQICAjb4U/gAAACV0lE" - "QVRIic2Vz1PaUBDHs5tkH9jROv4LDhUHrLXOlOml/p3+H/VYg6YJQz3UWkDDAJlob8J4AUxq" - "3tse4lBKEIV6cI9vdz7vuz/eW/h1daU9t+GzE18kFBERpxAWhAJAJpO5u7sbDodp7iJQIjIM" - "o16v7+/vtzsdk2giwJgLZxqGYZqXl5eWZf04O4ui6NPeHqTCngpFRCFEr9f76jjVarXf7wsh" - "hBBKqXTw41BEFETD21vbtstHR9fX10SUzWaZmZmllHNDiYiZz2q1Q8vyfV9HzGazIy9r2nxQ" - "0zR1XQ+CwLKsn7WaUkoQAUwWUEqpMT8O1XWdiLrdrm3b305OBoOBEMI0zSk3M7NSWuqmf6BJ" - "NwaDgeO69vFxt9dLyvdQNolSnqEUAKSU309PLcsKgkDX9dm4ETR9aIyIiFgulz8fHEgpl5eX" - "ETEtYdyS+iYjBZo2HnoPZWal1IdS6fXqarVaDYKAmWlaZyYsTpQCjLfrb/rM/Gpp6WOp9G57" - "u1GvO67rBwErNQP9pDlVSt2Goa7r73d3C8Vio9GoVCrtTkc9gAYAfuKLklJKKRFxZ2enUChc" - "eJ7rOK12W0ppEuEYmpnlXM9UKRWGISK+3drazOc9z6tUKl6z+TuOiWj03ck4ngM6jgaAYrG4" - "sbHRarVc1/WazTAMiUjTNKnUrDmdYcycqN7M59/kcu1Ox3Hd8/PzMAzjOF7867tXHUUAkMvl" - "1tfXfd//cniIACqlFBZb0QBARHEc39zcrKysTHgX3FHMHEWRUmptbS3t/a9tyszxtO6/vL3/" - "kP0BhtFQnDqk9wIAAAAASUVORK5CYII=") - -#---------------------------------------------------------------------- -Play = PyEmbeddedImage( - "iVBORw0KGgoAAAANSUhEUgAAABwAAAAcCAIAAAD9b0jDAAAAA3NCSVQICAjb4U/gAAACTUlE" - "QVRIidXWzU7bQBAH8JmxLW8SbglXLCchTsKFElEUu4aaHnhSnoInoBeEihoSwodEz5wKya67" - "Oz24UAiOgQhV6p5sy/r5v7OztvHH9TW896B3F/8hats2Ir4zenNzQ0Su6y5M249PENG27YOD" - "g5+3t192d33fJyKlFDMvjgIAIRrmo6Oj8/PzTqcThWGjXrcsS6WpMWZBlAFs2xZCAMDx8fFg" - "MAharTAMm82mEEJK+ZrUsygiWkQAQERCCGPMt5OTwelp0Gr1+/0gCBzHUUoVp55FAcCy/178" - "QzN/HwyGo1Gz0QijqB0EQogCOg8lmll3QnRdl5mHo9HZeNyo1/v9frfbFUKkaaq1fhlFotzC" - "4T19Nh6PLy58z4vCsLu2VhJCPk2dl9SyCjr0gb64vLy8uvI8b2trKwiCcqn0EOVp8zMDgG1Z" - "88THtBDCcZzhcLi/v//18JAeFe1J0uxBRAQAzFy8o5RSWuvV1dUkSYJWyxjzkDR/+sUxtdZK" - "qVq1Gm9vf9zcrFQqUsqimiJiAWqMkVJWKpUoDOM4rtVqSqnJZDJz27OkzEgEzybOzEopIvqw" - "vp4kied5Wuvn3Bw0L2maptoY3/d3k6Tb6SDidDqdN5s8NGup++OsfMvLy593dnq9XrlUki/t" - "0fkoIjNPp9OlpaU4jj9FUbValVJOCgMWoUQkpXRdt7exkSTJysrKrzSdV75XoQyAiHXf39vb" - "a7fbiPgmLhs484kmoru7O8dxsu576zs/P6kxplwuA0Dx+r4NzdyFuWz8Pz8TvwFpng4ClVur" - "2QAAAABJRU5ErkJggg==") - -#---------------------------------------------------------------------- -NextKeyFrame = PyEmbeddedImage( - "iVBORw0KGgoAAAANSUhEUgAAABwAAAAcCAIAAAD9b0jDAAAAA3NCSVQICAjb4U/gAAACNUlE" - "QVRIic2Vy27aQBSGj+3xBQNRlSJlQWhwSKPUSMkQmcu+Sl8zW56AVfMCTQgLVEQSbxCELhFi" - "wcUzc7qwihQ8NiTNImdny/P5/89tlNFwCO8d6rsTPyAUEXQdCAHE7VBFUXaCmqZ2d6c9PIBh" - "bIEi4nK5VFVVVbeYQMMg9/fq4yNGoGRDI2Os2+0yziuVim3bnDGMuFv/P87+JhQBRs/PnU7H" - "9/1Go+E4jqHrnPNYtCzIxrMCYOg6IPZ6vcFgUHbdWr1+mM8DAOf8jdC1ZELIYrH4dXv75PtV" - "z6OUfs7lBOdCiFdDETFgLLQalms6nf68ufnd63med3F+nk6nhRDJaEn18eUBTdNUVR2Px61W" - "q9ls9vt9xhghJKHzJDmNRpgNRHzy/eFo5LpurVr9Ui4rMW0XsQ8QZy1Er1ardrvt+75bq32f" - "TD4dHES/lNgPGJNC12wAmM/nf8bj2WwmFSuvvjTC+pim+bVUopSeXl5mr6+5TMFO0DXupFSi" - "lJaOj9OZDLMsBUA6ErKWWq3g31oRQnDObdt2HKdRrxcKBdu2OedBEERHPklpOJGhumwmUzo5" - "oZQWj44syxJCBEGw1ZkEyjhnjNm2/e3s7ILSYrFo6LoQgiUXMBmaSqUqlHrV6mE+b1kWY2x3" - "nASKiLqu/7i6yu7tWaYZ5i7pNGJ070mgmqblcrldzRICmhZ9rbz9ilZVZTIBQjCbhZdD+Irm" - "3wwhcH8fECEy1v8BBYCYtf3R7v34+AuNHRpDa7trrwAAAABJRU5ErkJggg==") - -#---------------------------------------------------------------------- -NextFrame = PyEmbeddedImage( - "iVBORw0KGgoAAAANSUhEUgAAABwAAAAcCAIAAAD9b0jDAAAAA3NCSVQICAjb4U/gAAACOUlE" - "QVRIidWVS2/aQBSFZ8ZjYxkTFmSBRFAgpk1CJTIgE/orq/wMJFbNAjbNLqsgxAKVh+INgrhL" - "HkK8PI8urCKCx01bsWju+vrTuef6noHj0Qgcu9DRie8dCiE8MlQIsdlsEEIIvT0EQkhV1WAn" - "PtBIKe10OpSxYrFoGAajVAghJUIIF4vFdDqNx+OxWIxzLlcKIRQAjF9eGo1GrVYbDAaMc4yx" - "1BBN03q93pe7u3a7HdG0UKUAAAiApqpAiG63OxwOP+Xzt5XKWSoFAGCMHTRzzj3P29coh+4k" - "Y4zX6/VTs/nsOGXbJoQkTk85Y/sICCFCKDjHIVQI4VHqu+ivazabfXt4+N7t2rZ9UyhEo1HO" - "eVDdfkm2L15/oCgKQsh13Xq9Xq1W+/0+pTTMaLlSaaPvhhDi2XFG43E+n78tlz9eXob9doHx" - "AQgbzUdvt9tWq+U4TqlUAkJIuXJPpdAdGwCwWq1+uK5pmkhmgnz70vL3E4lEPlgWIaRQKDw1" - "m/Tx8R+hO1zOsggh1sVF1DQxxmGbko2/3YJfscI5Z4wZhpHNZj9XKul02jAMxpjneb8JB4lS" - "/9h9dTHTtHI5Qkjm/FzXdf+Egs1vQyljlFLDMK6vrm4IyWQymqpyzmlggUIIznmQC/ffKITQ" - "crn8en+PFcUul89SKV3XaUhQIYQmk4nruslkMpFIvDrffagfffP5PHZyokcijLGw3NtxMcaM" - "sYOsgcHXVFEU6VB/XhJPgxH3t/WuX9P/FPoTFHYunoRw1IsAAAAASUVORK5CYII=") - -#---------------------------------------------------------------------- -LastFrame = PyEmbeddedImage( - "iVBORw0KGgoAAAANSUhEUgAAABwAAAAcCAIAAAD9b0jDAAAAA3NCSVQICAjb4U/gAAAClElE" - "QVRIie2VT0sbQRjG950/Gw8mW4QgCWxaMSdjwkq60YDmYD+A/QBiP5keq2IuHuKxxUNFqoI2" - "UuOlInahHpYkHhLdmXmnh5VNiLFS8CL4nhZm3t/zzvMsM/D76sp47iLPTnyFvkQoABDyqAYh" - "BAD+DwoA3W632WwyxiilA5u01r7vCyE454+B+iXvoZTSVru9Va1++fq10+2aphltAgAA+H5w" - "sL6xcXl5yRhjjD2Eaq0HoWHzzc1NrVZbXV09OjoytOacR2iNeHp6ura2tr297ft+LBaLvOKc" - "Hx4efl5fD+UNw+hpIiIhhHPued5WtXpycjI/P5+dnARChBBaa9M0AyG+7e01zs/nZmeLxWIi" - "kZBSEkJarZbneRGqB9WIiAgAjDGt9c+zs18XF47jVBYWkskkIhqGQQgxTbPZatV2dn7U65VK" - "JTc1xTkf8GSIO6EVpmlKKff39xuNhuu6t7e3kRWMUoNSz/M2Nzez2eyHxUWlVH9QLKIopcJx" - "en4TwhjzfX93d/eNZVFK+9NgjAkh6vX63d2dlUjQvt+x96W17u9BxCAIGGMzMzPLy8uZTEZK" - "Ga1KKYUQ4+PjH5eWPq2sJJNJqdSQ4yOi1toAQEQp5cjISCGfL5VK7yYmCMDx8XEoHKLTqZTr" - "uvl83rIsxphSKgiCYVCtpZQiCOLxuOM4ruu+zWQopUqpQIhwNM65bdvvi8VcLmdZllQqCAJE" - "TKVS07ncEKhSKmaaJdedK5cztg0AIQgAtNaolG3b5XI5Pz09OjoqhIhGk1IWCgXHcYQQ9wmF" - "zwkhpN1udzqddDodhjbg75/r67GxsUQ8LqUcyPNhQfRGEUIIIQO43okYQ8QncQ88/WdPf/RP" - "1ku8pF+hz1V/AVdHWFTfbzsRAAAAAElFTkSuQmCC") - -#---------------------------------------------------------------------- -Key = PyEmbeddedImage( - "iVBORw0KGgoAAAANSUhEUgAAABwAAAAcCAIAAAD9b0jDAAAAA3NCSVQICAjb4U/gAAACl0lE" - "QVRIie2Uv0sbYRjH3x+X9/JGk9wlYkg6icbJMf0LHCxo/QuKUCfR0TFqB/dKHSztYKHBYHCp" - "kIIFqZM6ODho3Y2tQ44EMRffu3tz79vhlcNGC5I4+h2/L3yen+8Df19cgKcWenLiM7RbKITw" - "vql1g6OUAikhQowxIUTw1GGmEEKdkEKh8GZq6v3KCgAAY9wttKen58Pqan5hwTCMcrm8sLhI" - "COkKSgg5Ozv79PlzcWPjy/r6j50du9HY3d2llHYO1XV9s1R6NTY2OjpqWRbGeG5u7uDwMGjr" - "LRRCiB4tz/N+nZ6OT0y4rgsAcBwnm82GNK1WqyGEQDB9IYTv+wAAhBDGmHOuaZqUUpl3hRBq" - "NBp2szk0OOh5HgBASkkpTSSTVcsyTVMIoakeHR8fb5ZKGsYN2242m5l0ulqtYozNROLurqia" - "GGPX19eGYUgplSmljEQiruOotdUAAJzz4eHh+fl5Sun3cvnn3t7y8nI+n0/29c3MzDRtuz1T" - "256dnXUcJxKJBJG45yGEVBhNxSGE6LpOKTUMIxqNJpPJWCwWi8USpklCoTZoPB4nhPy5vOzv" - "71f98X2/Vq8bhqHKQkH+QgghBOfccRwhhOu6nucFfiDf9ymlqVTqYH8/HA4DADDGlmVdXV2l" - "Uql/oEq+72cymZe5HGNsZGQkOzTEOW8blCpwYnz8a6FQr9ej0ahpmltbWy8ymd7eXvUK2y4/" - "xhhj7LouIURKyTm/fzIQQhDC15OTmqa9W1o6Ojr6tr1dLBaNeLzVaj0AfaR0Xa9UKm+np09O" - "TgYGBj6ureVyOcbY7dw6g0opw+Fw8+amcn6eTqdN02SMBTV1CFVCCIVCoVar1fZHOr+nAAC1" - "JA8E6wb6Pz1Dn15/AQsQSZkYzgBNAAAAAElFTkSuQmCC") - -#---------------------------------------------------------------------- -Stop = PyEmbeddedImage( - "iVBORw0KGgoAAAANSUhEUgAAABwAAAAcCAIAAAD9b0jDAAAAA3NCSVQICAjb4U/gAAAAvklE" - "QVRIie3VMQ6DMAwF0G9CEUxMzAwch4NwCEbuxyXoygiBkMQd2KoUM7Cg4tFSnixZ/qH3MODq" - "ii4XHzQO9IiQpvJTIlgLY06gRFgW3/dwDkRHqHMoiqiq4L2ExjGPo+k6TBOUOkK1VnUdtS2M" - "AfMhug+bZfBeQAEkSbB9n+0/6IPeAQ2dKTO0htbi7QcjKoQ6hzx/NQ22TUgpa6ksYe1XmgCg" - "wMe3B4pYe56u64lJATBjnmX0d91n+3+OfgDGM0GplgNFhQAAAABJRU5ErkJggg==") -#---------------------------------------------------------------------- -DeleteKey = PyEmbeddedImage( - "iVBORw0KGgoAAAANSUhEUgAAABwAAAAcCAIAAAD9b0jDAAAAA3NCSVQICAjb4U/gAAAEXUlE" - "QVRIibWWX0hUWRzHf+ece4/3TjPjvTMOrqM+lH9KmQhEszCC2OifLRRF+LKwb8X66Eug0UOP" - "Cz22+7JIGwxmEGmTWUahkhapLQSbwQZFm6iDOubM3DPn3nvOPozT6jhKQft7u/f+zuf3O7/v" - "+f3ORf98+ADf2vA3JxaC4q8Mg9DGJeufpUSWBYryxSlhcBy0spLHXQ9VFOXxY/z2LWjal+Qo" - "CaGxGI7HgZDNoQDOwYPqyAianQVV3ZopNY0+eCBDIXfXLrDtzaGuK02THztGYzFIp/PiryPq" - "Oh0f34ax0tq6jRC81fYBgHNRWens30/v3AEorJvUNPXNG/39+98TiR/b2q5evQoAZE0GBdYg" - "xpxIRFRV0f5+qaqA0LrPqorn5oqnpn55966zq8vw+WL37nVdukQp3QoKAMiy7JYW6fHQoSG5" - "VjRCgDHfw4d/VlT81tMTvX69u7v7weBgcmXl0aNHuq5vBc3my48eRcvLyvPnMuuNEGBM+/pw" - "S0t0bOz4oUPfHz4cj8cJIe3t7WPj40KIdVCEEM4zhLAQzqlT6vS0Oj0Nug6aVjQ4iCoqUvX1" - "f01Otp48mclkAIAxVlNToyrKwsJCVrFVqBCCc845dxxHSsk5F0II2+aOk2xtxcPD7uwsfvbM" - "tizrwIHEx4/JVKq6qopzDgBSSk3TAsHgfDyelUsBAErpy5cve27eVAhZSSZTqVS4rGx+fp4Q" - "YgYCLsZFyeQPg4NzlD7dvh2mpqx0+tOnT4ZhSClXz4OUHo8nwxhCaBVq23ZtbW1HR4eu6/di" - "scdPnly5cqWzszNYUnLh/Pkk57C0FIhGeSjUdOYMwXhlefnn9nbGmMfj+Vw9m3OMcTYMzsah" - "lAZMM2CahmH4fL5gMOj3+/1+fyAUCup6eHQULlzQmpu/GxkxQqGKykpK6ceZGSU3JVzXXVhc" - "NAwjqxX+nL8Q2TLajDEhRCaT4bYtAZTbtzMNDSIUshsaXK8XDwxohlFaWjr29KmmaQBACInH" - "44lEorS0dB30c8BwONzU2GhZViQSqY5E0N27orzc2bMHGEOM8SNHUCqljI+3nj37x40bi4uL" - "Pp/PNM1bt26Vh8Nerze7fZQ3+QkhhJBMJkOLi8noqDszw0+fRozlegUDgNbbK5qaTly8qNj2" - "5cuXX7x4caevLxqNGsXFjuMUgK5Wo6hIef1amZxkbW1ICMipvNpUluXv6/u7vv6nrq5XExPb" - "d+z49dq1xsZGy7JWdSsAVVU0N0cHBjLnzoGug+sWcJif9w4NJU6ceL+0VFZSYpqmZVkoNyU2" - "tCkhkE7T+/f58ePS6y1ABADbFmVlqX37vAMDddXVXr+f5U5oIShCAED7+53mZlFejjgvQMw6" - "Mubu3GnX1cneXjfX8ptAVVUdHhaVlc7u3f+JsxnXsuy9e2VJiTIxAWvmHuTXFCG0vCwNAzYE" - "39QwRum01PW1Yubfpl9HBAAh8ogboABfR8ylkvfif/lD+Rcv7QbV/D7nwgAAAABJRU5ErkJg" - "gg==") - -class TimeSlider(wx.Window): - """ - This is the Time Slider Panel. - """ - def __init__(self, parent, slidersize, sliderStartFrame, sliderEndFrame, curFrame): - wx.Window.__init__(self, parent, size = slidersize, style = wx.SUNKEN_BORDER) - - self._mainDialog = wx.GetTopLevelParent(self) - self._mouseIn = False - self.points = [] - self.numbers = [] - - self.curFrame = curFrame - self.sliderStartFrame = sliderStartFrame - self.sliderEndFrame = sliderEndFrame - self.frameNum = self.sliderEndFrame-self.sliderStartFrame+1 - - self.InitBuffer() - - self.Bind(wx.EVT_PAINT, self.OnPaint) - self.Bind(wx.EVT_SIZE, self.OnSize) - self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown) - self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp) - self.Bind(wx.EVT_MOTION, self.OnMotion) - - def InitBuffer(self): - self.w,self.h = self.GetClientSize() - self.buffer = wx.EmptyBitmap(self.w, self.h) - dc = wx.BufferedDC(wx.ClientDC(self), self.buffer) - self.DrawTimeSlider(dc) - self.DrawNumber(dc) - self.DrawFrame(dc) - self.DrawKeys(dc) - - def SetTimeSliderData(self, sliderStartFrame = 1, sliderEndFrame = 24, curFrame = 0): - self.curFrame = curFrame - self.sliderStartFrame = sliderStartFrame - self.sliderEndFrame = sliderEndFrame - self.frameNum = self.sliderEndFrame-self.sliderStartFrame+1 - - self.points = [] - self.numbers = [] - - self.InitBuffer() - self.Refresh() - - def OnPaint(self, evt): - dc = wx.BufferedPaintDC(self, self.buffer) - - def DrawTimeSlider(self,dc): - - dc.SetBackground(wx.Brush(self.GetBackgroundColour())) - dc.Clear() - - dc.SetPen(wx.BLACK_PEN) - dc.SetBrush(wx.BLACK_BRUSH) - dc.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL)) - - self.unitWidth = self.w/float(self.frameNum) - - if self.frameNum <= 20: - - self.points.append(((float(0),self.h),(float(0),self.h-15))) - - for i in range(1,self.frameNum): - temp = self.points[i-1][0][0]+self.unitWidth - self.points.append(((temp,self.h),(temp,self.h-15))) - - for i in range(self.frameNum): - self.numbers.append(self.sliderStartFrame+i) - - for i in range(self.frameNum): - dc.DrawLine(self.points[i][0][0], self.points[i][0][1], self.points[i][1][0], self.points[i][1][1]) - st = str(self.numbers[i]) - tw,th = dc.GetTextExtent(st) - dc.DrawText(st, self.points[i][0][0]+2, 0.5) - - elif self.frameNum <= 70: - - self.points.append(((self.unitWidth,self.h),(self.unitWidth,self.h-15))) - - for i in range(1,int((self.frameNum+1)/2)): - temp = self.points[i-1][0][0]+2*self.unitWidth - self.points.append(((temp,self.h),(temp,self.h-15))) - - for i in range(1,self.frameNum/2+1): - self.numbers.append(self.sliderStartFrame-1+i*2) - - for i in range(int((self.frameNum+1)/2)): - dc.DrawLine(self.points[i][0][0], self.points[i][0][1], self.points[i][1][0], self.points[i][1][1]) - - for i in range(self.frameNum/2): - st = str(self.numbers[i]) - tw,th = dc.GetTextExtent(st) - dc.DrawText(st, self.points[i][0][0]+2, 0.5) - - elif self.frameNum <= 150: - - self.points.append(((self.unitWidth*4.0,self.h),(self.unitWidth*4.0,self.h-15))) - - for i in range(1,int(self.frameNum/5)): - temp = self.points[i-1][0][0]+5*self.unitWidth - self.points.append(((temp,self.h),(temp,self.h-15))) - - for i in range(1,self.frameNum/5+1): - self.numbers.append(self.sliderStartFrame-1+i*5) - - for i in range(int(self.frameNum/5)): - dc.DrawLine(self.points[i][0][0], self.points[i][0][1], self.points[i][1][0], self.points[i][1][1]) - - for i in range(self.frameNum/5): - st = str(self.numbers[i]) - tw,th = dc.GetTextExtent(st) - dc.DrawText(st, self.points[i][0][0]+2, 0.5) - - elif self.frameNum <= 250: - - self.points.append(((self.unitWidth*9.0,self.h),(self.unitWidth*9.0,self.h-15))) - - for i in range(1,int(self.frameNum/10)): - temp = self.points[i-1][0][0]+10*self.unitWidth - self.points.append(((temp,self.h),(temp,self.h-15))) - - for i in range(1,self.frameNum/10+1): - self.numbers.append(self.sliderStartFrame+i*10) - - for i in range(int(self.frameNum/10)): - dc.DrawLine(self.points[i][0][0], self.points[i][0][1], self.points[i][1][0], self.points[i][1][1]) - - for i in range(self.frameNum/10): - st = str(self.numbers[i]) - tw,th = dc.GetTextExtent(st) - dc.DrawText(st, self.points[i][0][0]+2, 0.5) - - elif self.frameNum <= 1000: - - self.points.append(((self.unitWidth*49.0,self.h),(self.unitWidth*49.0,self.h-15))) - - for i in range(1,int(self.frameNum/50)): - temp = self.points[i-1][0][0]+50*self.unitWidth - self.points.append(((temp,self.h),(temp,self.h-15))) - - for i in range(1,self.frameNum/50+1): - self.numbers.append(self.sliderStartFrame-1+i*50) - - for i in range(int(self.frameNum/50)): - dc.DrawLine(self.points[i][0][0], self.points[i][0][1], self.points[i][1][0], self.points[i][1][1]) - - for i in range(self.frameNum/50): - st = str(self.numbers[i]) - tw,th = dc.GetTextExtent(st) - dc.DrawText(st, self.points[i][0][0]+2, 0.5) - - elif self.frameNum <= 2000: - - self.points.append(((self.unitWidth*99.0,self.h),(self.unitWidth*99.0,self.h-15))) - - for i in range(1,int(self.frameNum/100)): - temp = self.points[i-1][0][0]+100*self.unitWidth - self.points.append(((temp,self.h),(temp,self.h-15))) - - for i in range(1,self.frameNum/100+1): - self.numbers.append(self.sliderStartFrame-1+i*100) - - for i in range(int(self.frameNum/100)): - dc.DrawLine(self.points[i][0][0], self.points[i][0][1], self.points[i][1][0], self.points[i][1][1]) - - for i in range(self.frameNum/100): - st = str(self.numbers[i]) - tw,th = dc.GetTextExtent(st) - dc.DrawText(st, self.points[i][0][0]+2, 0.5) - - elif self.frameNum <= 10000: - - self.points.append(((self.unitWidth*999.0,self.h),(self.unitWidth*999.0,self.h-15))) - - for i in range(1,int(self.frameNum/1000)): - temp = self.points[i-1][0][0]+1000*self.unitWidth - self.points.append(((temp,self.h),(temp,self.h-15))) - - for i in range(1,self.frameNum/1000+1): - self.numbers.append(self.sliderStartFrame-1+i*1000) - - for i in range(int(self.frameNum/1000)): - dc.DrawLine(self.points[i][0][0], self.points[i][0][1], self.points[i][1][0], self.points[i][1][1]) - - for i in range(self.frameNum/1000): - st = str(self.numbers[i]) - tw,th = dc.GetTextExtent(st) - dc.DrawText(st, self.points[i][0][0]+2, 0.5) - - else: - pass - - - def DrawNumber(self, dc): - dc.SetPen(wx.BLACK_PEN) - dc.SetBrush(wx.BLACK_BRUSH) - dc.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL)) - - i = self.curFrame-self.sliderStartFrame - st = str(self.curFrame) - tw,th = dc.GetTextExtent(st) - dc.DrawText(st, float(self.unitWidth)*float(i)+2, self.h-th-0.5) - - def DrawFrame(self, dc): - i = self.curFrame-self.sliderStartFrame - pos = float(self.unitWidth)*float(i) - self.curRect = wx.Rect(pos, float(0), self.unitWidth, self.h) - - oldPen, oldBrush, oldMode = dc.GetPen(), dc.GetBrush(), dc.GetLogicalFunction() - - gray = wx.Colour(200, 200, 200) - grayPen = wx.Pen(gray) - grayBrush = wx.Brush(gray) - dc.SetPen(grayPen) - dc.SetBrush(grayBrush) - dc.SetLogicalFunction(wx.XOR) - dc.DrawRectangleRect(self.curRect) - - dc.SetPen(oldPen) - dc.SetBrush(oldBrush) - dc.SetLogicalFunction(oldMode) - - def DrawKeys(self, dc): - if len(self._mainDialog.keys) != 0: - for key in self._mainDialog.keys: - keyFrame = key - i = keyFrame-self.sliderStartFrame - pos = float(self.unitWidth)*float(i) - - oldPen, oldBrush, oldMode = dc.GetPen(), dc.GetBrush(), dc.GetLogicalFunction() - - dc.SetPen(wx.Pen("red")) - dc.SetBrush(wx.Brush("red")) - dc.SetLogicalFunction(wx.AND) - dc.DrawLine(pos, float(0), pos, self.h) - - dc.SetPen(oldPen) - dc.SetBrush(oldBrush) - dc.SetLogicalFunction(oldMode) - else: - pass - - def OnSize(self,evt): - self.InitBuffer() - - def OnLeftDown(self,evt): - point = (evt.GetX(), evt.GetY()) - - if point[1]>= float(0) and point[1]<= (float(self.h)-2.0): - if point[0]>= float(0) and point[0]<= float(self.w): - self._mouseIn = True - - if self._mouseIn: - self.CaptureMouse() - self.curFrame = int(float(point[0])/self.unitWidth)+self.sliderStartFrame - self._mainDialog.curFrame = self.curFrame - self._mainDialog.curFrameSpin.SetValue(self.curFrame) - self._mainDialog.OnAnimation(self.curFrame) - self.SetTimeSliderData(self.sliderStartFrame, self.sliderEndFrame, self.curFrame) - - def OnLeftUp(self,evt): - if self.GetCapture(): - self.ReleaseMouse() - self._mouseIn = False - - def OnMotion(self,evt): - self._mouseIn = False - if evt.Dragging() and evt.LeftIsDown(): - point = (evt.GetX(), evt.GetY()) - if point[1]>= float(0) and point[1]<= (float(self.h)-2.0): - if point[0]>= float(0) and point[0]<= float(self.w): - self._mouseIn = True - - if self._mouseIn: - self.curFrame = int(float(point[0])/self.unitWidth)+self.sliderStartFrame - self._mainDialog.curFrame = self.curFrame - self._mainDialog.curFrameSpin.SetValue(self.curFrame) - self._mainDialog.OnAnimation(self.curFrame) - self.SetTimeSliderData(self.sliderStartFrame, self.sliderEndFrame, self.curFrame) - - evt.Skip() - self._mouseIn = False - -class TimeRange(wx.Window): - """ - This is the Time Range Panel. - """ - def __init__(self, parent, rangesize, startFrame, endFrame, sliderStartFrame, sliderEndFrame): - wx.Window.__init__(self, parent, size = rangesize, style = wx.SUNKEN_BORDER) - - self._mainDialog = wx.GetTopLevelParent(self) - - self._mouseIn = False - - self.startFrame = startFrame - self.endFrame = endFrame - self.sliderStartFrame = sliderStartFrame - self.sliderEndFrame = sliderEndFrame - self.frameNum = self.endFrame-self.startFrame+1 - - self.InitBuffer() - - self.Bind(wx.EVT_PAINT, self.OnPaint) - self.Bind(wx.EVT_SIZE, self.OnSize) - self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown) - self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp) - self.Bind(wx.EVT_MOTION, self.OnMotion) - - def InitBuffer(self): - self.w,self.h = self.GetClientSize() - self.buffer = wx.EmptyBitmap(self.w, self.h) - dc = wx.BufferedDC(wx.ClientDC(self), self.buffer) - self.DrawTimeRange(dc) - - def SetTimeRangeData(self, startFrame = 1, endFrame = 24, sliderStartFrame = 1, sliderEndFrame = 24): - self.startFrame = startFrame - self.endFrame = endFrame - self.sliderStartFrame = sliderStartFrame - self.sliderEndFrame = sliderEndFrame - self.frameNum = self.endFrame-self.startFrame+1 - - self.InitBuffer() - self.Refresh() - - def OnPaint(self, evt): - dc = wx.BufferedPaintDC(self, self.buffer) - - def DrawTimeRange(self,dc): - dc.SetBackground(wx.Brush(wx.Colour(150, 150, 150))) - dc.Clear() - - dc.SetPen(wx.Pen(self.GetBackgroundColour())) - dc.SetBrush(wx.Brush(self.GetBackgroundColour())) - - self.unitWidth = (self.w-6.0)/float(self.frameNum) - self.rangePosX = 3.0+(float(self.sliderStartFrame-self.startFrame))*self.unitWidth - self.rangePosY = 2.0 - self.rangeWidth = float(self.sliderEndFrame-self.sliderStartFrame+1)*self.unitWidth - self.rangeHeight = self.h-4.0 - self.curRect = wx.Rect(self.rangePosX, self.rangePosY, self.rangeWidth, self.rangeHeight) - - dc.DrawRoundedRectangleRect(self.curRect, radius = 2) - - def OnSize(self,evt): - self.InitBuffer() - - def OnLeftDown(self,evt): - point = (evt.GetX(), evt.GetY()) - self.pos = 0 - - if point[1]>= self.rangePosY and point[1]<= self.rangePosY+self.rangeHeight: - if point[0]>= self.rangePosX and point[0]<= self.rangePosX+self.rangeWidth: - self._mouseIn = True - - if self._mouseIn: - self.CaptureMouse() - self.pos = point - - def OnLeftUp(self,evt): - if self.GetCapture(): - self.ReleaseMouse() - self._mouseIn = False - - def OnMotion(self,evt): - self._mouseIn = False - if evt.Dragging() and evt.LeftIsDown(): - newPos = (evt.GetX(), evt.GetY()) - if newPos[1]>= self.rangePosY and newPos[1]<= self.rangePosY+self.rangeHeight: - if newPos[0]>= self.rangePosX and newPos[0]<= self.rangePosX+self.rangeWidth: - self._mouseIn = True - - if self._mouseIn: - if newPos[0] == self.pos[0]: - evt.Skip() - self._mouseIn = False - if newPos[0] > self.pos[0]: - if float(newPos[0]-self.pos[0]) >= self.unitWidth: - if self.sliderEndFrame < self.endFrame: - self.sliderStartFrame += 1 - self.sliderEndFrame += 1 - self.SetTimeRangeData(self.startFrame, self.endFrame, self.sliderStartFrame, self.sliderEndFrame) - self.MainPanelUpdate() - self.pos = newPos - evt.Skip() - self._mouseIn = False - if newPos[0] < self.pos[0]: - if float(self.pos[0]-newPos[0]) >= self.unitWidth: - if self.sliderStartFrame > self.startFrame: - self.sliderStartFrame -=1 - self.sliderEndFrame -=1 - self.SetTimeRangeData(self.startFrame, self.endFrame, self.sliderStartFrame, self.sliderEndFrame) - self.MainPanelUpdate() - self.pos = newPos - evt.Skip() - self._mouseIn = False - evt.Skip() - self._mouseIn = False - - def MainPanelUpdate(self): - self._mainDialog.sliderStartFrame = self.sliderStartFrame - self._mainDialog.sliderEndFrame = self.sliderEndFrame - self._mainDialog.timeSliderStartSpin.SetValue(self.sliderStartFrame) - self._mainDialog.timeSliderEndSpin.SetValue(self.sliderEndFrame) - self._mainDialog.timeSlider.SetTimeSliderData(self._mainDialog.sliderStartFrame, self._mainDialog.sliderEndFrame, self._mainDialog.curFrame) - - -class AnimControlUI(wx.Dialog): - """ - This is the Animation Control main class implementation. - """ - def __init__(self, parent, editor): - wx.Dialog.__init__(self, parent, id=wx.ID_ANY, title="Animation Controller", - pos=wx.DefaultPosition, size=(920, 110)) - - self.editor = editor - self._initOver = False - - self.parallel = [] - if self.editor.animMgr.keyFramesInfo != []: - self.editor.animMgr.generateKeyFrames() - self.keys = self.editor.animMgr.keyFrames - self.editor.objectMgr.findActors(render) - self.editor.objectMgr.findNodes(render) - - self.prePlay = False - self.play = False - self.stop = True - - self.curFrame = 1 - self.startFrame = 1 - self.sliderStartFrame = 1 - self.endFrame = 24 - self.sliderEndFrame = 24 - - self.mainPanel1 = wx.Panel(self, -1) - - self.timeSlider = TimeSlider(self.mainPanel1, wx.Size(560, 35), self.sliderStartFrame, self.sliderEndFrame, self.curFrame) - self.curFrameSpin = wx.SpinCtrl(self.mainPanel1, -1, "",size = (70,25),min=self.startFrame, max=self.endFrame) - - bmpFirstFrame = FirstFrame.GetBitmap() - bmpPreFrame = PreFrame.GetBitmap() - bmpPreKeyFrame = PreKeyFrame.GetBitmap() - self.bmpPrePlay = PrePlay.GetBitmap() - self.bmpPlay = Play.GetBitmap() - bmpNextKeyFrame = NextKeyFrame.GetBitmap() - bmpNextFrame = NextFrame.GetBitmap() - bmpLastFrame = LastFrame.GetBitmap() - bmpKey = Key.GetBitmap() - self.bmpStop = Stop.GetBitmap() - bmpDeleteKey = DeleteKey.GetBitmap() - - self.buttonFirstFrame = wx.BitmapButton(self.mainPanel1, -1, bmpFirstFrame, size = (30,30),style = wx.BU_AUTODRAW) - self.buttonPreFrame = wx.BitmapButton(self.mainPanel1, -1, bmpPreFrame, size = (30,30),style = wx.BU_AUTODRAW) - self.buttonPreKeyFrame = wx.BitmapButton(self.mainPanel1, -1, bmpPreKeyFrame, size = (30,30),style = wx.BU_AUTODRAW) - self.buttonPrePlay = wx.BitmapButton(self.mainPanel1, -1, self.bmpPrePlay, size = (30,30),style = wx.BU_AUTODRAW) - self.buttonPlay = wx.BitmapButton(self.mainPanel1, -1, self.bmpPlay, size = (30,30),style = wx.BU_AUTODRAW) - self.buttonNextKeyFrame = wx.BitmapButton(self.mainPanel1, -1, bmpNextKeyFrame, size = (30,30),style = wx.BU_AUTODRAW) - self.buttonNextFrame = wx.BitmapButton(self.mainPanel1, -1, bmpNextFrame, size = (30,30),style = wx.BU_AUTODRAW) - self.buttonLastFrame = wx.BitmapButton(self.mainPanel1, -1, bmpLastFrame, size = (30,30),style = wx.BU_AUTODRAW) - - self.mainPanel2 = wx.Panel(self, -1) - - self.timeStartSpin = wx.SpinCtrl(self.mainPanel2, -1, "",size = (70,25),min=0, max=self.sliderEndFrame) - self.timeSliderStartSpin = wx.SpinCtrl(self.mainPanel2, -1, "",size = (70,25),min=self.startFrame, max=self.sliderEndFrame) - self.timeRange = TimeRange(self.mainPanel2, wx.Size(450, 25), self.startFrame, self.endFrame, self.sliderStartFrame, self.sliderEndFrame) - self.timeSliderEndSpin = wx.SpinCtrl(self.mainPanel2, -1, "",size = (70,25),min=self.sliderStartFrame, max=self.endFrame) - self.timeEndSpin = wx.SpinCtrl(self.mainPanel2, -1, "",size = (70,25),min=self.sliderStartFrame, max=10000) - self.buttonDeleteKey = wx.BitmapButton(self.mainPanel2, -1, bmpDeleteKey, size = (30,30),style = wx.BU_AUTODRAW) - - self.SetProperties() - self.DoLayout() - - self.Bind(wx.EVT_SPINCTRL, self.OnCurrentTime, self.curFrameSpin) - - self.Bind(wx.EVT_BUTTON, self.OnFirstFrame, self.buttonFirstFrame) - self.Bind(wx.EVT_BUTTON, self.OnPreFrame, self.buttonPreFrame) - self.Bind(wx.EVT_BUTTON, self.OnPreKeyFrame, self.buttonPreKeyFrame) - self.Bind(wx.EVT_BUTTON, self.OnPrePlay, self.buttonPrePlay) - self.Bind(wx.EVT_BUTTON, self.OnPlay, self.buttonPlay) - self.Bind(wx.EVT_BUTTON, self.OnNextKeyFrame, self.buttonNextKeyFrame) - self.Bind(wx.EVT_BUTTON, self.OnNextFrame, self.buttonNextFrame) - self.Bind(wx.EVT_BUTTON, self.OnLastFrame, self.buttonLastFrame) - - self.Bind(wx.EVT_SPINCTRL, self.OnTimeStartSpin, self.timeStartSpin) - self.Bind(wx.EVT_SPINCTRL, self.OnTimeSliderStartSpin, self.timeSliderStartSpin) - self.Bind(wx.EVT_SPINCTRL, self.OnTimeSliderEndSpin, self.timeSliderEndSpin) - self.Bind(wx.EVT_SPINCTRL, self.OnTimeEndSpin, self.timeEndSpin) - - self.Bind(wx.EVT_BUTTON, self.OnDeleteKey, self.buttonDeleteKey) - - self.Bind(wx.EVT_CLOSE, self.OnExit) - - self.OnPropKey() - self.OnAnimation(self.curFrame) - - self.timeUnit = float(1)/float(24)*float(1000) - self.timer = wx.Timer(self) - self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer) - - self._initOver = True - - def SetProperties(self): - self.curFrameSpin.SetValue(self.curFrame) - self.timeStartSpin.SetValue(self.startFrame) - self.timeSliderStartSpin.SetValue(self.sliderStartFrame) - self.timeSliderEndSpin.SetValue(self.sliderEndFrame) - self.timeEndSpin.SetValue(self.endFrame) - - def DoLayout(self): - dialogSizer = wx.BoxSizer(wx.VERTICAL) - mainSizer1 = wx.FlexGridSizer(1, 10, 0, 0) - mainSizer2 = wx.FlexGridSizer(1, 6, 0, 0) - - mainSizer1.Add(self.timeSlider, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5) - mainSizer1.Add(self.curFrameSpin, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, 3) - - mainSizer1.Add(self.buttonFirstFrame, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, 3) - mainSizer1.Add(self.buttonPreFrame, 0, wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, 3) - mainSizer1.Add(self.buttonPreKeyFrame, 0, wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, 3) - mainSizer1.Add(self.buttonPrePlay, 0, wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, 3) - mainSizer1.Add(self.buttonPlay, 0, wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, 3) - mainSizer1.Add(self.buttonNextKeyFrame, 0, wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, 3) - mainSizer1.Add(self.buttonNextFrame, 0, wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, 3) - mainSizer1.Add(self.buttonLastFrame, 0, wx.ALIGN_CENTER_VERTICAL) - - mainSizer2.Add(self.timeStartSpin, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, 5) - mainSizer2.Add(self.timeSliderStartSpin, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, 5) - mainSizer2.Add(self.timeRange, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, 5) - mainSizer2.Add(self.timeSliderEndSpin, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, 5) - mainSizer2.Add(self.timeEndSpin, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, 5) - mainSizer2.Add(self.buttonDeleteKey, 0, wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, 3) - - self.mainPanel1.SetSizerAndFit(mainSizer1) - self.mainPanel2.SetSizerAndFit(mainSizer2) - - dialogSizer.Add(self.mainPanel1, 1, wx.ALIGN_CENTER_VERTICAL|wx.TOP, 5) - dialogSizer.Add(self.mainPanel2, 1, wx.ALIGN_CENTER_VERTICAL|wx.TOP, 7) - - self.SetSizer(dialogSizer) - self.Layout() - - self.dialogSizer = dialogSizer - - def OnCurrentTime(self, evt): - self.curFrame = evt.GetInt() - self.timeSlider.SetTimeSliderData(self.sliderStartFrame, self.sliderEndFrame, self.curFrame) - self.OnAnimation(self.curFrame) - - def OnControl(self): - self.curFrameSpin.SetValue(self.curFrame) - self.timeSlider.SetTimeSliderData(self.sliderStartFrame, self.sliderEndFrame, self.curFrame) - self.OnAnimation(self.curFrame) - - def OnFirstFrame(self,evt): - self.curFrame = self.sliderStartFrame - self.OnControl() - - def OnPreFrame(self,evt): - if self.curFrame-1 >= self.startFrame: - self.curFrame -= 1 - self.OnControl() - else: - evt.Skip() - - def sortKey(self): - for i in range(0, len(self.keys)-1): - for j in range(i+1, len(self.keys)): - if self.keys[i]>self.keys[j]: - temp = self.keys[i] - self.keys[i] = self.keys[j] - self.keys[j] = temp - - def OnPreKeyFrame(self,evt): - self.sortKey() - if self.curFrame <= self.keys[0] or self.curFrame > self.keys[len(self.keys)-1]: - self.curFrame = self.keys[len(self.keys)-1] - else: - for i in range(1, len(self.keys)): - if self.curFrame <= self.keys[i] and self.curFrame > self.keys[i-1]: - self.curFrame = self.keys[i-1] - break - self.OnControl() - - def OnTimer(self,evt): - if self.prePlay == True and self.stop == False and self.play == False: - if self.curFrame-1>=self.sliderStartFrame: - self.curFrame -= 1 - self.OnControl() - elif self.curFrame == self.sliderStartFrame: - self.curFrame = self.sliderEndFrame - self.OnControl() - - if self.play == True and self.stop == False and self.prePlay == False: - if self.curFrame+1<=self.sliderEndFrame: - self.curFrame += 1 - self.OnControl() - elif self.curFrame == self.sliderEndFrame: - self.curFrame = self.sliderStartFrame - self.OnControl() - - def OnPrePlay(self,evt): - if self.prePlay == False and self.stop == True and self.play == False: - self.buttonPrePlay = wx.BitmapButton(self.mainPanel1, -1, self.bmpStop, size = (30,30),style = wx.BU_AUTODRAW) - self.DoLayout() - self.prePlay = True - self.stop = False - self.timer.Start(self.timeUnit) - evt.Skip() - - elif self.prePlay == True and self.stop == False and self.play == False: - self.buttonPrePlay = wx.BitmapButton(self.mainPanel1, -1, self.bmpPrePlay, size = (30,30),style = wx.BU_AUTODRAW) - self.DoLayout() - self.prePlay = False - self.stop = True - self.timer.Stop() - evt.Skip() - else: - evt.Skip() - - def OnPlay(self,evt): - if self.play == False and self.stop == True and self.prePlay == False: - self.buttonPlay = wx.BitmapButton(self.mainPanel1, -1, self.bmpStop, size = (30,30),style = wx.BU_AUTODRAW) - self.DoLayout() - self.play = True - self.stop = False - self.timer.Start(self.timeUnit) - evt.Skip() - - elif self.play == True and self.stop == False and self.prePlay == False: - self.buttonPlay = wx.BitmapButton(self.mainPanel1, -1, self.bmpPlay, size = (30,30),style = wx.BU_AUTODRAW) - self.DoLayout() - self.play = False - self.stop = True - self.timer.Stop() - evt.Skip() - else: - evt.Skip() - - def OnNextKeyFrame(self,evt): - self.sortKey() - if self.curFrame < self.keys[0] or self.curFrame >= self.keys[len(self.keys)-1]: - self.curFrame = self.keys[0] - else: - for i in range(0, len(self.keys)-1): - if self.curFrame >= self.keys[i] and self.curFrame < self.keys[i+1]: - self.curFrame = self.keys[i+1] - break - self.OnControl() - - def OnNextFrame(self,evt): - if self.curFrame+1 <= self.endFrame: - self.curFrame += 1 - self.OnControl() - else: - evt.Skip() - - def OnLastFrame(self,evt): - self.curFrame = self.sliderEndFrame - self.OnControl() - - def OnTime(self): - preFrame = self.curFrame - self.curFrameSpin.SetRange(self.startFrame,self.endFrame) - self.curFrame = preFrame - self.timeSlider.SetTimeSliderData(self.sliderStartFrame, self.sliderEndFrame, self.curFrame) - self.timeRange.SetTimeRangeData(self.startFrame, self.endFrame, self.sliderStartFrame, self.sliderEndFrame) - self.parallel = self.editor.animMgr.createParallel(self.startFrame,self.endFrame) - - def OnTimeStartSpin(self,evt): - self.startFrame = evt.GetInt() - self.timeSliderStartSpin.SetRange(self.startFrame, self.sliderEndFrame) - if self.startFrame >= self.sliderStartFrame: - self.sliderStartFrame = self.startFrame - self.timeSliderStartSpin.SetValue(self.sliderStartFrame) - self.OnTime() - else: - self.OnTime() - - def OnTimeSliderStartSpin(self,evt): - self.sliderStartFrame = evt.GetInt() - self.timeEndSpin.SetRange(self.sliderStartFrame, 10000) - self.OnTime() - - def OnTimeSliderEndSpin(self,evt): - self.sliderEndFrame = evt.GetInt() - self.timeStartSpin.SetRange(0, self.sliderEndFrame) - self.OnTime() - - def OnTimeEndSpin(self,evt): - self.endFrame = evt.GetInt() - self.timeSliderEndSpin.SetRange(self.sliderStartFrame, self.endFrame) - if self.endFrame <= self.sliderEndFrame: - self.sliderEndFrame = self.endFrame - self.timeSliderEndSpin.SetValue(self.sliderEndFrame) - self.OnTime() - else: - self.OnTime() - - def OnDeleteKey(self,evt): - for i in range(0,len(self.keys)): - if self.curFrame == self.keys[i]: - del self.keys[i] - break - - for j in self.editor.animMgr.keyFramesInfo.keys(): - for k in range(0,len(self.editor.animMgr.keyFramesInfo[j])): - if self.curFrame == self.editor.animMgr.keyFramesInfo[j][k][0]: - del self.editor.animMgr.keyFramesInfo[j][k] - break - - for l in self.editor.animMgr.keyFramesInfo.keys(): - if len(self.editor.animMgr.keyFramesInfo[l]) == 0: - del self.editor.animMgr.keyFramesInfo[l] - - self.OnPropKey() - self.OnAnimation(self.curFrame) - - def OnPropKey(self): - self.parallel = self.editor.animMgr.createParallel(self.startFrame, self.endFrame) - self.timeSlider.SetTimeSliderData(self.sliderStartFrame, self.sliderEndFrame, self.curFrame) - - - def OnAnimation(self, curFrame): - time = float(curFrame-1)/float(24) - self.parallel.setT(time) - if self.editor.GRAPH_EDITOR == True: - self.editor.ui.graphEditorUI.curFrameChange() - - def OnExit(self,evt): - for actor in self.editor.objectMgr.Actor: - actorAnim = os.path.basename(actor[OG.OBJ_ANIM]) - actor[OG.OBJ_NP].loop(actorAnim) - self.parallel = None - self.Destroy() - self.editor.ui.editAnimMenuItem.Check(False) - self.editor.mode = self.editor.BASE_MODE - - - - - - - \ No newline at end of file +""" + This is the GUI for the Animation Control Panel +""" +from direct.interval.IntervalGlobal import * +from direct.actor.Actor import * +from panda3d.core import VBase3,VBase4 +import ObjectGlobals as OG +import AnimGlobals as AG + +import os,wx, time +from wx.lib.embeddedimage import PyEmbeddedImage + +#---------------------------------------------------------------------- +FirstFrame = PyEmbeddedImage( + "iVBORw0KGgoAAAANSUhEUgAAABwAAAAcCAIAAAD9b0jDAAAAA3NCSVQICAjb4U/gAAACh0lE" + "QVRIie2Uz08aQRTHd368CZzYGGNjPWkTlB7EK0QSewSSamL9R+upXmpko/LLskgqhrDGyqb4" + "Y40CB3dnd6aHMYBIjSZe2vhOk/2+93nf93Z3UOvsTHvtwK9OfIP+f1CEEKUUITRWJYQQQl4A" + "RQgBpQihVqvV6/UwflBCCGGM3XY6tm33H9JhGWPMOR9xFwhhnZzs7e21bPvL+rqu60KIe3eU" + "3tzcVCqVQqHwYW5ubW0tCIIBlDFmmmbTsjLptBoEADjnjUajWCodHx/3er2JiQklqWEdxzGr" + "1R8HB7/bbU3TotHoqFOMcfv8vFarZdJpxpjruvV6vVAs1ut1z/MopQBACAEAAGi32xXTLJfL" + "l5eXGGMAUJ3Gj88Y45w3LSu/v9+0LNd1AYAxpmlaEASE0uvr659HR+Vy2XEcla9pmpRS0zQy" + "tOsBFCEkhPi2tZXP533fD4VCqqY/iue6Xzc3r66uGGPDUr98kNw/SSkJIclE4tPKiq7rnHNl" + "QYUQIhwOp5aXF+bnlfERKKUDf3RYkFJOTk5ms9n40lJuZ6d6eOh5HgDcu5AyFoslk8liqWQY" + "xsXFxcjnOQYqhPB9PwgCzvn76emNjY3FeNzI5ZrNpjKMCQmCAACSicR8NLqfz5dLpU63q9Dk" + "sVMhRCQSmZmZQQhJKTnnCKGPsdjc7KxpmoZhtGxbCIEwVr11Xc9mMvHFxZ1crlarqfzBfp++" + "+THGlNLbTmd3d/fX6enn1dV3U1O+7ysVAIQQjUbj+/Z2bGEhlUqpXT+AKpuP0WpxjuOEw+FQ" + "KDScgxACgG63e3d3F4lEnuV0uFi1HNtVXQjq99VG3v4T8Tecij7uvsczoS+KN+g/Av0D3hpG" + "5dYDHHkAAAAASUVORK5CYII=") + + +#---------------------------------------------------------------------- +PreFrame = PyEmbeddedImage( + "iVBORw0KGgoAAAANSUhEUgAAABwAAAAcCAIAAAD9b0jDAAAAA3NCSVQICAjb4U/gAAACQ0lE" + "QVRIieWVzW4aMRSFbV+DCHTDJlkAYZMKAek2fQHYddElu/SteA+eoNk0iPA7BBBQgtQJI6Gi" + "ZoQKM2PP2F24P2RmKFGVRauenSX707nH99r4XtfRc4s8O/G/ghKMMcaHoQAAAIdxhFBKGeeM" + "MR/XDxVCrFYr0zQP4hzH0TStVqvpuk4p3d3waAEA6/W6Wq2m0ul3l5cIISmlDwcAm81mPp83" + "m827+ZwCFAoFn9NHUEXZWpZt20F3GGPLsiaTidbvz2Yzx3EQQvFkkgSy8kPVeUJ+xQIACjcc" + "DjudziddZ4ypBIQQyshh6C4OIWSa5sfZrNVqGYZh2zal9GeCUkq19KUUDsUIUUpN0xwOh71e" + "b2EYnHNCSCQSCe5EgZYKgWKMGefvr64Gt7f3i4XnebvuQhQoP7z5CSG2ZX15ePA8T2W6D+i7" + "gL1OpZQUoFwuF4vFD9fXo9HI2m6B0lA0CZuU8KJUPelM5u3Jyavz80ajMZ1OXdf9vesDUOXX" + "c10gpFAsZk5PB4NBvV5fLpdCiF1rT70oH5ozFj86en1x8fLsrN1ud7vdz6sVAKgo1UPxpJby" + "SQghhEgmk6VSKZ/PN25u+pq2tSzFCsYRMqacc9d1g2jP8xBCqVTqzfFxsVCo1+vj8Zgx9n2u" + "9kGFEIlEolKpJOJxGeg+Jdd1CSG5XC6bzbbabcMwghOFfR8fxjgajQohOOfhWfyQyvTrZgOE" + "xGKxXW5I+er5OSghBEboRSIhpfyTi9oniZAMBIr+0o/vH4d+A5itKwKTfnzPAAAAAElFTkSu" + "QmCC") + + +#---------------------------------------------------------------------- +PreKeyFrame = PyEmbeddedImage( + "iVBORw0KGgoAAAANSUhEUgAAABwAAAAcCAIAAAD9b0jDAAAAA3NCSVQICAjb4U/gAAACPUlE" + "QVRIib3Vz0/aYBgH8OfHiyTGgAsciJMl6A5j7OLO4+48eHT/qjflSDPlRweNEqPGrTF2hQwW" + "gbR9nx2Yi9Ii1bE9x7b55Pu87/Ok+PXqChZdtHDxv6FEsLS0UJQZXVcdHIBSi0OJ0HXV4aHE" + "QJmZmGOgML99BCAipZTjOPVard/vE00jT2gTEYkIEV3XbZpms9HwfP/T3l4mk9FaPwdVSmmt" + "v7uuaZqmaV5fX2utX66tEbOIPC0pIjIzANi23basRqPR7XaDIGBmRAQACImPoZNmtda2bbda" + "raZpOo4zeaiUAgARYebwgUajiJhIJPzR6Jtt12u1k5OTG8f5Y90vVgrjoIQ4Ho/Pz87ax8df" + "TLM/GABAIpGIbkckVvtE9PP2dn9//8KyiFkp9fvsogoRI99Ohw+CIJ1K7e7ulsvllZWVIAim" + "xuVBIqVinakAIFE+n8/t7LwtlarVauf0dDgaRUeeMQDRt+95HiG+3tx8lc+32m2jWr24vASA" + "yfDPCj4HBQAR8X2fmd9vbW0UCs1m8/PRkXNzowH4buUnIxW+qTnDLyKe56VSqQ/l8pti0TCM" + "Rr3+o9+fuDwjeKw1DYIAAbKZzMft7WKxaBiGZVnD4XDWHcbdfZnQiBuFwvr6eqfTqVQqAhBe" + "/Blo1Hd3b8T3fSZ6Vyrlcrler7eUTIbzhlBEmLU/92jP816srqbTaREJh8UHv2hEGI9xMJBs" + "9pG8c+thUhFIJmV5GXz/2SJE/E5E/lKMQhdR/wT9BR51CSZZ1VE7AAAAAElFTkSuQmCC") + +#---------------------------------------------------------------------- +PrePlay = PyEmbeddedImage( + "iVBORw0KGgoAAAANSUhEUgAAABwAAAAcCAIAAAD9b0jDAAAAA3NCSVQICAjb4U/gAAACV0lE" + "QVRIic2Vz1PaUBDHs5tkH9jROv4LDhUHrLXOlOml/p3+H/VYg6YJQz3UWkDDAJlob8J4AUxq" + "3tse4lBKEIV6cI9vdz7vuz/eW/h1daU9t+GzE18kFBERpxAWhAJAJpO5u7sbDodp7iJQIjIM" + "o16v7+/vtzsdk2giwJgLZxqGYZqXl5eWZf04O4ui6NPeHqTCngpFRCFEr9f76jjVarXf7wsh" + "hBBKqXTw41BEFETD21vbtstHR9fX10SUzWaZmZmllHNDiYiZz2q1Q8vyfV9HzGazIy9r2nxQ" + "0zR1XQ+CwLKsn7WaUkoQAUwWUEqpMT8O1XWdiLrdrm3b305OBoOBEMI0zSk3M7NSWuqmf6BJ" + "NwaDgeO69vFxt9dLyvdQNolSnqEUAKSU309PLcsKgkDX9dm4ETR9aIyIiFgulz8fHEgpl5eX" + "ETEtYdyS+iYjBZo2HnoPZWal1IdS6fXqarVaDYKAmWlaZyYsTpQCjLfrb/rM/Gpp6WOp9G57" + "u1GvO67rBwErNQP9pDlVSt2Goa7r73d3C8Vio9GoVCrtTkc9gAYAfuKLklJKKRFxZ2enUChc" + "eJ7rOK12W0ppEuEYmpnlXM9UKRWGISK+3drazOc9z6tUKl6z+TuOiWj03ck4ngM6jgaAYrG4" + "sbHRarVc1/WazTAMiUjTNKnUrDmdYcycqN7M59/kcu1Ox3Hd8/PzMAzjOF7867tXHUUAkMvl" + "1tfXfd//cniIACqlFBZb0QBARHEc39zcrKysTHgX3FHMHEWRUmptbS3t/a9tyszxtO6/vL3/" + "kP0BhtFQnDqk9wIAAAAASUVORK5CYII=") + +#---------------------------------------------------------------------- +Play = PyEmbeddedImage( + "iVBORw0KGgoAAAANSUhEUgAAABwAAAAcCAIAAAD9b0jDAAAAA3NCSVQICAjb4U/gAAACTUlE" + "QVRIidXWzU7bQBAH8JmxLW8SbglXLCchTsKFElEUu4aaHnhSnoInoBeEihoSwodEz5wKya67" + "Oz24UAiOgQhV6p5sy/r5v7OztvHH9TW896B3F/8hats2Ir4zenNzQ0Su6y5M249PENG27YOD" + "g5+3t192d33fJyKlFDMvjgIAIRrmo6Oj8/PzTqcThWGjXrcsS6WpMWZBlAFs2xZCAMDx8fFg" + "MAharTAMm82mEEJK+ZrUsygiWkQAQERCCGPMt5OTwelp0Gr1+/0gCBzHUUoVp55FAcCy/178" + "QzN/HwyGo1Gz0QijqB0EQogCOg8lmll3QnRdl5mHo9HZeNyo1/v9frfbFUKkaaq1fhlFotzC" + "4T19Nh6PLy58z4vCsLu2VhJCPk2dl9SyCjr0gb64vLy8uvI8b2trKwiCcqn0EOVp8zMDgG1Z" + "88THtBDCcZzhcLi/v//18JAeFe1J0uxBRAQAzFy8o5RSWuvV1dUkSYJWyxjzkDR/+sUxtdZK" + "qVq1Gm9vf9zcrFQqUsqimiJiAWqMkVJWKpUoDOM4rtVqSqnJZDJz27OkzEgEzybOzEopIvqw" + "vp4kied5Wuvn3Bw0L2maptoY3/d3k6Tb6SDidDqdN5s8NGup++OsfMvLy593dnq9XrlUki/t" + "0fkoIjNPp9OlpaU4jj9FUbValVJOCgMWoUQkpXRdt7exkSTJysrKrzSdV75XoQyAiHXf39vb" + "a7fbiPgmLhs484kmoru7O8dxsu576zs/P6kxplwuA0Dx+r4NzdyFuWz8Pz8TvwFpng4ClVur" + "2QAAAABJRU5ErkJggg==") + +#---------------------------------------------------------------------- +NextKeyFrame = PyEmbeddedImage( + "iVBORw0KGgoAAAANSUhEUgAAABwAAAAcCAIAAAD9b0jDAAAAA3NCSVQICAjb4U/gAAACNUlE" + "QVRIic2Vy27aQBSGj+3xBQNRlSJlQWhwSKPUSMkQmcu+Sl8zW56AVfMCTQgLVEQSbxCELhFi" + "wcUzc7qwihQ8NiTNImdny/P5/89tlNFwCO8d6rsTPyAUEXQdCAHE7VBFUXaCmqZ2d6c9PIBh" + "bIEi4nK5VFVVVbeYQMMg9/fq4yNGoGRDI2Os2+0yziuVim3bnDGMuFv/P87+JhQBRs/PnU7H" + "9/1Go+E4jqHrnPNYtCzIxrMCYOg6IPZ6vcFgUHbdWr1+mM8DAOf8jdC1ZELIYrH4dXv75PtV" + "z6OUfs7lBOdCiFdDETFgLLQalms6nf68ufnd63med3F+nk6nhRDJaEn18eUBTdNUVR2Px61W" + "q9ls9vt9xhghJKHzJDmNRpgNRHzy/eFo5LpurVr9Ui4rMW0XsQ8QZy1Er1ardrvt+75bq32f" + "TD4dHES/lNgPGJNC12wAmM/nf8bj2WwmFSuvvjTC+pim+bVUopSeXl5mr6+5TMFO0DXupFSi" + "lJaOj9OZDLMsBUA6ErKWWq3g31oRQnDObdt2HKdRrxcKBdu2OedBEERHPklpOJGhumwmUzo5" + "oZQWj44syxJCBEGw1ZkEyjhnjNm2/e3s7ILSYrFo6LoQgiUXMBmaSqUqlHrV6mE+b1kWY2x3" + "nASKiLqu/7i6yu7tWaYZ5i7pNGJ070mgmqblcrldzRICmhZ9rbz9ilZVZTIBQjCbhZdD+Irm" + "3wwhcH8fECEy1v8BBYCYtf3R7v34+AuNHRpDa7trrwAAAABJRU5ErkJggg==") + +#---------------------------------------------------------------------- +NextFrame = PyEmbeddedImage( + "iVBORw0KGgoAAAANSUhEUgAAABwAAAAcCAIAAAD9b0jDAAAAA3NCSVQICAjb4U/gAAACOUlE" + "QVRIidWVS2/aQBSFZ8ZjYxkTFmSBRFAgpk1CJTIgE/orq/wMJFbNAjbNLqsgxAKVh+INgrhL" + "HkK8PI8urCKCx01bsWju+vrTuef6noHj0Qgcu9DRie8dCiE8MlQIsdlsEEIIvT0EQkhV1WAn" + "PtBIKe10OpSxYrFoGAajVAghJUIIF4vFdDqNx+OxWIxzLlcKIRQAjF9eGo1GrVYbDAaMc4yx" + "1BBN03q93pe7u3a7HdG0UKUAAAiApqpAiG63OxwOP+Xzt5XKWSoFAGCMHTRzzj3P29coh+4k" + "Y4zX6/VTs/nsOGXbJoQkTk85Y/sICCFCKDjHIVQI4VHqu+ivazabfXt4+N7t2rZ9UyhEo1HO" + "eVDdfkm2L15/oCgKQsh13Xq9Xq1W+/0+pTTMaLlSaaPvhhDi2XFG43E+n78tlz9eXob9doHx" + "AQgbzUdvt9tWq+U4TqlUAkJIuXJPpdAdGwCwWq1+uK5pmkhmgnz70vL3E4lEPlgWIaRQKDw1" + "m/Tx8R+hO1zOsggh1sVF1DQxxmGbko2/3YJfscI5Z4wZhpHNZj9XKul02jAMxpjneb8JB4lS" + "/9h9dTHTtHI5Qkjm/FzXdf+Egs1vQyljlFLDMK6vrm4IyWQymqpyzmlggUIIznmQC/ffKITQ" + "crn8en+PFcUul89SKV3XaUhQIYQmk4nruslkMpFIvDrffagfffP5PHZyokcijLGw3NtxMcaM" + "sYOsgcHXVFEU6VB/XhJPgxH3t/WuX9P/FPoTFHYunoRw1IsAAAAASUVORK5CYII=") + +#---------------------------------------------------------------------- +LastFrame = PyEmbeddedImage( + "iVBORw0KGgoAAAANSUhEUgAAABwAAAAcCAIAAAD9b0jDAAAAA3NCSVQICAjb4U/gAAAClElE" + "QVRIie2VT0sbQRjG950/Gw8mW4QgCWxaMSdjwkq60YDmYD+A/QBiP5keq2IuHuKxxUNFqoI2" + "UuOlInahHpYkHhLdmXmnh5VNiLFS8CL4nhZm3t/zzvMsM/D76sp47iLPTnyFvkQoABDyqAYh" + "BAD+DwoA3W632WwyxiilA5u01r7vCyE454+B+iXvoZTSVru9Va1++fq10+2aphltAgAA+H5w" + "sL6xcXl5yRhjjD2Eaq0HoWHzzc1NrVZbXV09OjoytOacR2iNeHp6ura2tr297ft+LBaLvOKc" + "Hx4efl5fD+UNw+hpIiIhhHPued5WtXpycjI/P5+dnARChBBaa9M0AyG+7e01zs/nZmeLxWIi" + "kZBSEkJarZbneRGqB9WIiAgAjDGt9c+zs18XF47jVBYWkskkIhqGQQgxTbPZatV2dn7U65VK" + "JTc1xTkf8GSIO6EVpmlKKff39xuNhuu6t7e3kRWMUoNSz/M2Nzez2eyHxUWlVH9QLKIopcJx" + "en4TwhjzfX93d/eNZVFK+9NgjAkh6vX63d2dlUjQvt+x96W17u9BxCAIGGMzMzPLy8uZTEZK" + "Ga1KKYUQ4+PjH5eWPq2sJJNJqdSQ4yOi1toAQEQp5cjISCGfL5VK7yYmCMDx8XEoHKLTqZTr" + "uvl83rIsxphSKgiCYVCtpZQiCOLxuOM4ruu+zWQopUqpQIhwNM65bdvvi8VcLmdZllQqCAJE" + "TKVS07ncEKhSKmaaJdedK5cztg0AIQgAtNaolG3b5XI5Pz09OjoqhIhGk1IWCgXHcYQQ9wmF" + "zwkhpN1udzqddDodhjbg75/r67GxsUQ8LqUcyPNhQfRGEUIIIQO43okYQ8QncQ88/WdPf/RP" + "1ku8pF+hz1V/AVdHWFTfbzsRAAAAAElFTkSuQmCC") + +#---------------------------------------------------------------------- +Key = PyEmbeddedImage( + "iVBORw0KGgoAAAANSUhEUgAAABwAAAAcCAIAAAD9b0jDAAAAA3NCSVQICAjb4U/gAAACl0lE" + "QVRIie2Uv0sbYRjH3x+X9/JGk9wlYkg6icbJMf0LHCxo/QuKUCfR0TFqB/dKHSztYKHBYHCp" + "kIIFqZM6ODho3Y2tQ44EMRffu3tz79vhlcNGC5I4+h2/L3yen+8Df19cgKcWenLiM7RbKITw" + "vql1g6OUAikhQowxIUTw1GGmEEKdkEKh8GZq6v3KCgAAY9wttKen58Pqan5hwTCMcrm8sLhI" + "COkKSgg5Ozv79PlzcWPjy/r6j50du9HY3d2llHYO1XV9s1R6NTY2OjpqWRbGeG5u7uDwMGjr" + "LRRCiB4tz/N+nZ6OT0y4rgsAcBwnm82GNK1WqyGEQDB9IYTv+wAAhBDGmHOuaZqUUpl3hRBq" + "NBp2szk0OOh5HgBASkkpTSSTVcsyTVMIoakeHR8fb5ZKGsYN2242m5l0ulqtYozNROLurqia" + "GGPX19eGYUgplSmljEQiruOotdUAAJzz4eHh+fl5Sun3cvnn3t7y8nI+n0/29c3MzDRtuz1T" + "256dnXUcJxKJBJG45yGEVBhNxSGE6LpOKTUMIxqNJpPJWCwWi8USpklCoTZoPB4nhPy5vOzv" + "71f98X2/Vq8bhqHKQkH+QgghBOfccRwhhOu6nucFfiDf9ymlqVTqYH8/HA4DADDGlmVdXV2l" + "Uql/oEq+72cymZe5HGNsZGQkOzTEOW8blCpwYnz8a6FQr9ej0ahpmltbWy8ymd7eXvUK2y4/" + "xhhj7LouIURKyTm/fzIQQhDC15OTmqa9W1o6Ojr6tr1dLBaNeLzVaj0AfaR0Xa9UKm+np09O" + "TgYGBj6ureVyOcbY7dw6g0opw+Fw8+amcn6eTqdN02SMBTV1CFVCCIVCoVar1fZHOr+nAAC1" + "JA8E6wb6Pz1Dn15/AQsQSZkYzgBNAAAAAElFTkSuQmCC") + +#---------------------------------------------------------------------- +Stop = PyEmbeddedImage( + "iVBORw0KGgoAAAANSUhEUgAAABwAAAAcCAIAAAD9b0jDAAAAA3NCSVQICAjb4U/gAAAAvklE" + "QVRIie3VMQ6DMAwF0G9CEUxMzAwch4NwCEbuxyXoygiBkMQd2KoUM7Cg4tFSnixZ/qH3MODq" + "ii4XHzQO9IiQpvJTIlgLY06gRFgW3/dwDkRHqHMoiqiq4L2ExjGPo+k6TBOUOkK1VnUdtS2M" + "AfMhug+bZfBeQAEkSbB9n+0/6IPeAQ2dKTO0htbi7QcjKoQ6hzx/NQ22TUgpa6ksYe1XmgCg" + "wMe3B4pYe56u64lJATBjnmX0d91n+3+OfgDGM0GplgNFhQAAAABJRU5ErkJggg==") +#---------------------------------------------------------------------- +DeleteKey = PyEmbeddedImage( + "iVBORw0KGgoAAAANSUhEUgAAABwAAAAcCAIAAAD9b0jDAAAAA3NCSVQICAjb4U/gAAAEXUlE" + "QVRIibWWX0hUWRzHf+ece4/3TjPjvTMOrqM+lH9KmQhEszCC2OifLRRF+LKwb8X66Eug0UOP" + "Cz22+7JIGwxmEGmTWUahkhapLQSbwQZFm6iDOubM3DPn3nvOPozT6jhKQft7u/f+zuf3O7/v" + "+f3ORf98+ADf2vA3JxaC4q8Mg9DGJeufpUSWBYryxSlhcBy0spLHXQ9VFOXxY/z2LWjal+Qo" + "CaGxGI7HgZDNoQDOwYPqyAianQVV3ZopNY0+eCBDIXfXLrDtzaGuK02THztGYzFIp/PiryPq" + "Oh0f34ax0tq6jRC81fYBgHNRWens30/v3AEorJvUNPXNG/39+98TiR/b2q5evQoAZE0GBdYg" + "xpxIRFRV0f5+qaqA0LrPqorn5oqnpn55966zq8vw+WL37nVdukQp3QoKAMiy7JYW6fHQoSG5" + "VjRCgDHfw4d/VlT81tMTvX69u7v7weBgcmXl0aNHuq5vBc3my48eRcvLyvPnMuuNEGBM+/pw" + "S0t0bOz4oUPfHz4cj8cJIe3t7WPj40KIdVCEEM4zhLAQzqlT6vS0Oj0Nug6aVjQ4iCoqUvX1" + "f01Otp48mclkAIAxVlNToyrKwsJCVrFVqBCCc845dxxHSsk5F0II2+aOk2xtxcPD7uwsfvbM" + "tizrwIHEx4/JVKq6qopzDgBSSk3TAsHgfDyelUsBAErpy5cve27eVAhZSSZTqVS4rGx+fp4Q" + "YgYCLsZFyeQPg4NzlD7dvh2mpqx0+tOnT4ZhSClXz4OUHo8nwxhCaBVq23ZtbW1HR4eu6/di" + "scdPnly5cqWzszNYUnLh/Pkk57C0FIhGeSjUdOYMwXhlefnn9nbGmMfj+Vw9m3OMcTYMzsah" + "lAZMM2CahmH4fL5gMOj3+/1+fyAUCup6eHQULlzQmpu/GxkxQqGKykpK6ceZGSU3JVzXXVhc" + "NAwjqxX+nL8Q2TLajDEhRCaT4bYtAZTbtzMNDSIUshsaXK8XDwxohlFaWjr29KmmaQBACInH" + "44lEorS0dB30c8BwONzU2GhZViQSqY5E0N27orzc2bMHGEOM8SNHUCqljI+3nj37x40bi4uL" + "Pp/PNM1bt26Vh8Nerze7fZQ3+QkhhJBMJkOLi8noqDszw0+fRozlegUDgNbbK5qaTly8qNj2" + "5cuXX7x4caevLxqNGsXFjuMUgK5Wo6hIef1amZxkbW1ICMipvNpUluXv6/u7vv6nrq5XExPb" + "d+z49dq1xsZGy7JWdSsAVVU0N0cHBjLnzoGug+sWcJif9w4NJU6ceL+0VFZSYpqmZVkoNyU2" + "tCkhkE7T+/f58ePS6y1ABADbFmVlqX37vAMDddXVXr+f5U5oIShCAED7+53mZlFejjgvQMw6" + "Mubu3GnX1cneXjfX8ptAVVUdHhaVlc7u3f+JsxnXsuy9e2VJiTIxAWvmHuTXFCG0vCwNAzYE" + "39QwRum01PW1Yubfpl9HBAAh8ogboABfR8ylkvfif/lD+Rcv7QbV/D7nwgAAAABJRU5ErkJg" + "gg==") + +class TimeSlider(wx.Window): + """ + This is the Time Slider Panel. + """ + def __init__(self, parent, slidersize, sliderStartFrame, sliderEndFrame, curFrame): + wx.Window.__init__(self, parent, size = slidersize, style = wx.SUNKEN_BORDER) + + self._mainDialog = wx.GetTopLevelParent(self) + self._mouseIn = False + self.points = [] + self.numbers = [] + + self.curFrame = curFrame + self.sliderStartFrame = sliderStartFrame + self.sliderEndFrame = sliderEndFrame + self.frameNum = self.sliderEndFrame-self.sliderStartFrame+1 + + self.InitBuffer() + + self.Bind(wx.EVT_PAINT, self.OnPaint) + self.Bind(wx.EVT_SIZE, self.OnSize) + self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown) + self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp) + self.Bind(wx.EVT_MOTION, self.OnMotion) + + def InitBuffer(self): + self.w,self.h = self.GetClientSize() + self.buffer = wx.EmptyBitmap(self.w, self.h) + dc = wx.BufferedDC(wx.ClientDC(self), self.buffer) + self.DrawTimeSlider(dc) + self.DrawNumber(dc) + self.DrawFrame(dc) + self.DrawKeys(dc) + + def SetTimeSliderData(self, sliderStartFrame = 1, sliderEndFrame = 24, curFrame = 0): + self.curFrame = curFrame + self.sliderStartFrame = sliderStartFrame + self.sliderEndFrame = sliderEndFrame + self.frameNum = self.sliderEndFrame-self.sliderStartFrame+1 + + self.points = [] + self.numbers = [] + + self.InitBuffer() + self.Refresh() + + def OnPaint(self, evt): + dc = wx.BufferedPaintDC(self, self.buffer) + + def DrawTimeSlider(self,dc): + + dc.SetBackground(wx.Brush(self.GetBackgroundColour())) + dc.Clear() + + dc.SetPen(wx.BLACK_PEN) + dc.SetBrush(wx.BLACK_BRUSH) + dc.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL)) + + self.unitWidth = self.w/float(self.frameNum) + + if self.frameNum <= 20: + + self.points.append(((float(0),self.h),(float(0),self.h-15))) + + for i in range(1,self.frameNum): + temp = self.points[i-1][0][0]+self.unitWidth + self.points.append(((temp,self.h),(temp,self.h-15))) + + for i in range(self.frameNum): + self.numbers.append(self.sliderStartFrame+i) + + for i in range(self.frameNum): + dc.DrawLine(self.points[i][0][0], self.points[i][0][1], self.points[i][1][0], self.points[i][1][1]) + st = str(self.numbers[i]) + tw,th = dc.GetTextExtent(st) + dc.DrawText(st, self.points[i][0][0]+2, 0.5) + + elif self.frameNum <= 70: + + self.points.append(((self.unitWidth,self.h),(self.unitWidth,self.h-15))) + + for i in range(1,int((self.frameNum+1)/2)): + temp = self.points[i-1][0][0]+2*self.unitWidth + self.points.append(((temp,self.h),(temp,self.h-15))) + + for i in range(1,self.frameNum/2+1): + self.numbers.append(self.sliderStartFrame-1+i*2) + + for i in range(int((self.frameNum+1)/2)): + dc.DrawLine(self.points[i][0][0], self.points[i][0][1], self.points[i][1][0], self.points[i][1][1]) + + for i in range(self.frameNum/2): + st = str(self.numbers[i]) + tw,th = dc.GetTextExtent(st) + dc.DrawText(st, self.points[i][0][0]+2, 0.5) + + elif self.frameNum <= 150: + + self.points.append(((self.unitWidth*4.0,self.h),(self.unitWidth*4.0,self.h-15))) + + for i in range(1,int(self.frameNum/5)): + temp = self.points[i-1][0][0]+5*self.unitWidth + self.points.append(((temp,self.h),(temp,self.h-15))) + + for i in range(1,self.frameNum/5+1): + self.numbers.append(self.sliderStartFrame-1+i*5) + + for i in range(int(self.frameNum/5)): + dc.DrawLine(self.points[i][0][0], self.points[i][0][1], self.points[i][1][0], self.points[i][1][1]) + + for i in range(self.frameNum/5): + st = str(self.numbers[i]) + tw,th = dc.GetTextExtent(st) + dc.DrawText(st, self.points[i][0][0]+2, 0.5) + + elif self.frameNum <= 250: + + self.points.append(((self.unitWidth*9.0,self.h),(self.unitWidth*9.0,self.h-15))) + + for i in range(1,int(self.frameNum/10)): + temp = self.points[i-1][0][0]+10*self.unitWidth + self.points.append(((temp,self.h),(temp,self.h-15))) + + for i in range(1,self.frameNum/10+1): + self.numbers.append(self.sliderStartFrame+i*10) + + for i in range(int(self.frameNum/10)): + dc.DrawLine(self.points[i][0][0], self.points[i][0][1], self.points[i][1][0], self.points[i][1][1]) + + for i in range(self.frameNum/10): + st = str(self.numbers[i]) + tw,th = dc.GetTextExtent(st) + dc.DrawText(st, self.points[i][0][0]+2, 0.5) + + elif self.frameNum <= 1000: + + self.points.append(((self.unitWidth*49.0,self.h),(self.unitWidth*49.0,self.h-15))) + + for i in range(1,int(self.frameNum/50)): + temp = self.points[i-1][0][0]+50*self.unitWidth + self.points.append(((temp,self.h),(temp,self.h-15))) + + for i in range(1,self.frameNum/50+1): + self.numbers.append(self.sliderStartFrame-1+i*50) + + for i in range(int(self.frameNum/50)): + dc.DrawLine(self.points[i][0][0], self.points[i][0][1], self.points[i][1][0], self.points[i][1][1]) + + for i in range(self.frameNum/50): + st = str(self.numbers[i]) + tw,th = dc.GetTextExtent(st) + dc.DrawText(st, self.points[i][0][0]+2, 0.5) + + elif self.frameNum <= 2000: + + self.points.append(((self.unitWidth*99.0,self.h),(self.unitWidth*99.0,self.h-15))) + + for i in range(1,int(self.frameNum/100)): + temp = self.points[i-1][0][0]+100*self.unitWidth + self.points.append(((temp,self.h),(temp,self.h-15))) + + for i in range(1,self.frameNum/100+1): + self.numbers.append(self.sliderStartFrame-1+i*100) + + for i in range(int(self.frameNum/100)): + dc.DrawLine(self.points[i][0][0], self.points[i][0][1], self.points[i][1][0], self.points[i][1][1]) + + for i in range(self.frameNum/100): + st = str(self.numbers[i]) + tw,th = dc.GetTextExtent(st) + dc.DrawText(st, self.points[i][0][0]+2, 0.5) + + elif self.frameNum <= 10000: + + self.points.append(((self.unitWidth*999.0,self.h),(self.unitWidth*999.0,self.h-15))) + + for i in range(1,int(self.frameNum/1000)): + temp = self.points[i-1][0][0]+1000*self.unitWidth + self.points.append(((temp,self.h),(temp,self.h-15))) + + for i in range(1,self.frameNum/1000+1): + self.numbers.append(self.sliderStartFrame-1+i*1000) + + for i in range(int(self.frameNum/1000)): + dc.DrawLine(self.points[i][0][0], self.points[i][0][1], self.points[i][1][0], self.points[i][1][1]) + + for i in range(self.frameNum/1000): + st = str(self.numbers[i]) + tw,th = dc.GetTextExtent(st) + dc.DrawText(st, self.points[i][0][0]+2, 0.5) + + else: + pass + + + def DrawNumber(self, dc): + dc.SetPen(wx.BLACK_PEN) + dc.SetBrush(wx.BLACK_BRUSH) + dc.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL)) + + i = self.curFrame-self.sliderStartFrame + st = str(self.curFrame) + tw,th = dc.GetTextExtent(st) + dc.DrawText(st, float(self.unitWidth)*float(i)+2, self.h-th-0.5) + + def DrawFrame(self, dc): + i = self.curFrame-self.sliderStartFrame + pos = float(self.unitWidth)*float(i) + self.curRect = wx.Rect(pos, float(0), self.unitWidth, self.h) + + oldPen, oldBrush, oldMode = dc.GetPen(), dc.GetBrush(), dc.GetLogicalFunction() + + gray = wx.Colour(200, 200, 200) + grayPen = wx.Pen(gray) + grayBrush = wx.Brush(gray) + dc.SetPen(grayPen) + dc.SetBrush(grayBrush) + dc.SetLogicalFunction(wx.XOR) + dc.DrawRectangleRect(self.curRect) + + dc.SetPen(oldPen) + dc.SetBrush(oldBrush) + dc.SetLogicalFunction(oldMode) + + def DrawKeys(self, dc): + if len(self._mainDialog.keys) != 0: + for key in self._mainDialog.keys: + keyFrame = key + i = keyFrame-self.sliderStartFrame + pos = float(self.unitWidth)*float(i) + + oldPen, oldBrush, oldMode = dc.GetPen(), dc.GetBrush(), dc.GetLogicalFunction() + + dc.SetPen(wx.Pen("red")) + dc.SetBrush(wx.Brush("red")) + dc.SetLogicalFunction(wx.AND) + dc.DrawLine(pos, float(0), pos, self.h) + + dc.SetPen(oldPen) + dc.SetBrush(oldBrush) + dc.SetLogicalFunction(oldMode) + else: + pass + + def OnSize(self,evt): + self.InitBuffer() + + def OnLeftDown(self,evt): + point = (evt.GetX(), evt.GetY()) + + if point[1]>= float(0) and point[1]<= (float(self.h)-2.0): + if point[0]>= float(0) and point[0]<= float(self.w): + self._mouseIn = True + + if self._mouseIn: + self.CaptureMouse() + self.curFrame = int(float(point[0])/self.unitWidth)+self.sliderStartFrame + self._mainDialog.curFrame = self.curFrame + self._mainDialog.curFrameSpin.SetValue(self.curFrame) + self._mainDialog.OnAnimation(self.curFrame) + self.SetTimeSliderData(self.sliderStartFrame, self.sliderEndFrame, self.curFrame) + + def OnLeftUp(self,evt): + if self.GetCapture(): + self.ReleaseMouse() + self._mouseIn = False + + def OnMotion(self,evt): + self._mouseIn = False + if evt.Dragging() and evt.LeftIsDown(): + point = (evt.GetX(), evt.GetY()) + if point[1]>= float(0) and point[1]<= (float(self.h)-2.0): + if point[0]>= float(0) and point[0]<= float(self.w): + self._mouseIn = True + + if self._mouseIn: + self.curFrame = int(float(point[0])/self.unitWidth)+self.sliderStartFrame + self._mainDialog.curFrame = self.curFrame + self._mainDialog.curFrameSpin.SetValue(self.curFrame) + self._mainDialog.OnAnimation(self.curFrame) + self.SetTimeSliderData(self.sliderStartFrame, self.sliderEndFrame, self.curFrame) + + evt.Skip() + self._mouseIn = False + +class TimeRange(wx.Window): + """ + This is the Time Range Panel. + """ + def __init__(self, parent, rangesize, startFrame, endFrame, sliderStartFrame, sliderEndFrame): + wx.Window.__init__(self, parent, size = rangesize, style = wx.SUNKEN_BORDER) + + self._mainDialog = wx.GetTopLevelParent(self) + + self._mouseIn = False + + self.startFrame = startFrame + self.endFrame = endFrame + self.sliderStartFrame = sliderStartFrame + self.sliderEndFrame = sliderEndFrame + self.frameNum = self.endFrame-self.startFrame+1 + + self.InitBuffer() + + self.Bind(wx.EVT_PAINT, self.OnPaint) + self.Bind(wx.EVT_SIZE, self.OnSize) + self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown) + self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp) + self.Bind(wx.EVT_MOTION, self.OnMotion) + + def InitBuffer(self): + self.w,self.h = self.GetClientSize() + self.buffer = wx.EmptyBitmap(self.w, self.h) + dc = wx.BufferedDC(wx.ClientDC(self), self.buffer) + self.DrawTimeRange(dc) + + def SetTimeRangeData(self, startFrame = 1, endFrame = 24, sliderStartFrame = 1, sliderEndFrame = 24): + self.startFrame = startFrame + self.endFrame = endFrame + self.sliderStartFrame = sliderStartFrame + self.sliderEndFrame = sliderEndFrame + self.frameNum = self.endFrame-self.startFrame+1 + + self.InitBuffer() + self.Refresh() + + def OnPaint(self, evt): + dc = wx.BufferedPaintDC(self, self.buffer) + + def DrawTimeRange(self,dc): + dc.SetBackground(wx.Brush(wx.Colour(150, 150, 150))) + dc.Clear() + + dc.SetPen(wx.Pen(self.GetBackgroundColour())) + dc.SetBrush(wx.Brush(self.GetBackgroundColour())) + + self.unitWidth = (self.w-6.0)/float(self.frameNum) + self.rangePosX = 3.0+(float(self.sliderStartFrame-self.startFrame))*self.unitWidth + self.rangePosY = 2.0 + self.rangeWidth = float(self.sliderEndFrame-self.sliderStartFrame+1)*self.unitWidth + self.rangeHeight = self.h-4.0 + self.curRect = wx.Rect(self.rangePosX, self.rangePosY, self.rangeWidth, self.rangeHeight) + + dc.DrawRoundedRectangleRect(self.curRect, radius = 2) + + def OnSize(self,evt): + self.InitBuffer() + + def OnLeftDown(self,evt): + point = (evt.GetX(), evt.GetY()) + self.pos = 0 + + if point[1]>= self.rangePosY and point[1]<= self.rangePosY+self.rangeHeight: + if point[0]>= self.rangePosX and point[0]<= self.rangePosX+self.rangeWidth: + self._mouseIn = True + + if self._mouseIn: + self.CaptureMouse() + self.pos = point + + def OnLeftUp(self,evt): + if self.GetCapture(): + self.ReleaseMouse() + self._mouseIn = False + + def OnMotion(self,evt): + self._mouseIn = False + if evt.Dragging() and evt.LeftIsDown(): + newPos = (evt.GetX(), evt.GetY()) + if newPos[1]>= self.rangePosY and newPos[1]<= self.rangePosY+self.rangeHeight: + if newPos[0]>= self.rangePosX and newPos[0]<= self.rangePosX+self.rangeWidth: + self._mouseIn = True + + if self._mouseIn: + if newPos[0] == self.pos[0]: + evt.Skip() + self._mouseIn = False + if newPos[0] > self.pos[0]: + if float(newPos[0]-self.pos[0]) >= self.unitWidth: + if self.sliderEndFrame < self.endFrame: + self.sliderStartFrame += 1 + self.sliderEndFrame += 1 + self.SetTimeRangeData(self.startFrame, self.endFrame, self.sliderStartFrame, self.sliderEndFrame) + self.MainPanelUpdate() + self.pos = newPos + evt.Skip() + self._mouseIn = False + if newPos[0] < self.pos[0]: + if float(self.pos[0]-newPos[0]) >= self.unitWidth: + if self.sliderStartFrame > self.startFrame: + self.sliderStartFrame -=1 + self.sliderEndFrame -=1 + self.SetTimeRangeData(self.startFrame, self.endFrame, self.sliderStartFrame, self.sliderEndFrame) + self.MainPanelUpdate() + self.pos = newPos + evt.Skip() + self._mouseIn = False + evt.Skip() + self._mouseIn = False + + def MainPanelUpdate(self): + self._mainDialog.sliderStartFrame = self.sliderStartFrame + self._mainDialog.sliderEndFrame = self.sliderEndFrame + self._mainDialog.timeSliderStartSpin.SetValue(self.sliderStartFrame) + self._mainDialog.timeSliderEndSpin.SetValue(self.sliderEndFrame) + self._mainDialog.timeSlider.SetTimeSliderData(self._mainDialog.sliderStartFrame, self._mainDialog.sliderEndFrame, self._mainDialog.curFrame) + + +class AnimControlUI(wx.Dialog): + """ + This is the Animation Control main class implementation. + """ + def __init__(self, parent, editor): + wx.Dialog.__init__(self, parent, id=wx.ID_ANY, title="Animation Controller", + pos=wx.DefaultPosition, size=(920, 110)) + + self.editor = editor + self._initOver = False + + self.parallel = [] + if self.editor.animMgr.keyFramesInfo != []: + self.editor.animMgr.generateKeyFrames() + self.keys = self.editor.animMgr.keyFrames + self.editor.objectMgr.findActors(render) + self.editor.objectMgr.findNodes(render) + + self.prePlay = False + self.play = False + self.stop = True + + self.curFrame = 1 + self.startFrame = 1 + self.sliderStartFrame = 1 + self.endFrame = 24 + self.sliderEndFrame = 24 + + self.mainPanel1 = wx.Panel(self, -1) + + self.timeSlider = TimeSlider(self.mainPanel1, wx.Size(560, 35), self.sliderStartFrame, self.sliderEndFrame, self.curFrame) + self.curFrameSpin = wx.SpinCtrl(self.mainPanel1, -1, "",size = (70,25),min=self.startFrame, max=self.endFrame) + + bmpFirstFrame = FirstFrame.GetBitmap() + bmpPreFrame = PreFrame.GetBitmap() + bmpPreKeyFrame = PreKeyFrame.GetBitmap() + self.bmpPrePlay = PrePlay.GetBitmap() + self.bmpPlay = Play.GetBitmap() + bmpNextKeyFrame = NextKeyFrame.GetBitmap() + bmpNextFrame = NextFrame.GetBitmap() + bmpLastFrame = LastFrame.GetBitmap() + bmpKey = Key.GetBitmap() + self.bmpStop = Stop.GetBitmap() + bmpDeleteKey = DeleteKey.GetBitmap() + + self.buttonFirstFrame = wx.BitmapButton(self.mainPanel1, -1, bmpFirstFrame, size = (30,30),style = wx.BU_AUTODRAW) + self.buttonPreFrame = wx.BitmapButton(self.mainPanel1, -1, bmpPreFrame, size = (30,30),style = wx.BU_AUTODRAW) + self.buttonPreKeyFrame = wx.BitmapButton(self.mainPanel1, -1, bmpPreKeyFrame, size = (30,30),style = wx.BU_AUTODRAW) + self.buttonPrePlay = wx.BitmapButton(self.mainPanel1, -1, self.bmpPrePlay, size = (30,30),style = wx.BU_AUTODRAW) + self.buttonPlay = wx.BitmapButton(self.mainPanel1, -1, self.bmpPlay, size = (30,30),style = wx.BU_AUTODRAW) + self.buttonNextKeyFrame = wx.BitmapButton(self.mainPanel1, -1, bmpNextKeyFrame, size = (30,30),style = wx.BU_AUTODRAW) + self.buttonNextFrame = wx.BitmapButton(self.mainPanel1, -1, bmpNextFrame, size = (30,30),style = wx.BU_AUTODRAW) + self.buttonLastFrame = wx.BitmapButton(self.mainPanel1, -1, bmpLastFrame, size = (30,30),style = wx.BU_AUTODRAW) + + self.mainPanel2 = wx.Panel(self, -1) + + self.timeStartSpin = wx.SpinCtrl(self.mainPanel2, -1, "",size = (70,25),min=0, max=self.sliderEndFrame) + self.timeSliderStartSpin = wx.SpinCtrl(self.mainPanel2, -1, "",size = (70,25),min=self.startFrame, max=self.sliderEndFrame) + self.timeRange = TimeRange(self.mainPanel2, wx.Size(450, 25), self.startFrame, self.endFrame, self.sliderStartFrame, self.sliderEndFrame) + self.timeSliderEndSpin = wx.SpinCtrl(self.mainPanel2, -1, "",size = (70,25),min=self.sliderStartFrame, max=self.endFrame) + self.timeEndSpin = wx.SpinCtrl(self.mainPanel2, -1, "",size = (70,25),min=self.sliderStartFrame, max=10000) + self.buttonDeleteKey = wx.BitmapButton(self.mainPanel2, -1, bmpDeleteKey, size = (30,30),style = wx.BU_AUTODRAW) + + self.SetProperties() + self.DoLayout() + + self.Bind(wx.EVT_SPINCTRL, self.OnCurrentTime, self.curFrameSpin) + + self.Bind(wx.EVT_BUTTON, self.OnFirstFrame, self.buttonFirstFrame) + self.Bind(wx.EVT_BUTTON, self.OnPreFrame, self.buttonPreFrame) + self.Bind(wx.EVT_BUTTON, self.OnPreKeyFrame, self.buttonPreKeyFrame) + self.Bind(wx.EVT_BUTTON, self.OnPrePlay, self.buttonPrePlay) + self.Bind(wx.EVT_BUTTON, self.OnPlay, self.buttonPlay) + self.Bind(wx.EVT_BUTTON, self.OnNextKeyFrame, self.buttonNextKeyFrame) + self.Bind(wx.EVT_BUTTON, self.OnNextFrame, self.buttonNextFrame) + self.Bind(wx.EVT_BUTTON, self.OnLastFrame, self.buttonLastFrame) + + self.Bind(wx.EVT_SPINCTRL, self.OnTimeStartSpin, self.timeStartSpin) + self.Bind(wx.EVT_SPINCTRL, self.OnTimeSliderStartSpin, self.timeSliderStartSpin) + self.Bind(wx.EVT_SPINCTRL, self.OnTimeSliderEndSpin, self.timeSliderEndSpin) + self.Bind(wx.EVT_SPINCTRL, self.OnTimeEndSpin, self.timeEndSpin) + + self.Bind(wx.EVT_BUTTON, self.OnDeleteKey, self.buttonDeleteKey) + + self.Bind(wx.EVT_CLOSE, self.OnExit) + + self.OnPropKey() + self.OnAnimation(self.curFrame) + + self.timeUnit = float(1)/float(24)*float(1000) + self.timer = wx.Timer(self) + self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer) + + self._initOver = True + + def SetProperties(self): + self.curFrameSpin.SetValue(self.curFrame) + self.timeStartSpin.SetValue(self.startFrame) + self.timeSliderStartSpin.SetValue(self.sliderStartFrame) + self.timeSliderEndSpin.SetValue(self.sliderEndFrame) + self.timeEndSpin.SetValue(self.endFrame) + + def DoLayout(self): + dialogSizer = wx.BoxSizer(wx.VERTICAL) + mainSizer1 = wx.FlexGridSizer(1, 10, 0, 0) + mainSizer2 = wx.FlexGridSizer(1, 6, 0, 0) + + mainSizer1.Add(self.timeSlider, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5) + mainSizer1.Add(self.curFrameSpin, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, 3) + + mainSizer1.Add(self.buttonFirstFrame, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, 3) + mainSizer1.Add(self.buttonPreFrame, 0, wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, 3) + mainSizer1.Add(self.buttonPreKeyFrame, 0, wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, 3) + mainSizer1.Add(self.buttonPrePlay, 0, wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, 3) + mainSizer1.Add(self.buttonPlay, 0, wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, 3) + mainSizer1.Add(self.buttonNextKeyFrame, 0, wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, 3) + mainSizer1.Add(self.buttonNextFrame, 0, wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, 3) + mainSizer1.Add(self.buttonLastFrame, 0, wx.ALIGN_CENTER_VERTICAL) + + mainSizer2.Add(self.timeStartSpin, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, 5) + mainSizer2.Add(self.timeSliderStartSpin, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, 5) + mainSizer2.Add(self.timeRange, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, 5) + mainSizer2.Add(self.timeSliderEndSpin, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, 5) + mainSizer2.Add(self.timeEndSpin, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, 5) + mainSizer2.Add(self.buttonDeleteKey, 0, wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, 3) + + self.mainPanel1.SetSizerAndFit(mainSizer1) + self.mainPanel2.SetSizerAndFit(mainSizer2) + + dialogSizer.Add(self.mainPanel1, 1, wx.ALIGN_CENTER_VERTICAL|wx.TOP, 5) + dialogSizer.Add(self.mainPanel2, 1, wx.ALIGN_CENTER_VERTICAL|wx.TOP, 7) + + self.SetSizer(dialogSizer) + self.Layout() + + self.dialogSizer = dialogSizer + + def OnCurrentTime(self, evt): + self.curFrame = evt.GetInt() + self.timeSlider.SetTimeSliderData(self.sliderStartFrame, self.sliderEndFrame, self.curFrame) + self.OnAnimation(self.curFrame) + + def OnControl(self): + self.curFrameSpin.SetValue(self.curFrame) + self.timeSlider.SetTimeSliderData(self.sliderStartFrame, self.sliderEndFrame, self.curFrame) + self.OnAnimation(self.curFrame) + + def OnFirstFrame(self,evt): + self.curFrame = self.sliderStartFrame + self.OnControl() + + def OnPreFrame(self,evt): + if self.curFrame-1 >= self.startFrame: + self.curFrame -= 1 + self.OnControl() + else: + evt.Skip() + + def sortKey(self): + for i in range(0, len(self.keys)-1): + for j in range(i+1, len(self.keys)): + if self.keys[i]>self.keys[j]: + temp = self.keys[i] + self.keys[i] = self.keys[j] + self.keys[j] = temp + + def OnPreKeyFrame(self,evt): + self.sortKey() + if self.curFrame <= self.keys[0] or self.curFrame > self.keys[len(self.keys)-1]: + self.curFrame = self.keys[len(self.keys)-1] + else: + for i in range(1, len(self.keys)): + if self.curFrame <= self.keys[i] and self.curFrame > self.keys[i-1]: + self.curFrame = self.keys[i-1] + break + self.OnControl() + + def OnTimer(self,evt): + if self.prePlay == True and self.stop == False and self.play == False: + if self.curFrame-1>=self.sliderStartFrame: + self.curFrame -= 1 + self.OnControl() + elif self.curFrame == self.sliderStartFrame: + self.curFrame = self.sliderEndFrame + self.OnControl() + + if self.play == True and self.stop == False and self.prePlay == False: + if self.curFrame+1<=self.sliderEndFrame: + self.curFrame += 1 + self.OnControl() + elif self.curFrame == self.sliderEndFrame: + self.curFrame = self.sliderStartFrame + self.OnControl() + + def OnPrePlay(self,evt): + if self.prePlay == False and self.stop == True and self.play == False: + self.buttonPrePlay = wx.BitmapButton(self.mainPanel1, -1, self.bmpStop, size = (30,30),style = wx.BU_AUTODRAW) + self.DoLayout() + self.prePlay = True + self.stop = False + self.timer.Start(self.timeUnit) + evt.Skip() + + elif self.prePlay == True and self.stop == False and self.play == False: + self.buttonPrePlay = wx.BitmapButton(self.mainPanel1, -1, self.bmpPrePlay, size = (30,30),style = wx.BU_AUTODRAW) + self.DoLayout() + self.prePlay = False + self.stop = True + self.timer.Stop() + evt.Skip() + else: + evt.Skip() + + def OnPlay(self,evt): + if self.play == False and self.stop == True and self.prePlay == False: + self.buttonPlay = wx.BitmapButton(self.mainPanel1, -1, self.bmpStop, size = (30,30),style = wx.BU_AUTODRAW) + self.DoLayout() + self.play = True + self.stop = False + self.timer.Start(self.timeUnit) + evt.Skip() + + elif self.play == True and self.stop == False and self.prePlay == False: + self.buttonPlay = wx.BitmapButton(self.mainPanel1, -1, self.bmpPlay, size = (30,30),style = wx.BU_AUTODRAW) + self.DoLayout() + self.play = False + self.stop = True + self.timer.Stop() + evt.Skip() + else: + evt.Skip() + + def OnNextKeyFrame(self,evt): + self.sortKey() + if self.curFrame < self.keys[0] or self.curFrame >= self.keys[len(self.keys)-1]: + self.curFrame = self.keys[0] + else: + for i in range(0, len(self.keys)-1): + if self.curFrame >= self.keys[i] and self.curFrame < self.keys[i+1]: + self.curFrame = self.keys[i+1] + break + self.OnControl() + + def OnNextFrame(self,evt): + if self.curFrame+1 <= self.endFrame: + self.curFrame += 1 + self.OnControl() + else: + evt.Skip() + + def OnLastFrame(self,evt): + self.curFrame = self.sliderEndFrame + self.OnControl() + + def OnTime(self): + preFrame = self.curFrame + self.curFrameSpin.SetRange(self.startFrame,self.endFrame) + self.curFrame = preFrame + self.timeSlider.SetTimeSliderData(self.sliderStartFrame, self.sliderEndFrame, self.curFrame) + self.timeRange.SetTimeRangeData(self.startFrame, self.endFrame, self.sliderStartFrame, self.sliderEndFrame) + self.parallel = self.editor.animMgr.createParallel(self.startFrame,self.endFrame) + + def OnTimeStartSpin(self,evt): + self.startFrame = evt.GetInt() + self.timeSliderStartSpin.SetRange(self.startFrame, self.sliderEndFrame) + if self.startFrame >= self.sliderStartFrame: + self.sliderStartFrame = self.startFrame + self.timeSliderStartSpin.SetValue(self.sliderStartFrame) + self.OnTime() + else: + self.OnTime() + + def OnTimeSliderStartSpin(self,evt): + self.sliderStartFrame = evt.GetInt() + self.timeEndSpin.SetRange(self.sliderStartFrame, 10000) + self.OnTime() + + def OnTimeSliderEndSpin(self,evt): + self.sliderEndFrame = evt.GetInt() + self.timeStartSpin.SetRange(0, self.sliderEndFrame) + self.OnTime() + + def OnTimeEndSpin(self,evt): + self.endFrame = evt.GetInt() + self.timeSliderEndSpin.SetRange(self.sliderStartFrame, self.endFrame) + if self.endFrame <= self.sliderEndFrame: + self.sliderEndFrame = self.endFrame + self.timeSliderEndSpin.SetValue(self.sliderEndFrame) + self.OnTime() + else: + self.OnTime() + + def OnDeleteKey(self,evt): + for i in range(0,len(self.keys)): + if self.curFrame == self.keys[i]: + del self.keys[i] + break + + for j in self.editor.animMgr.keyFramesInfo.keys(): + for k in range(0,len(self.editor.animMgr.keyFramesInfo[j])): + if self.curFrame == self.editor.animMgr.keyFramesInfo[j][k][0]: + del self.editor.animMgr.keyFramesInfo[j][k] + break + + for l in self.editor.animMgr.keyFramesInfo.keys(): + if len(self.editor.animMgr.keyFramesInfo[l]) == 0: + del self.editor.animMgr.keyFramesInfo[l] + + self.OnPropKey() + self.OnAnimation(self.curFrame) + + def OnPropKey(self): + self.parallel = self.editor.animMgr.createParallel(self.startFrame, self.endFrame) + self.timeSlider.SetTimeSliderData(self.sliderStartFrame, self.sliderEndFrame, self.curFrame) + + + def OnAnimation(self, curFrame): + time = float(curFrame-1)/float(24) + self.parallel.setT(time) + if self.editor.GRAPH_EDITOR == True: + self.editor.ui.graphEditorUI.curFrameChange() + + def OnExit(self,evt): + for actor in self.editor.objectMgr.Actor: + actorAnim = os.path.basename(actor[OG.OBJ_ANIM]) + actor[OG.OBJ_NP].loop(actorAnim) + self.parallel = None + self.Destroy() + self.editor.ui.editAnimMenuItem.Check(False) + self.editor.mode = self.editor.BASE_MODE + + + + + + + diff --git a/direct/src/leveleditor/AnimGlobals.py b/direct/src/leveleditor/AnimGlobals.py index 4decd4d5af..0571cfbabc 100755 --- a/direct/src/leveleditor/AnimGlobals.py +++ b/direct/src/leveleditor/AnimGlobals.py @@ -1,53 +1,53 @@ -""" -This contains data structure and constants related with animation handling. -""" - -# index for keyFramesInfo list structure -# data strucrure: {[nodeUID, propertyName] : [frameNum, -# value, -# [inSlopeX, inSlopeY], -# [outSlopeX, outSlopeY]]} -UID = 0 -PROP_NAME = 1 - -FRAME = 0 -VALUE = 1 -INSLOPE = 2 -OUTSLOPE = 3 - -# index for curveAnimation list structure -# data strucrure: {[nodeUID, curveUID] : [nodeUID, -# curveUID, -# time]} -NODE = 0 -CURVE = 1 - -NODE = 0 -CURVE = 1 -TIME = 2 - -# index for animation curve generation information list structure(self.X, self.Y, self.Z in GraphEditorUI) -# data structur: [key, -# i , -# [[keyFrameX, keyFrameY], keyFrame_select], -# [[inTangentX, inTangentY], inTangent_select], -# [[outTangentX, outTangentY], outTangent_select], -# [inSlopeX, inSlopeY], -# [outSlopeX, outSlopeY]] - -KEY = 0 -I = 1 -KEYFRAME = 2 -IN_TANGENT = 3 -OUT_TANGENT = 4 -IN_SLOPE = 5 -OUT_SLOPE = 6 - -LOCAL_VALUE = 0 -SELECT = 1 - -#index for coordinate -X = 0 -Y = 1 -Z = 2 - +""" +This contains data structure and constants related with animation handling. +""" + +# index for keyFramesInfo list structure +# data strucrure: {[nodeUID, propertyName] : [frameNum, +# value, +# [inSlopeX, inSlopeY], +# [outSlopeX, outSlopeY]]} +UID = 0 +PROP_NAME = 1 + +FRAME = 0 +VALUE = 1 +INSLOPE = 2 +OUTSLOPE = 3 + +# index for curveAnimation list structure +# data strucrure: {[nodeUID, curveUID] : [nodeUID, +# curveUID, +# time]} +NODE = 0 +CURVE = 1 + +NODE = 0 +CURVE = 1 +TIME = 2 + +# index for animation curve generation information list structure(self.X, self.Y, self.Z in GraphEditorUI) +# data structur: [key, +# i , +# [[keyFrameX, keyFrameY], keyFrame_select], +# [[inTangentX, inTangentY], inTangent_select], +# [[outTangentX, outTangentY], outTangent_select], +# [inSlopeX, inSlopeY], +# [outSlopeX, outSlopeY]] + +KEY = 0 +I = 1 +KEYFRAME = 2 +IN_TANGENT = 3 +OUT_TANGENT = 4 +IN_SLOPE = 5 +OUT_SLOPE = 6 + +LOCAL_VALUE = 0 +SELECT = 1 + +#index for coordinate +X = 0 +Y = 1 +Z = 2 + diff --git a/direct/src/leveleditor/AnimMgr.py b/direct/src/leveleditor/AnimMgr.py index ffa69a6b16..6be3aa58f6 100755 --- a/direct/src/leveleditor/AnimMgr.py +++ b/direct/src/leveleditor/AnimMgr.py @@ -1,10 +1,10 @@ -""" -Defines AnimMgr -""" -from AnimMgrBase import * - -class AnimMgr(AnimMgrBase): - """ Animation will create, manage, update animations in the scene """ - - def __init__(self, editor): - AnimMgrBase.__init__(self, editor) +""" +Defines AnimMgr +""" +from AnimMgrBase import * + +class AnimMgr(AnimMgrBase): + """ Animation will create, manage, update animations in the scene """ + + def __init__(self, editor): + AnimMgrBase.__init__(self, editor) diff --git a/direct/src/leveleditor/AnimMgrBase.py b/direct/src/leveleditor/AnimMgrBase.py index 157836337c..ecc0a55ae3 100755 --- a/direct/src/leveleditor/AnimMgrBase.py +++ b/direct/src/leveleditor/AnimMgrBase.py @@ -1,367 +1,367 @@ -""" -Defines AnimMgrBase -""" - -import os, wx, math - -from direct.interval.IntervalGlobal import * -from panda3d.core import VBase3,VBase4 -import ObjectGlobals as OG -import AnimGlobals as AG - -class AnimMgrBase: - """ AnimMgr will create, manage, update animations in the scene """ - - def __init__(self, editor): - self.editor = editor - self.graphEditorCounter = 0 - - self.keyFramesInfo = {} - self.curveAnimation = {} - - #normal properties - self.lerpFuncs={ - 'H' : self.lerpFuncH, - 'P' : self.lerpFuncP, - 'R' : self.lerpFuncR, - 'SX' : self.lerpFuncSX, - 'SY' : self.lerpFuncSY, - 'SZ' : self.lerpFuncSZ, - 'CR' : self.lerpFuncCR, - 'CG' : self.lerpFuncCG, - 'CB' : self.lerpFuncCB, - 'CA' : self.lerpFuncCA - } - - #Properties which has animation curves - self.curveLerpFuncs={ - 'X' : [ self.lerpFuncX, self.lerpCurveFuncX ], - 'Y' : [ self.lerpFuncY, self.lerpCurveFuncY ], - 'Z' : [ self.lerpFuncZ, self.lerpCurveFuncZ ] - } - - def reset(self): - self.keyFramesInfo = {} - self.curveAnimation = {} - - def generateKeyFrames(self): - #generate keyFrame list - self.keyFrames = [] - for property in self.keyFramesInfo.keys(): - for frameInfo in self.keyFramesInfo[property]: - frame = frameInfo[AG.FRAME] - exist = False - for keyFrame in self.keyFrames: - if frame == keyFrame: - exist = True - break - if exist == False: - self.keyFrames.append(frame) - - def generateSlope(self, list): - #generate handler slope of every keyframe for animation curve - listLen = len(list) - if listLen == 2: - slope =[float(list[1][AG.FRAME]-list[0][AG.FRAME]),(float(list[1][AG.VALUE])-float(list[0][AG.VALUE]))] - list[0][AG.INSLOPE] = slope - list[1][AG.INSLOPE] = slope - list[0][AG.OUTSLOPE] = list[0][AG.INSLOPE] - list[1][AG.OUTSLOPE] = list[1][AG.INSLOPE] - return - - if listLen >= 3: - list[0][AG.INSLOPE] = [float(list[1][AG.FRAME] - list[0][AG.FRAME]),(float(list[1][AG.VALUE]) - float(list[0][AG.VALUE]))] - list[0][AG.OUTSLOPE] = list[0][AG.INSLOPE] - for i in range(1, listLen-1): - list[i][AG.INSLOPE] = [float(list[i+1][AG.FRAME] - list[i-1][AG.FRAME]),(float(list[i+1][AG.VALUE]) - float(list[i-1][AG.VALUE]))] - list[i][AG.OUTSLOPE] = list[i][AG.INSLOPE] - list[listLen-1][AG.INSLOPE] = [float(list[listLen-1][AG.FRAME] - list[listLen-2][AG.FRAME]),(float(list[listLen-1][AG.VALUE]) - float(list[listLen-2][AG.VALUE]))] - list[listLen-1][AG.OUTSLOPE] = list[listLen-1][AG.INSLOPE] - return - - def removeAnimInfo(self, uid): - for property in self.keyFramesInfo.keys(): - if property[AG.UID] == uid: - del self.keyFramesInfo[property] - self.generateKeyFrames() - if self.editor.mode == self.editor.ANIM_MODE: - self.editor.ui.animUI.OnPropKey() - - def singleCurveAnimation(self, nodePath, curve, time): - rope = curve[OG.OBJ_NP] - self.points = rope.getPoints(time) - self.hprs = [] - temp = render.attachNewNode("temp") - temp.setHpr(0,0,0) - for i in range(len(self.points)-1): - temp.setPos(self.points[i]) - temp.lookAt(self.points[i+1]) - hpr = temp.getHpr() - ## self.hprs.append(hpr) - self.hprs.append(VBase3(hpr[0]+180,hpr[1],hpr[2])) - self.hprs.append(self.hprs[len(self.points)-2]) - - curveSequenceName = str(nodePath[OG.OBJ_UID])+' '+str(curve[OG.OBJ_UID])+' '+str(time) - self.curveSequence = Sequence(name = curveSequenceName) - - for i in range(len(self.points)-1): - myLerp = LerpPosHprInterval(nodePath[OG.OBJ_NP], float(1)/float(24), self.points[i+1], self.hprs[i+1], self.points[i], self.hprs[i]) - self.curveSequence.append(myLerp) - - return self.curveSequence - - def createParallel(self, startFrame, endFrame): - self.parallel = [] - self.parallel = Parallel(name="Current Parallel") - - self.createCurveAnimation(self.parallel) - self.createActorAnimation(self.parallel, startFrame, endFrame) - self.createKeyFrameAnimation(self.parallel, startFrame, endFrame) - self.createCurveKeyFrameAnimation(self.parallel, startFrame, endFrame) - - return self.parallel - - def createCurveAnimation(self, parallel): - for key in self.curveAnimation: - curveInfo = self.curveAnimation[key] - nodePath = self.editor.objectMgr.findObjectById(curveInfo[AG.NODE]) - curve = self.editor.objectMgr.findObjectById(curveInfo[AG.CURVE]) - time = curveInfo[AG.TIME] - sequence = self.singleCurveAnimation(nodePath, curve, time) - parallel.append(sequence) - - def createActorAnimation(self, parallel, startFrame, endFrame): - self.editor.objectMgr.findActors(render) - for actor in self.editor.objectMgr.Actor: - actorAnim = os.path.basename(actor[OG.OBJ_ANIM]) - myInterval = ActorInterval(actor[OG.OBJ_NP], actorAnim, loop=1, duration = float(endFrame-startFrame+1)/float(24)) - parallel.append(myInterval) - - def createKeyFrameAnimation(self, parallel, startFrame, endFrame): - #generate key frame animation for normal property - self.editor.objectMgr.findNodes(render) - for node in self.editor.objectMgr.Nodes: - for property in self.keyFramesInfo.keys(): - if property[AG.UID] == node[OG.OBJ_UID] and property[AG.PROP_NAME] != 'X' and property[AG.PROP_NAME] != 'Y' and property[AG.PROP_NAME] != 'Z': - mysequence = Sequence(name = node[OG.OBJ_UID]) - keyFramesInfo = self.keyFramesInfo[property] - if len(keyFramesInfo) == 1: - myLerp = LerpFunc(self.lerpFuncs[property[AG.PROP_NAME]],fromData=float(keyFramesInfo[0][AG.VALUE]),toData=float(keyFramesInfo[0][AG.VALUE]),duration = float(endFrame-startFrame)/float(24),blendType = 'noBlend',extraArgs = [node[OG.OBJ_NP]]) - mysequence.append(myLerp) - parallel.append(mysequence) - - if len(keyFramesInfo) != 1: - myLerp = LerpFunc(self.lerpFuncs[property[AG.PROP_NAME]],fromData=float(keyFramesInfo[0][AG.VALUE]),toData=float(keyFramesInfo[0][AG.VALUE]),duration = float(keyFramesInfo[0][AG.FRAME]-startFrame)/float(24),blendType = 'noBlend',extraArgs = [node[OG.OBJ_NP]]) - mysequence.append(myLerp) - - for key in range(0,len(keyFramesInfo)-1): - myLerp = LerpFunc(self.lerpFuncs[property[AG.PROP_NAME]],fromData=float(keyFramesInfo[key][AG.VALUE]),toData=float(keyFramesInfo[key+1][AG.VALUE]),duration = float(keyFramesInfo[key+1][AG.FRAME]-keyFramesInfo[key][AG.FRAME])/float(24),blendType = 'noBlend',extraArgs = [node[OG.OBJ_NP]]) - mysequence.append(myLerp) - - myLerp = LerpFunc(self.lerpFuncs[property[AG.PROP_NAME]],fromData=float(keyFramesInfo[len(keyFramesInfo)-1][AG.VALUE]),toData=float(keyFramesInfo[len(keyFramesInfo)-1][AG.VALUE]),duration = float(endFrame-keyFramesInfo[len(keyFramesInfo)-1][AG.FRAME])/float(24),blendType = 'noBlend',extraArgs = [node[OG.OBJ_NP]]) - mysequence.append(myLerp) - parallel.append(mysequence) - - def createCurveKeyFrameAnimation(self, parallel, startFrame, endFrame): - #generate key frame animation for the property which is controled by animation curve - self.editor.objectMgr.findNodes(render) - for node in self.editor.objectMgr.Nodes: - for property in self.keyFramesInfo.keys(): - if property[AG.UID] == node[OG.OBJ_UID]: - if property[AG.PROP_NAME] == 'X' or property[AG.PROP_NAME] == 'Y' or property[AG.PROP_NAME] == 'Z': - mysequence = Sequence(name = node[OG.OBJ_UID]) - keyFramesInfo = self.keyFramesInfo[property] - if len(keyFramesInfo) == 1: - myLerp = LerpFunc(self.curveLerpFuncs[property[AG.PROP_NAME]][0],fromData=float(keyFramesInfo[0][AG.VALUE]),toData=float(keyFramesInfo[0][AG.VALUE]),duration = float(endFrame-startFrame)/float(24),blendType = 'noBlend',extraArgs = [node[OG.OBJ_NP]]) - mysequence.append(myLerp) - parallel.append(mysequence) - - if len(keyFramesInfo) == 2: - myLerp = LerpFunc(self.curveLerpFuncs[property[AG.PROP_NAME]][0],fromData=float(keyFramesInfo[0][AG.VALUE]),toData=float(keyFramesInfo[0][AG.VALUE]),duration = float(keyFramesInfo[0][AG.FRAME]-startFrame)/float(24),blendType = 'noBlend',extraArgs = [node[OG.OBJ_NP]]) - mysequence.append(myLerp) - - for key in range(0,len(keyFramesInfo)-1): - self.keyFrameInfoForSingleLerp = keyFramesInfo - self.keyInfoForSingleLerp = key - myLerp = LerpFunc(self.curveLerpFuncs[property[AG.PROP_NAME]][0],fromData=float(keyFramesInfo[key][AG.VALUE]),toData=float(keyFramesInfo[key+1][AG.VALUE]),duration = float(keyFramesInfo[key+1][AG.FRAME]-keyFramesInfo[key][AG.FRAME])/float(24),blendType = 'noBlend',extraArgs = [node[OG.OBJ_NP]]) - mysequence.append(myLerp) - - myLerp = LerpFunc(self.curveLerpFuncs[property[AG.PROP_NAME]][0],fromData=float(keyFramesInfo[len(keyFramesInfo)-1][AG.VALUE]),toData=float(keyFramesInfo[len(keyFramesInfo)-1][AG.VALUE]),duration = float(endFrame-keyFramesInfo[len(keyFramesInfo)-1][AG.FRAME])/float(24),blendType = 'noBlend',extraArgs = [node[OG.OBJ_NP]]) - mysequence.append(myLerp) - parallel.append(mysequence) - - if len(keyFramesInfo) > 2: - myLerp = LerpFunc(self.curveLerpFuncs[property[AG.PROP_NAME]][0],fromData=float(keyFramesInfo[0][AG.VALUE]),toData=float(keyFramesInfo[0][1]),duration = float(keyFramesInfo[0][AG.FRAME]-startFrame)/float(24),blendType = 'noBlend',extraArgs = [node[OG.OBJ_NP]]) - mysequence.append(myLerp) - - for key in range(0,len(keyFramesInfo)-1): - myLerp = LerpFunc(self.curveLerpFuncs[property[AG.PROP_NAME]][1],fromData=float(keyFramesInfo[key][AG.FRAME]),toData=float(keyFramesInfo[key+1][AG.FRAME]),duration = float(keyFramesInfo[key+1][AG.FRAME]-keyFramesInfo[key][AG.FRAME])/float(24),blendType = 'noBlend',extraArgs = [[node[OG.OBJ_NP], keyFramesInfo, key]]) - mysequence.append(myLerp) - - myLerp = LerpFunc(self.curveLerpFuncs[property[AG.PROP_NAME]][0],fromData=float(keyFramesInfo[len(keyFramesInfo)-1][AG.VALUE]),toData=float(keyFramesInfo[len(keyFramesInfo)-1][AG.VALUE]),duration = float(endFrame-keyFramesInfo[len(keyFramesInfo)-1][AG.FRAME])/float(24),blendType = 'noBlend',extraArgs = [node[OG.OBJ_NP]]) - mysequence.append(myLerp) - parallel.append(mysequence) - - def getPos(self, x, list, i): - #get the value from animation curve - x1 = float(list[i][AG.FRAME]) - y1 = float(list[i][AG.VALUE]) - - x4 = float(list[i+1][AG.FRAME]) - y4 = float(list[i+1][AG.VALUE]) - - t1x = list[i][AG.OUTSLOPE][0] - t1y = list[i][AG.OUTSLOPE][1] - - t2x = list[i+1][AG.INSLOPE][0] - t2y = list[i+1][AG.INSLOPE][1] - - x2 = x1 + (x4 - x1) / float(3) - scale1 = (x2 - x1) / t1x - y2 = y1 + t1y * scale1 - - x3 = x4 - (x4 - x1) / float(3) - scale2 = (x4 - x3) / t2x - y3 = y4 - t2y * scale2 - - ax = - float(1) * x1 + float(3) * x2 - float(3) * x3 + float(1) * x4 - bx = float(3) * x1 - float(6) * x2 + float(3) * x3 + float(0) * x4 - cx = - float(3) * x1 + float(3) * x2 + float(0) * x3 + float(0) * x4 - dx = float(1) * x1 + float(0) * x2 - float(0) * x3 + float(0) * x4 - - ay = - float(1) * y1 + float(3) * y2 - float(3) * y3 + float(1) * y4 - by = float(3) * y1 - float(6) * y2 + float(3) * y3 + float(0) * y4 - cy = - float(3) * y1 + float(3) * y2 + float(0) * y3 + float(0) * y4 - dy = float(1) * y1 + float(0) * y2 - float(0) * y3 + float(0) * y4 - - if ax == 0 and bx == 0 and cx == 0: - return 0 - - if ax == 0 and bx == 0 and cx != 0: - a = cx - b = dx-x - t = -b/a - y = ay * t*t*t + by * t*t + cy * t + dy - return y - - if ax == 0 and bx!= 0: - a=bx - b=cx - c=dx-x - t=(-b+math.sqrt(b**2-4.0*a*c))/2*a - if t>=0 and t<=1: - y = ay * t*t*t + by * t*t + cy * t + dy - return y - else: - t=(-b-math.sqrt(b**2-4.0*a*c))/2*a - y = ay * t*t*t + by * t*t + cy * t + dy - return y - - if ax != 0: - a = ax - b = bx - c = cx - d = dx - float(x) - t = self.calculateT(a, b, c, d, x) - y = ay * t*t*t + by * t*t + cy * t + dy - return y - - def calculateT(self, a, b, c, d, x): - #Newton EQUATION - t = float(1) - t2 = t - t -= (a*t*t*t+b*t*t+c*t+d)/(float(3)*a*t*t+float(2)*b*t+c) - if abs(t-t2) <= 0.000001: - return t - else: - while abs(t - t2) > 0.000001: - t2 = t - t -= (a*t*t*t+b*t*t+c*t+d)/(float(3)*a*t*t+float(2)*b*t+c) - return t - - def lerpFuncX(self,pos,np): - np.setX(pos) - - def lerpFuncY(self,pos,np): - np.setY(pos) - - def lerpFuncZ(self,pos,np): - np.setZ(pos) - - def lerpCurveFuncX(self,t,extraArgs): - np = extraArgs[0] - pos = self.getPos(t, extraArgs[1], extraArgs[2]) - np.setX(pos) - - def lerpCurveFuncY(self,t,extraArgs): - np = extraArgs[0] - pos = self.getPos(t, extraArgs[1], extraArgs[2]) - np.setY(pos) - - def lerpCurveFuncZ(self,t,extraArgs): - np = extraArgs[0] - pos = self.getPos(t, extraArgs[1], extraArgs[2]) - np.setZ(pos) - - def lerpFuncH(self,angle,np): - np.setH(angle) - - def lerpFuncP(self,angle,np): - np.setP(angle) - - def lerpFuncR(self,angle,np): - np.setR(angle) - - def lerpFuncSX(self,scale,np): - np.setSx(scale) - - def lerpFuncSY(self,scale,np): - np.setSy(scale) - - def lerpFuncSZ(self,scale,np): - np.setSz(scale) - - def lerpFuncCR(self,R,np): - obj = self.editor.objectMgr.findObjectByNodePath(np) - r = obj[OG.OBJ_RGBA][0] - g = obj[OG.OBJ_RGBA][1] - b = obj[OG.OBJ_RGBA][2] - a = obj[OG.OBJ_RGBA][3] - self.colorUpdate(R,g,b,a,np) - - def lerpFuncCG(self,G,np): - obj = self.editor.objectMgr.findObjectByNodePath(np) - r = obj[OG.OBJ_RGBA][0] - g = obj[OG.OBJ_RGBA][1] - b = obj[OG.OBJ_RGBA][2] - a = obj[OG.OBJ_RGBA][3] - self.colorUpdate(r,G,b,a,np) - - def lerpFuncCB(self,B,np): - obj = self.editor.objectMgr.findObjectByNodePath(np) - r = obj[OG.OBJ_RGBA][0] - g = obj[OG.OBJ_RGBA][1] - b = obj[OG.OBJ_RGBA][2] - a = obj[OG.OBJ_RGBA][3] - self.colorUpdate(r,g,B,a,np) - - def lerpFuncCA(self,A,np): - obj = self.editor.objectMgr.findObjectByNodePath(np) - r = obj[OG.OBJ_RGBA][0] - g = obj[OG.OBJ_RGBA][1] - b = obj[OG.OBJ_RGBA][2] - a = obj[OG.OBJ_RGBA][3] - self.colorUpdate(r,g,b,A,np) - - def colorUpdate(self, r, g, b, a, np): - if base.direct.selected.last == None: - self.editor.objectMgr.updateObjectColor(r, g, b, a, np) - elif self.editor.objectMgr.findObjectByNodePath(np) == self.editor.objectMgr.findObjectByNodePath(base.direct.selected.last): - self.editor.ui.objectPropertyUI.propCR.setValue(r) - self.editor.ui.objectPropertyUI.propCG.setValue(g) - self.editor.ui.objectPropertyUI.propCB.setValue(b) - self.editor.ui.objectPropertyUI.propCA.setValue(a) - self.editor.objectMgr.updateObjectColor(r, g, b, a, np) - else: - self.editor.objectMgr.updateObjectColor(r, g, b, a, np) - \ No newline at end of file +""" +Defines AnimMgrBase +""" + +import os, wx, math + +from direct.interval.IntervalGlobal import * +from panda3d.core import VBase3,VBase4 +import ObjectGlobals as OG +import AnimGlobals as AG + +class AnimMgrBase: + """ AnimMgr will create, manage, update animations in the scene """ + + def __init__(self, editor): + self.editor = editor + self.graphEditorCounter = 0 + + self.keyFramesInfo = {} + self.curveAnimation = {} + + #normal properties + self.lerpFuncs={ + 'H' : self.lerpFuncH, + 'P' : self.lerpFuncP, + 'R' : self.lerpFuncR, + 'SX' : self.lerpFuncSX, + 'SY' : self.lerpFuncSY, + 'SZ' : self.lerpFuncSZ, + 'CR' : self.lerpFuncCR, + 'CG' : self.lerpFuncCG, + 'CB' : self.lerpFuncCB, + 'CA' : self.lerpFuncCA + } + + #Properties which has animation curves + self.curveLerpFuncs={ + 'X' : [ self.lerpFuncX, self.lerpCurveFuncX ], + 'Y' : [ self.lerpFuncY, self.lerpCurveFuncY ], + 'Z' : [ self.lerpFuncZ, self.lerpCurveFuncZ ] + } + + def reset(self): + self.keyFramesInfo = {} + self.curveAnimation = {} + + def generateKeyFrames(self): + #generate keyFrame list + self.keyFrames = [] + for property in self.keyFramesInfo.keys(): + for frameInfo in self.keyFramesInfo[property]: + frame = frameInfo[AG.FRAME] + exist = False + for keyFrame in self.keyFrames: + if frame == keyFrame: + exist = True + break + if exist == False: + self.keyFrames.append(frame) + + def generateSlope(self, list): + #generate handler slope of every keyframe for animation curve + listLen = len(list) + if listLen == 2: + slope =[float(list[1][AG.FRAME]-list[0][AG.FRAME]),(float(list[1][AG.VALUE])-float(list[0][AG.VALUE]))] + list[0][AG.INSLOPE] = slope + list[1][AG.INSLOPE] = slope + list[0][AG.OUTSLOPE] = list[0][AG.INSLOPE] + list[1][AG.OUTSLOPE] = list[1][AG.INSLOPE] + return + + if listLen >= 3: + list[0][AG.INSLOPE] = [float(list[1][AG.FRAME] - list[0][AG.FRAME]),(float(list[1][AG.VALUE]) - float(list[0][AG.VALUE]))] + list[0][AG.OUTSLOPE] = list[0][AG.INSLOPE] + for i in range(1, listLen-1): + list[i][AG.INSLOPE] = [float(list[i+1][AG.FRAME] - list[i-1][AG.FRAME]),(float(list[i+1][AG.VALUE]) - float(list[i-1][AG.VALUE]))] + list[i][AG.OUTSLOPE] = list[i][AG.INSLOPE] + list[listLen-1][AG.INSLOPE] = [float(list[listLen-1][AG.FRAME] - list[listLen-2][AG.FRAME]),(float(list[listLen-1][AG.VALUE]) - float(list[listLen-2][AG.VALUE]))] + list[listLen-1][AG.OUTSLOPE] = list[listLen-1][AG.INSLOPE] + return + + def removeAnimInfo(self, uid): + for property in self.keyFramesInfo.keys(): + if property[AG.UID] == uid: + del self.keyFramesInfo[property] + self.generateKeyFrames() + if self.editor.mode == self.editor.ANIM_MODE: + self.editor.ui.animUI.OnPropKey() + + def singleCurveAnimation(self, nodePath, curve, time): + rope = curve[OG.OBJ_NP] + self.points = rope.getPoints(time) + self.hprs = [] + temp = render.attachNewNode("temp") + temp.setHpr(0,0,0) + for i in range(len(self.points)-1): + temp.setPos(self.points[i]) + temp.lookAt(self.points[i+1]) + hpr = temp.getHpr() + ## self.hprs.append(hpr) + self.hprs.append(VBase3(hpr[0]+180,hpr[1],hpr[2])) + self.hprs.append(self.hprs[len(self.points)-2]) + + curveSequenceName = str(nodePath[OG.OBJ_UID])+' '+str(curve[OG.OBJ_UID])+' '+str(time) + self.curveSequence = Sequence(name = curveSequenceName) + + for i in range(len(self.points)-1): + myLerp = LerpPosHprInterval(nodePath[OG.OBJ_NP], float(1)/float(24), self.points[i+1], self.hprs[i+1], self.points[i], self.hprs[i]) + self.curveSequence.append(myLerp) + + return self.curveSequence + + def createParallel(self, startFrame, endFrame): + self.parallel = [] + self.parallel = Parallel(name="Current Parallel") + + self.createCurveAnimation(self.parallel) + self.createActorAnimation(self.parallel, startFrame, endFrame) + self.createKeyFrameAnimation(self.parallel, startFrame, endFrame) + self.createCurveKeyFrameAnimation(self.parallel, startFrame, endFrame) + + return self.parallel + + def createCurveAnimation(self, parallel): + for key in self.curveAnimation: + curveInfo = self.curveAnimation[key] + nodePath = self.editor.objectMgr.findObjectById(curveInfo[AG.NODE]) + curve = self.editor.objectMgr.findObjectById(curveInfo[AG.CURVE]) + time = curveInfo[AG.TIME] + sequence = self.singleCurveAnimation(nodePath, curve, time) + parallel.append(sequence) + + def createActorAnimation(self, parallel, startFrame, endFrame): + self.editor.objectMgr.findActors(render) + for actor in self.editor.objectMgr.Actor: + actorAnim = os.path.basename(actor[OG.OBJ_ANIM]) + myInterval = ActorInterval(actor[OG.OBJ_NP], actorAnim, loop=1, duration = float(endFrame-startFrame+1)/float(24)) + parallel.append(myInterval) + + def createKeyFrameAnimation(self, parallel, startFrame, endFrame): + #generate key frame animation for normal property + self.editor.objectMgr.findNodes(render) + for node in self.editor.objectMgr.Nodes: + for property in self.keyFramesInfo.keys(): + if property[AG.UID] == node[OG.OBJ_UID] and property[AG.PROP_NAME] != 'X' and property[AG.PROP_NAME] != 'Y' and property[AG.PROP_NAME] != 'Z': + mysequence = Sequence(name = node[OG.OBJ_UID]) + keyFramesInfo = self.keyFramesInfo[property] + if len(keyFramesInfo) == 1: + myLerp = LerpFunc(self.lerpFuncs[property[AG.PROP_NAME]],fromData=float(keyFramesInfo[0][AG.VALUE]),toData=float(keyFramesInfo[0][AG.VALUE]),duration = float(endFrame-startFrame)/float(24),blendType = 'noBlend',extraArgs = [node[OG.OBJ_NP]]) + mysequence.append(myLerp) + parallel.append(mysequence) + + if len(keyFramesInfo) != 1: + myLerp = LerpFunc(self.lerpFuncs[property[AG.PROP_NAME]],fromData=float(keyFramesInfo[0][AG.VALUE]),toData=float(keyFramesInfo[0][AG.VALUE]),duration = float(keyFramesInfo[0][AG.FRAME]-startFrame)/float(24),blendType = 'noBlend',extraArgs = [node[OG.OBJ_NP]]) + mysequence.append(myLerp) + + for key in range(0,len(keyFramesInfo)-1): + myLerp = LerpFunc(self.lerpFuncs[property[AG.PROP_NAME]],fromData=float(keyFramesInfo[key][AG.VALUE]),toData=float(keyFramesInfo[key+1][AG.VALUE]),duration = float(keyFramesInfo[key+1][AG.FRAME]-keyFramesInfo[key][AG.FRAME])/float(24),blendType = 'noBlend',extraArgs = [node[OG.OBJ_NP]]) + mysequence.append(myLerp) + + myLerp = LerpFunc(self.lerpFuncs[property[AG.PROP_NAME]],fromData=float(keyFramesInfo[len(keyFramesInfo)-1][AG.VALUE]),toData=float(keyFramesInfo[len(keyFramesInfo)-1][AG.VALUE]),duration = float(endFrame-keyFramesInfo[len(keyFramesInfo)-1][AG.FRAME])/float(24),blendType = 'noBlend',extraArgs = [node[OG.OBJ_NP]]) + mysequence.append(myLerp) + parallel.append(mysequence) + + def createCurveKeyFrameAnimation(self, parallel, startFrame, endFrame): + #generate key frame animation for the property which is controled by animation curve + self.editor.objectMgr.findNodes(render) + for node in self.editor.objectMgr.Nodes: + for property in self.keyFramesInfo.keys(): + if property[AG.UID] == node[OG.OBJ_UID]: + if property[AG.PROP_NAME] == 'X' or property[AG.PROP_NAME] == 'Y' or property[AG.PROP_NAME] == 'Z': + mysequence = Sequence(name = node[OG.OBJ_UID]) + keyFramesInfo = self.keyFramesInfo[property] + if len(keyFramesInfo) == 1: + myLerp = LerpFunc(self.curveLerpFuncs[property[AG.PROP_NAME]][0],fromData=float(keyFramesInfo[0][AG.VALUE]),toData=float(keyFramesInfo[0][AG.VALUE]),duration = float(endFrame-startFrame)/float(24),blendType = 'noBlend',extraArgs = [node[OG.OBJ_NP]]) + mysequence.append(myLerp) + parallel.append(mysequence) + + if len(keyFramesInfo) == 2: + myLerp = LerpFunc(self.curveLerpFuncs[property[AG.PROP_NAME]][0],fromData=float(keyFramesInfo[0][AG.VALUE]),toData=float(keyFramesInfo[0][AG.VALUE]),duration = float(keyFramesInfo[0][AG.FRAME]-startFrame)/float(24),blendType = 'noBlend',extraArgs = [node[OG.OBJ_NP]]) + mysequence.append(myLerp) + + for key in range(0,len(keyFramesInfo)-1): + self.keyFrameInfoForSingleLerp = keyFramesInfo + self.keyInfoForSingleLerp = key + myLerp = LerpFunc(self.curveLerpFuncs[property[AG.PROP_NAME]][0],fromData=float(keyFramesInfo[key][AG.VALUE]),toData=float(keyFramesInfo[key+1][AG.VALUE]),duration = float(keyFramesInfo[key+1][AG.FRAME]-keyFramesInfo[key][AG.FRAME])/float(24),blendType = 'noBlend',extraArgs = [node[OG.OBJ_NP]]) + mysequence.append(myLerp) + + myLerp = LerpFunc(self.curveLerpFuncs[property[AG.PROP_NAME]][0],fromData=float(keyFramesInfo[len(keyFramesInfo)-1][AG.VALUE]),toData=float(keyFramesInfo[len(keyFramesInfo)-1][AG.VALUE]),duration = float(endFrame-keyFramesInfo[len(keyFramesInfo)-1][AG.FRAME])/float(24),blendType = 'noBlend',extraArgs = [node[OG.OBJ_NP]]) + mysequence.append(myLerp) + parallel.append(mysequence) + + if len(keyFramesInfo) > 2: + myLerp = LerpFunc(self.curveLerpFuncs[property[AG.PROP_NAME]][0],fromData=float(keyFramesInfo[0][AG.VALUE]),toData=float(keyFramesInfo[0][1]),duration = float(keyFramesInfo[0][AG.FRAME]-startFrame)/float(24),blendType = 'noBlend',extraArgs = [node[OG.OBJ_NP]]) + mysequence.append(myLerp) + + for key in range(0,len(keyFramesInfo)-1): + myLerp = LerpFunc(self.curveLerpFuncs[property[AG.PROP_NAME]][1],fromData=float(keyFramesInfo[key][AG.FRAME]),toData=float(keyFramesInfo[key+1][AG.FRAME]),duration = float(keyFramesInfo[key+1][AG.FRAME]-keyFramesInfo[key][AG.FRAME])/float(24),blendType = 'noBlend',extraArgs = [[node[OG.OBJ_NP], keyFramesInfo, key]]) + mysequence.append(myLerp) + + myLerp = LerpFunc(self.curveLerpFuncs[property[AG.PROP_NAME]][0],fromData=float(keyFramesInfo[len(keyFramesInfo)-1][AG.VALUE]),toData=float(keyFramesInfo[len(keyFramesInfo)-1][AG.VALUE]),duration = float(endFrame-keyFramesInfo[len(keyFramesInfo)-1][AG.FRAME])/float(24),blendType = 'noBlend',extraArgs = [node[OG.OBJ_NP]]) + mysequence.append(myLerp) + parallel.append(mysequence) + + def getPos(self, x, list, i): + #get the value from animation curve + x1 = float(list[i][AG.FRAME]) + y1 = float(list[i][AG.VALUE]) + + x4 = float(list[i+1][AG.FRAME]) + y4 = float(list[i+1][AG.VALUE]) + + t1x = list[i][AG.OUTSLOPE][0] + t1y = list[i][AG.OUTSLOPE][1] + + t2x = list[i+1][AG.INSLOPE][0] + t2y = list[i+1][AG.INSLOPE][1] + + x2 = x1 + (x4 - x1) / float(3) + scale1 = (x2 - x1) / t1x + y2 = y1 + t1y * scale1 + + x3 = x4 - (x4 - x1) / float(3) + scale2 = (x4 - x3) / t2x + y3 = y4 - t2y * scale2 + + ax = - float(1) * x1 + float(3) * x2 - float(3) * x3 + float(1) * x4 + bx = float(3) * x1 - float(6) * x2 + float(3) * x3 + float(0) * x4 + cx = - float(3) * x1 + float(3) * x2 + float(0) * x3 + float(0) * x4 + dx = float(1) * x1 + float(0) * x2 - float(0) * x3 + float(0) * x4 + + ay = - float(1) * y1 + float(3) * y2 - float(3) * y3 + float(1) * y4 + by = float(3) * y1 - float(6) * y2 + float(3) * y3 + float(0) * y4 + cy = - float(3) * y1 + float(3) * y2 + float(0) * y3 + float(0) * y4 + dy = float(1) * y1 + float(0) * y2 - float(0) * y3 + float(0) * y4 + + if ax == 0 and bx == 0 and cx == 0: + return 0 + + if ax == 0 and bx == 0 and cx != 0: + a = cx + b = dx-x + t = -b/a + y = ay * t*t*t + by * t*t + cy * t + dy + return y + + if ax == 0 and bx!= 0: + a=bx + b=cx + c=dx-x + t=(-b+math.sqrt(b**2-4.0*a*c))/2*a + if t>=0 and t<=1: + y = ay * t*t*t + by * t*t + cy * t + dy + return y + else: + t=(-b-math.sqrt(b**2-4.0*a*c))/2*a + y = ay * t*t*t + by * t*t + cy * t + dy + return y + + if ax != 0: + a = ax + b = bx + c = cx + d = dx - float(x) + t = self.calculateT(a, b, c, d, x) + y = ay * t*t*t + by * t*t + cy * t + dy + return y + + def calculateT(self, a, b, c, d, x): + #Newton EQUATION + t = float(1) + t2 = t + t -= (a*t*t*t+b*t*t+c*t+d)/(float(3)*a*t*t+float(2)*b*t+c) + if abs(t-t2) <= 0.000001: + return t + else: + while abs(t - t2) > 0.000001: + t2 = t + t -= (a*t*t*t+b*t*t+c*t+d)/(float(3)*a*t*t+float(2)*b*t+c) + return t + + def lerpFuncX(self,pos,np): + np.setX(pos) + + def lerpFuncY(self,pos,np): + np.setY(pos) + + def lerpFuncZ(self,pos,np): + np.setZ(pos) + + def lerpCurveFuncX(self,t,extraArgs): + np = extraArgs[0] + pos = self.getPos(t, extraArgs[1], extraArgs[2]) + np.setX(pos) + + def lerpCurveFuncY(self,t,extraArgs): + np = extraArgs[0] + pos = self.getPos(t, extraArgs[1], extraArgs[2]) + np.setY(pos) + + def lerpCurveFuncZ(self,t,extraArgs): + np = extraArgs[0] + pos = self.getPos(t, extraArgs[1], extraArgs[2]) + np.setZ(pos) + + def lerpFuncH(self,angle,np): + np.setH(angle) + + def lerpFuncP(self,angle,np): + np.setP(angle) + + def lerpFuncR(self,angle,np): + np.setR(angle) + + def lerpFuncSX(self,scale,np): + np.setSx(scale) + + def lerpFuncSY(self,scale,np): + np.setSy(scale) + + def lerpFuncSZ(self,scale,np): + np.setSz(scale) + + def lerpFuncCR(self,R,np): + obj = self.editor.objectMgr.findObjectByNodePath(np) + r = obj[OG.OBJ_RGBA][0] + g = obj[OG.OBJ_RGBA][1] + b = obj[OG.OBJ_RGBA][2] + a = obj[OG.OBJ_RGBA][3] + self.colorUpdate(R,g,b,a,np) + + def lerpFuncCG(self,G,np): + obj = self.editor.objectMgr.findObjectByNodePath(np) + r = obj[OG.OBJ_RGBA][0] + g = obj[OG.OBJ_RGBA][1] + b = obj[OG.OBJ_RGBA][2] + a = obj[OG.OBJ_RGBA][3] + self.colorUpdate(r,G,b,a,np) + + def lerpFuncCB(self,B,np): + obj = self.editor.objectMgr.findObjectByNodePath(np) + r = obj[OG.OBJ_RGBA][0] + g = obj[OG.OBJ_RGBA][1] + b = obj[OG.OBJ_RGBA][2] + a = obj[OG.OBJ_RGBA][3] + self.colorUpdate(r,g,B,a,np) + + def lerpFuncCA(self,A,np): + obj = self.editor.objectMgr.findObjectByNodePath(np) + r = obj[OG.OBJ_RGBA][0] + g = obj[OG.OBJ_RGBA][1] + b = obj[OG.OBJ_RGBA][2] + a = obj[OG.OBJ_RGBA][3] + self.colorUpdate(r,g,b,A,np) + + def colorUpdate(self, r, g, b, a, np): + if base.direct.selected.last == None: + self.editor.objectMgr.updateObjectColor(r, g, b, a, np) + elif self.editor.objectMgr.findObjectByNodePath(np) == self.editor.objectMgr.findObjectByNodePath(base.direct.selected.last): + self.editor.ui.objectPropertyUI.propCR.setValue(r) + self.editor.ui.objectPropertyUI.propCG.setValue(g) + self.editor.ui.objectPropertyUI.propCB.setValue(b) + self.editor.ui.objectPropertyUI.propCA.setValue(a) + self.editor.objectMgr.updateObjectColor(r, g, b, a, np) + else: + self.editor.objectMgr.updateObjectColor(r, g, b, a, np) + diff --git a/direct/src/leveleditor/CurveAnimUI.py b/direct/src/leveleditor/CurveAnimUI.py index 7afea3879d..b779b2c615 100755 --- a/direct/src/leveleditor/CurveAnimUI.py +++ b/direct/src/leveleditor/CurveAnimUI.py @@ -1,159 +1,159 @@ -""" - This is the GUI for the Curve Animation -""" -import os, wx, time - -from direct.interval.IntervalGlobal import * -from direct.actor.Actor import * -from direct.showutil.Rope import Rope -import ObjectGlobals as OG - -class CurveAnimUI(wx.Dialog): - """ - This is the Curve Animation Panel implementation. - """ - def __init__(self, parent, editor): - wx.Dialog.__init__(self, parent, id=wx.ID_ANY, title="Curve Animation", - pos=wx.DefaultPosition, size=(430, 140)) - - self.editor = editor - self.nodePath = None - self.curve = None - - self.mainPanel = wx.Panel(self, -1) - - self.chooseNode = wx.StaticText( self.mainPanel, -1, "Choose NodePath:") - self.chooseNodeTxt = wx.TextCtrl( self.mainPanel, -1, "") - self.chooseNodeButton = wx.Button( self.mainPanel, -1, "Choose..") - - self.chooseCurve = wx.StaticText( self.mainPanel, -1, "Choose attch Curve:") - self.chooseCurveTxt = wx.TextCtrl( self.mainPanel, -1, "") - self.chooseCurveButton = wx.Button( self.mainPanel, -1, "Choose..") - - self.duritionTime = wx.StaticText( self.mainPanel, -1, "Durition(Frame):") - self.duritionTimeSpin = wx.SpinCtrl( self.mainPanel, -1, "",size = (70,25), min=24, max=10000) - - self.createAnimButton = wx.Button( self.mainPanel, -1, "Creat") - self.saveAnimButton = wx.Button( self.mainPanel, -1, "Save Animation") - - self.SetProperties() - self.DoLayout() - - self.Bind(wx.EVT_BUTTON, self.OnChooseNode, self.chooseNodeButton) - self.Bind(wx.EVT_BUTTON, self.OnChooseCurve, self.chooseCurveButton) - self.Bind(wx.EVT_BUTTON, self.OnCreateAnim, self.createAnimButton) - self.Bind(wx.EVT_BUTTON, self.OnSaveAnim, self.saveAnimButton) - - self.Bind(wx.EVT_CLOSE, self.OnExit) - - def SetProperties(self): - self.duritionTimeSpin.SetValue(24) - self.chooseNodeTxt.SetMinSize((200,21)) - self.chooseCurveTxt.SetMinSize((200,21)) - self.saveAnimButton.SetToolTipString("Save the animation to the global animation control") - - def DoLayout(self): - dialogSizer = wx.BoxSizer(wx.VERTICAL) - mainSizer = wx.FlexGridSizer(4, 3, 0, 0) - - mainSizer.Add(self.chooseNode, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, 10) - mainSizer.Add(self.chooseNodeTxt, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, 5) - mainSizer.Add(self.chooseNodeButton, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, 5) - - mainSizer.Add(self.chooseCurve, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, 10) - mainSizer.Add(self.chooseCurveTxt, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, 5) - mainSizer.Add(self.chooseCurveButton, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, 5) - - mainSizer.Add(self.duritionTime, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, 10) - mainSizer.Add(self.duritionTimeSpin, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, 5) - mainSizer.Add(self.createAnimButton, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, 5) - - mainSizer.Add(self.saveAnimButton, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, 5) - - self.mainPanel.SetSizerAndFit(mainSizer) - - dialogSizer.Add(self.mainPanel, 1, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5) - - self.SetSizer(dialogSizer) - self.Layout() - - def OnChooseNode(self, evt): - if base.direct.selected.last == None or base.direct.selected.last.hasTag('Controller') or not base.direct.selected.last.hasTag('OBJRoot'): - dlg = wx.MessageDialog(None, 'Please select an object.', 'NOTICE', wx.OK ) - dlg.ShowModal() - dlg.Destroy() - else: - obj = self.editor.objectMgr.findObjectByNodePath(base.direct.selected.last) - if obj[OG.OBJ_DEF].name == '__Curve__': - dlg = wx.MessageDialog(None, 'Please select an object, not a curve.', 'NOTICE', wx.OK ) - dlg.ShowModal() - dlg.Destroy() - else: - self.nodePath = obj - self.chooseNodeTxt.SetValue(str(self.nodePath[OG.OBJ_UID])) - - def OnChooseCurve(self, evt): - if base.direct.selected.last == None or base.direct.selected.last.hasTag('Controller') or not base.direct.selected.last.hasTag('OBJRoot'): - dlg = wx.MessageDialog(None, 'Please select a curve.', 'NOTICE', wx.OK ) - dlg.ShowModal() - dlg.Destroy() - else: - obj = self.editor.objectMgr.findObjectByNodePath(base.direct.selected.last) - if obj[OG.OBJ_DEF].name != '__Curve__': - dlg = wx.MessageDialog(None, 'Please select a curve, not an object.', 'NOTICE', wx.OK ) - dlg.ShowModal() - dlg.Destroy() - elif obj[OG.OBJ_DEF].name == '__Curve__': - self.curve = obj - self.chooseCurveTxt.SetValue(str(self.curve[OG.OBJ_UID])) - - def OnCreateAnim(self, evt): - self.time = self.duritionTimeSpin.GetValue() - if self.nodePath == None or self.curve == None: - dlg = wx.MessageDialog(None, 'Please select an object and a curve first.', 'NOTICE', wx.OK ) - dlg.ShowModal() - dlg.Destroy() - else: - self.curveSequence = self.editor.animMgr.singleCurveAnimation(self.nodePath, self.curve, self.time) - self.curveSequence.start() - - def OnSaveAnim(self,evt): - if not self.curveSequence: - dlg = wx.MessageDialog(None, 'Please create a animation first.', 'NOTICE', wx.OK ) - dlg.ShowModal() - dlg.Destroy() - else: - if self.editor.animMgr.curveAnimation == {}: - self.editor.animMgr.curveAnimation[(self.nodePath[OG.OBJ_UID],self.curve[OG.OBJ_UID])] = (self.nodePath[OG.OBJ_UID],self.curve[OG.OBJ_UID],self.time) - self.editor.updateStatusReadout('Sucessfully saved to global animation list') - return - - hasKey = False - for key in self.editor.animMgr.curveAnimation.keys(): - if key == (self.nodePath[OG.OBJ_UID],self.curve[OG.OBJ_UID]): - dlg = wx.MessageDialog(None, 'Already have the animation for this object attach to this curve.', 'NOTICE', wx.OK ) - dlg.ShowModal() - dlg.Destroy() - hasKey = True - return - elif self.nodePath[OG.OBJ_UID] == key[0]: - dlg = wx.MessageDialog(None, 'This object is already attached to a curve.', 'NOTICE', wx.OK ) - dlg.ShowModal() - dlg.Destroy() - hasKey = True - return - - if hasKey == False and self.editor.animMgr.curveAnimation != {}: - self.editor.animMgr.curveAnimation[(self.nodePath[OG.OBJ_UID],self.curve[OG.OBJ_UID])] = (self.nodePath[OG.OBJ_UID],self.curve[OG.OBJ_UID],self.time) - self.editor.updateStatusReadout('Sucessfully saved to global animation list') - - def OnExit(self,evt): - self.Destroy() - self.editor.ui.curveAnimMenuItem.Check(False) - - - - - - - \ No newline at end of file +""" + This is the GUI for the Curve Animation +""" +import os, wx, time + +from direct.interval.IntervalGlobal import * +from direct.actor.Actor import * +from direct.showutil.Rope import Rope +import ObjectGlobals as OG + +class CurveAnimUI(wx.Dialog): + """ + This is the Curve Animation Panel implementation. + """ + def __init__(self, parent, editor): + wx.Dialog.__init__(self, parent, id=wx.ID_ANY, title="Curve Animation", + pos=wx.DefaultPosition, size=(430, 140)) + + self.editor = editor + self.nodePath = None + self.curve = None + + self.mainPanel = wx.Panel(self, -1) + + self.chooseNode = wx.StaticText( self.mainPanel, -1, "Choose NodePath:") + self.chooseNodeTxt = wx.TextCtrl( self.mainPanel, -1, "") + self.chooseNodeButton = wx.Button( self.mainPanel, -1, "Choose..") + + self.chooseCurve = wx.StaticText( self.mainPanel, -1, "Choose attch Curve:") + self.chooseCurveTxt = wx.TextCtrl( self.mainPanel, -1, "") + self.chooseCurveButton = wx.Button( self.mainPanel, -1, "Choose..") + + self.duritionTime = wx.StaticText( self.mainPanel, -1, "Durition(Frame):") + self.duritionTimeSpin = wx.SpinCtrl( self.mainPanel, -1, "",size = (70,25), min=24, max=10000) + + self.createAnimButton = wx.Button( self.mainPanel, -1, "Creat") + self.saveAnimButton = wx.Button( self.mainPanel, -1, "Save Animation") + + self.SetProperties() + self.DoLayout() + + self.Bind(wx.EVT_BUTTON, self.OnChooseNode, self.chooseNodeButton) + self.Bind(wx.EVT_BUTTON, self.OnChooseCurve, self.chooseCurveButton) + self.Bind(wx.EVT_BUTTON, self.OnCreateAnim, self.createAnimButton) + self.Bind(wx.EVT_BUTTON, self.OnSaveAnim, self.saveAnimButton) + + self.Bind(wx.EVT_CLOSE, self.OnExit) + + def SetProperties(self): + self.duritionTimeSpin.SetValue(24) + self.chooseNodeTxt.SetMinSize((200,21)) + self.chooseCurveTxt.SetMinSize((200,21)) + self.saveAnimButton.SetToolTipString("Save the animation to the global animation control") + + def DoLayout(self): + dialogSizer = wx.BoxSizer(wx.VERTICAL) + mainSizer = wx.FlexGridSizer(4, 3, 0, 0) + + mainSizer.Add(self.chooseNode, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, 10) + mainSizer.Add(self.chooseNodeTxt, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, 5) + mainSizer.Add(self.chooseNodeButton, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, 5) + + mainSizer.Add(self.chooseCurve, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, 10) + mainSizer.Add(self.chooseCurveTxt, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, 5) + mainSizer.Add(self.chooseCurveButton, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, 5) + + mainSizer.Add(self.duritionTime, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, 10) + mainSizer.Add(self.duritionTimeSpin, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, 5) + mainSizer.Add(self.createAnimButton, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, 5) + + mainSizer.Add(self.saveAnimButton, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, 5) + + self.mainPanel.SetSizerAndFit(mainSizer) + + dialogSizer.Add(self.mainPanel, 1, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5) + + self.SetSizer(dialogSizer) + self.Layout() + + def OnChooseNode(self, evt): + if base.direct.selected.last == None or base.direct.selected.last.hasTag('Controller') or not base.direct.selected.last.hasTag('OBJRoot'): + dlg = wx.MessageDialog(None, 'Please select an object.', 'NOTICE', wx.OK ) + dlg.ShowModal() + dlg.Destroy() + else: + obj = self.editor.objectMgr.findObjectByNodePath(base.direct.selected.last) + if obj[OG.OBJ_DEF].name == '__Curve__': + dlg = wx.MessageDialog(None, 'Please select an object, not a curve.', 'NOTICE', wx.OK ) + dlg.ShowModal() + dlg.Destroy() + else: + self.nodePath = obj + self.chooseNodeTxt.SetValue(str(self.nodePath[OG.OBJ_UID])) + + def OnChooseCurve(self, evt): + if base.direct.selected.last == None or base.direct.selected.last.hasTag('Controller') or not base.direct.selected.last.hasTag('OBJRoot'): + dlg = wx.MessageDialog(None, 'Please select a curve.', 'NOTICE', wx.OK ) + dlg.ShowModal() + dlg.Destroy() + else: + obj = self.editor.objectMgr.findObjectByNodePath(base.direct.selected.last) + if obj[OG.OBJ_DEF].name != '__Curve__': + dlg = wx.MessageDialog(None, 'Please select a curve, not an object.', 'NOTICE', wx.OK ) + dlg.ShowModal() + dlg.Destroy() + elif obj[OG.OBJ_DEF].name == '__Curve__': + self.curve = obj + self.chooseCurveTxt.SetValue(str(self.curve[OG.OBJ_UID])) + + def OnCreateAnim(self, evt): + self.time = self.duritionTimeSpin.GetValue() + if self.nodePath == None or self.curve == None: + dlg = wx.MessageDialog(None, 'Please select an object and a curve first.', 'NOTICE', wx.OK ) + dlg.ShowModal() + dlg.Destroy() + else: + self.curveSequence = self.editor.animMgr.singleCurveAnimation(self.nodePath, self.curve, self.time) + self.curveSequence.start() + + def OnSaveAnim(self,evt): + if not self.curveSequence: + dlg = wx.MessageDialog(None, 'Please create a animation first.', 'NOTICE', wx.OK ) + dlg.ShowModal() + dlg.Destroy() + else: + if self.editor.animMgr.curveAnimation == {}: + self.editor.animMgr.curveAnimation[(self.nodePath[OG.OBJ_UID],self.curve[OG.OBJ_UID])] = (self.nodePath[OG.OBJ_UID],self.curve[OG.OBJ_UID],self.time) + self.editor.updateStatusReadout('Sucessfully saved to global animation list') + return + + hasKey = False + for key in self.editor.animMgr.curveAnimation.keys(): + if key == (self.nodePath[OG.OBJ_UID],self.curve[OG.OBJ_UID]): + dlg = wx.MessageDialog(None, 'Already have the animation for this object attach to this curve.', 'NOTICE', wx.OK ) + dlg.ShowModal() + dlg.Destroy() + hasKey = True + return + elif self.nodePath[OG.OBJ_UID] == key[0]: + dlg = wx.MessageDialog(None, 'This object is already attached to a curve.', 'NOTICE', wx.OK ) + dlg.ShowModal() + dlg.Destroy() + hasKey = True + return + + if hasKey == False and self.editor.animMgr.curveAnimation != {}: + self.editor.animMgr.curveAnimation[(self.nodePath[OG.OBJ_UID],self.curve[OG.OBJ_UID])] = (self.nodePath[OG.OBJ_UID],self.curve[OG.OBJ_UID],self.time) + self.editor.updateStatusReadout('Sucessfully saved to global animation list') + + def OnExit(self,evt): + self.Destroy() + self.editor.ui.curveAnimMenuItem.Check(False) + + + + + + + diff --git a/direct/src/leveleditor/CurveEditor.py b/direct/src/leveleditor/CurveEditor.py index 3aa1e25d18..bc1d907c22 100755 --- a/direct/src/leveleditor/CurveEditor.py +++ b/direct/src/leveleditor/CurveEditor.py @@ -18,27 +18,27 @@ class CurveEditor(DirectObject): self.i = 0 self.ropeNum = 0 self.curve = [] - self.curveControl = [] + self.curveControl = [] self.currentRope = None self.degree = 3 - + def createCurve(self): if self.editor.mode == self.editor.CREATE_CURVE_MODE: self.view = self.editor.ui.currentView - + #Get the mouse position x = base.direct.dr.mouseX - y = base.direct.dr.mouseY - + y = base.direct.dr.mouseY + if self.editor.fMoveCamera == False and self.view != None: self.createControler(x,y) if self.currentRope != None: self.currentRope.detachNode() self.ropeUpdate(self.curve) self.accept("DIRECT-enter", self.onBaseMode) - - self.accept("DIRECT-enter", self.onBaseMode) - + + self.accept("DIRECT-enter", self.onBaseMode) + def editCurve(self, task): if self.editor.mode == self.editor.EDIT_CURVE_MODE: if self.editor.fMoveCamera == False: @@ -50,9 +50,9 @@ class CurveEditor(DirectObject): self.point = item #temporarily save the controler information for further use self.currentCurve = self.currentRope.ropeNode.getCurve() self.currentCurve.setVertex(item[0], self.selected.getPos()) - self.accept("DIRECT-delete", self.onControlerDelete) - return task.cont - + self.accept("DIRECT-delete", self.onControlerDelete) + return task.cont + def onControlerDelete(self): if self.editor.mode == self.editor.EDIT_CURVE_MODE: self.curve.remove(self.curve[self.point[0]]) @@ -69,7 +69,7 @@ class CurveEditor(DirectObject): self.currentRope = Rope() self.currentRope.setup(self.degree, curve) self.currentRope.reparentTo(render) - + def onBaseMode(self): self.editor.preMode = self.editor.mode self.editor.mode = self.editor.BASE_MODE @@ -90,17 +90,17 @@ class CurveEditor(DirectObject): base.direct.manipulationControl.enableManipulation() self.editor.ui.createCurveMenuItem.Check(False) self.editor.ui.editCurveMenuItem.Check(False) - + def updateScene(self): curveObjNP = self.editor.objectMgr.addNewCurve(self.curveControl, self.degree, nodePath=self.currentRope) curveObj = self.editor.objectMgr.findObjectByNodePath(curveObjNP) for item in self.curveControl: item[1].reparentTo(curveObjNP) self.editor.objectMgr.updateObjectPropValue(curveObj, 'Degree', self.degree, fSelectObject=False, fUndo=False) - + def doneEdit(self): base.direct.selected.last = None - + def createControler(self, x, y): if self.view != None: self.controler = render.attachNewNode("controler") @@ -113,7 +113,7 @@ class CurveEditor(DirectObject): self.controler.setTag('OBJRoot','1') self.controler.setTag('Controller','1') #controller Tag self.i += 1 - + iRay = SelectionRay(self.view.camera) iRay.collider.setFromLens(self.view.camNode, x, y) iRay.collideWithBitMask(BitMask32.bit(21)) @@ -130,7 +130,7 @@ class CurveEditor(DirectObject): if base.direct.manipulationControl.fGridSnap: snappedPos = self.view.grid.computeSnapPoint(np.getPos()) np.setPos(snappedPos) - + # update temp nodePath's HPR and scale with newobj's np.setHpr(self.controler.getHpr()) np.setScale(self.controler.getScale()) @@ -143,4 +143,4 @@ class CurveEditor(DirectObject): self.curve.append((None, self.controler.getPos())) self.curveControl.append((self.i-1, self.controler)) - + diff --git a/direct/src/leveleditor/FileMgr.py b/direct/src/leveleditor/FileMgr.py index 7baee7d25b..c1b39fda98 100755 --- a/direct/src/leveleditor/FileMgr.py +++ b/direct/src/leveleditor/FileMgr.py @@ -9,7 +9,7 @@ import ObjectGlobals as OG class FileMgr: """ To handle data file """ - + def __init__(self, editor=None): self.editor = editor diff --git a/direct/src/leveleditor/GraphEditorUI.py b/direct/src/leveleditor/GraphEditorUI.py index c8990495af..5e69cf6710 100755 --- a/direct/src/leveleditor/GraphEditorUI.py +++ b/direct/src/leveleditor/GraphEditorUI.py @@ -31,7 +31,7 @@ ZoomIn = PyEmbeddedImage( "c3N/f19RlJDb6/V0Xb+/v8/n829ofZzzVCqlz82dn5//abUk6UmyEEIIkc1k2u32r3o9uCq8" "+PHJsuz7vud5IfTffABZljnnwejLnb9/grEiQih2vVd9J36kup4fH+w3/S/QvwejQg8ibHgo" "AAAAAElFTkSuQmCC") - + #---------------------------------------------------------------------- ZoomOut = PyEmbeddedImage( "iVBORw0KGgoAAAANSUhEUgAAABwAAAAcCAIAAAD9b0jDAAAAA3NCSVQICAjb4U/gAAACmUlE" @@ -48,7 +48,7 @@ ZoomOut = PyEmbeddedImage( "REJIrVbr3KNhGL6ijGKMj46OdnZ2CoVCNBqVRAjhr5ubUqmUm5kxksleIpA+fYyxg4ODfD4f" "jUY559IohHB3dzebzSYTiQARAKA8/fEJIVRVhRC2Wi3faSEEIUTahKCknbAAgF4iAEBV1WdF" "Ge1kCZgO7vZEX6X+c/Q3Qy8zmmCLWqIAAAAASUVORK5CYII=") - + #---------------------------------------------------------------------- OneTangent = PyEmbeddedImage( "iVBORw0KGgoAAAANSUhEUgAAABwAAAAcCAIAAAD9b0jDAAAAA3NCSVQICAjb4U/gAAACKUlE" @@ -63,7 +63,7 @@ OneTangent = PyEmbeddedImage( "sXfPtuO7u39brV+lkgiHmRBDKZOhbepThDHpOJ8zmZ7jLMZiq6YJhPSXxYyLSEkZMgx9ebl8" "clLKZO6bTTbgkFN7ZV+e47xcW4tubIQjkWcrKyjl/zpmK/9BlDH0vIfZUogBZAoAKCWhVCk1" "tHrnggLAk/9I/wC0eekA1bLbIQAAAABJRU5ErkJggg==") - + #---------------------------------------------------------------------- TwoTangents = PyEmbeddedImage( "iVBORw0KGgoAAAANSUhEUgAAABwAAAAcCAIAAAD9b0jDAAAAA3NCSVQICAjb4U/gAAACL0lE" @@ -78,7 +78,7 @@ TwoTangents = PyEmbeddedImage( "6ZZ71LnRLXY1MDJzI5Rc+6wwR5PlTDIZjsd9gYBjuTSwEajneypR4dV2qXxq1F/dG5fLodg9" "U9OOThGOHgYAg7FrF8fKKqjng/4rl+xeYl+ozeEMsNsiwmCftnnXQg6EcgABICxyAGAcut2x" "wdADt+uFdYv/9OU/Qf9d9A9dhOgRU8MmewAAAABJRU5ErkJggg==") - + #---------------------------------------------------------------------- class GraphEditorWindow(wx.Window): @@ -87,28 +87,28 @@ class GraphEditorWindow(wx.Window): """ def __init__(self, parent, windowSize, property, xRange, yRange, curFrame, object): wx.Window.__init__(self, parent, size = windowSize, style = wx.SUNKEN_BORDER) - + self._mainDialog = wx.GetTopLevelParent(self) self.w,self.h = self.GetClientSize() - + self.zoom = float(2) self._mouseIn = False self._selectRec = False self._selectHandler = False self._OneTangent = True - + self.object = object self.curFrame = curFrame self.property = property - + self.zeroPos = (float(0), self.h/float(2)) self.zero = 0 self.unitWidth = self.w/float(xRange) self.unitHeight = self.h/float(yRange) - + self.generateInfo() self.InitBuffer() - + self.Bind(wx.EVT_PAINT, self.OnPaint) self.Bind(wx.EVT_SIZE, self.OnSize) self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown) @@ -116,19 +116,19 @@ class GraphEditorWindow(wx.Window): self.Bind(wx.EVT_MIDDLE_DOWN, self.OnMiddleDown) self.Bind(wx.EVT_MIDDLE_UP, self.OnMiddleUp) self.Bind(wx.EVT_MOTION, self.OnMotion) - + def refresh(self): self._mouseIn = False self._selectRec = False self._selectHandler = False self.generateInfo() - + def generateInfo(self): #generate the information for animation curve generation self.X = [] self.Y = [] self.Z = [] - + if self._mainDialog.editor.animMgr.keyFramesInfo != {}: self.keyFramesInfo = self._mainDialog.editor.animMgr.keyFramesInfo for key in self.keyFramesInfo.keys(): @@ -147,18 +147,18 @@ class GraphEditorWindow(wx.Window): item = self.keyFramesInfo[key][i] handler = self.generateHandler(item) self.Z.append([key, i, handler[0], handler[1], handler[2], handler[3], handler[4]]) - + def generateHandler(self, item): #generate the position for the control handler - x1 = self.zeroPos[0] + float(item[AG.FRAME])*self.unitWidth + x1 = self.zeroPos[0] + float(item[AG.FRAME])*self.unitWidth y1 = self.zeroPos[1] - float(item[AG.VALUE])*self.unitHeight - + t1x = item[AG.INSLOPE][0]*self.unitWidth t1y = item[AG.INSLOPE][1]*self.unitHeight - - t2x = item[AG.OUTSLOPE][0]*self.unitWidth + + t2x = item[AG.OUTSLOPE][0]*self.unitWidth t2y = item[AG.OUTSLOPE][1]*self.unitHeight - + tanA = t1y/t1x temp1 = float(1)/(tanA**2+1) if t1x <0 : @@ -170,10 +170,10 @@ class GraphEditorWindow(wx.Window): sinA = -math.sqrt(abs(temp2)) if t1y >=0: sinA = math.sqrt(abs(temp2)) - + x2 = x1-float(self.unitWidth*self.zoom)*cosA y2 = y1+float(self.unitWidth*self.zoom)*sinA - + tanA = t2y/t2x temp1 = float(1)/(tanA**2+1) if t2x <0 : @@ -185,12 +185,12 @@ class GraphEditorWindow(wx.Window): sinA = -math.sqrt(abs(temp2)) if t2y >=0: sinA = math.sqrt(abs(temp2)) - + x3 = x1+float(self.unitWidth*self.zoom)*cosA y3 = y1-float(self.unitWidth*self.zoom)*sinA - + return [[(x1,y1),0],[(x2,y2),0],[(x3,y3),0],[t1x,t1y],[t2x,t2y]] - + def InitBuffer(self): self.buffer = wx.EmptyBitmap(self.w, self.h) dc = wx.BufferedDC(wx.ClientDC(self), self.buffer) @@ -199,32 +199,32 @@ class GraphEditorWindow(wx.Window): self.DrawFrame(dc) self.DrawCurve(dc) self.DrawSelectRec(dc) - + def SetGraphEditorData(self, property, curFrame = 1): self.curFrame = curFrame self.property = property - + self.InitBuffer() - + def OnPaint(self, evt): dc = wx.BufferedPaintDC(self, self.buffer) - + def DrawXCoord(self,dc): dc.SetBackground(wx.Brush(wx.Colour(200, 200, 200))) dc.Clear() - + dc.SetPen(wx.BLACK_PEN) dc.SetBrush(wx.BLACK_BRUSH) dc.SetFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.NORMAL)) - - dc.DrawLine(self.zeroPos[0], float(0), self.zeroPos[0], self.h) + + dc.DrawLine(self.zeroPos[0], float(0), self.zeroPos[0], self.h) st = str(self.zero) - self.tw,self.th = dc.GetTextExtent(st) + self.tw,self.th = dc.GetTextExtent(st) dc.DrawText(st, self.zeroPos[0]+1.0, self.h-self.th-0.5) - + dc.SetPen(wx.Pen(wx.Colour(150, 150, 150))) dc.SetBrush(wx.Brush(wx.Colour(150, 150, 150))) - + if self.unitWidth >= 25: posPos = self.zeroPos[0]+self.unitWidth posNum = self.zero + 1 @@ -234,16 +234,16 @@ class GraphEditorWindow(wx.Window): self.drawXNumber(dc, st, posPos) posPos += self.unitWidth posNum += 1 - + negPos = self.zeroPos[0]-self.unitWidth negNum = self.zero - 1 while negPos >= float(0): dc.DrawLine(negPos, float(0), negPos, self.h) st = str(negNum) self.drawXNumber(dc, st, negPos) - negPos -= self.unitWidth + negPos -= self.unitWidth posNum -= 1 - + elif self.unitWidth >= 10 and self.unitWidth <= 25: posPos = self.zeroPos[0]+self.unitWidth*float(2) posNum = self.zero + 2 @@ -251,18 +251,18 @@ class GraphEditorWindow(wx.Window): dc.DrawLine(posPos, float(0), posPos, self.h) st = str(posNum) self.drawXNumber(dc, st, posPos) - posPos += self.unitWidth*float(2) + posPos += self.unitWidth*float(2) posNum += 2 - + negPos = self.zeroPos[0]-self.unitWidth*float(2) negNum = self.zero - 2 while negPos >= float(0): dc.DrawLine(negPos, float(0), negPos, self.h) st = str(negNum) self.drawXNumber(dc, st, negPos) - negPos -= self.unitWidth*float(2) + negPos -= self.unitWidth*float(2) posNum -= 2 - + elif self.unitWidth >= 2 and self.unitWidth <= 10: posPos = self.zeroPos[0]+self.unitWidth*float(5) posNum = self.zero + 5 @@ -270,31 +270,31 @@ class GraphEditorWindow(wx.Window): dc.DrawLine(posPos, float(0), posPos, self.h) st = str(posNum) self.drawXNumber(dc, st, posPos) - posPos += self.unitWidth*float(5) + posPos += self.unitWidth*float(5) posNum += 5 - + negPos = self.zeroPos[0]-self.unitWidth*float(5) negNum = self.zero - 5 while negPos >= float(0): dc.DrawLine(negPos, float(0), negPos, self.h) st = str(negNum) self.drawXNumber(dc, st, negPos) - negPos -= self.unitWidth*float(5) + negPos -= self.unitWidth*float(5) posNum -= 5 - + def DrawYCoord(self,dc): dc.SetPen(wx.BLACK_PEN) dc.SetBrush(wx.BLACK_BRUSH) dc.SetFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.NORMAL)) - - dc.DrawLine(float(0), self.zeroPos[1], self.w, self.zeroPos[1]) + + dc.DrawLine(float(0), self.zeroPos[1], self.w, self.zeroPos[1]) st = str(self.zero) dc.DrawText(st, 5.0, self.zeroPos[1]-1.0) - + dc.SetPen(wx.Pen(wx.Colour(150, 150, 150))) dc.SetBrush(wx.Brush(wx.Colour(150, 150, 150))) dc.SetLogicalFunction(wx.AND) - + posPos = self.zeroPos[1]-self.unitHeight*float(5) posNum = self.zero + 5 while posPos >= float(0): @@ -303,38 +303,38 @@ class GraphEditorWindow(wx.Window): self.drawYNumber(dc, st, posPos) posPos -= self.unitHeight*float(5) posNum += 5 - + negPos = self.zeroPos[1]+self.unitHeight*float(5) negNum = self.zero - 5 while negPos <= self.h: dc.DrawLine(float(0), negPos, self.w, negPos) st = str(negNum) self.drawYNumber(dc, st, negPos) - negPos += self.unitHeight*float(5) + negPos += self.unitHeight*float(5) negNum -= 5 - + def drawXNumber(self, dc, st, pos): oldPen, oldBrush, oldMode = dc.GetPen(), dc.GetBrush(), dc.GetLogicalFunction() - + dc.SetPen(wx.BLACK_PEN) dc.SetBrush(wx.BLACK_BRUSH) dc.DrawText(st, pos+1.0, self.h-self.th-0.5) - + dc.SetPen(oldPen) dc.SetBrush(oldBrush) dc.SetLogicalFunction(oldMode) - + def drawYNumber(self, dc, st, pos): oldPen, oldBrush, oldMode = dc.GetPen(), dc.GetBrush(), dc.GetLogicalFunction() - + dc.SetPen(wx.BLACK_PEN) dc.SetBrush(wx.BLACK_BRUSH) dc.DrawText(st, 5.0, pos-1.0) - + dc.SetPen(oldPen) dc.SetBrush(oldBrush) dc.SetLogicalFunction(oldMode) - + def DrawFrame(self, dc): if self._mainDialog.editor.mode == self._mainDialog.editor.ANIM_MODE: curFramePos = self.zeroPos[0]+self.curFrame*self.unitWidth @@ -343,28 +343,28 @@ class GraphEditorWindow(wx.Window): dc.DrawLine(curFramePos, float(0), curFramePos, self.h) else: pass - + def drawX(self, dc): dc.SetPen(wx.Pen("red")) dc.SetBrush(wx.Brush("red")) self.drawSingleCurve(self.X, dc) self.drawKeys(self.X, dc) self.drawHandler(self.X, dc) - + def drawY(self, dc): dc.SetPen(wx.Pen("green")) dc.SetBrush(wx.Brush("green")) self.drawSingleCurve(self.Y, dc) self.drawKeys(self.Y, dc) self.drawHandler(self.Y, dc) - + def drawZ(self, dc): dc.SetPen(wx.Pen("blue")) dc.SetBrush(wx.Brush("blue")) self.drawSingleCurve(self.Z, dc) self.drawKeys(self.Z, dc) self.drawHandler(self.Z, dc) - + def DrawCurve(self, dc): if self.property == self._mainDialog.namestr: self.drawX(dc) @@ -378,89 +378,89 @@ class GraphEditorWindow(wx.Window): self.drawY(dc) return if self.property == property[AG.Z]: - self.drawZ(dc) - return - + self.drawZ(dc) + return + def drawSingleCurve(self, list, dc): if len(list) == 1: dc.DrawPoint(list[0][AG.KEYFRAME][AG.LOCAL_VALUE][0], list[0][AG.KEYFRAME][AG.LOCAL_VALUE][1]) return - + if len(list) == 2: dc.DrawLine(list[0][AG.KEYFRAME][AG.LOCAL_VALUE][0], list[0][AG.KEYFRAME][AG.LOCAL_VALUE][1], list[1][AG.KEYFRAME][AG.LOCAL_VALUE][0], list[1][AG.KEYFRAME][AG.LOCAL_VALUE][1]) return - + if len(list)>=3 : for i in range(len(list)-1): x1 = list[i][AG.KEYFRAME][AG.LOCAL_VALUE][0] y1 = list[i][AG.KEYFRAME][AG.LOCAL_VALUE][1] - + x4 = list[i+1][AG.KEYFRAME][AG.LOCAL_VALUE][0] y4 = list[i+1][AG.KEYFRAME][AG.LOCAL_VALUE][1] - + t1x = list[i][AG.OUT_SLOPE][0] t1y = list[i][AG.OUT_SLOPE][1] - + t2x = list[i+1][AG.IN_SLOPE][0] t2y = list[i+1][AG.IN_SLOPE][1] - - x2 = x1 + (x4 - x1) / float(3); - scale1 = (x2 - x1) / t1x; - y2 = y1 - t1y * scale1; - - - x3 = x4 - (x4 - x1) / float(3); - scale2 = (x4 - x3) / t2x; - y3 = y4 + t2y * scale2; - - ax = - float(1) * x1 + float(3) * x2 - float(3) * x3 + float(1) * x4; - bx = float(3) * x1 - float(6) * x2 + float(3) * x3 + float(0) * x4; - cx = - float(3) * x1 + float(3) * x2 + float(0) * x3 + float(0) * x4; - dx = float(1) * x1 + float(0) * x2 - float(0) * x3 + float(0) * x4; - - ay = - float(1) * y1 + float(3) * y2 - float(3) * y3 + float(1) * y4; - by = float(3) * y1 - float(6) * y2 + float(3) * y3 + float(0) * y4; - cy = - float(3) * y1 + float(3) * y2 + float(0) * y3 + float(0) * y4; - dy = float(1) * y1 + float(0) * y2 - float(0) * y3 + float(0) * y4; - preX = x1 - preY = y1 + x2 = x1 + (x4 - x1) / float(3); + scale1 = (x2 - x1) / t1x; + y2 = y1 - t1y * scale1; + + + x3 = x4 - (x4 - x1) / float(3); + scale2 = (x4 - x3) / t2x; + y3 = y4 + t2y * scale2; + + ax = - float(1) * x1 + float(3) * x2 - float(3) * x3 + float(1) * x4; + bx = float(3) * x1 - float(6) * x2 + float(3) * x3 + float(0) * x4; + cx = - float(3) * x1 + float(3) * x2 + float(0) * x3 + float(0) * x4; + dx = float(1) * x1 + float(0) * x2 - float(0) * x3 + float(0) * x4; + + ay = - float(1) * y1 + float(3) * y2 - float(3) * y3 + float(1) * y4; + by = float(3) * y1 - float(6) * y2 + float(3) * y3 + float(0) * y4; + cy = - float(3) * y1 + float(3) * y2 + float(0) * y3 + float(0) * y4; + dy = float(1) * y1 + float(0) * y2 - float(0) * y3 + float(0) * y4; + + preX = x1 + preY = y1 t = 0.001 - + while t<=float(1): - x = ax * t*t*t + bx * t*t + cx * t + dx; + x = ax * t*t*t + bx * t*t + cx * t + dx; y = ay * t*t*t + by * t*t + cy * t + dy; - curX = x + curX = x curY = y - + dc.DrawLine(preX, preY, curX, curY) - + preX = curX preY = curY - - t += 0.001 + + t += 0.001 def drawKeys(self, list, dc): for i in range(len(list)): pointX = list[i][AG.KEYFRAME][AG.LOCAL_VALUE][0] pointY = list[i][AG.KEYFRAME][AG.LOCAL_VALUE][1] - + if list[i][AG.KEYFRAME][AG.SELECT] == 0: dc.SetPen(wx.Pen("black",3)) dc.SetBrush(wx.Brush("black")) dc.DrawCircle(pointX, pointY, 2) - + if list[i][AG.KEYFRAME][AG.SELECT] == 1: dc.SetPen(wx.Pen("cyan",3)) dc.SetBrush(wx.Brush("cyan")) dc.DrawCircle(pointX, pointY, 2) - + def drawHandler(self, list, dc): for i in range(len(list)): if list[i][AG.KEYFRAME][AG.SELECT] == 1: X1 = list[i][AG.KEYFRAME][AG.LOCAL_VALUE][0] - Y1 = list[i][AG.KEYFRAME][AG.LOCAL_VALUE][1] + Y1 = list[i][AG.KEYFRAME][AG.LOCAL_VALUE][1] if self._OneTangent == True: for j in range(3,5): X = list[i][j][AG.LOCAL_VALUE][0] @@ -469,18 +469,18 @@ class GraphEditorWindow(wx.Window): dc.SetPen(wx.Pen("cyan",3)) dc.SetBrush(wx.Brush("cyan")) dc.DrawCircle(X, Y, 2) - + dc.SetPen(wx.Pen("cyan",1)) dc.DrawLine(X1, Y1, X, Y) - + if list[i][j][AG.SELECT] == 0: dc.SetPen(wx.Pen("brown",3)) dc.SetBrush(wx.Brush("brown")) dc.DrawCircle(X, Y, 2) - + dc.SetPen(wx.Pen("brown",1)) dc.DrawLine(X1, Y1, X, Y) - + if self._OneTangent == False: if list[i][AG.IN_TANGENT][AG.SELECT] == 1: X = list[i][AG.IN_TANGENT][AG.LOCAL_VALUE][0] @@ -491,17 +491,17 @@ class GraphEditorWindow(wx.Window): dc.SetPen(wx.Pen("cyan",1)) dc.DrawLine(X1, Y1, X, Y) - + if list[i][AG.IN_TANGENT][AG.SELECT] == 0: X = list[i][AG.IN_TANGENT][AG.LOCAL_VALUE][0] Y = list[i][AG.IN_TANGENT][AG.LOCAL_VALUE][1] dc.SetPen(wx.Pen("navy",3)) dc.SetBrush(wx.Brush("navy")) dc.DrawCircle(X, Y, 2) - + dc.SetPen(wx.Pen("navy",1)) dc.DrawLine(X1, Y1, X, Y) - + if list[i][AG.OUT_TANGENT][AG.SELECT] == 1: X = list[i][AG.OUT_TANGENT][AG.LOCAL_VALUE][0] Y = list[i][AG.OUT_TANGENT][AG.LOCAL_VALUE][1] @@ -511,7 +511,7 @@ class GraphEditorWindow(wx.Window): dc.SetPen(wx.Pen("cyan",1)) dc.DrawLine(X1, Y1, X, Y) - + if list[i][AG.OUT_TANGENT][AG.SELECT] == 0: X = list[i][AG.OUT_TANGENT][AG.LOCAL_VALUE][0] Y = list[i][AG.OUT_TANGENT][AG.LOCAL_VALUE][1] @@ -531,21 +531,21 @@ class GraphEditorWindow(wx.Window): dc.DrawLine(self.pos[0], self.pos[1], self.newPos[0], self.pos[1]) dc.DrawLine(self.newPos[0], self.newPos[1], self.pos[0], self.newPos[1]) dc.DrawLine(self.newPos[0], self.newPos[1], self.newPos[0], self.pos[1]) - + def OnSize(self,evt): self.InitBuffer() - + def OnLeftDown(self,evt): point = (evt.GetX(), evt.GetY()) - + if point[1]>= float(0) and point[1]<= float(self.h): if point[0]>= float(0) and point[0]<= float(self.w): self._mouseIn = True - + if self._mouseIn: self.CaptureMouse() self.pos = point - + def OnLeftUp(self,evt): if self.GetCapture(): self.ReleaseMouse() @@ -553,22 +553,22 @@ class GraphEditorWindow(wx.Window): self._selectRec = False self.setSelection() self.SetGraphEditorData(self.property, self.curFrame) - + def OnMiddleDown(self,evt): point = (evt.GetX(), evt.GetY()) - + if point[1]>= float(0) and point[1]<= float(self.h): if point[0]>= float(0) and point[0]<= float(self.w): self._mouseIn = True - + if self._mouseIn: self.CaptureMouse() self.midPos = point - + def OnMiddleUp(self, evt): if self.GetCapture(): self.ReleaseMouse() - + def OnMotion(self,evt): self._mouseIn = False if evt.Dragging() and evt.LeftIsDown(): @@ -576,7 +576,7 @@ class GraphEditorWindow(wx.Window): if self.newPos[1]>= float(0) and self.newPos[1]<= float(self.h): if self.newPos[0]>= float(0) and self.newPos[0]<= float(self.w): self._mouseIn = True - + if self._mouseIn: if self.newPos == self.pos: evt.Skip() @@ -584,13 +584,13 @@ class GraphEditorWindow(wx.Window): else: self._selectRec = True self.SetGraphEditorData(self.property, self.curFrame) - + if evt.Dragging() and evt.MiddleIsDown(): self.newMidPos = (evt.GetX(), evt.GetY()) if self.newMidPos[1]>= float(0) and self.newMidPos[1]<= float(self.h): if self.newMidPos[0]>= float(0) and self.newMidPos[0]<= float(self.w): self._mouseIn = True - + if self._mouseIn: if self.newMidPos == self.midPos: evt.Skip() @@ -599,9 +599,9 @@ class GraphEditorWindow(wx.Window): self.recalculateSlope() self.onAnimation() self.midPos = self.newMidPos - + evt.Skip() - self._mouseIn = False + self._mouseIn = False self._selectRec = False def setExistKey(self, list): @@ -617,15 +617,15 @@ class GraphEditorWindow(wx.Window): inside = self.inside(self.pos, self.newPos, (list[i][j][AG.LOCAL_VALUE][0], list[i][j][AG.LOCAL_VALUE][1])) if inside == False: list[i][j][AG.SELECT] = 0 - if inside == True: + if inside == True: list[i][j][AG.SELECT] = 1 find = True flag = True if find == False: list[i][AG.KEYFRAME][AG.SELECT] == 0 - - return flag - + + return flag + def setNewKey(self, list): for i in range(len(list)): inside = self.inside(self.pos, self.newPos, (list[i][2][0][0], list[i][2][0][1])) @@ -633,7 +633,7 @@ class GraphEditorWindow(wx.Window): list[i][AG.KEYFRAME][AG.SELECT] = 1 if inside == False: list[i][AG.KEYFRAME][AG.SELECT] = 0 - + def setSelection(self): if self.property == self._mainDialog.namestr: self.setSelectionBase(self.X) @@ -648,15 +648,15 @@ class GraphEditorWindow(wx.Window): return if self.property == property[AG.Z]: self.setSelectionBase(self.Z) - return - + return + def setSelectionBase(self, list): self.setExistKey(list) if self.setExistKey(list) == True: return else: self.setNewKey(list) - + def inside(self, point0, point1, point): if point0[0]<=point1[0] and point0[1]<=point1[1]: if point0[0]= 0 + return v.dot(n) >= 0 iRay.sortEntries() for entry in iRay.getEntries(): @@ -87,7 +87,7 @@ class PandaTextDropTarget(wx.TextDropTarget): if base.direct.manipulationControl.fGridSnap: snappedPos = self.view.grid.computeSnapPoint(np.getPos()) np.setPos(snappedPos) - + # update temp nodePath's HPR and scale with newobj's np.setHpr(newobj.getHpr()) np.setScale(newobj.getScale()) @@ -127,7 +127,7 @@ ID_ANIM = 701 ID_GRAPH = 702 class LevelEditorUIBase(WxPandaShell): - """ Class for Panda3D LevelEditor """ + """ Class for Panda3D LevelEditor """ def __init__(self, editor): self.MENU_TEXTS.update({ ID_NEW : ("&New", "LE-NewScene"), @@ -154,7 +154,7 @@ class LevelEditorUIBase(WxPandaShell): }) self.editor = editor - WxPandaShell.__init__(self, fStartDirect=True) + WxPandaShell.__init__(self, fStartDirect=True) self.contextMenu = ViewportMenu() self.bindKeyEvents(True) @@ -171,7 +171,7 @@ class LevelEditorUIBase(WxPandaShell): def createMenu(self): menuItem = self.menuFile.Insert(0, ID_NEW, self.MENU_TEXTS[ID_NEW][0]) self.Bind(wx.EVT_MENU, self.onNew, menuItem) - + menuItem = self.menuFile.Insert(1, ID_OPEN, self.MENU_TEXTS[ID_OPEN][0]) self.Bind(wx.EVT_MENU, self.onOpen, menuItem) @@ -218,30 +218,30 @@ class LevelEditorUIBase(WxPandaShell): self.hotKeysMenuItem = self.menuOptions.Append(ID_HOT_KEYS, self.MENU_TEXTS[ID_HOT_KEYS][0]) self.Bind(wx.EVT_MENU, self.onHotKeys, self.hotKeysMenuItem) - + self.menuCurve = wx.Menu() self.menuBar.Insert(3, self.menuCurve, "&CurveMode") - + self.createCurveMenuItem = self.menuCurve.Append(ID_CREATE_CURVE, self.MENU_TEXTS[ID_CREATE_CURVE][0], kind = wx.ITEM_CHECK) self.Bind(wx.EVT_MENU, self.onCreateCurve, self.createCurveMenuItem) - + self.editCurveMenuItem = self.menuCurve.Append(ID_EDIT_CURVE, self.MENU_TEXTS[ID_EDIT_CURVE][0], kind = wx.ITEM_CHECK) self.Bind(wx.EVT_MENU, self.onEditCurve, self.editCurveMenuItem) - + self.curveAnimMenuItem = self.menuCurve.Append(ID_CURVE_ANIM, self.MENU_TEXTS[ID_CURVE_ANIM][0], kind = wx.ITEM_CHECK) self.Bind(wx.EVT_MENU, self.onCurveAnim, self.curveAnimMenuItem) - + self.menuAnim = wx.Menu() self.menuBar.Insert(4, self.menuAnim, "&AnimationMode") - + self.editAnimMenuItem = self.menuAnim.Append(ID_ANIM, self.MENU_TEXTS[ID_ANIM][0], kind = wx.ITEM_CHECK) self.Bind(wx.EVT_MENU, self.onAnimation, self.editAnimMenuItem) - + self.graphEditorMenuItem = self.menuAnim.Append(ID_GRAPH, self.MENU_TEXTS[ID_GRAPH][0], kind = wx.ITEM_CHECK) self.Bind(wx.EVT_MENU, self.onGraphEditor, self.graphEditorMenuItem) - + WxPandaShell.createMenu(self) - + def onGraphEditor(self,e): if base.direct.selected.last == None: dlg = wx.MessageDialog(None, 'Please select a object first.', 'NOTICE', wx.OK ) @@ -253,7 +253,7 @@ class LevelEditorUIBase(WxPandaShell): self.graphEditorUI = GraphEditorUI(self, self.editor, currentObj) self.graphEditorUI.Show() self.graphEditorMenuItem.Check(True) - + def onAnimation(self,e): if self.editor.mode != self.editor.ANIM_MODE: self.animUI = AnimControlUI(self, self.editor) @@ -261,17 +261,17 @@ class LevelEditorUIBase(WxPandaShell): self.editor.mode = self.editor.ANIM_MODE if self.editor.mode == self.editor.ANIM_MODE: self.editAnimMenuItem.Check(True) - + def onCurveAnim(self,e): self.curveAnimUI = CurveAnimUI(self, self.editor) self.curveAnimUI.Show() self.curveAnimMenuItem.Check(True) - + def onCreateCurve(self,e): """Function to invoke curve creating, need to check previous mode""" if self.editor.mode == self.editor.CREATE_CURVE_MODE: self.createCurveMenuItem.Check(False) - self.editor.curveEditor.onBaseMode() + self.editor.curveEditor.onBaseMode() else: if self.editor.mode == self.editor.EDIT_CURVE_MODE: self.editor.curveEditor.onBaseMode() @@ -293,12 +293,12 @@ class LevelEditorUIBase(WxPandaShell): degreeUI.Destroy() base.direct.manipulationControl.disableManipulation() self.editCurveMenuItem.Check(False) - + def onEditCurve(self,e): """Function to invoke curve editing and translate global information to local information. Need to check previous mode""" if self.editor.mode == self.editor.EDIT_CURVE_MODE: self.editCurveMenuItem.Check(False) - self.editor.curveEditor.onBaseMode() + self.editor.curveEditor.onBaseMode() else: if self.editor.mode == self.editor.CREATE_CURVE_MODE: self.editor.curveEditor.onBaseMode() @@ -329,13 +329,13 @@ class LevelEditorUIBase(WxPandaShell): dlg.ShowModal() dlg.Destroy() self.editCurveMenuItem.Check(False) - + def updateMenu(self): hotKeyDict = {} for hotKey in base.direct.hotKeyMap.keys(): desc = base.direct.hotKeyMap[hotKey] hotKeyDict[desc[1]] = hotKey - + for id in self.MENU_TEXTS.keys(): desc = self.MENU_TEXTS[id] if desc[1]: @@ -346,7 +346,7 @@ class LevelEditorUIBase(WxPandaShell): def createInterface(self): WxPandaShell.createInterface(self) - + self.leftBarUpNB = wx.Notebook(self.leftBarUpPane, style=wx.NB_BOTTOM) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.leftBarUpNB, 1, wx.EXPAND) @@ -440,7 +440,7 @@ class LevelEditorUIBase(WxPandaShell): messenger.send('page_down-up') else: evt.Skip() - + def onKeyEvent(self, evt): input = '' if evt.GetKeyCode() in range(97, 123): # for keys from a to z @@ -523,7 +523,7 @@ class LevelEditorUIBase(WxPandaShell): for grid in [self.perspView.grid, self.topView.grid, self.frontView.grid, self.leftView.grid]: if not grid.isHidden(): grid.hide() - + def toggleGridSnap(self, evt): if self.gridSnapMenuItem.IsChecked(): base.direct.manipulationControl.fGridSnap = 1 @@ -531,15 +531,15 @@ class LevelEditorUIBase(WxPandaShell): grid.fXyzSnap = 1 else: - base.direct.manipulationControl.fGridSnap = 0 + base.direct.manipulationControl.fGridSnap = 0 for grid in [self.perspView.grid, self.topView.grid, self.frontView.grid, self.leftView.grid]: grid.fXyzSnap = 0 - + def onGridSize(self, evt): gridSizeUI = GridSizeUI(self, -1, 'Change Grid Size', self.perspView.grid.gridSize, self.perspView.grid.gridSpacing) gridSizeUI.ShowModal() gridSizeUI.Destroy() - + def onShowPandaObjects(self, evt): self.sceneGraphUI.showPandaObjectChildren() @@ -563,7 +563,7 @@ class LevelEditorUIBase(WxPandaShell): self.leftView.grid.gridSize = newSize self.leftView.grid.gridSpacing = newSpacing - self.leftView.grid.updateGrid() + self.leftView.grid.updateGrid() def onHotKeys(self, evt): hotKeyUI = HotKeyUI(self, -1, 'Hot Key List') @@ -621,7 +621,7 @@ class GridSizeUI(wx.Dialog): pos = (10, 115), size=(220, -1), style=wx.SL_HORIZONTAL | wx.SL_LABELS) self.gridSpacingSlider.Enable() - + okButton = wx.Button(self, -1, 'Apply', size=(70, 20)) okButton.Bind(wx.EVT_BUTTON, self.onApply) vbox.Add(panel) @@ -641,7 +641,7 @@ class ViewportMenu(wx.Menu): """Represents a menu that appears when right-clicking a viewport.""" def __init__(self): wx.Menu.__init__(self) - + def addItem(self, name, parent = None, call = None, id = None): if id == None: id = wx.NewId() if parent == None: parent = self @@ -664,20 +664,20 @@ class CurveDegreeUI(wx.Dialog): self.parent = parent panel = wx.Panel(self, -1) degreeBox = wx.BoxSizer(wx.VERTICAL) - + degreeList = ['2','3','4'] - + self.degree = wx.RadioBox(panel, -1, 'Curve Degree', (5, 5), wx.DefaultSize, degreeList, 3, wx.RA_SPECIFY_COLS) self.degree.SetToolTipString("Select the degree of the curve.") self.degree.SetSelection(1) - + okButton = wx.Button(self, -1, 'Apply', size=(70, 20)) okButton.Bind(wx.EVT_BUTTON, self.onApply) - + degreeBox.Add(panel, 1, wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM, 5) degreeBox.Add(okButton, 0, wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM, 5) self.SetSizer(degreeBox) - + def onApply(self, evt): if(str(self.degree.GetSelection())=='0'): self.parent.editor.curveEditor.degree = 2 diff --git a/direct/src/leveleditor/LevelLoaderBase.py b/direct/src/leveleditor/LevelLoaderBase.py index 6ec8f736c8..c5b9c6b907 100755 --- a/direct/src/leveleditor/LevelLoaderBase.py +++ b/direct/src/leveleditor/LevelLoaderBase.py @@ -20,7 +20,7 @@ class LevelLoaderBase: del base.objectPalette del base.protoPalette del base.objectHandler - del base.objectMgr + del base.objectMgr def loadFromFile(self, fileName, filePath=None): if filePath is None: @@ -34,4 +34,4 @@ class LevelLoaderBase: return True except: print 'failed to load %s'%fileName - return None + return None diff --git a/direct/src/leveleditor/MayaConverter.py b/direct/src/leveleditor/MayaConverter.py index ec5d3835c7..cf13b1259d 100755 --- a/direct/src/leveleditor/MayaConverter.py +++ b/direct/src/leveleditor/MayaConverter.py @@ -21,7 +21,7 @@ class Process: self.process.Bind(wx.EVT_END_PROCESS, end_callback) return raise StartupError - + def Poll(self, input=''): if (input or self.b) and self.process and self.process._stdin_: if self.b or len(input) > 512: @@ -44,12 +44,12 @@ class Process: else: x.append('') return x - + def CloseInp(self): if self.process and self.process._stdin_: self.process.CloseOutput() self.process._stdin_ = None - + def Kill(self, ks='SIGKILL'): errors = {wx.KILL_BAD_SIGNAL: "KILL_BAD_SIGNAL", wx.KILL_ACCESS_DENIED: "KILL_ACCESS_DENIED", @@ -65,7 +65,7 @@ class Process: r = 65535 self.CloseInp() return 1, None - + if r not in (wx.KILL_OK, wx.KILL_NO_PROCESS, 65535): return 0, (self.process.pid, signal, errors.get(r, "UNKNOWN_KILL_ERROR %s"%r)) else: @@ -101,7 +101,7 @@ class MayaConverter(wx.Dialog): self.convertToMaya() else: pass - + self.timer = wx.Timer(self, -1) self.Bind(wx.EVT_TIMER, self.onPoll, self.timer) self.timer.Start(100) @@ -127,17 +127,17 @@ class MayaConverter(wx.Dialog): def onEgg2MayaEnded(self, evt): self.process.CloseInp() for i in self.process.Poll(): - self.output.AppendText(i) + self.output.AppendText(i) self.process = None def onBam2EggEnded(self, evt): self.process.CloseInp() for i in self.process.Poll(): - self.output.AppendText(i) + self.output.AppendText(i) eggFileName = self.mayaFile + ".egg" command = 'egg2maya -ui ft -uo ft %s -o %s'%(eggFileName, self.mayaFile) self.process = Process(self, command, lambda p0=None: self.onEgg2MayaEnded(p0)) - + def onPoll(self, evt): if self.process: for i in self.process.Poll(): @@ -146,7 +146,7 @@ class MayaConverter(wx.Dialog): def onModelProcessEnded(self, evt): self.process.CloseInp() for i in self.process.Poll(): - self.output.AppendText(i) + self.output.AppendText(i) self.process = None command = 'maya2egg -uo ft -a chan %s -o %s.anim.egg'%(self.mayaFile, self.mayaFile) self.process = Process(self, command, lambda p0 = None: self.onProcessEnded(p0)) @@ -164,7 +164,7 @@ class MayaConverter(wx.Dialog): if self.obj: objDef = self.obj[OG.OBJ_DEF] objNP = self.obj[OG.OBJ_NP] - animName = "%s.anim.egg"%self.mayaFile + animName = "%s.anim.egg"%self.mayaFile if animName not in objDef.anims: objDef.anims.append(animName) name = os.path.basename(animName) @@ -183,4 +183,4 @@ class MayaConverter(wx.Dialog): if self.callBack: self.callBack(result) - + diff --git a/direct/src/leveleditor/ObjectHandler.py b/direct/src/leveleditor/ObjectHandler.py index 1bd6bd76f2..e51bf2b8fb 100755 --- a/direct/src/leveleditor/ObjectHandler.py +++ b/direct/src/leveleditor/ObjectHandler.py @@ -11,7 +11,7 @@ import ObjectGlobals as OG class ObjectHandler: """ ObjectHandler will create and update objects """ - + def __init__(self, editor): self.editor = editor @@ -33,7 +33,7 @@ class ObjectHandler: a.reparentTo(root) b.reparentTo(root) return root - + def updateDoubleSmiley(self, val, obj): objNP = obj[OG.OBJ_NP] if objNP.find('left'): @@ -73,4 +73,4 @@ class PandaActor(Actor.Actor): self.setScale(0.005) - + diff --git a/direct/src/leveleditor/ObjectMgr.py b/direct/src/leveleditor/ObjectMgr.py index 3f870489c2..d3219dde70 100755 --- a/direct/src/leveleditor/ObjectMgr.py +++ b/direct/src/leveleditor/ObjectMgr.py @@ -5,6 +5,6 @@ from ObjectMgrBase import * class ObjectMgr(ObjectMgrBase): """ ObjectMgr will create, manage, update objects in the scene """ - + def __init__(self, editor): ObjectMgrBase.__init__(self, editor) diff --git a/direct/src/leveleditor/ObjectMgrBase.py b/direct/src/leveleditor/ObjectMgrBase.py index 2524ca404e..bb16f47e4d 100755 --- a/direct/src/leveleditor/ObjectMgrBase.py +++ b/direct/src/leveleditor/ObjectMgrBase.py @@ -18,7 +18,7 @@ class PythonNodePath(NodePath): class ObjectMgrBase: """ ObjectMgr will create, manage, update objects in the scene """ - + def __init__(self, editor): self.editor = editor @@ -30,9 +30,9 @@ class ObjectMgrBase: self.lastUid = '' self.lastUidMode = 0 - self.currNodePath = None + self.currNodePath = None self.currLiveNP = None - + self.Actor = [] self.findActors(render) self.Nodes = [] @@ -50,7 +50,7 @@ class ObjectMgrBase: for np in self.npIndex.keys(): del self.npIndex[np] - + self.objects = {} self.npIndex = {} self.saveData = [] @@ -80,7 +80,7 @@ class ObjectMgrBase: """ function to add new curve to the scene from file""" curve = [] curveControl = [] - + #transfer the curve information from simple positions into control nodes for item in curveInfo: controler = render.attachNewNode("controler") @@ -92,38 +92,38 @@ class ObjectMgrBase: controler.setScale(0.2) controler.reparentTo(render) controler.setTag('OBJRoot','1') - controler.setTag('Controller','1') + controler.setTag('Controller','1') curve.append((None, item[1])) curveControl.append((item[0], controler)) - + self.editor.curveEditor.degree = degree self.editor.curveEditor.ropeUpdate (curve) #add new curve to the scene curveObjNP = self.addNewCurve(curveControl, degree, uid, parent, fSelectObject, nodePath = self.editor.curveEditor.currentRope) curveObj = self.findObjectByNodePath(curveObjNP) self.editor.objectMgr.updateObjectPropValue(curveObj, 'Degree', degree, fSelectObject=False, fUndo=False) - + for item in curveControl: item[1].reparentTo(curveObjNP) item[1].hide() - + curveControl = [] curve = [] self.editor.curveEditor.currentRope = None - + return curveObjNP def addNewCurve(self, curveInfo, degree, uid=None, parent=None, fSelectObject=True, nodePath=None): """ function to add new curve to the scene""" if parent is None: parent = self.editor.NPParent - + if uid is None: uid = self.genUniqueId() if self.editor: objDef = self.editor.objectPalette.findItem('__Curve__') - + if nodePath is None: # we need to create curve # and then create newobj with newly created curve @@ -141,10 +141,10 @@ class ObjectMgrBase: properties['Degree'] = degree properties['curveInfo'] = curveInfo - + # insert obj data to main repository self.objects[uid] = [uid, newobj, objDef, None, None, properties, (1,1,1,1)] - self.npIndex[NodePath(newobj)] = uid + self.npIndex[NodePath(newobj)] = uid if self.editor: if fSelectObject: @@ -191,7 +191,7 @@ class ObjectMgrBase: if self.editor: func = Functor(getattr(self.editor, "objectHandler%s"%funcName)) else: # when loaded outside of LE - func = Functor(getattr(base, "objectHandler%s"%funcName)) + func = Functor(getattr(base, "objectHandler%s"%funcName)) else: # when it's not using default objectHandler, whole name of the handling obj # should be included in function name @@ -209,7 +209,7 @@ class ObjectMgrBase: newobj = Actor(Filename.fromOsSpecific(model).getFullpath()) if hasattr(objDef, 'animDict') and objDef.animDict != {}: objDef.anims = objDef.animDict.get(model) - + elif objDef.model is not None: # since this obj is simple model let's load the model if model is None: @@ -223,7 +223,7 @@ class ObjectMgrBase: newobj = PythonNodePath(newobjModel) else: newobj = None - + else: newobj = hidden.attachNewNode(objDef.name) else: @@ -245,7 +245,7 @@ class ObjectMgrBase: if i == 0: anim = animFile newobj.loop(animName) - + if newobj is None: return None @@ -271,7 +271,7 @@ class ObjectMgrBase: def removeObjectById(self, uid): obj = self.findObjectById(uid) nodePath = obj[OG.OBJ_NP] - + for i in range(0,len(self.Actor)): if self.Actor[i] == obj: del self.Actor[i] @@ -281,7 +281,7 @@ class ObjectMgrBase: del self.Nodes[i] break self.editor.animMgr.removeAnimInfo(obj[OG.OBJ_UID]) - + del self.objects[uid] del self.npIndex[nodePath] @@ -291,7 +291,7 @@ class ObjectMgrBase: self.removeObjectByNodePath(child) nodePath.remove() - self.editor.fNeedToSave = True + self.editor.fNeedToSave = True def removeObjectByNodePath(self, nodePath): uid = self.npIndex.get(nodePath) @@ -305,7 +305,7 @@ class ObjectMgrBase: del self.Nodes[i] break self.editor.animMgr.removeAnimInfo(uid) - + del self.objects[uid] del self.npIndex[nodePath] @@ -372,9 +372,9 @@ class ObjectMgrBase: objProp = obj[OG.OBJ_PROP] self.editor.ui.objectPropertyUI.updateProps(obj, objDef.movable) self.editor.fNeedToSave = True - + def onEnterObjectPropUI(self, event): - taskMgr.remove('_le_updateObjectUITask') + taskMgr.remove('_le_updateObjectUITask') self.editor.ui.bindKeyEvents(False) def onLeaveObjectPropUI(self, event): @@ -389,7 +389,7 @@ class ObjectMgrBase: t = Task.Task(self.updateObjectUITask) t.np = self.currNodePath taskMgr.add(t, '_le_updateObjectUITask') - + def updateObjectUITask(self, state): self.editor.ui.objectPropertyUI.propX.setValue(state.np.getX()) self.editor.ui.objectPropertyUI.propY.setValue(state.np.getY()) @@ -414,18 +414,18 @@ class ObjectMgrBase: r = r + 360.0 while r > 360: - r = r - 360.0 - + r = r - 360.0 + self.editor.ui.objectPropertyUI.propH.setValue(h) self.editor.ui.objectPropertyUI.propP.setValue(p) - self.editor.ui.objectPropertyUI.propR.setValue(r) + self.editor.ui.objectPropertyUI.propR.setValue(r) self.editor.ui.objectPropertyUI.propSX.setValue(state.np.getSx()) self.editor.ui.objectPropertyUI.propSY.setValue(state.np.getSy()) self.editor.ui.objectPropertyUI.propSZ.setValue(state.np.getSz()) - + return Task.cont - + def updateObjectTransform(self, event): if self.currNodePath is None: return @@ -454,15 +454,15 @@ class ObjectMgrBase: r = r + 360.0 while r > 360: - r = r - 360.0 - + r = r - 360.0 + np.setH(h) np.setP(p) np.setR(r) np.setSx(float(self.editor.ui.objectPropertyUI.propSX.getValue())) np.setSy(float(self.editor.ui.objectPropertyUI.propSY.getValue())) - np.setSz(float(self.editor.ui.objectPropertyUI.propSZ.getValue())) + np.setSz(float(self.editor.ui.objectPropertyUI.propSZ.getValue())) obj = self.findObjectByNodePath(self.currNodePath) action = ActionTransformObj(self.editor, obj[OG.OBJ_UID], Mat4(np.getMat())) @@ -470,13 +470,13 @@ class ObjectMgrBase: np.remove() action() self.editor.fNeedToSave = True - + def setObjectTransform(self, uid, xformMat): obj = self.findObjectById(uid) if obj: obj[OG.OBJ_NP].setMat(xformMat) self.editor.fNeedToSave = True - + def updateObjectColor(self, r, g, b, a, np=None): if np is None: np = self.currNodePath @@ -492,7 +492,7 @@ class ObjectMgrBase: child.setTransparency(1) child.setColorScale(r, g, b, a) self.editor.fNeedToSave = True - + def updateObjectModel(self, model, obj, fSelectObject=True): """ replace object's model """ if obj[OG.OBJ_MODEL] != model: @@ -502,7 +502,7 @@ class ObjectMgrBase: objDef = obj[OG.OBJ_DEF] objRGBA = obj[OG.OBJ_RGBA] uid = obj[OG.OBJ_UID] - + # load new model if objDef.actor: try: @@ -520,7 +520,7 @@ class ObjectMgrBase: # reparent children objNP.findAllMatches("=OBJRoot").reparentTo(newobj) - + # reparent to parent newobj.reparentTo(objNP.getParent()) @@ -551,7 +551,7 @@ class ObjectMgrBase: self.updateObjectAnim(animList[0], obj, fSelectObject=fSelectObject) else: if fSelectObject: - base.direct.select(newobj, fUndo=0) + base.direct.select(newobj, fUndo=0) def updateObjectAnim(self, anim, obj, fSelectObject=True): """ replace object's anim """ @@ -585,19 +585,19 @@ class ObjectMgrBase: """ When an obj's property is updated in UI, this will update it's value in data structure. - And call update function if defined. + And call update function if defined. """ - + objDef = obj[OG.OBJ_DEF] objProp = obj[OG.OBJ_PROP] - + propDef = objDef.properties[propName] if propDef is None: return propType = propDef[OG.PROP_TYPE] propDataType = propDef[OG.PROP_DATATYPE] - + if propType == OG.PROP_UI_SLIDE: if len(propDef) <= OG.PROP_RANGE: return @@ -646,11 +646,11 @@ class ObjectMgrBase: def updateObjectPropValue(self, obj, propName, val, fSelectObject=False, fUndo=True): """ Update object property value and - call update function if defined. + call update function if defined. """ objDef = obj[OG.OBJ_DEF] objProp = obj[OG.OBJ_PROP] - + propDef = objDef.properties[propName] propDataType = propDef[OG.PROP_DATATYPE] @@ -690,7 +690,7 @@ class ObjectMgrBase: undoFunc = Functor(getattr(self.editor, "objectHandler%s"%funcName), **undoKwargs) else: # when loaded outside of LE func = Functor(getattr(base, "objectHandler%s"%funcName), **kwargs) - undoFunc = Functor(getattr(base, ".objectHandler%s"%funcName), **undoKwargs) + undoFunc = Functor(getattr(base, ".objectHandler%s"%funcName), **undoKwargs) else: func = Functor(eval(funcName), **kwargs) undoFunc = Functor(eval(funcName), **undoKwargs) @@ -701,7 +701,7 @@ class ObjectMgrBase: # finally call update function #func(**kwargs) else: - oldVal = objProp[propName] + oldVal = objProp[propName] func = None undoFunc = None action = ActionUpdateObjectProp(self.editor, fSelectObject, obj, propName, val, oldVal, func, undoFunc) @@ -730,7 +730,7 @@ class ObjectMgrBase: And call update function if defined. """ obj = self.findObjectByNodePath(nodePath) - + if obj: for propName in propValues: self.updateObjectPropValue(obj, propName, propValues[propName]) @@ -751,7 +751,7 @@ class ObjectMgrBase: objAnim = obj[OG.OBJ_ANIM] objProp = obj[OG.OBJ_PROP] objRGBA = obj[OG.OBJ_RGBA] - + if parentId: parentStr = "objects['%s']"%parentId else: @@ -779,22 +779,22 @@ class ObjectMgrBase: newobjCurveInfo = [] for item in objCurveInfo: newobjCurveInfo.append((item[0], item[1].getPos())) - - self.saveData.append("\nobjects['%s'] = objectMgr.addNewCurveFromFile(%s, %s, '%s', %s, False, None)"%(uid, newobjCurveInfo, self.objDegree, uid, parentStr)) + + self.saveData.append("\nobjects['%s'] = objectMgr.addNewCurveFromFile(%s, %s, '%s', %s, False, None)"%(uid, newobjCurveInfo, self.objDegree, uid, parentStr)) else: self.saveData.append("\nobjects['%s'] = objectMgr.addNewObject('%s', '%s', %s, %s, %s, False, None, %s)"%(uid, objDef.name, uid, modelStr, parentStr, animStr, nameStr)) - + self.saveData.append("if objects['%s']:"%uid) self.saveData.append(" objects['%s'].setPos(%s)"%(uid, np.getPos())) self.saveData.append(" objects['%s'].setHpr(%s)"%(uid, np.getHpr())) self.saveData.append(" objects['%s'].setScale(%s)"%(uid, np.getScale())) self.saveData.append(" objectMgr.updateObjectColor(%f, %f, %f, %f, objects['%s'])"%(objRGBA[0], objRGBA[1], objRGBA[2], objRGBA[3], uid)) - + if objDef.name == '__Curve__': pass else: self.saveData.append(" objectMgr.updateObjectProperties(objects['%s'], %s)"%(uid,objProp)) - + self.traverse(child, uid) def getSaveData(self): @@ -862,7 +862,7 @@ class ObjectMgrBase: newChildObjNP = self.duplicateObject(childNP, parent) if newChildObjNP is not None: self.duplicateChild(childNP, newChildObjNP) - + def duplicateSelected(self): selectedNPs = base.direct.selected.getSelectedAsList() duplicatedNPs = [] @@ -907,7 +907,7 @@ class ObjectMgrBase: def flatten(self, newobjModel, model, objDef, uid): # override this to flatten models pass - + def findActors(self, parent): for child in parent.getChildren(): if child.hasTag('OBJRoot') and not child.hasTag('Controller'): @@ -916,10 +916,10 @@ class ObjectMgrBase: if obj: if isinstance(obj[OG.OBJ_NP],Actor): self.Actor.append(obj) - + self.findActors(child) - + def findNodes(self, parent): for child in parent.getChildren(): if child.hasTag('OBJRoot') and not child.hasTag('Controller'): @@ -927,7 +927,7 @@ class ObjectMgrBase: if obj: self.Nodes.append(obj) - + self.findActors(child) - - + + diff --git a/direct/src/leveleditor/ObjectPalette.py b/direct/src/leveleditor/ObjectPalette.py index d7b1a0e7d6..4b08ad1360 100755 --- a/direct/src/leveleditor/ObjectPalette.py +++ b/direct/src/leveleditor/ObjectPalette.py @@ -52,7 +52,7 @@ class ObjectDoubleSmileys(ObjectProp): # it means this function belongs to the default objectHandler. 1.0, [0, 10, 0.1]] - + class ObjectPalette(ObjectPaletteBase): def __init__(self): ObjectPaletteBase.__init__(self) @@ -84,7 +84,7 @@ class ObjectPalette(ObjectPaletteBase): {'val':OG.ARG_VAL, 'obj':OG.ARG_OBJ}), 1, [1, 10]], }), - 'Prop') # This object type will be added under the 'Prop' group. + 'Prop') # This object type will be added under the 'Prop' group. self.add(ObjectDoubleSmileys(name='H Double Smiley', createFunction = ('.createDoubleSmiley', {})), # When the createFunction is defined like this, diff --git a/direct/src/leveleditor/ObjectPaletteBase.py b/direct/src/leveleditor/ObjectPaletteBase.py index dc5624c5da..1946926c89 100755 --- a/direct/src/leveleditor/ObjectPaletteBase.py +++ b/direct/src/leveleditor/ObjectPaletteBase.py @@ -77,7 +77,7 @@ class ObjectPaletteBase: def addHidden(self, item): if hasattr(item, 'name'): - self.data[item.name] = item + self.data[item.name] = item def deleteStruct(self, name, deleteItems): try: @@ -97,7 +97,7 @@ class ObjectPaletteBase: deleteItems = {} node = self.deleteStruct(name, deleteItems) if node is not None: - deleteItems[name] = node + deleteItems[name] = node for key in deleteItems.keys(): item = self.dataStruct.pop(key) except: diff --git a/direct/src/leveleditor/ObjectPropertyUI.py b/direct/src/leveleditor/ObjectPropertyUI.py index 9e918f6048..0be0910523 100755 --- a/direct/src/leveleditor/ObjectPropertyUI.py +++ b/direct/src/leveleditor/ObjectPropertyUI.py @@ -55,7 +55,7 @@ class AnimFileDrop(wx.FileDropTarget): objNP.loop(name) obj[OG.OBJ_ANIM] = animName self.editor.ui.objectPropertyUI.updateProps(obj) - + class ObjectPropUI(wx.Panel): """ Base class for ObjectPropUIs, @@ -77,20 +77,20 @@ class ObjectPropUI(wx.Panel): sizer.Add(self.labelPane) sizer.Add(self.uiPane, 1, wx.EXPAND, 0) self.SetSizer(sizer) - + self.setKeyButton.Bind(wx.EVT_BUTTON, self.onKey) def onKey(self,evt): self.parent = wx.GetTopLevelParent(self) if self.parent.editor.mode == self.parent.editor.ANIM_MODE: obj= self.parent.editor.objectMgr.findObjectByNodePath(base.direct.selected.last) - + objUID = obj[OG.OBJ_UID] propertyName = self.label.GetLabelText() - + value = self.getValue() frame = self.parent.editor.ui.animUI.curFrame - + if (objUID, propertyName) in self.parent.editor.animMgr.keyFramesInfo: for i in range(len(self.parent.editor.animMgr.keyFramesInfo[(objUID,propertyName)])): if self.parent.editor.animMgr.keyFramesInfo[(objUID,propertyName)][i][AG.FRAME] == frame: @@ -104,27 +104,27 @@ class ObjectPropUI(wx.Panel): temp = sortKeyList[i] sortKeyList[i] = sortKeyList[j] sortKeyList[j] = temp - + self.parent.editor.animMgr.generateSlope(self.parent.editor.animMgr.keyFramesInfo[(objUID,propertyName)]) else: self.parent.editor.animMgr.keyFramesInfo[(objUID,propertyName)] = [[frame, value, [], []]] - + exist = False for keyFrame in self.parent.editor.animMgr.keyFrames: if frame == keyFrame: exist = True break - + if exist == False: self.parent.editor.animMgr.keyFrames.append(frame) self.parent.editor.ui.animUI.OnPropKey() else: self.parent.editor.ui.animUI.OnPropKey() - + else: evt.Skip() - + def setValue(self, value): self.ui.SetValue(value) @@ -290,7 +290,7 @@ class ObjectPropUITime(wx.Panel): if valFunc: self.uiAmPm.Bind(self.eventType, valFunc) self.uiHour.Bind(self.eventType, valFunc) - self.uiMin.Bind(self.eventType, valFunc) + self.uiMin.Bind(self.eventType, valFunc) class ColorPicker(CubeColourDialog): def __init__(self, parent, colourData=None, style=CCD_SHOW_ALPHA, alpha = 255, updateCB=None, exitCB=None): @@ -347,7 +347,7 @@ class ObjectPropertyUI(ScrolledPanel): self.propCR.setValue(r) self.propCG.setValue(g) self.propCB.setValue(b) - self.propCA.setValue(a) + self.propCA.setValue(a) self.editor.objectMgr.updateObjectColor(r, g, b, a) @@ -377,7 +377,7 @@ class ObjectPropertyUI(ScrolledPanel): self.colorPicker.DrawAlpha() self.editor.objectMgr.updateObjectColor(r, g, b, a) - + def openColorPicker(self, evt, colourData, alpha): if self.colorPicker: self.lastColorPickerPos = self.colorPicker.GetPosition() @@ -388,10 +388,10 @@ class ObjectPropertyUI(ScrolledPanel): self.colorPicker.Show() if self.lastColorPickerPos: self.colorPicker.SetPosition(self.lastColorPickerPos) - + def updateProps(self, obj, movable=True): self.clearPropUI() - + self.propPane = wx.Panel(self) mainSizer = wx.BoxSizer(wx.VERTICAL) mainSizer.Add(self.propPane, 1, wx.EXPAND, 0) @@ -439,8 +439,8 @@ class ObjectPropertyUI(ScrolledPanel): objRGBA = obj[OG.OBJ_RGBA] self.propCR = ObjectPropUISlider(self.lookPane, 'CR', objRGBA[0], 0, 1) self.propCG = ObjectPropUISlider(self.lookPane, 'CG', objRGBA[1], 0, 1) - self.propCB = ObjectPropUISlider(self.lookPane, 'CB', objRGBA[2], 0, 1) - self.propCA = ObjectPropUISlider(self.lookPane, 'CA', objRGBA[3], 0, 1) + self.propCB = ObjectPropUISlider(self.lookPane, 'CB', objRGBA[2], 0, 1) + self.propCA = ObjectPropUISlider(self.lookPane, 'CA', objRGBA[3], 0, 1) colorProps = [self.propCR, self.propCG, self.propCB, self.propCA] for colorProp in colorProps: @@ -470,7 +470,7 @@ class ObjectPropertyUI(ScrolledPanel): else: modelList = objDef.models propUI = ObjectPropUICombo(self.lookPane, 'model', defaultModel, modelList, obj, callBack=objDef.updateModelFunction) - sizer.Add(propUI) + sizer.Add(propUI) propUI.bindFunc(self.editor.objectMgr.onEnterObjectPropUI, self.editor.objectMgr.onLeaveObjectPropUI, @@ -480,9 +480,9 @@ class ObjectPropertyUI(ScrolledPanel): if len(objDef.anims) > 0 or animList: if animList is None: animList = objDef.anims - + propUI = ObjectPropUICombo(self.lookPane, 'anim', obj[OG.OBJ_ANIM], animList) - sizer.Add(propUI) + sizer.Add(propUI) propUI.bindFunc(self.editor.objectMgr.onEnterObjectPropUI, self.editor.objectMgr.onLeaveObjectPropUI, @@ -543,20 +543,20 @@ class ObjectPropertyUI(ScrolledPanel): continue propUI = ObjectPropUISpinner(self.propsPane, key, value, propRange[OG.RANGE_MIN], propRange[OG.RANGE_MAX]) - sizer.Add(propUI) + sizer.Add(propUI) elif propType == OG.PROP_UI_CHECK: if value is None: continue propUI = ObjectPropUICheck(self.propsPane, key, value) - sizer.Add(propUI) + sizer.Add(propUI) elif propType == OG.PROP_UI_RADIO: if len(propDef) <= OG.PROP_RANGE: continue propRange = propDef[OG.PROP_RANGE] - + if value is None: continue @@ -572,7 +572,7 @@ class ObjectPropertyUI(ScrolledPanel): elif propType == OG.PROP_UI_COMBO: if len(propDef) <= OG.PROP_RANGE: continue - propRange = propDef[OG.PROP_RANGE] + propRange = propDef[OG.PROP_RANGE] if value is None: continue @@ -589,7 +589,7 @@ class ObjectPropertyUI(ScrolledPanel): elif propType == OG.PROP_UI_COMBO_DYNAMIC: if len(propDef) <= OG.PROP_DYNAMIC_KEY: continue - + propDynamicKey = propDef[OG.PROP_DYNAMIC_KEY] if propDynamicKey == OG.PROP_MODEL: dynamicRangeKey = obj[OG.OBJ_MODEL] @@ -618,7 +618,7 @@ class ObjectPropertyUI(ScrolledPanel): if value not in propRange: value = propRange[0] self.editor.objectMgr.updateObjectPropValue(obj, key, value, fUndo=False) - + propUI = ObjectPropUICombo(self.propsPane, key, value, propRange) sizer.Add(propUI) @@ -629,7 +629,7 @@ class ObjectPropertyUI(ScrolledPanel): propUI = ObjectPropUITime(self.propsPane, key, value) sizer.Add(propUI) - + else: # unspported property type continue @@ -648,4 +648,4 @@ class ObjectPropertyUI(ScrolledPanel): self.nb.SetSelection(1) elif self.lastPropTab == 'Properties': self.nb.SetSelection(2) - + diff --git a/direct/src/leveleditor/PaletteTreeCtrl.py b/direct/src/leveleditor/PaletteTreeCtrl.py index 9959aaeaac..f774f0dac5 100644 --- a/direct/src/leveleditor/PaletteTreeCtrl.py +++ b/direct/src/leveleditor/PaletteTreeCtrl.py @@ -97,7 +97,7 @@ class PaletteTreeCtrl(wx.TreeCtrl): itemText = self.GetItemText(item) if item and itemText != self.rootName: self.Delete(item) - self.paletteUI.palette.delete(itemText) + self.paletteUI.palette.delete(itemText) def DeleteSelected(self): item = self.GetSelection() diff --git a/direct/src/leveleditor/ProtoObjs.py b/direct/src/leveleditor/ProtoObjs.py index 208c784bd6..a1bc137a3e 100755 --- a/direct/src/leveleditor/ProtoObjs.py +++ b/direct/src/leveleditor/ProtoObjs.py @@ -1,40 +1,40 @@ -""" -Palette for Prototyping -""" -import os -import imp -import types - -class ProtoObjs: - def __init__(self, name): - self.dirname = os.path.dirname(__file__) - self.name = name; - self.filename = "/%s.py"%(name) - self.data = {} - - def populate(self): - moduleName = self.name - try: - file, pathname, description = imp.find_module(moduleName, [self.dirname]) - module = imp.load_module(moduleName, file, pathname, description) - self.data = module.protoData - except: - print "%s doesn't exist"%(self.name) - return - - def saveProtoData(self, f): - if not f: - return - - for key in self.data.keys(): - f.write("\t'%s':'%s',\n"%(key, self.data[key])) - - def saveToFile(self): - try: - f = open(self.dirname + self.filename, 'w') - f.write("protoData = {\n") - self.saveProtoData(f) - f.write("}\n") - f.close() - except: - pass +""" +Palette for Prototyping +""" +import os +import imp +import types + +class ProtoObjs: + def __init__(self, name): + self.dirname = os.path.dirname(__file__) + self.name = name; + self.filename = "/%s.py"%(name) + self.data = {} + + def populate(self): + moduleName = self.name + try: + file, pathname, description = imp.find_module(moduleName, [self.dirname]) + module = imp.load_module(moduleName, file, pathname, description) + self.data = module.protoData + except: + print "%s doesn't exist"%(self.name) + return + + def saveProtoData(self, f): + if not f: + return + + for key in self.data.keys(): + f.write("\t'%s':'%s',\n"%(key, self.data[key])) + + def saveToFile(self): + try: + f = open(self.dirname + self.filename, 'w') + f.write("protoData = {\n") + self.saveProtoData(f) + f.write("}\n") + f.close() + except: + pass diff --git a/direct/src/leveleditor/ProtoObjsUI.py b/direct/src/leveleditor/ProtoObjsUI.py index f68fd3cb7f..67fb60f4b9 100755 --- a/direct/src/leveleditor/ProtoObjsUI.py +++ b/direct/src/leveleditor/ProtoObjsUI.py @@ -1,132 +1,132 @@ -""" -Defines ProtoObjs List UI -""" -import wx -import os -import cPickle as pickl - -from pandac.PandaModules import * -from ProtoObjs import * - -class ProtoDropTarget(wx.PyDropTarget): - """Implements drop target functionality to receive files, bitmaps and text""" - def __init__(self, ui): - wx.PyDropTarget.__init__(self) - self.ui = ui - self.do = wx.DataObjectComposite() # the dataobject that gets filled with the appropriate data - self.filedo = wx.FileDataObject() - self.textdo = wx.TextDataObject() - self.bmpdo = wx.BitmapDataObject() - self.do.Add(self.filedo) - self.do.Add(self.bmpdo) - self.do.Add(self.textdo) - self.SetDataObject(self.do) - - def OnData(self, x, y, d): - """ - Handles drag/dropping files/text or a bitmap - """ - if self.GetData(): - df = self.do.GetReceivedFormat().GetType() - if df in [wx.DF_UNICODETEXT, wx.DF_TEXT]: - text = self.textdo.GetText() - # self.editor.ui.protoFontsUI.tree.ChangeHierarchy(text, x, y) - - elif df == wx.DF_FILENAME: - for name in self.filedo.GetFilenames(): - self.ui.AquireFile(name) - - elif df == wx.DF_BITMAP: - bmp = self.bmpdo.GetBitmap() - - return d # you must return this - -class ProtoObjsUI(wx.Panel): - def __init__(self, parent, editor, protoObjs, supportedExts): - wx.Panel.__init__(self, parent) - - self.editor = editor - self.protoObjs = protoObjs - self.supportedExts = supportedExts - - self.llist = wx.ListCtrl(self, -1, style=wx.LC_REPORT) - self.llist.InsertColumn(0, "Files") - - sizer = wx.BoxSizer(wx.VERTICAL) - sizer.Add(self.llist, 1, wx.EXPAND, 0) - self.SetSizer(sizer); self.Layout() - - parentSizer = wx.BoxSizer(wx.VERTICAL) - parentSizer.Add(self, 1, wx.EXPAND, 0) - parent.SetSizer(parentSizer); parent.Layout() - - self.opDelete = "Delete" - self.menuItems = list() - self.menuItems.append(self.opDelete) - - self.popupmenu = wx.Menu() - for item in self.menuItems: - menuItem = self.popupmenu.Append(-1, item) - self.Bind(wx.EVT_MENU, self.onPopupItemSelected, menuItem) - self.Bind(wx.EVT_CONTEXT_MENU, self.onShowPopup) - - self.SetDropTarget(ProtoDropTarget(self)) - - def populate(self): - for key in self.protoObjs.data.keys(): - self.add(self.protoObjs.data[key]) - - # All subclasses should implement this method - def addObj(self, filename): - raise NotImplementedError - - def onPopupItemSelected(self, event): - menuItem = self.popupmenu.FindItemById(event.GetId()) - text = menuItem.GetText() - if text == self.opDelete: - self.remove() - - def onShowPopup(self, event): - pos = event.GetPosition() - pos = self.ScreenToClient(pos) - self.PopupMenu(self.popupmenu, pos) - - def findLabel(self, text): - found = False - for index in range(self.llist.GetItemCount()): - itemtext = self.llist.GetItemText(index) - if itemtext == text: - return True - return found - - def removeItem(self, index): - if index != -1: - key = self.llist.GetItemText(index) - del(self.protoObjs.data[key]) - item = self.llist.DeleteItem(index) - - def remove(self): - index = self.llist.GetFirstSelected() - self.removeItem(index) - - def add(self, filename): - name = os.path.basename(filename) - for ext in self.supportedExts: - if name.upper().endswith(ext.upper()): - try: - index = self.llist.InsertStringItem(self.llist.GetItemCount(), name) - self.protoObjs.data[name]= filename - self.addObj(filename) - except: - pass - break - - def addNewItem(self, result): - ProtoObjsUI.AquireFile(self, result[1]) - - def AquireFile(self, filename): - label = self.findLabel(filename) - if label: - self.removeItem(label) - filenameFull = Filename.fromOsSpecific(filename).getFullpath() - self.add(filenameFull) +""" +Defines ProtoObjs List UI +""" +import wx +import os +import cPickle as pickl + +from pandac.PandaModules import * +from ProtoObjs import * + +class ProtoDropTarget(wx.PyDropTarget): + """Implements drop target functionality to receive files, bitmaps and text""" + def __init__(self, ui): + wx.PyDropTarget.__init__(self) + self.ui = ui + self.do = wx.DataObjectComposite() # the dataobject that gets filled with the appropriate data + self.filedo = wx.FileDataObject() + self.textdo = wx.TextDataObject() + self.bmpdo = wx.BitmapDataObject() + self.do.Add(self.filedo) + self.do.Add(self.bmpdo) + self.do.Add(self.textdo) + self.SetDataObject(self.do) + + def OnData(self, x, y, d): + """ + Handles drag/dropping files/text or a bitmap + """ + if self.GetData(): + df = self.do.GetReceivedFormat().GetType() + if df in [wx.DF_UNICODETEXT, wx.DF_TEXT]: + text = self.textdo.GetText() + # self.editor.ui.protoFontsUI.tree.ChangeHierarchy(text, x, y) + + elif df == wx.DF_FILENAME: + for name in self.filedo.GetFilenames(): + self.ui.AquireFile(name) + + elif df == wx.DF_BITMAP: + bmp = self.bmpdo.GetBitmap() + + return d # you must return this + +class ProtoObjsUI(wx.Panel): + def __init__(self, parent, editor, protoObjs, supportedExts): + wx.Panel.__init__(self, parent) + + self.editor = editor + self.protoObjs = protoObjs + self.supportedExts = supportedExts + + self.llist = wx.ListCtrl(self, -1, style=wx.LC_REPORT) + self.llist.InsertColumn(0, "Files") + + sizer = wx.BoxSizer(wx.VERTICAL) + sizer.Add(self.llist, 1, wx.EXPAND, 0) + self.SetSizer(sizer); self.Layout() + + parentSizer = wx.BoxSizer(wx.VERTICAL) + parentSizer.Add(self, 1, wx.EXPAND, 0) + parent.SetSizer(parentSizer); parent.Layout() + + self.opDelete = "Delete" + self.menuItems = list() + self.menuItems.append(self.opDelete) + + self.popupmenu = wx.Menu() + for item in self.menuItems: + menuItem = self.popupmenu.Append(-1, item) + self.Bind(wx.EVT_MENU, self.onPopupItemSelected, menuItem) + self.Bind(wx.EVT_CONTEXT_MENU, self.onShowPopup) + + self.SetDropTarget(ProtoDropTarget(self)) + + def populate(self): + for key in self.protoObjs.data.keys(): + self.add(self.protoObjs.data[key]) + + # All subclasses should implement this method + def addObj(self, filename): + raise NotImplementedError + + def onPopupItemSelected(self, event): + menuItem = self.popupmenu.FindItemById(event.GetId()) + text = menuItem.GetText() + if text == self.opDelete: + self.remove() + + def onShowPopup(self, event): + pos = event.GetPosition() + pos = self.ScreenToClient(pos) + self.PopupMenu(self.popupmenu, pos) + + def findLabel(self, text): + found = False + for index in range(self.llist.GetItemCount()): + itemtext = self.llist.GetItemText(index) + if itemtext == text: + return True + return found + + def removeItem(self, index): + if index != -1: + key = self.llist.GetItemText(index) + del(self.protoObjs.data[key]) + item = self.llist.DeleteItem(index) + + def remove(self): + index = self.llist.GetFirstSelected() + self.removeItem(index) + + def add(self, filename): + name = os.path.basename(filename) + for ext in self.supportedExts: + if name.upper().endswith(ext.upper()): + try: + index = self.llist.InsertStringItem(self.llist.GetItemCount(), name) + self.protoObjs.data[name]= filename + self.addObj(filename) + except: + pass + break + + def addNewItem(self, result): + ProtoObjsUI.AquireFile(self, result[1]) + + def AquireFile(self, filename): + label = self.findLabel(filename) + if label: + self.removeItem(label) + filenameFull = Filename.fromOsSpecific(filename).getFullpath() + self.add(filenameFull) diff --git a/direct/src/leveleditor/ProtoPaletteUI.py b/direct/src/leveleditor/ProtoPaletteUI.py index c212734a41..7c19e85754 100755 --- a/direct/src/leveleditor/ProtoPaletteUI.py +++ b/direct/src/leveleditor/ProtoPaletteUI.py @@ -162,12 +162,12 @@ class ProtoPaletteUI(wx.Panel): def AquireFile(self, filename): name = os.path.basename(filename) - + if self.editor.protoPalette.findItem(name): item = self.tree.traverse(self.tree.root, name) if item: self.tree.DeleteItem(item) - + modelname = Filename.fromOsSpecific(filename).getFullpath() if modelname.endswith('.mb') or\ modelname.endswith('.ma'): @@ -183,7 +183,7 @@ class ProtoPaletteUI(wx.Panel): def addNewItem(self, result): if len(result) == 2: - itemData = ObjectBase(name=result[0], model=result[1], actor=False) + itemData = ObjectBase(name=result[0], model=result[1], actor=False) elif len(result) == 3: itemData = ObjectBase(name=result[0], model=result[1], anims=[result[2]], actor=True) else: diff --git a/direct/src/leveleditor/SceneGraphUI.py b/direct/src/leveleditor/SceneGraphUI.py index 7555d07045..0a6ca41b69 100755 --- a/direct/src/leveleditor/SceneGraphUI.py +++ b/direct/src/leveleditor/SceneGraphUI.py @@ -2,7 +2,7 @@ Defines Scene Graph tree UI """ from SceneGraphUIBase import * - + class SceneGraphUI(SceneGraphUIBase): def __init__(self, parent, editor): SceneGraphUIBase.__init__(self, parent, editor) diff --git a/direct/src/leveleditor/SceneGraphUIBase.py b/direct/src/leveleditor/SceneGraphUIBase.py index 65bb775d5f..b8c4bc9b7e 100755 --- a/direct/src/leveleditor/SceneGraphUIBase.py +++ b/direct/src/leveleditor/SceneGraphUIBase.py @@ -17,7 +17,7 @@ class SceneGraphUIDropTarget(wx.TextDropTarget): def OnDropText(self, x, y, text): print "in SceneGraphUIDropTarget::OnDropText..." self.editor.ui.sceneGraphUI.changeHierarchy(text, x, y) - + class SceneGraphUIBase(wx.Panel): def __init__(self, parent, editor): wx.Panel.__init__(self, parent) @@ -49,7 +49,7 @@ class SceneGraphUIBase(wx.Panel): self.menu = wx.Menu() self.populateMenu() self.Bind(wx.EVT_CONTEXT_MENU, self.onShowPopup) - + def reset(self): #import pdb;set_trace() itemList = list() @@ -135,7 +135,7 @@ class SceneGraphUIBase(wx.Panel): namestr = "%s_%s_%s"%(obj[OG.OBJ_DEF].name, name, obj[OG.OBJ_UID]) newItem = self.tree.AppendItem(parent, namestr) self.tree.SetItemPyData(newItem, obj[OG.OBJ_UID]) - + # adding children of PandaObj if self.shouldShowPandaObjChildren: self.addPandaObjectChildren(newItem) @@ -159,7 +159,7 @@ class SceneGraphUIBase(wx.Panel): child = self.traverse(item, itemId) if child is not None: return child - + # continue iteration to the next child item, cookie = self.tree.GetNextChild(parent, cookie) return None @@ -273,7 +273,7 @@ class SceneGraphUIBase(wx.Panel): return obj[OG.OBJ_NP].setName(newName) - namestr = "%s_%s_%s"%(obj[OG.OBJ_DEF].name, newName, obj[OG.OBJ_UID]) + namestr = "%s_%s_%s"%(obj[OG.OBJ_DEF].name, newName, obj[OG.OBJ_UID]) self.tree.SetItemText(item, namestr) def deSelect(self, itemId): diff --git a/direct/src/leveleditor/testData.py b/direct/src/leveleditor/testData.py index 835b0ca1d6..28d4a04d1c 100755 --- a/direct/src/leveleditor/testData.py +++ b/direct/src/leveleditor/testData.py @@ -1,72 +1,72 @@ -from pandac.PandaModules import * - -if hasattr(base, 'le'): - objectMgr = base.le.objectMgr - ui = base.le.ui - ui.sceneGraphUI.reset() - -else: - objectMgr = base.objectMgr -# temporary place holder for nodepath -objects = {} - -objects['1252538687.73gjeon'] = objectMgr.addNewObject('Smiley', '1252538687.73gjeon', 'models/smiley.egg', None) -if objects['1252538687.73gjeon']: - objects['1252538687.73gjeon'].setPos(Point3(8.66381, 0, 7.13246)) - objects['1252538687.73gjeon'].setHpr(VBase3(0, 0, 0)) - objects['1252538687.73gjeon'].setScale(VBase3(1, 1, 1)) - objectMgr.updateObjectColor(1.000000, 1.000000, 1.000000, 1.000000, objects['1252538687.73gjeon']) - objectMgr.updateObjectProperties(objects['1252538687.73gjeon'], {'123': 1, 'Abc': 'a', 'Number': 1, 'Happy': True}) - -objects['1252538690.2gjeon'] = objectMgr.addNewObject('H Double Smiley', '1252538690.2gjeon', None, objects['1252538687.73gjeon']) -if objects['1252538690.2gjeon']: - objects['1252538690.2gjeon'].setPos(Point3(0, 0, 2.12046)) - objects['1252538690.2gjeon'].setHpr(VBase3(0, 0, 0)) - objects['1252538690.2gjeon'].setScale(VBase3(1, 1, 1)) - objectMgr.updateObjectColor(1.000000, 1.000000, 1.000000, 1.000000, objects['1252538690.2gjeon']) - objectMgr.updateObjectProperties(objects['1252538690.2gjeon'], {'Distance': 2.0, 'Abc': 'a'}) - -objects['1252539696.69gjeon'] = objectMgr.addNewObject('H Double Smiley', '1252539696.69gjeon', None, objects['1252538687.73gjeon']) -if objects['1252539696.69gjeon']: - objects['1252539696.69gjeon'].setPos(Point3(-9.53674e-006, 0, 0)) - objects['1252539696.69gjeon'].setHpr(VBase3(0, 0, 0)) - objects['1252539696.69gjeon'].setScale(VBase3(1, 1, 1)) - objectMgr.updateObjectColor(1.000000, 1.000000, 1.000000, 1.000000, objects['1252539696.69gjeon']) - objectMgr.updateObjectProperties(objects['1252539696.69gjeon'], {'Distance': 2.0, 'Abc': 'a'}) - -objects['1252539897.22gjeon'] = objectMgr.addNewObject('H Double Smiley', '1252539897.22gjeon', None, objects['1252538687.73gjeon']) -if objects['1252539897.22gjeon']: - objects['1252539897.22gjeon'].setPos(Point3(0.06987, 0, -2.12046)) - objects['1252539897.22gjeon'].setHpr(VBase3(0, 0, 0)) - objects['1252539897.22gjeon'].setScale(VBase3(1, 1, 1)) - objectMgr.updateObjectColor(1.000000, 1.000000, 1.000000, 1.000000, objects['1252539897.22gjeon']) - objectMgr.updateObjectProperties(objects['1252539897.22gjeon'], {'Distance': 2.0, 'Abc': 'a'}) - -objects['1252538689.13gjeon'] = objectMgr.addNewObject('V Double Smiley', '1252538689.13gjeon', None, objects['1252538687.73gjeon']) -if objects['1252538689.13gjeon']: - objects['1252538689.13gjeon'].setPos(Point3(6.07152, 0, -0.863791)) - objects['1252538689.13gjeon'].setHpr(VBase3(0, 0, 0)) - objects['1252538689.13gjeon'].setScale(VBase3(1, 1, 1)) - objectMgr.updateObjectColor(1.000000, 1.000000, 1.000000, 1.000000, objects['1252538689.13gjeon']) - objectMgr.updateObjectProperties(objects['1252538689.13gjeon'], {'Distance': 1.0, 'Abc': 'a'}) - -objects['1252539974.19gjeon'] = objectMgr.addNewObject('Smiley', '1252539974.19gjeon', 'models/frowney.egg', objects['1252538689.13gjeon']) -if objects['1252539974.19gjeon']: - objects['1252539974.19gjeon'].setPos(Point3(0.06987, 0, 3.09209)) - objects['1252539974.19gjeon'].setHpr(VBase3(0, 0, 0)) - objects['1252539974.19gjeon'].setScale(VBase3(1, 1, 1)) - objectMgr.updateObjectColor(1.000000, 1.000000, 1.000000, 1.000000, objects['1252539974.19gjeon']) - objectMgr.updateObjectProperties(objects['1252539974.19gjeon'], {'123': 1, 'Abc': 'a', 'Number': 1, 'Happy': True}) - -objects['1252623762.9gjeon'] = objectMgr.addNewObject('Panda', '1252623762.9gjeon', None, None) -if objects['1252623762.9gjeon']: - objects['1252623762.9gjeon'].setPos(Point3(0, 0, 0)) - objects['1252623762.9gjeon'].setHpr(VBase3(0, 0, 0)) - objects['1252623762.9gjeon'].setScale(VBase3(0.005, 0.005, 0.005)) - objectMgr.updateObjectColor(1.000000, 0.000000, 0.000000, 0.517647, objects['1252623762.9gjeon']) - objectMgr.updateObjectProperties(objects['1252623762.9gjeon'], {}) - -if hasattr(base, 'le'): - ui.layerEditorUI.reset() - ui.layerEditorUI.addLayerEntry('Layer1', 1 ) - ui.layerEditorUI.addLayerData(1, '1252538687.73gjeon') +from pandac.PandaModules import * + +if hasattr(base, 'le'): + objectMgr = base.le.objectMgr + ui = base.le.ui + ui.sceneGraphUI.reset() + +else: + objectMgr = base.objectMgr +# temporary place holder for nodepath +objects = {} + +objects['1252538687.73gjeon'] = objectMgr.addNewObject('Smiley', '1252538687.73gjeon', 'models/smiley.egg', None) +if objects['1252538687.73gjeon']: + objects['1252538687.73gjeon'].setPos(Point3(8.66381, 0, 7.13246)) + objects['1252538687.73gjeon'].setHpr(VBase3(0, 0, 0)) + objects['1252538687.73gjeon'].setScale(VBase3(1, 1, 1)) + objectMgr.updateObjectColor(1.000000, 1.000000, 1.000000, 1.000000, objects['1252538687.73gjeon']) + objectMgr.updateObjectProperties(objects['1252538687.73gjeon'], {'123': 1, 'Abc': 'a', 'Number': 1, 'Happy': True}) + +objects['1252538690.2gjeon'] = objectMgr.addNewObject('H Double Smiley', '1252538690.2gjeon', None, objects['1252538687.73gjeon']) +if objects['1252538690.2gjeon']: + objects['1252538690.2gjeon'].setPos(Point3(0, 0, 2.12046)) + objects['1252538690.2gjeon'].setHpr(VBase3(0, 0, 0)) + objects['1252538690.2gjeon'].setScale(VBase3(1, 1, 1)) + objectMgr.updateObjectColor(1.000000, 1.000000, 1.000000, 1.000000, objects['1252538690.2gjeon']) + objectMgr.updateObjectProperties(objects['1252538690.2gjeon'], {'Distance': 2.0, 'Abc': 'a'}) + +objects['1252539696.69gjeon'] = objectMgr.addNewObject('H Double Smiley', '1252539696.69gjeon', None, objects['1252538687.73gjeon']) +if objects['1252539696.69gjeon']: + objects['1252539696.69gjeon'].setPos(Point3(-9.53674e-006, 0, 0)) + objects['1252539696.69gjeon'].setHpr(VBase3(0, 0, 0)) + objects['1252539696.69gjeon'].setScale(VBase3(1, 1, 1)) + objectMgr.updateObjectColor(1.000000, 1.000000, 1.000000, 1.000000, objects['1252539696.69gjeon']) + objectMgr.updateObjectProperties(objects['1252539696.69gjeon'], {'Distance': 2.0, 'Abc': 'a'}) + +objects['1252539897.22gjeon'] = objectMgr.addNewObject('H Double Smiley', '1252539897.22gjeon', None, objects['1252538687.73gjeon']) +if objects['1252539897.22gjeon']: + objects['1252539897.22gjeon'].setPos(Point3(0.06987, 0, -2.12046)) + objects['1252539897.22gjeon'].setHpr(VBase3(0, 0, 0)) + objects['1252539897.22gjeon'].setScale(VBase3(1, 1, 1)) + objectMgr.updateObjectColor(1.000000, 1.000000, 1.000000, 1.000000, objects['1252539897.22gjeon']) + objectMgr.updateObjectProperties(objects['1252539897.22gjeon'], {'Distance': 2.0, 'Abc': 'a'}) + +objects['1252538689.13gjeon'] = objectMgr.addNewObject('V Double Smiley', '1252538689.13gjeon', None, objects['1252538687.73gjeon']) +if objects['1252538689.13gjeon']: + objects['1252538689.13gjeon'].setPos(Point3(6.07152, 0, -0.863791)) + objects['1252538689.13gjeon'].setHpr(VBase3(0, 0, 0)) + objects['1252538689.13gjeon'].setScale(VBase3(1, 1, 1)) + objectMgr.updateObjectColor(1.000000, 1.000000, 1.000000, 1.000000, objects['1252538689.13gjeon']) + objectMgr.updateObjectProperties(objects['1252538689.13gjeon'], {'Distance': 1.0, 'Abc': 'a'}) + +objects['1252539974.19gjeon'] = objectMgr.addNewObject('Smiley', '1252539974.19gjeon', 'models/frowney.egg', objects['1252538689.13gjeon']) +if objects['1252539974.19gjeon']: + objects['1252539974.19gjeon'].setPos(Point3(0.06987, 0, 3.09209)) + objects['1252539974.19gjeon'].setHpr(VBase3(0, 0, 0)) + objects['1252539974.19gjeon'].setScale(VBase3(1, 1, 1)) + objectMgr.updateObjectColor(1.000000, 1.000000, 1.000000, 1.000000, objects['1252539974.19gjeon']) + objectMgr.updateObjectProperties(objects['1252539974.19gjeon'], {'123': 1, 'Abc': 'a', 'Number': 1, 'Happy': True}) + +objects['1252623762.9gjeon'] = objectMgr.addNewObject('Panda', '1252623762.9gjeon', None, None) +if objects['1252623762.9gjeon']: + objects['1252623762.9gjeon'].setPos(Point3(0, 0, 0)) + objects['1252623762.9gjeon'].setHpr(VBase3(0, 0, 0)) + objects['1252623762.9gjeon'].setScale(VBase3(0.005, 0.005, 0.005)) + objectMgr.updateObjectColor(1.000000, 0.000000, 0.000000, 0.517647, objects['1252623762.9gjeon']) + objectMgr.updateObjectProperties(objects['1252623762.9gjeon'], {}) + +if hasattr(base, 'le'): + ui.layerEditorUI.reset() + ui.layerEditorUI.addLayerEntry('Layer1', 1 ) + ui.layerEditorUI.addLayerData(1, '1252538687.73gjeon') diff --git a/direct/src/motiontrail/MotionTrail.py b/direct/src/motiontrail/MotionTrail.py index bf11cf5493..f678b34c7e 100644 --- a/direct/src/motiontrail/MotionTrail.py +++ b/direct/src/motiontrail/MotionTrail.py @@ -48,7 +48,7 @@ class MotionTrail(NodePath, DirectObject): motion_trail_list = [ ] motion_trail_task_name = "motion_trail_task" - global_enable = True + global_enable = True @classmethod def setGlobalEnable (self, enable): @@ -128,7 +128,7 @@ class MotionTrail(NodePath, DirectObject): self.use_nurbs = False self.resolution_distance = 0.5 - + self.cmotion_trail = CMotionTrail ( ) self.cmotion_trail.setGeomNode (self.geom_node) @@ -137,7 +137,7 @@ class MotionTrail(NodePath, DirectObject): self.use_python_version = True else: self.use_python_version = False - + return def delete(self): @@ -146,7 +146,7 @@ class MotionTrail(NodePath, DirectObject): self.cmotion_trail.resetVertexList ( ) self.removeNode() return - + def print_matrix (self, matrix): separator = ' ' print matrix.getCell (0, 0), separator, matrix.getCell (0, 1), separator, matrix.getCell (0, 2), separator, matrix.getCell (0, 3) @@ -162,12 +162,12 @@ class MotionTrail(NodePath, DirectObject): index = 0 while (index < total_motion_trails): motion_trail = MotionTrail.motion_trail_list [index] - - if (MotionTrail.global_enable): + + if (MotionTrail.global_enable): if (motion_trail.use_python_version): # Python version if (motion_trail.active and motion_trail.check_for_update (current_time)): - transform = None + transform = None if (motion_trail.root_node_path != None) and (motion_trail.root_node_path != render): motion_trail.root_node_path.update ( ) @@ -181,7 +181,7 @@ class MotionTrail(NodePath, DirectObject): else: # C++ version if (motion_trail.active and motion_trail.cmotion_trail.checkForUpdate (current_time)): - transform = None + transform = None if (motion_trail.root_node_path != None) and (motion_trail.root_node_path != render): motion_trail.root_node_path.update ( ) @@ -197,9 +197,9 @@ class MotionTrail(NodePath, DirectObject): else: motion_trail.reset_motion_trail() motion_trail.reset_motion_trail_geometry() - + index += 1 - + return Task.cont def add_vertex (self, vertex_id, vertex_function, context): @@ -223,11 +223,11 @@ class MotionTrail(NodePath, DirectObject): self.modified_vertices = True return - + def set_texture (self, texture): self.texture = texture - if (texture): + if (texture): self.geom_node_path.setTexture (texture) # texture.setWrapU(Texture.WMClamp) # texture.setWrapV(Texture.WMClamp) @@ -282,7 +282,7 @@ class MotionTrail(NodePath, DirectObject): vertex_index += 1 self.modified_vertices = False - + return def register_motion_trail (self): @@ -415,7 +415,7 @@ class MotionTrail(NodePath, DirectObject): """ print "total_frames", total_frames - + index = 0; while (index < total_frames): motion_trail_frame = self.frame_list [index] @@ -434,14 +434,14 @@ class MotionTrail(NodePath, DirectObject): if (self.calculate_relative_matrix): inverse_matrix = Mat4 (transform) inverse_matrix.invertInPlace ( ) - + if (self.use_nurbs and (total_frames >= 5)): total_distance = 0.0 vector = Vec3 ( ) nurbs_curve_evaluator_list = [ ] - + total_vertex_segments = self.total_vertices - 1 # create a NurbsCurveEvaluator for each vertex (the starting point for the trail) @@ -452,7 +452,7 @@ class MotionTrail(NodePath, DirectObject): nurbs_curve_evaluator_list = nurbs_curve_evaluator_list + [nurbs_curve_evaluator] index += 1 - # add vertices to each NurbsCurveEvaluator + # add vertices to each NurbsCurveEvaluator segment_index = 0 while (segment_index < total_segments): motion_trail_frame_start = self.frame_list [segment_index] @@ -479,7 +479,7 @@ class MotionTrail(NodePath, DirectObject): nurbs_curve_evaluator = nurbs_curve_evaluator_list [vertex_segement_index] nurbs_curve_evaluator.setVertex (segment_index, v0) - + while (vertex_segement_index < total_vertex_segments): motion_trail_vertex_start = self.vertex_list [vertex_segement_index] @@ -489,7 +489,7 @@ class MotionTrail(NodePath, DirectObject): v3 = end_transform.xform (motion_trail_vertex_end.vertex) nurbs_curve_evaluator = nurbs_curve_evaluator_list [vertex_segement_index + 1] - + nurbs_curve_evaluator.setVertex (segment_index, v1) if (vertex_segement_index == (total_vertex_segments - 1)): @@ -509,13 +509,13 @@ class MotionTrail(NodePath, DirectObject): nurbs_curve_evaluator = nurbs_curve_evaluator_list [index] nurbs_curve_result = nurbs_curve_evaluator.evaluate ( ) nurbs_curve_result_list = nurbs_curve_result_list + [nurbs_curve_result] - + nurbs_start_t = nurbs_curve_result.getStartT() nurbs_end_t = nurbs_curve_result.getEndT() index += 1 - # create quads from NurbsCurveResult + # create quads from NurbsCurveResult total_curve_segments = total_distance / self.resolution_distance if (total_curve_segments < total_segments): total_curve_segments = total_segments; @@ -530,10 +530,10 @@ class MotionTrail(NodePath, DirectObject): if (x < 0.0): x = 0.0 return x - + curve_segment_index = 0.0 while (curve_segment_index < total_curve_segments): - + vertex_segement_index = 0 if (True): @@ -542,7 +542,7 @@ class MotionTrail(NodePath, DirectObject): else: st = curve_segment_index / total_segments et = (curve_segment_index + 1.0) / total_segments - + start_t = st end_t = et @@ -560,7 +560,7 @@ class MotionTrail(NodePath, DirectObject): t0 = Vec2 (one_minus_x (st), motion_trail_vertex_start.v) t2 = Vec2 (one_minus_x (et), motion_trail_vertex_start.v) - + while (vertex_segement_index < total_vertex_segments): motion_trail_vertex_start = self.vertex_list [vertex_segement_index] @@ -582,7 +582,7 @@ class MotionTrail(NodePath, DirectObject): start_nurbs_curve_result.evalPoint (start_nurbs_start_t + (start_delta_t * et), v2); end_nurbs_curve_result.evalPoint (end_nurbs_start_t + (end_delta_t * et), v3); - + # color vertex_end_color = motion_trail_vertex_end.end_color + (motion_trail_vertex_end.start_color - motion_trail_vertex_end.end_color) @@ -607,7 +607,7 @@ class MotionTrail(NodePath, DirectObject): curve_segment_index += 1.0 - else: + else: segment_index = 0 while (segment_index < total_segments): @@ -701,7 +701,7 @@ class MotionTrail(NodePath, DirectObject): if (self.geom_node != None): self.geom_node.removeAllGeoms ( ) return - + def attach_motion_trail (self): self.reset_motion_trail ( ) return diff --git a/direct/src/p3d/DWBPackageInstaller.py b/direct/src/p3d/DWBPackageInstaller.py index 4d32e4d503..c4daa67cb1 100644 --- a/direct/src/p3d/DWBPackageInstaller.py +++ b/direct/src/p3d/DWBPackageInstaller.py @@ -71,7 +71,7 @@ class DWBPackageInstaller(DirectWaitBar, PackageInstaller): if self['perPackage']: self['value'] = progress * self['range'] - + def downloadProgress(self, overallProgress): """ This callback is made repeatedly between downloadStarted() and downloadFinished() to update the current progress through @@ -91,6 +91,6 @@ class DWBPackageInstaller(DirectWaitBar, PackageInstaller): call to downloadStarted(). """ self.hide() - + if self['finished']: self['finished'](success) diff --git a/direct/src/p3d/InstalledPackageData.py b/direct/src/p3d/InstalledPackageData.py index c6ebed3ec1..09ee81cda6 100644 --- a/direct/src/p3d/InstalledPackageData.py +++ b/direct/src/p3d/InstalledPackageData.py @@ -27,4 +27,4 @@ class InstalledPackageData: else: self.displayName = dirnode.pathname.getBasename() - + diff --git a/direct/src/p3d/JavaScript.py b/direct/src/p3d/JavaScript.py index f10ad28d1d..3b6d295032 100644 --- a/direct/src/p3d/JavaScript.py +++ b/direct/src/p3d/JavaScript.py @@ -39,7 +39,7 @@ class ConcreteStruct: are to be passed to the concrete instance. By default, this returns all properties of the object. You can override this to restrict the set of properties that are uploaded. """ - + return self.__dict__.items() class BrowserObject: @@ -93,7 +93,7 @@ class BrowserObject: del kw['needsResponse'] if kw: raise ArgumentError, 'Keyword arguments not supported' - + try: parentObj, attribName = self.__childObject if parentObj: @@ -125,7 +125,7 @@ class BrowserObject: # Cache the method object on the parent so we won't # have to look up the method wrapper again next time. parentObj.__cacheMethod(attribName) - + else: # Call it as a plain function. result = self.__runner.scriptRequest('call', self, value = args, needsResponse = needsResponse) @@ -156,7 +156,7 @@ class BrowserObject: if self.__runner.scriptRequest('has_method', self, propertyName = name): # Yes, so create a method wrapper for it. return self.__cacheMethod(name) - + raise AttributeError(name) if isinstance(value, BrowserObject): @@ -252,7 +252,7 @@ class MethodWrapper: del kw['needsResponse'] if kw: raise ArgumentError, 'Keyword arguments not supported' - + try: parentObj, attribName = self.__childObject # Call it as a method. diff --git a/direct/src/p3d/Packager.py b/direct/src/p3d/Packager.py index e097e8da3c..f7d6855a90 100644 --- a/direct/src/p3d/Packager.py +++ b/direct/src/p3d/Packager.py @@ -397,7 +397,7 @@ class Packager: total = sum([x for x in self.ignoredDirFiles.values()]) self.notify.warning("excluded %s files not marked for inclusion: %s" \ % (total, ", ".join(["'" + ext + "'" for ext in exts]))) - + if not self.host: self.host = self.packager.host @@ -2220,7 +2220,7 @@ class Packager: # ignoring any request to specify a particular download host, # e.g. for testing and development. self.ignoreSetHost = False - + # Set this to true to verbosely log files ignored by dir(). self.verbosePrint = False @@ -2439,12 +2439,12 @@ class Packager: # Files for which warnings should be suppressed when they are # not handled by dir() - self.suppressWarningForExtensions = ['', 'pyc', 'pyo', - 'p3d', 'pdef', + self.suppressWarningForExtensions = ['', 'pyc', 'pyo', + 'p3d', 'pdef', 'c', 'C', 'cxx', 'cpp', 'h', 'H', 'hpp', 'pp', 'I', 'pem', 'p12', 'crt', 'o', 'obj', 'a', 'lib', 'bc', 'll'] - + # System files that should never be packaged. For # case-insensitive filesystems (like Windows and OSX), put the # lowercase filename here. Case-sensitive filesystems should @@ -3677,17 +3677,17 @@ class Packager: self.currentPackage.excludeFile(filename) - def do_includeExtensions(self, executableExtensions = None, extractExtensions = None, - imageExtensions = None, textExtensions = None, + def do_includeExtensions(self, executableExtensions = None, extractExtensions = None, + imageExtensions = None, textExtensions = None, uncompressibleExtensions = None, unprocessedExtensions = None, suppressWarningForExtensions = None): """ Ensure that dir() will include files with the given extensions. The extensions should not have '.' prefixes. - + All except 'suppressWarningForExtensions' allow the given kinds of files to be packaged with their respective semantics (read the source). - - 'suppressWarningForExtensions' lists extensions *expected* to be ignored, + + 'suppressWarningForExtensions' lists extensions *expected* to be ignored, so no warnings will be emitted for them. """ if executableExtensions: @@ -3791,9 +3791,9 @@ class Packager: elif not ext in self.suppressWarningForExtensions: newCount = self.currentPackage.ignoredDirFiles.get(ext, 0) + 1 self.currentPackage.ignoredDirFiles[ext] = newCount - + if self.verbosePrint: - self.notify.warning("ignoring file %s" % filename) + self.notify.warning("ignoring file %s" % filename) def readContentsFile(self): """ Reads the contents.xml file at the beginning of diff --git a/direct/src/p3d/SeqValue.py b/direct/src/p3d/SeqValue.py index 6ae527578d..c146944dfa 100644 --- a/direct/src/p3d/SeqValue.py +++ b/direct/src/p3d/SeqValue.py @@ -37,7 +37,7 @@ class SeqValue: """ Sets the seq from the indicated string of dot-separated integers. Raises ValueError on error. """ assert isinstance(value, types.StringTypes) - + self.value = () if value: value = value.split('.') @@ -84,4 +84,4 @@ class SeqValue: def __str__(self): return 'SeqValue%s' % (repr(self.value)) - + diff --git a/direct/src/p3d/ppackage.py b/direct/src/p3d/ppackage.py index 7ca16fd4f9..cf42ea8403 100755 --- a/direct/src/p3d/ppackage.py +++ b/direct/src/p3d/ppackage.py @@ -130,7 +130,7 @@ Options: -v Emit a warning for any file not recognized by the dir() command (indicating there may be a need for addExtensions(...)). - + -h Display this help """ @@ -202,7 +202,7 @@ for opt, arg in opts: elif opt == '-v': verbosePrint = True - + elif opt == '-h': usage(0) else: diff --git a/direct/src/particles/ParticleEffect.py b/direct/src/particles/ParticleEffect.py index bfd4e0c7c9..c645aea962 100644 --- a/direct/src/particles/ParticleEffect.py +++ b/direct/src/particles/ParticleEffect.py @@ -44,7 +44,7 @@ class ParticleEffect(NodePath): def getName(self): # override NodePath.getName() return self.name - + def reset(self): self.removeAllForces() self.removeAllParticles() @@ -81,7 +81,7 @@ class ParticleEffect(NodePath): for p in self.particlesDict.values(): p.disable() self.fEnabled = 0 - + def isEnabled(self): """ Note: this may be misleading if enable(), disable() not used diff --git a/direct/src/particles/ParticleFloorTest.py b/direct/src/particles/ParticleFloorTest.py index 8bb021eed0..3ee1bce319 100755 --- a/direct/src/particles/ParticleFloorTest.py +++ b/direct/src/particles/ParticleFloorTest.py @@ -8,13 +8,13 @@ from direct.particles import ForceGroup class ParticleFloorTest(NodePath): def __init__(self): NodePath.__init__(self, "particleFloorTest") - + # Sort Order of Particles self.setDepthWrite(0) # Load Particle Effects self.f = ParticleEffect.ParticleEffect() - self.f.reparentTo(self) + self.f.reparentTo(self) self.p0 = Particles.Particles('particles-1') # Particles parameters self.p0.setFactory("PointParticleFactory") @@ -25,7 +25,7 @@ class ParticleFloorTest(NodePath): self.p0.setLitterSize(7) self.p0.setLitterSpread(2) self.p0.setSystemLifespan(0.0000) - #self.p0.setLocalVelocityFlag(1) + #self.p0.setLocalVelocityFlag(1) self.p0.setFloorZ(-1.0) self.p0.setSystemGrowsOlderFlag(0) # Factory parameters @@ -35,7 +35,7 @@ class ParticleFloorTest(NodePath): self.p0.factory.setMassSpread(1.00) self.p0.factory.setTerminalVelocityBase(400.0000) self.p0.factory.setTerminalVelocitySpread(0.0000) - self.f.addParticles(self.p0) + self.f.addParticles(self.p0) if 1: f0 = ForceGroup.ForceGroup('frict') # Force parameters @@ -43,7 +43,7 @@ class ParticleFloorTest(NodePath): force0.setActive(1) f0.addForce(force0) self.f.addForceGroup(f0) - + def start(self): self.f.enable() diff --git a/direct/src/particles/ParticleTest.py b/direct/src/particles/ParticleTest.py index c409a3df9f..7399417b52 100644 --- a/direct/src/particles/ParticleTest.py +++ b/direct/src/particles/ParticleTest.py @@ -1,22 +1,22 @@ if __name__ == "__main__": from direct.directbase.TestStart import * - + from panda3d.physics import LinearVectorForce from panda3d.core import Vec3 import ParticleEffect from direct.tkpanels import ParticlePanel import Particles import ForceGroup - + # Showbase base.enableParticles() - + # ForceGroup fg = ForceGroup.ForceGroup() gravity = LinearVectorForce(Vec3(0.0, 0.0, -10.0)) fg.addForce(gravity) - + # Particles p = Particles.Particles() @@ -26,7 +26,7 @@ if __name__ == "__main__": #pe.setPos(0.0, 5.0, 4.0) pe.addForceGroup(fg) pe.addParticles(p) - + # Particle Panel pp = ParticlePanel.ParticlePanel(pe) diff --git a/direct/src/plugin_installer/make_installer.py b/direct/src/plugin_installer/make_installer.py index 772962348e..0d0f12b0dc 100755 --- a/direct/src/plugin_installer/make_installer.py +++ b/direct/src/plugin_installer/make_installer.py @@ -125,7 +125,7 @@ Description_plist = """ def findExecutable(filename): """ Searches for the named .exe or .dll file along the system PATH and returns its full path if found, or None if not found. """ - + if sys.platform == "win32": for p in os.defpath.split(";") + os.environ["PATH"].split(";"): if os.path.isfile(os.path.join(p, filename)): @@ -135,7 +135,7 @@ def findExecutable(filename): if os.path.isfile(os.path.join(p, filename)): return os.path.join(p, filename) return None - + if not options.nsis: makensis = findExecutable('makensis.exe') @@ -217,7 +217,7 @@ def parseDependenciesUnix(tempFile): """ Reads the indicated temporary file, the output from otool -XL or ldd, to determine the list of dll's this executable file depends on. """ - + lines = open(tempFile, 'rU').readlines() filenames = [] for l in lines: @@ -228,7 +228,7 @@ def addDependencies(path, pathname, file, pluginDependencies, dependentFiles, re """ Checks the named file for DLL dependencies, and adds any appropriate dependencies found into pluginDependencies and dependentFiles. """ - + tempFile = tempfile.mktemp('.txt', 'p3d_') if sys.platform == "darwin": command = 'otool -XL "%s" >"%s"' @@ -308,14 +308,14 @@ def getDllVersion(filename): tempdata.close() os.unlink(tempfile) return ','.join(data.strip().split('.')) - + def makeCabFile(ocx, pluginDependencies): """ Creates an ActiveX CAB file. Windows only. """ ocxFullpath = findExecutable(ocx) cabFilename = os.path.splitext(ocx)[0] + '.cab' - + cabarc = 'cabarc' signcode = 'signcode' if options.mssdk: @@ -345,7 +345,7 @@ def makeCabFile(ocx, pluginDependencies): os.unlink(cabFilename) except OSError: pass - + cmd = '"%s" -s 6144 n "%s"' % (cabarc, cabFilename) for fullpath in fullpaths: cmd += ' "%s"' % (fullpath) @@ -357,7 +357,7 @@ def makeCabFile(ocx, pluginDependencies): if not os.path.exists(cabFilename): print "Couldn't generate %s" % (cabFilename) sys.exit(1) - + print "Successfully generated %s" % (cabFilename) if options.spc and options.pvk: @@ -367,7 +367,7 @@ def makeCabFile(ocx, pluginDependencies): result = subprocess.call(cmd) if result: sys.exit(result) - + def makeInstaller(): # Locate the plugin(s). pluginFiles = {} @@ -430,7 +430,7 @@ def makeInstaller(): # package files works around the problem and doesn't seem to # cause additional problems, so we'll do that. pkgname = 'p3d-setup-%s.pkg' % (options.version) - + if os.path.exists(tmproot): shutil.rmtree(tmproot) if os.path.isfile(pkgname): @@ -449,7 +449,7 @@ def makeInstaller(): shutil.copyfile(pluginFiles[panda3d], dst_panda3d) os.chmod(dst_panda3d, 493) # 0o755 shutil.copytree(pluginFiles[panda3dapp], dst_panda3dapp) - + tmpresdir = tempfile.mktemp('', 'p3d-resources') if os.path.exists(tmpresdir): shutil.rmtree(tmpresdir) @@ -501,7 +501,7 @@ def makeInstaller(): CMD += ' -p "%s"' % (pkgname) CMD += ' -i "%s"' % (infoFilename) CMD += ' -d "%s"' % (descriptionFilename) - + print "" print CMD @@ -520,7 +520,7 @@ def makeInstaller(): if not os.path.exists(pkgname): print "Unable to create %s." % (pkgname) sys.exit(1) - + # Pack the .pkg into a .dmg if not os.path.exists(tmproot): os.makedirs(tmproot) if os.path.isdir(pkgname): @@ -536,7 +536,7 @@ def makeInstaller(): if result: sys.exit(result) shutil.rmtree(tmproot) - + # Compress the .dmg (and make it read-only) if os.path.exists("p3d-setup.dmg"): os.remove("p3d-setup.dmg") @@ -546,7 +546,7 @@ def makeInstaller(): result = subprocess.call(CMD, shell = True) if result: sys.exit(result) - + elif sys.platform == 'win32': # Now build the NSIS command. CMD = "\"" + options.nsis + "\" /V3 " @@ -579,15 +579,15 @@ def makeInstaller(): if options.start: CMD += '/DADD_START_MENU ' - + if options.welcome_image: CMD += '/DMUI_WELCOMEFINISHPAGE_BITMAP="' + options.welcome_image + '" ' CMD += '/DMUI_UNWELCOMEFINISHPAGE_BITMAP="' + options.welcome_image + '" ' if options.install_icon: CMD += '/DINSTALL_ICON="' + options.install_icon + '" ' - CMD += '"' + this_dir + '\\p3d_installer.nsi"' - + CMD += '"' + this_dir + '\\p3d_installer.nsi"' + print "" print CMD print "packing..." diff --git a/direct/src/plugin_npapi/make_osx_bundle.py b/direct/src/plugin_npapi/make_osx_bundle.py index bbfc616962..8d83b35310 100755 --- a/direct/src/plugin_npapi/make_osx_bundle.py +++ b/direct/src/plugin_npapi/make_osx_bundle.py @@ -48,7 +48,7 @@ def makeBundle(startDir): exeFilename.makeDir() resourceFilename = Filename(bundleFilename, 'Contents/Resources/nppanda3d.rsrc') resourceFilename.makeDir() - + # Compile the .r file to an .rsrc file. os.system('/Developer/Tools/Rez -useDF -o %s %s' % ( resourceFilename.toOsSpecific(), Filename(fstartDir, "nppanda3d.r").toOsSpecific())) @@ -94,4 +94,4 @@ if __name__ == '__main__': # We don't need the dmg these days; the installer is better. #buildDmg(startDir) - + diff --git a/direct/src/plugin_standalone/make_osx_bundle.py b/direct/src/plugin_standalone/make_osx_bundle.py index dbeede9d88..20807f6974 100755 --- a/direct/src/plugin_standalone/make_osx_bundle.py +++ b/direct/src/plugin_standalone/make_osx_bundle.py @@ -60,7 +60,7 @@ def makeBundle(startDir): bundleFilename = Filename(rootFilename, 'Panda3D.app') if os.path.exists(bundleFilename.toOsSpecific()): shutil.rmtree(bundleFilename.toOsSpecific()) - + plistFilename = Filename(bundleFilename, 'Contents/Info.plist') plistFilename.makeDir() exeFilename = Filename(bundleFilename, 'Contents/MacOS/panda3d_mac') @@ -94,4 +94,4 @@ if __name__ == '__main__': startDir = os.path.split(sys.argv[0])[0] makeBundle(startDir) - + diff --git a/direct/src/showbase/Audio3DManager.py b/direct/src/showbase/Audio3DManager.py index 28dffc4bd7..270a7e56c4 100644 --- a/direct/src/showbase/Audio3DManager.py +++ b/direct/src/showbase/Audio3DManager.py @@ -252,12 +252,12 @@ class Audio3DManager: """ # Update the positions of all sounds based on the objects # to which they are attached - + # The audio manager is not active so do nothing if hasattr(self.audio_manager, "getActive"): if self.audio_manager.getActive()==0: return Task.cont - + for known_object in self.sound_dict.keys(): tracked_sound = 0 while tracked_sound < len(self.sound_dict[known_object]): @@ -274,11 +274,11 @@ class Audio3DManager: forward = self.root.getRelativeVector(self.listener_target, Vec3.forward()) up = self.root.getRelativeVector(self.listener_target, Vec3.up()) vel = self.getListenerVelocity() - self.audio_manager.audio3dSetListenerAttributes(pos[0], pos[1], pos[2], vel[0], vel[1], vel[2], forward[0], forward[1], forward[2], up[0], up[1], up[2]) + self.audio_manager.audio3dSetListenerAttributes(pos[0], pos[1], pos[2], vel[0], vel[1], vel[2], forward[0], forward[1], forward[2], up[0], up[1], up[2]) else: self.audio_manager.audio3dSetListenerAttributes(0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1) return Task.cont - + def disable(self): """ Detaches any existing sounds and removes the update task @@ -288,4 +288,4 @@ class Audio3DManager: for object in self.sound_dict.keys(): for sound in self.sound_dict[object]: self.detachSound(sound) - + diff --git a/direct/src/showbase/BufferViewer.py b/direct/src/showbase/BufferViewer.py index 0b0f5c3356..5490d1dd92 100644 --- a/direct/src/showbase/BufferViewer.py +++ b/direct/src/showbase/BufferViewer.py @@ -365,10 +365,10 @@ class BufferViewer(DirectObject): if (v_sizey < sizey) or (v_sizex < sizex): sizey = v_sizey sizex = v_sizex - + adjustment = 2 h_sizex = float (base.win.getXSize() - adjustment) / float (cols) - + h_sizex -= bordersize if (h_sizex < 1.0): h_sizex = 1.0 @@ -384,7 +384,7 @@ class BufferViewer(DirectObject): if (sizey == 0): sizey = (sizex*aspecty) // aspectx # Convert from pixels to render2d-units. - fsizex = (2.0 * sizex) / float(base.win.getXSize()) + fsizex = (2.0 * sizex) / float(base.win.getXSize()) fsizey = (2.0 * sizey) / float(base.win.getYSize()) fpixelx = 2.0 / float(base.win.getXSize()) fpixely = 2.0 / float(base.win.getYSize()) @@ -416,9 +416,9 @@ class BufferViewer(DirectObject): index = c + r*cols if (index < ncards): index = (index + self.cardindex) % len(cards) - + posx = dirx * (1.0 - ((c + 0.5) * (fsizex + fpixelx * bordersize))) - (fpixelx * dirx) - posy = diry * (1.0 - ((r + 0.5) * (fsizey + fpixely * bordersize))) - (fpixely * diry) + posy = diry * (1.0 - ((r + 0.5) * (fsizey + fpixely * bordersize))) - (fpixely * diry) placer = NodePath("card-structure") placer.setPos(Point3.rfu(posx, 0, posy)) placer.setScale(Vec3.rfu(fsizex*0.5, 1.0, fsizey*0.5)) diff --git a/direct/src/showbase/BulletinBoard.py b/direct/src/showbase/BulletinBoard.py index 8b4a8500c7..52265a1334 100755 --- a/direct/src/showbase/BulletinBoard.py +++ b/direct/src/showbase/BulletinBoard.py @@ -38,7 +38,7 @@ class BulletinBoard: BulletinBoard.notify.info('update: posting %s' % (postName)) self._dict[postName] = value messenger.send(self.getEvent(postName)) - + def remove(self, postName): if postName in self._dict: del self._dict[postName] diff --git a/direct/src/showbase/ContainerLeakDetector.py b/direct/src/showbase/ContainerLeakDetector.py index 7180ffe543..580656d65e 100755 --- a/direct/src/showbase/ContainerLeakDetector.py +++ b/direct/src/showbase/ContainerLeakDetector.py @@ -280,7 +280,7 @@ class ObjectRef: # TODO: check that this is still the object we originally pointed to yield self._getContainerByEval(evalStr, curObj=curObj) - + def getEvalStrGen(self, getInstance=False): str = '' prevIndirection = None @@ -392,7 +392,7 @@ class FindContainers(Job): return len(startObj) except: return 1 - + def _isDeadEnd(self, obj, objName=None): if type(obj) in (types.BooleanType, types.BuiltinFunctionType, types.BuiltinMethodType, types.ComplexType, @@ -667,7 +667,7 @@ class CheckContainers(Job): Job to check container sizes and find potential leaks; sub-job of ContainerLeakDetector """ ReprItems = 5 - + def __init__(self, name, leakDetector, index): Job.__init__(self, name) self._leakDetector = leakDetector @@ -681,7 +681,7 @@ class CheckContainers(Job): def getPriority(self): return Job.Priorities.Normal - + def run(self): try: self._leakDetector._index2containerId2len[self._index] = {} @@ -826,10 +826,10 @@ class FPTObjsOfType(Job): def _handleLDDestroy(self): self.destroy() - + def getPriority(self): return Job.Priorities.High - + def run(self): ids = self._leakDetector.getContainerIds() try: @@ -886,10 +886,10 @@ class FPTObjsNamed(Job): def _handleLDDestroy(self): self.destroy() - + def getPriority(self): return Job.Priorities.High - + def run(self): ids = self._leakDetector.getContainerIds() try: @@ -937,7 +937,7 @@ class PruneObjectRefs(Job): def getPriority(self): return Job.Priorities.Normal - + def run(self): try: ids = self._leakDetector.getContainerIds() @@ -1039,7 +1039,7 @@ class ContainerLeakDetector(Job): def _getDestroyEvent(self): # sent when leak detector is about to be destroyed return 'cldDestroy-%s' % self._serialNum - + def getLeakEvent(self): # sent when a leak is detected # passes description string as argument @@ -1094,12 +1094,12 @@ class ContainerLeakDetector(Job): j = FPTObjsOfType(name, self, ot, doneCallback) jobMgr.add(j) return j - + def getPathsToContainersNamed(self, name, on, doneCallback=None): j = FPTObjsNamed(name, self, on, doneCallback) jobMgr.add(j) return j - + def _scheduleNextLeakCheck(self): taskMgr.doMethodLater(self._nextCheckDelay, self._checkForLeaks, self._getCheckTaskName()) diff --git a/direct/src/showbase/ContainerReport.py b/direct/src/showbase/ContainerReport.py index fb5b1a4de1..fd80977f92 100755 --- a/direct/src/showbase/ContainerReport.py +++ b/direct/src/showbase/ContainerReport.py @@ -86,7 +86,7 @@ class ContainerReport(Job): if type(parentObj) in (types.StringType, types.UnicodeType): continue - + if type(parentObj) in (types.ModuleType, types.InstanceType): child = parentObj.__dict__ if self._examine(child): @@ -176,7 +176,7 @@ class ContainerReport(Job): self.printingEnd() yield Job.Done - + def _enqueueContainer(self, obj, pathStr=None): # call this to add a container that should be examined before any (other) direct # children of __builtins__ diff --git a/direct/src/showbase/CountedResource.py b/direct/src/showbase/CountedResource.py index d966cf9b3b..1a89c663ff 100755 --- a/direct/src/showbase/CountedResource.py +++ b/direct/src/showbase/CountedResource.py @@ -5,7 +5,7 @@ class CountedResource(object): counting semantics in order to model shared resources. RAIA stands for "Resource Allocation Is Acquisition" (see 'Effective C++' for a more in-depth explanation) - + When a resource is needed, create an appropriate CountedResource object. If the resource is already available (meaning another CountedResource object of the same type already exists), no action @@ -24,7 +24,7 @@ class CountedResource(object): If you define your own __init__ and __del__ methods, you MUST be sure to call down to the ones defined in CountedResource. - + Notes: Until we figure out a way to wrangle a bit more functionality out of Python, you MUST NOT inherit from any class that has @@ -36,14 +36,14 @@ class CountedResource(object): this file to see how to accomplish this (This is useful for dependent resources). """ - + @classmethod def incrementCounter(cls): try: cls.RESOURCE_COUNTER += 1 except AttributeError: cls.RESOURCE_COUNTER = 1 - + if cls.RESOURCE_COUNTER == 1: cls.acquire() @@ -60,15 +60,15 @@ class CountedResource(object): @classmethod def getCount(cls): return cls.RESOURCE_COUNTER - + @classmethod def acquire(cls): pass - + @classmethod def release(cls): pass - + def __init__(self): cls = type(self) cls.RESOURCE_COUNTER_INIT_FAILED = True @@ -82,7 +82,7 @@ class CountedResource(object): def __del__(self): self.decrementCounter() - + if __debug__ and __name__ == '__main__': class MouseResource(CountedResource): """ @@ -98,7 +98,7 @@ if __debug__ and __name__ == '__main__': # Now acquire the resource this class is # managing. print '-- Acquire Mouse' - + @classmethod def release(cls): # First, release the resource this class is @@ -110,7 +110,7 @@ if __debug__ and __name__ == '__main__': # the future, so do it now for good measure. super(MouseResource, cls).release() - + def __init__(self): super(MouseResource, self).__init__() @@ -129,7 +129,7 @@ if __debug__ and __name__ == '__main__': def acquire(cls): super(CursorResource, cls).acquire() print '-- Acquire Cursor' - + @classmethod def release(cls): print '-- Release Cursor' @@ -145,13 +145,13 @@ if __debug__ and __name__ == '__main__': # Call the super-classes __init__() # after all required resources are # referenced. - super(CursorResource, self).__init__() - + super(CursorResource, self).__init__() + def __del__(self): # Free up the most dependent resource # first, the one this class is managing. super(CursorResource, self).__del__() - + # Now unlink any required resources. del self.__mouseResource @@ -160,17 +160,17 @@ if __debug__ and __name__ == '__main__': def acquire(cls): super(InvalidResource, cls).acquire() print '-- Acquire Invalid' - + @classmethod def release(cls): print '-- Release Invalid' super(InvalidResource, cls).release() - + print '\nAllocate Mouse' m = MouseResource() print 'Free up Mouse' del m - + print '\nAllocate Cursor' c = CursorResource() print 'Free up Cursor' @@ -183,7 +183,7 @@ if __debug__ and __name__ == '__main__': del c print 'Free up Mouse' del m - + print '\nAllocate Mouse then Cursor' m = MouseResource() c = CursorResource() @@ -191,7 +191,7 @@ if __debug__ and __name__ == '__main__': del m print 'Free up Cursor' del c - + print '\nAllocate Cursor then Mouse' c = CursorResource() m = MouseResource() @@ -199,13 +199,13 @@ if __debug__ and __name__ == '__main__': del m print 'Free up Cursor' del c - + print '\nAllocate Cursor then Mouse' c = CursorResource() m = MouseResource() print 'Free up Cursor' del c - + # example of an invalid subclass try: print '\nAllocate Invalid' @@ -223,7 +223,7 @@ if __debug__ and __name__ == '__main__': c = CursorResource() print 'Cursor will be freed on function exit' - + demoFunc() diff --git a/direct/src/showbase/DirectObject.py b/direct/src/showbase/DirectObject.py index 62cf20d344..f881d65b5a 100644 --- a/direct/src/showbase/DirectObject.py +++ b/direct/src/showbase/DirectObject.py @@ -48,14 +48,14 @@ class DirectObject: kwargs['owner']=self task = taskMgr.add(*args, **kwargs) return task - + def doMethodLater(self, *args, **kwargs): if(not hasattr(self,"_taskList")): self._taskList ={} - kwargs['owner']=self + kwargs['owner']=self task = taskMgr.doMethodLater(*args, **kwargs) return task - + def removeTask(self, taskOrName): if type(taskOrName) == type(''): # we must use a copy, since task.remove will modify self._taskList @@ -63,7 +63,7 @@ class DirectObject: taskListValues = self._taskList.values() for task in taskListValues: if task.name == taskOrName: - task.remove() + task.remove() else: taskOrName.remove() @@ -76,15 +76,15 @@ class DirectObject: self._taskList[task.id] = task def _clearTask(self, task): - del self._taskList[task.id] - + del self._taskList[task.id] + def detectLeaks(self): if not __dev__: return - + # call this after the DirectObject instance has been destroyed # if it's leaking, will notify user - + # make sure we're not still listening for messenger events events = messenger.getAllAccepting(self) # make sure we're not leaking tasks diff --git a/direct/src/showbase/DistancePhasedNode.py b/direct/src/showbase/DistancePhasedNode.py index 368209806e..b94e31d028 100755 --- a/direct/src/showbase/DistancePhasedNode.py +++ b/direct/src/showbase/DistancePhasedNode.py @@ -6,7 +6,7 @@ from PhasedObject import PhasedObject class DistancePhasedNode(PhasedObject, DirectObject, NodePath): """ This class defines a PhasedObject,NodePath object that will handle the phasing - of an object in the scene graph according to its distance from some + of an object in the scene graph according to its distance from some other collider object(such as an avatar). Since it's a NodePath, you can parent it to another object in the @@ -38,8 +38,8 @@ class DistancePhasedNode(PhasedObject, DirectObject, NodePath): that this will only be used after a reset or phase change in order to fully transition to the correct phase in a single pass. Most of the time, it will be reacting to events from the main - collision traverser. - + collision traverser. + IMPORTANT!: The following only applies when autoCleanup == True: If you unload the last phase, by either calling cleanup() or by exitting the last phase's distance, @@ -53,7 +53,7 @@ class DistancePhasedNode(PhasedObject, DirectObject, NodePath): notify = directNotify.newCategory("DistancePhasedObject") __InstanceSequence = 0 __InstanceDeque = [] - + @staticmethod def __allocateId(): """ @@ -98,7 +98,7 @@ class DistancePhasedNode(PhasedObject, DirectObject, NodePath): self.cTrav = base.cTrav self.fromCollideNode = fromCollideNode self._colSpheres = [] - + self.reset() def __del__(self): @@ -115,20 +115,20 @@ class DistancePhasedNode(PhasedObject, DirectObject, NodePath): def __str__(self): return '%s in phase \'%s\'' % (NodePath.__str__(self), self.getPhase()) - + def cleanup(self): """ Disables all collisions. Ignores all owned event listeners. - Unloads all unloaded phases. + Unloads all unloaded phases. """ self.__disableCollisions(cleanup = True) for sphere in self._colSpheres: sphere.remove() self._colSpheres = [] PhasedObject.cleanup(self) - + def setPhaseCollideMask(self, mask): """ Sets the intoCollideMasks for our collision spheres. @@ -136,14 +136,14 @@ class DistancePhasedNode(PhasedObject, DirectObject, NodePath): self.phaseCollideMask = mask for sphere in self._colSpheres: self.colSphere.node().setIntoCollideMask(self.phaseCollideMask) - + def reset(self): """ Unloads all loaded phases and puts the phase node in the startup state is if it had just been initialized. """ self.cleanup() - self.__oneTimeCollide() + self.__oneTimeCollide() for name, dist in self.phaseParamList: cSphere = CollisionSphere(0.0, 0.0, 0.0, dist) cSphere.setTangible(0) @@ -164,7 +164,7 @@ class DistancePhasedNode(PhasedObject, DirectObject, NodePath): self.cTrav.addCollider(self.fromCollideNode,cHandler) self.__enableCollisions(-1) - + def setPhase(self, aPhase): """ See PhasedObject.setPhase() @@ -173,18 +173,18 @@ class DistancePhasedNode(PhasedObject, DirectObject, NodePath): PhasedObject.setPhase(self, aPhase) self.__disableCollisions() self.__enableCollisions(phase) - + if phase == -1 and self.autoCleanup: self.cleanup() else: self.__oneTimeCollide() - + def __getEnterEvent(self, phaseName): return '%sPhaseNode%s-%d' % (self.enterPrefix, phaseName, self.__id) def __getExitEvent(self, phaseName): return '%sPhaseNode%s-%d' % (self.exitPrefix, phaseName, self.__id) - + def __enableCollisions(self, phase): """ Turns on collisions for the spheres bounding this @@ -222,7 +222,7 @@ class DistancePhasedNode(PhasedObject, DirectObject, NodePath): if x > 0 or not self.autoCleanup or cleanup: sphere.stash() self.ignore(self.__getExitEvent(phaseName)) - + def __handleEnterEvent(self, phaseName, cEntry): self.setPhase(phaseName) @@ -248,7 +248,7 @@ class DistancePhasedNode(PhasedObject, DirectObject, NodePath): # Only traverse ourself self.cTrav.traverse(self) base.eventMgr.doEvents() - + class BufferedDistancePhasedNode(DistancePhasedNode): """ This class is similar to DistancePhasedNode except you can also @@ -314,7 +314,7 @@ class BufferedDistancePhasedNode(DistancePhasedNode): sphere.node().modifySolid(0).setRadius(self.bufferParamList[x+phase+1][1][0]) sphere.node().markInternalBoundsStale() - + if __debug__ and 0: cSphere = CollisionSphere(0,0,0,0.1) cNode = CollisionNode('camCol') @@ -323,13 +323,13 @@ if __debug__ and 0: cNodePath.reparentTo(base.cam) # cNodePath.show() # cNodePath.setPos(25,0,0) - + base.cTrav = CollisionTraverser() - + eventHandler = CollisionHandlerEvent() eventHandler.addInPattern('enter%in') eventHandler.addOutPattern('exit%in') - + # messenger.toggleVerbose() base.cTrav.addCollider(cNodePath,eventHandler) diff --git a/direct/src/showbase/EventGroup.py b/direct/src/showbase/EventGroup.py index 4a80976194..baf26193f4 100755 --- a/direct/src/showbase/EventGroup.py +++ b/direct/src/showbase/EventGroup.py @@ -20,7 +20,7 @@ class EventGroup(DirectObject.DirectObject): generated and is available as EventGroup.getDoneEvent(). Examples: - + # waits for gotRed and gotBlue, then sends out 'gotColors' EventGroup('getRedAndBlue', ('gotRed', 'gotBlue'), doneEvent='gotColors') @@ -100,7 +100,7 @@ class EventGroup(DirectObject.DirectObject): self._completed = True messenger.send(self._doneEvent) self.destroy() - + def __repr__(self): return '%s(\'%s\', %s, doneEvent=\'%s\') # completed=%s' % ( self.__class__.__name__, diff --git a/direct/src/showbase/EventManager.py b/direct/src/showbase/EventManager.py index 367d24c051..2443c74b5a 100644 --- a/direct/src/showbase/EventManager.py +++ b/direct/src/showbase/EventManager.py @@ -15,7 +15,7 @@ class EventManager: # delayed import, since this is imported by the Toontown Launcher # before the complete PandaModules have been downloaded. PStatCollector = None - + def __init__(self, eventQueue = None): """ Create a C++ event queue and handler @@ -73,7 +73,7 @@ class EventManager: # Must be some user defined type, return the ptr # which will be downcast to that type. return eventParameter.getPtr() - + def processEvent(self, event): """ Process a C++ event @@ -97,7 +97,7 @@ class EventManager: # ************************************************************** # ******** Duplicate any changes in processEventPstats ********* # ************************************************************** - # Send the event, we used to send it with the event + # Send the event, we used to send it with the event # name as a parameter, but now you can use extraArgs for that if paramList: messenger.send(eventName, paramList) @@ -106,7 +106,7 @@ class EventManager: # Also send the event down into C++ land if self.eventHandler: self.eventHandler.dispatchEvent(event) - + else: # An unnamed event from C++ is probably a bad thing EventManager.notify.warning('unnamed event in processEvent') @@ -131,7 +131,7 @@ class EventManager: if (EventManager.notify.getDebug() and eventName != 'NewFrame'): EventManager.notify.debug('received C++ event named: ' + eventName + ' parameters: ' + repr(paramList)) - # Send the event, we used to send it with the event + # Send the event, we used to send it with the event # name as a parameter, but now you can use extraArgs for that # ******************************************************** # ******** Duplicate any changes in processEvent ********* @@ -164,7 +164,7 @@ class EventManager: if self.eventHandler: cppPstatCollector.stop() pstatCollector.stop() - + else: # An unnamed event from C++ is probably a bad thing EventManager.notify.warning('unnamed event in processEvent') diff --git a/direct/src/showbase/Factory.py b/direct/src/showbase/Factory.py index ff25dc75bd..fcf9301976 100755 --- a/direct/src/showbase/Factory.py +++ b/direct/src/showbase/Factory.py @@ -8,11 +8,11 @@ class Factory: """This class manages a list of object types and their corresponding constructors. Objects may be created on-demand from their type. Object types may be any hashable piece of unique data (such as a string). - + This class is intended to be derived from. Subclasses should call self._registerTypes to set up type constructors.""" notify = directNotify.newCategory('Factory') - + def __init__(self): self._type2ctor = {} @@ -27,7 +27,7 @@ class Factory: def _registerTypes(self, type2ctor): for type, ctor in type2ctor.items(): self._registerType(type, ctor) - + def nullCtor(self, *args, **kwArgs): return None - + diff --git a/direct/src/showbase/FindCtaPaths.py b/direct/src/showbase/FindCtaPaths.py index c2f341544f..74d63b9617 100755 --- a/direct/src/showbase/FindCtaPaths.py +++ b/direct/src/showbase/FindCtaPaths.py @@ -32,7 +32,7 @@ def deCygwinify(path): path = os.path.normpath(pandaRoot + path) return path - + def getPaths(): """ Add to sys.path the appropriate director(ies) to search for the @@ -50,7 +50,7 @@ def getPaths(): # parent directory of each one on sys.path. In many cases, # these will all be siblings, so we filter out duplicate # parent directories. - + print 'Appending to sys.path based on $CTPROJS:' # First, get the list of packages, then reverse the list to @@ -64,7 +64,7 @@ def getPaths(): # Now walk through the packages and figure out the parent of # each referenced directory. - + parents = [] for package in packages: tree = os.getenv(package) @@ -77,7 +77,7 @@ def getPaths(): parent, base = os.path.split(tree) if base != package.lower(): print " Warning: $%s refers to a directory named %s (instead of %s)" % (package, base, package.lower()) - + if parent not in parents: parents.append(parent) @@ -97,6 +97,6 @@ def getPaths(): print " %s" % (parent) if parent not in sys.path: sys.path.append(parent) - + getPaths() diff --git a/direct/src/showbase/Finder.py b/direct/src/showbase/Finder.py index 4c81b64b99..b3b2031633 100644 --- a/direct/src/showbase/Finder.py +++ b/direct/src/showbase/Finder.py @@ -80,7 +80,7 @@ def rebindClass(filename): # not our temp one from the execfile. This will help us preserve # class variables and other state on the original class. realNameSpace[className] = realClass - + # Remove the temp file we made file.close() os.remove(filename) @@ -91,7 +91,7 @@ def rebindClass(filename): def copyFuncs(fromClass, toClass): replaceFuncList = [] newFuncList = [] - + # Copy the functions from fromClass into toClass dictionary for funcName, newFunc in fromClass.__dict__.items(): # Filter out for functions @@ -154,7 +154,7 @@ def replaceMessengerFunc(replaceFuncList): messenger except: return - for oldFunc, funcName, newFunc in replaceFuncList: + for oldFunc, funcName, newFunc in replaceFuncList: res = messenger.replaceMethod(oldFunc, newFunc) if res: print ('replaced %s messenger function(s): %s' % (res, funcName)) @@ -164,7 +164,7 @@ def replaceTaskMgrFunc(replaceFuncList): taskMgr except: return - for oldFunc, funcName, newFunc in replaceFuncList: + for oldFunc, funcName, newFunc in replaceFuncList: if taskMgr.replaceMethod(oldFunc, newFunc): print ('replaced taskMgr function: %s' % funcName) @@ -186,7 +186,7 @@ def replaceCRFunc(replaceFuncList): # I throw in the isFake check. I still think the fake cr should be eliminated. if hasattr(base.cr,'isFake'): return - for oldFunc, funcName, newFunc in replaceFuncList: + for oldFunc, funcName, newFunc in replaceFuncList: if base.cr.replaceMethod(oldFunc, newFunc): print ('replaced DistributedObject function: %s' % funcName) @@ -195,7 +195,7 @@ def replaceAIRFunc(replaceFuncList): simbase.air except: return - for oldFunc, funcName, newFunc in replaceFuncList: + for oldFunc, funcName, newFunc in replaceFuncList: if simbase.air.replaceMethod(oldFunc, newFunc): print ('replaced DistributedObject function: %s' % funcName) @@ -205,7 +205,7 @@ def replaceIvalFunc(replaceFuncList): if not sys.modules.get('base.direct.interval.IntervalManager'): return from direct.interval.FunctionInterval import FunctionInterval - for oldFunc, funcName, newFunc in replaceFuncList: + for oldFunc, funcName, newFunc in replaceFuncList: res = FunctionInterval.replaceMethod(oldFunc, newFunc) if res: print ('replaced %s interval function(s): %s' % (res, funcName)) diff --git a/direct/src/showbase/GarbageReport.py b/direct/src/showbase/GarbageReport.py index c04fb42367..72dcaf13c7 100755 --- a/direct/src/showbase/GarbageReport.py +++ b/direct/src/showbase/GarbageReport.py @@ -165,7 +165,7 @@ class GarbageReport(Job): yield None for result in self._getReferents(self.garbage[i]): yield None - byNum, byRef = result + byNum, byRef = result self.referentsByNumber[i] = byNum self.referentsByReference[i] = byRef @@ -426,7 +426,7 @@ class GarbageReport(Job): desc2num.setdefault(cycleBySyntax, 0) desc2num[cycleBySyntax] += 1 return desc2num - + def getGarbage(self): return self.garbage diff --git a/direct/src/showbase/Job.py b/direct/src/showbase/Job.py index 03695a84bd..4eb511d9a8 100755 --- a/direct/src/showbase/Job.py +++ b/direct/src/showbase/Job.py @@ -17,7 +17,7 @@ class Job(DirectObject): # with priority of 100. Priorities = ScratchPad(Min=1, Low=100, Normal=1000, High=10000) _SerialGen = SerialNumGen() - + def __init__(self, name): self._name = name self._generator = None diff --git a/direct/src/showbase/JobManager.py b/direct/src/showbase/JobManager.py index 6e5ca10742..3474b42f18 100755 --- a/direct/src/showbase/JobManager.py +++ b/direct/src/showbase/JobManager.py @@ -64,7 +64,7 @@ class JobManager: elif pri > self._highestPriority: self._highestPriority = pri self.notify.debug('added job: %s' % job.getJobName()) - + def remove(self, job): jobId = job._getJobId() # look up the job's priority @@ -213,7 +213,7 @@ class JobManager: if __debug__: job._pstats.stop() break - + if len(self._pri2jobId2job) == 0: # there's nothing left to do, all the jobs are done! break diff --git a/direct/src/showbase/LeakDetectors.py b/direct/src/showbase/LeakDetectors.py index 0ceadf40bb..92bc944fc8 100755 --- a/direct/src/showbase/LeakDetectors.py +++ b/direct/src/showbase/LeakDetectors.py @@ -136,7 +136,7 @@ class TaskLeakDetectorBase: for i in xrange(10): taskName = taskName.replace('%s' % i, '') return taskName - + class _TaskNamePatternLeakDetector(LeakDetector, TaskLeakDetectorBase): # tracks the number of each individual task type # e.g. are we leaking 'examine-' tasks @@ -280,7 +280,7 @@ class MessageTypesLeakDetector(LeakDetector, MessageLeakDetectorBase): jobMgr.add(self._createJob) # are we leaking message types? return len(self._msgName2detector) - + class _MessageListenerTypeLeakDetector(LeakDetector): # tracks the number of each object type that is listening for events def __init__(self, typeName): diff --git a/direct/src/showbase/Loader.py b/direct/src/showbase/Loader.py index adee7fbe2b..a1743ee8a1 100644 --- a/direct/src/showbase/Loader.py +++ b/direct/src/showbase/Loader.py @@ -20,7 +20,7 @@ class Loader(DirectObject): """ notify = directNotify.newCategory("Loader") loaderIndex = 0 - + class Callback: def __init__(self, numObjects, gotList, callback, extraArgs): self.objects = [None] * numObjects @@ -113,9 +113,9 @@ class Loader(DirectObject): support, the asynchronous interface still exists and still behaves exactly as described, except that loadModel() might not return immediately. - + """ - + assert Loader.notify.debug("Loading model: %s" % (modelPath)) if loaderOptions == None: loaderOptions = LoaderOptions() @@ -151,12 +151,12 @@ class Loader(DirectObject): # Assume we were given a list of model pathnames. modelList = modelPath gotList = True - + if callback is None: # We got no callback, so it's a synchronous load. result = [] - for modelPath in modelList: + for modelPath in modelList: node = self.loader.loadSync(Filename(modelPath), loaderOptions) if (node != None): nodePath = NodePath(node) @@ -179,7 +179,7 @@ class Loader(DirectObject): # load. We'll return immediately, but when all of the # requested models have been loaded, we'll invoke the # callback (passing it the models on the parameter list). - + cb = Loader.Callback(len(modelList), gotList, callback, extraArgs) i=0 for modelPath in modelList: @@ -197,7 +197,7 @@ class Loader(DirectObject): """Cancels an aysynchronous loading or flatten request issued earlier. The callback associated with the request will not be called after cancelRequest() has been performed. """ - + if not cb.cancelled: cb.cancelled = True for request in cb.requests: @@ -208,7 +208,7 @@ class Loader(DirectObject): """ Returns true if an asynchronous loading or flatten request issued earlier is still pending, or false if it has completed or been cancelled. """ - + return bool(cb.requests) def loadModelOnce(self, modelPath): @@ -289,7 +289,7 @@ class Loader(DirectObject): assert Loader.notify.debug("Unloading model: %s" % (modelNode.getFullpath())) ModelPool.releaseModel(modelNode) - def saveModel(self, modelPath, node, loaderOptions = None, + def saveModel(self, modelPath, node, loaderOptions = None, callback = None, extraArgs = [], priority = None): """ Saves the model (a NodePath or PandaNode) to the indicated filename path. Returns true on success, false on failure. If @@ -344,7 +344,7 @@ class Loader(DirectObject): # save. We'll return immediately, but when all of the # requested models have been saved, we'll invoke the # callback (passing it the models on the parameter list). - + cb = Loader.Callback(len(modelList), gotList, callback, extraArgs) i=0 for modelPath, node in modelList: @@ -357,7 +357,7 @@ class Loader(DirectObject): self.loader.saveAsync(request) cb.requests[request] = True return cb - + # font loading funcs def loadFont(self, modelPath, @@ -490,7 +490,7 @@ class Loader(DirectObject): parameters do not apply, though pixelsPerUnit still does apply and roughly controls the tightness of the curve approximation (and the number of vertices generated). - + """ assert Loader.notify.debug("Loading font: %s" % (modelPath)) if phaseChecker: @@ -628,7 +628,7 @@ class Loader(DirectObject): texture.setMagfilter(magfilter) if anisotropicDegree is not None: texture.setAnisotropicDegree(anisotropicDegree) - + return texture def load3DTexture(self, texturePattern, readMipmaps = False, okMissing = False, @@ -766,12 +766,12 @@ class Loader(DirectObject): load the sound file, but this distinction allows the sound effects and/or the music files to be adjusted as a group, independently of the other group.""" - + # showbase-created sfxManager should always be at front of list if(self.base.sfxManagerList): return self.loadSound(self.base.sfxManagerList[0], *args, **kw) return None - + def loadMusic(self, *args, **kw): """Loads one or more sound files, specifically designated as a "music" file (that is, uses the musicManager to load the @@ -784,7 +784,7 @@ class Loader(DirectObject): return self.loadSound(self.base.musicManager, *args, **kw) else: return None - + def loadSound(self, manager, soundPath, positional = False, callback = None, extraArgs = []): @@ -794,7 +794,7 @@ class Loader(DirectObject): callback is specified, the loading happens in the background, just as in loadModel(); otherwise, the loading happens before loadSound() returns.""" - + if isinstance(soundPath, types.StringTypes) or \ isinstance(soundPath, Filename): # We were given a single sound pathname. @@ -827,7 +827,7 @@ class Loader(DirectObject): # load. We'll return immediately, but when all of the # requested sounds have been loaded, we'll invoke the # callback (passing it the sounds on the parameter list). - + cb = Loader.Callback(len(soundList), gotList, callback, extraArgs) for i in range(len(soundList)): soundPath = soundList[i] @@ -878,7 +878,7 @@ class Loader(DirectObject): If a callback is specified, then it is called after the operation is finished, receiving the flattened model (or a list of flattened models).""" - + if isinstance(model, NodePath): # We were given a single model. modelList = [model] @@ -904,7 +904,7 @@ class Loader(DirectObject): cb.requests[request] = True return cb - def __asyncFlattenDone(self, models, + def __asyncFlattenDone(self, models, gotList, callback, origModelList, extraArgs): """ The asynchronous flatten operation has completed; quietly drop in the new models. """ diff --git a/direct/src/showbase/MirrorDemo.py b/direct/src/showbase/MirrorDemo.py index ac49ee307a..f72142b634 100755 --- a/direct/src/showbase/MirrorDemo.py +++ b/direct/src/showbase/MirrorDemo.py @@ -40,7 +40,7 @@ def setupMirror(name, width, height, rootCamera = None): cm.setFrame(width / 2.0, -width / 2.0, -height / 2.0, height / 2.0) cm.setHasUvs(1) card = root.attachNewNode(cm.generate()) - + # Create a PlaneNode to represent the mirror's position, for # computing where the mirror's camera belongs each frame. plane = Plane(Vec3(0, 1, 0), Point3(0, 0, 0)) @@ -95,7 +95,7 @@ def setupMirror(name, width, height, rootCamera = None): ll = cameraNP.getRelativePoint(card, Point3(-width / 2.0, 0, -height / 2.0)) lr = cameraNP.getRelativePoint(card, Point3(width / 2.0, 0, -height / 2.0)) lens.setFrustumFromCorners(ul, ur, ll, lr, Lens.FCCameraPlane | Lens.FCOffAxis | Lens.FCAspectRatio) - + return Task.cont # Add it with a fairly high priority to make it happen late in the @@ -108,7 +108,7 @@ def setupMirror(name, width, height, rootCamera = None): card.setTexture(buffer.getTexture()) return root - + def showFrustum(np): # Utility function to reveal the frustum for a particular camera. cameraNP = np.find('**/+Camera') @@ -117,4 +117,4 @@ def showFrustum(np): geomNode = GeomNode('frustum') geomNode.addGeom(lens.makeGeometry()) cameraNP.attachNewNode(geomNode) - + diff --git a/direct/src/showbase/ObjectReport.py b/direct/src/showbase/ObjectReport.py index c0200ae285..084557f4b1 100755 --- a/direct/src/showbase/ObjectReport.py +++ b/direct/src/showbase/ObjectReport.py @@ -189,4 +189,4 @@ class ObjectReport: stateStack.push((adj, None, 0)) continue """ - + diff --git a/direct/src/showbase/OnScreenDebug.py b/direct/src/showbase/OnScreenDebug.py index addd59f3ad..dc7c819638 100755 --- a/direct/src/showbase/OnScreenDebug.py +++ b/direct/src/showbase/OnScreenDebug.py @@ -19,7 +19,7 @@ class OnScreenDebug: def load(self): if self.onScreenText: return - + fontPath = config.GetString("on-screen-debug-font", "cmtt12") fontScale = config.GetFloat("on-screen-debug-font-scale", 0.05) @@ -31,7 +31,7 @@ class OnScreenDebug: bgColor = color[config.GetString("on-screen-debug-bg-color", "black")] fgColor.setW(config.GetFloat("on-screen-debug-fg-alpha", 0.85)) bgColor.setW(config.GetFloat("on-screen-debug-bg-alpha", 0.85)) - + font = loader.loadFont(fontPath) if not font.isValid(): print "failed to load OnScreenDebug font", fontPath @@ -57,7 +57,7 @@ class OnScreenDebug: #isNew = " is" isNew = "=" else: - # This data is not for the current + # This data is not for the current # frame (key roughly equals value): #isNew = "was" isNew = "~" diff --git a/direct/src/showbase/PhasedObject.py b/direct/src/showbase/PhasedObject.py index 077a0c2d48..43c43c4b53 100755 --- a/direct/src/showbase/PhasedObject.py +++ b/direct/src/showbase/PhasedObject.py @@ -30,7 +30,7 @@ class PhasedObject: definition lower in this file. """ notify = directNotify.newCategory("PhasedObject") - + def __init__(self, aliasMap = {}): self.phase = -1 self.phaseAliasMap = {} @@ -47,19 +47,19 @@ class PhasedObject: outStr = PhasedObject.__repr__(self) outStr += ' in phase \'%s\'' % self.getPhase() return outStr - + def setAlias(self, phase, alias): """ Map an alias to a phase number. phase must be >= 0 and alias must be a string of characters suitable for python variable names. - - The mapping must be one-to-one. + + The mapping must be one-to-one. """ assert isinstance(phase,int) and phase >= 0 assert isinstance(alias,str) - + self.phaseAliasMap[phase] = alias self.aliasPhaseMap[alias] = phase @@ -69,14 +69,14 @@ class PhasedObject: Otherwise, returns the phase number. """ return self.phaseAliasMap.get(phase, phase) - + def getAliasPhase(self, alias): """ Returns the phase number of an alias, if it exists. Otherwise, returns the alias. """ return self.aliasPhaseMap.get(alias, alias) - + def getPhase(self): """ Returns the current phase (or alias, if defined) @@ -94,11 +94,11 @@ class PhasedObject: """ assert not self.__phasing, 'Already phasing. Cannot setPhase() while phasing in progress.' self.__phasing = True - + phase = self.aliasPhaseMap.get(aPhase,aPhase) assert isinstance(phase,int), 'Phase alias \'%s\' not found' % aPhase assert phase >= -1, 'Invalid phase number \'%s\'' % phase - + if phase > self.phase: for x in range(self.phase + 1, phase + 1): self.__loadPhase(x) @@ -130,7 +130,7 @@ class PhasedObject: def __phaseNotFound(self, mode, aPhase): assert self.notify.debug('%s%s() not found!\n' % (mode,aPhase)) - + if __debug__: class AnfaPhasedObject(PhasedObject): """ @@ -166,28 +166,28 @@ if __debug__: def __init__(self): PhasedObject.__init__(self, {'At':3, 'Near':2, 'Far':1, 'Away':0}) self.setPhase('Away') - + def loadPhaseAway(self): print 'loading Away' def unloadPhaseAway(self): print 'unloading Away' - + def loadPhaseFar(self): print 'loading Far' def unloadPhaseFar(self): print 'unloading Far' - + def loadPhaseNear(self): print 'loading Near' - + def unloadPhaseNear(self): print 'unloading Near' - + def loadPhaseAt(self): print 'loading At' - + def unloadPhaseAt(self): print 'unloading At' - + diff --git a/direct/src/showbase/ProfileSession.py b/direct/src/showbase/ProfileSession.py index 828272be8c..0d7c7bd8c2 100755 --- a/direct/src/showbase/ProfileSession.py +++ b/direct/src/showbase/ProfileSession.py @@ -84,11 +84,11 @@ class ProfileSession: # 'profile' module # # defers formatting of profile results until they are requested - # + # # implementation sidesteps memory leak in Python profile module, # and redirects file output to RAM file for efficiency TrueClock = TrueClock.getGlobalPtr() - + notify = directNotify.newCategory("ProfileSession") def __init__(self, name, func=None, logAfterProfile=False): @@ -210,7 +210,7 @@ class ProfileSession: del __builtin__.__dict__['globalProfileSessionResult'] self._successfulProfiles += 1 - + if self._logAfterProfile: self.notify.info(self.getResults()) @@ -254,7 +254,7 @@ class ProfileSession: self._logAfterProfile = logAfterProfile def getLogAfterProfile(self): return self._logAfterProfile - + def setLines(self, lines): self._lines = lines def getLines(self): @@ -300,7 +300,7 @@ class ProfileSession: self._restoreRamFile(filename) self._stats.add(filename) self._discardRamFile(filename) - + if statsChanged: self._stats.strip_dirs() # throw out any cached result strings @@ -324,7 +324,7 @@ class ProfileSession: callInfo = self._callInfo if totalTime is Default: totalTime = self._totalTime - + self._compileStats() if totalTime is None: @@ -366,4 +366,4 @@ class ProfileSession: self._resultCache[k] = output return output - + diff --git a/direct/src/showbase/ReferrerSearch.py b/direct/src/showbase/ReferrerSearch.py index 3ef9e3f226..06272f5d05 100755 --- a/direct/src/showbase/ReferrerSearch.py +++ b/direct/src/showbase/ReferrerSearch.py @@ -13,7 +13,7 @@ class ReferrerSearch(Job): self.depth = 0 self.found = 0 self.shouldPrintStats = False - + def __call__(self): safeReprNotify = _getSafeReprNotify() info = safeReprNotify.getInfo() @@ -25,7 +25,7 @@ class ReferrerSearch(Job): finally: self.obj = None pass - + safeReprNotify.setInfo(info) pass @@ -40,7 +40,7 @@ class ReferrerSearch(Job): for x in self.stepGenerator(0, [self.obj]): yield None pass - + yield Job.Done pass @@ -54,7 +54,7 @@ class ReferrerSearch(Job): def __del__(self): print 'ReferrerSearch garbage collected' - + def truncateAtNewLine(self, s): if s.find('\n') == -1: return s @@ -64,7 +64,7 @@ class ReferrerSearch(Job): def printStatsWhenAble(self): self.shouldPrintStats = True pass - + def myrepr(self, referrer, refersTo): pre = '' if (isinstance(referrer, dict)): @@ -90,12 +90,12 @@ class ReferrerSearch(Job): post = self.truncateAtNewLine(fastRepr(refersTo)) + "-> " return '%s%s' % (pre, post) - + def step(self, depth, path): if self.shouldPrintStats: self.printStats(path) self.shouldPrintStats = False - + at = path[-1] if id(at) in self.visited: @@ -125,7 +125,7 @@ class ReferrerSearch(Job): # traversing further up the ref tree. if (self.isManyRef(at, path, referrers)): return - + while(referrers): ref = referrers.pop() self.depth+=1 @@ -138,7 +138,7 @@ class ReferrerSearch(Job): def stepGenerator(self, depth, path): if self.shouldPrintStats: self.printStats(path) - + self.shouldPrintStats = False at = path[-1] @@ -146,11 +146,11 @@ class ReferrerSearch(Job): # check for success if (self.isAtRoot(at, path)): self.found += 1 - raise StopIteration + raise StopIteration if id(at) in self.visited: # don't continue down this path - raise StopIteration + raise StopIteration # mark our progress after checking goal self.visited.add(id(at)) @@ -175,8 +175,8 @@ class ReferrerSearch(Job): # and as such no further knowledge would be gained from # traversing further up the ref tree. if (self.isManyRef(at, path, referrers)): - raise StopIteration - + raise StopIteration + while(referrers): ref = referrers.pop() self.depth+=1 @@ -188,16 +188,16 @@ class ReferrerSearch(Job): yield None pass - + def printStats(self, path): path = list(reversed(path)) path.insert(0,0) print 'RefPath(%s) - Stats - visited(%s) | found(%s) | depth(%s) | CurrentPath(%s)' % \ (self._id, len(self.visited), self.found, self.depth, ''.join(self.myrepr(path[x], path[x+1]) for x in xrange(len(path)-1))) pass - + def isAtRoot(self, at, path): - # Now we define our 'roots', or places where we will + # Now we define our 'roots', or places where we will # end this particular thread of search # We found a circular reference @@ -212,7 +212,7 @@ class ReferrerSearch(Job): return True - + # __builtins__ if at is __builtins__: sys.stdout.write("RefPath(%s): __builtins__-> " % self._id) @@ -223,7 +223,7 @@ class ReferrerSearch(Job): pass print return True - + # any module scope if inspect.ismodule(at): sys.stdout.write("RefPath(%s): Module(%s)-> " % (self._id, at.__name__)) @@ -263,7 +263,7 @@ class ReferrerSearch(Job): pass print return True - + # messenger if at is messenger: sys.stdout.write("RefPath(%s): messenger-> " % self._id) @@ -311,7 +311,7 @@ class ReferrerSearch(Job): return True else: sys.stdout.write("RefPath(%s): ManyRefsAllowed(%s)[%s]-> " % (self._id, len(referrers), fastRepr(at, maxLen = 1, strFactor = 30))) - print + print pass pass return False diff --git a/direct/src/showbase/SfxPlayer.py b/direct/src/showbase/SfxPlayer.py index 496481e6a4..2fb97eae32 100644 --- a/direct/src/showbase/SfxPlayer.py +++ b/direct/src/showbase/SfxPlayer.py @@ -71,7 +71,7 @@ class SfxPlayer: if sfx: if not cutoff: cutoff = self.cutoffDistance - + self.setFinalVolume(sfx, node, volume, listenerNode, cutoff) # don't start over if it's already playing, unless @@ -95,6 +95,6 @@ class SfxPlayer: if node is not None: finalVolume *= node.getNetAudioVolume() sfx.setVolume(finalVolume) - - - + + + diff --git a/direct/src/showbase/ShadowPlacer.py b/direct/src/showbase/ShadowPlacer.py index 4417075ca4..b05bc3e8eb 100755 --- a/direct/src/showbase/ShadowPlacer.py +++ b/direct/src/showbase/ShadowPlacer.py @@ -17,7 +17,7 @@ import DirectObject class ShadowPlacer(DirectObject.DirectObject): notify = DirectNotifyGlobal.directNotify.newCategory("ShadowPlacer") - + if __debug__: count = 0 activeCount = 0 @@ -71,7 +71,7 @@ class ShadowPlacer(DirectObject.DirectObject): # activate the collider with the traverser and pusher #self.on() - + self.lifter.addCollider(self.cRayNodePath, shadowNodePath) def delete(self): @@ -145,7 +145,7 @@ class ShadowPlacer(DirectObject.DirectObject): def resetToOrigin(self): if self.shadowNodePath: self.shadowNodePath.setPos(0,0,0) - + if __debug__: def debugDisplay(self): """for debugging""" diff --git a/direct/src/showbase/TaskThreaded.py b/direct/src/showbase/TaskThreaded.py index 28ba6a0a9b..b320e84453 100755 --- a/direct/src/showbase/TaskThreaded.py +++ b/direct/src/showbase/TaskThreaded.py @@ -12,7 +12,7 @@ class TaskThreaded: notify = directNotify.newCategory("TaskThreaded") _Serial = SerialNumGen() - + def __init__(self, name, threaded=True, timeslice=None, callback=None): # timeslice is how long this thread should take every frame. self.__name = name diff --git a/direct/src/showbase/Transitions.py b/direct/src/showbase/Transitions.py index 349a4106c5..d626eee41f 100644 --- a/direct/src/showbase/Transitions.py +++ b/direct/src/showbase/Transitions.py @@ -123,7 +123,7 @@ class Transitions: if finishIval: transitionIval.append(finishIval) return transitionIval - + def fadeIn(self, t=0.5, finishIval=None): """ Play a fade in transition over t seconds. @@ -138,7 +138,7 @@ class Transitions: base.graphicsEngine.renderFrame() render.prepareScene(gsg) render2d.prepareScene(gsg) - + if (t == 0): # Fade in immediately with no lerp #print "transitiosn: fadeIn 0.0" @@ -169,7 +169,7 @@ class Transitions: elif ConfigVariableBool('no-loading-screen', False): if finishIval: self.transitionIval = finishIval - self.transitionIval.start() + self.transitionIval.start() else: # Create a sequence that lerps the color out, then # parents the fade to hidden @@ -324,18 +324,18 @@ class Transitions: # Allow DirectLabels to be parented to the letterbox sensibly self.letterbox.setBin('unsorted', 0) - + # Allow a custom look to the letterbox graphic. # TODO: This model isn't available everywhere. We should # pass it in as a parameter. button = loader.loadModel('models/gui/toplevel_gui', okMissing = True) - + barImage = None if button: barImage = button.find('**/generic_button') - + self.letterboxTop = DirectFrame( parent = self.letterbox, guiId = 'letterboxTop', @@ -360,7 +360,7 @@ class Transitions: borderWidth = (0, 0), frameSize = (-1, 1, 0, 0.2), pos = (0, 0, -1), - image = barImage, + image = barImage, image_scale = (2.25,1,.5), image_pos = (0,0,.1), image_color = (0.3,0.3,0.3,1), @@ -372,7 +372,7 @@ class Transitions: self.letterboxBottom.setBin('sorted',0) self.letterbox.reparentTo(render2d, -1) self.letterboxOff(0) - + def noLetterbox(self): """ Removes any current letterbox tasks and parents the letterbox polygon away diff --git a/direct/src/showutil/BuildGeometry.py b/direct/src/showutil/BuildGeometry.py index 7a7ff73b49..c01c33c42b 100644 --- a/direct/src/showutil/BuildGeometry.py +++ b/direct/src/showutil/BuildGeometry.py @@ -6,7 +6,7 @@ GEO_ID = 0 def circleX(angle, radius, centerX, centerY): x = radius * cos(angle) + centerX return x - + def circleY(angle, radius, centerX, centerY): y = radius * sin(angle) + centerY return y @@ -17,13 +17,13 @@ def getCirclePoints(segCount, centerX, centerY, radius, wideX= 1.0, wideY = 1.0) coordX = wideX * (circleX(((pi * 2.0) * float(float(seg) / float(segCount))), radius, centerX, centerY)) coordY = wideY * (circleY(((pi * 2.0) * float(float(seg) / float(segCount))), radius, centerX, centerY)) returnShape.append((coordX, coordY, 1)) - + coordX = wideX * (circleX(((pi * 2.0) * float(0 / segCount)), radius, centerX, centerY)) coordY = wideY * (circleY(((pi * 2.0) * float(0 / segCount)), radius, centerX, centerY)) returnShape.append((coordX, coordY, 1)) return returnShape - - + + def addCircle(attachNode, vertexCount, radius, color = Vec4(1.0, 1.0, 1.0, 1.0), centerColor = None, layer = 0): targetGN=GeomNode("target Circle") if centerColor == None: @@ -36,26 +36,26 @@ def addCircle(attachNode, vertexCount, radius, color = Vec4(1.0, 1.0, 1.0, 1.0), targetCircleColorWriter = GeomVertexWriter(targetCircleVertexData, "color") targetCircleVertexWriter.addData3f(0.0, 0.0, zFloat) #center targetCircleColorWriter.addData4f(centerColor[0], centerColor[1], centerColor[2], centerColor[3]) - + for vertex in targetCircleShape: targetCircleVertexWriter.addData3f(0.0 + vertex[0] , 0.0 + vertex[1] , zFloat) targetCircleColorWriter.addData4f(color[0], color[1], color[2], color[3]) #targetCircleColorWriter.addData4f(1.0, 1.0, 1.0, 1.0) - + targetTris=GeomTrifans(Geom.UHStatic) # triangle object - + sizeTarget = len(targetCircleShape) - targetTris.addVertex(0) + targetTris.addVertex(0) for countVertex in range(1, sizeTarget + 1): targetTris.addVertex(countVertex) - targetTris.addVertex(1) + targetTris.addVertex(1) targetTris.closePrimitive() targetGeom=Geom(targetCircleVertexData) targetGeom.addPrimitive(targetTris) attachNode.addGeom(targetGeom) return targetGeom - + def addCircleGeom(rootNode, vertexCount, radius, color = Vec4(1.0, 1.0, 1.0, 1.0), centerColor = None, layer = 0): global GEO_ID GN=GeomNode("Circle %s" % (GEO_ID)) @@ -63,25 +63,25 @@ def addCircleGeom(rootNode, vertexCount, radius, color = Vec4(1.0, 1.0, 1.0, 1. NodePathGeom = rootNode.attachNewNode(GN) geo = addCircle(GN, vertexCount, radius, color, centerColor,layer) return NodePathGeom, GN, geo - + def addSquare(attachNode, sizeX, sizeY, color = Vec4(1.0, 1.0, 1.0, 1.0), layer = 0): targetGN=GeomNode("Square Geom") sX = sizeX / 2.0 sY = sizeY / 2.0 - + color1 = color color2 = color color3 = color gFormat = GeomVertexFormat.getV3n3cpt2() boxVertexData = GeomVertexData("vertices", gFormat, Geom.UHDynamic) - + boxVertexWriter = GeomVertexWriter(boxVertexData, "vertex") boxNormalWriter = GeomVertexWriter(boxVertexData, "normal") boxColorWriter = GeomVertexWriter(boxVertexData, "color") boxTextureWriter = GeomVertexWriter(boxVertexData, "texcoord") - + boxVertexWriter.addData3f(-sX, sY, 0.0) boxNormalWriter.addData3f(0, 0, 1) boxColorWriter.addData4f(color[0], color[1], color[2], color[3]) @@ -101,22 +101,22 @@ def addSquare(attachNode, sizeX, sizeY, color = Vec4(1.0, 1.0, 1.0, 1.0), layer boxNormalWriter.addData3f(0, 0, 1) boxColorWriter.addData4f(color[0], color[1], color[2], color[3]) boxTextureWriter.addData2f(1.0, 1.0) - + boxTris=GeomTristrips(Geom.UHStatic) # trianglestrip obejcet - + boxTris.addVertex(1) - boxTris.addVertex(2) - boxTris.addVertex(0) - boxTris.addVertex(3) + boxTris.addVertex(2) + boxTris.addVertex(0) + boxTris.addVertex(3) boxTris.closePrimitive() boxGeom=Geom(boxVertexData) boxGeom.addPrimitive(boxTris) - - + + attachNode.addGeom(boxGeom) return boxGeom - + def addSquareGeom(rootNode, sizeX, sizeY, color = Vec4(1.0, 1.0, 1.0, 1.0), layer = 0): global GEO_ID GN=GeomNode("Square %s" % (GEO_ID)) @@ -124,13 +124,13 @@ def addSquareGeom(rootNode, sizeX, sizeY, color = Vec4(1.0, 1.0, 1.0, 1.0), laye NodePathGeom = rootNode.attachNewNode(GN) geo = addSquare(GN, sizeX, sizeY, color, layer) return NodePathGeom, GN, geo - + def addBox(attachNode, sizeX, sizeY, sizeZ, color = Vec4(1.0, 1.0, 1.0, 1.0), darken = 0): targetGN=GeomNode("Box Geom") sX = sizeX / 2.0 sY = sizeY / 2.0 sZ = sizeZ / 2.0 - + color1 = color color2 = color color3 = color @@ -141,14 +141,14 @@ def addBox(attachNode, sizeX, sizeY, sizeZ, color = Vec4(1.0, 1.0, 1.0, 1.0), da gFormat = GeomVertexFormat.getV3n3cp() boxVertexData = GeomVertexData("vertices", gFormat, Geom.UHDynamic) - + boxVertexWriter = GeomVertexWriter(boxVertexData, "vertex") boxNormalWriter = GeomVertexWriter(boxVertexData, "normal") boxColorWriter = GeomVertexWriter(boxVertexData, "color") - - + + #Front - + boxVertexWriter.addData3f(sX, sY, sZ) boxNormalWriter.addData3f(0, 1, 0) boxColorWriter.addData4f(color[0], color[1], color[2], color[3]) @@ -164,9 +164,9 @@ def addBox(attachNode, sizeX, sizeY, sizeZ, color = Vec4(1.0, 1.0, 1.0, 1.0), da boxVertexWriter.addData3f(-sX, sY, sZ) boxNormalWriter.addData3f(0, 1, 0) boxColorWriter.addData4f(color1[0], color1[1], color1[2], color1[3]) - + #Back - + boxVertexWriter.addData3f(-sX, -sY, sZ) boxNormalWriter.addData3f(0, -1, 0) boxColorWriter.addData4f(color2[0], color2[1], color2[2], color2[3]) @@ -182,9 +182,9 @@ def addBox(attachNode, sizeX, sizeY, sizeZ, color = Vec4(1.0, 1.0, 1.0, 1.0), da boxVertexWriter.addData3f(sX, -sY, sZ) boxNormalWriter.addData3f(0, -1, 0) boxColorWriter.addData4f(color2[0], color2[1], color2[2], color2[3]) - + #Top - + boxVertexWriter.addData3f(-sX, sY, sZ) boxNormalWriter.addData3f(0, 0, 1) boxColorWriter.addData4f(color[0], color[1], color[2], color[3]) @@ -200,9 +200,9 @@ def addBox(attachNode, sizeX, sizeY, sizeZ, color = Vec4(1.0, 1.0, 1.0, 1.0), da boxVertexWriter.addData3f(sX, sY, sZ) boxNormalWriter.addData3f(0, 0, 1) boxColorWriter.addData4f(color[0], color[1], color[2], color[3]) - + #Bottom - + boxVertexWriter.addData3f(sX, sY, -sZ) boxNormalWriter.addData3f(0, 0, -1) boxColorWriter.addData4f(color3[0], color3[1], color3[2], color3[3]) @@ -218,9 +218,9 @@ def addBox(attachNode, sizeX, sizeY, sizeZ, color = Vec4(1.0, 1.0, 1.0, 1.0), da boxVertexWriter.addData3f(-sX, sY, -sZ) boxNormalWriter.addData3f(0, 0, -1) boxColorWriter.addData4f(color3[0], color3[1], color3[2], color3[3]) - + #Right - + boxVertexWriter.addData3f(sX, sY, sZ) boxNormalWriter.addData3f(0, 0, 1) boxColorWriter.addData4f(color[0], color[1], color[2], color[3]) @@ -236,10 +236,10 @@ def addBox(attachNode, sizeX, sizeY, sizeZ, color = Vec4(1.0, 1.0, 1.0, 1.0), da boxVertexWriter.addData3f(sX, sY, -sZ) boxNormalWriter.addData3f(0, 0, 1) boxColorWriter.addData4f(color1[0], color1[1], color1[2], color1[3]) - - + + #Left - + boxVertexWriter.addData3f(-sX, sY, -sZ) boxNormalWriter.addData3f(0, 0, 1) boxColorWriter.addData4f(color2[0], color2[1], color2[2], color2[3]) @@ -256,51 +256,51 @@ def addBox(attachNode, sizeX, sizeY, sizeZ, color = Vec4(1.0, 1.0, 1.0, 1.0), da boxNormalWriter.addData3f(0, 0, 1) boxColorWriter.addData4f(color2[0], color2[1], color2[2], color2[3]) - + boxTris=GeomTristrips(Geom.UHStatic) # trianglestrip obejcet boxTris.addVertex(0)#(1) - boxTris.addVertex(1)#(2) - boxTris.addVertex(3)#(0) - boxTris.addVertex(2)#(3) + boxTris.addVertex(1)#(2) + boxTris.addVertex(3)#(0) + boxTris.addVertex(2)#(3) boxTris.closePrimitive() - + boxTris.addVertex(5) - boxTris.addVertex(6) - boxTris.addVertex(4) - boxTris.addVertex(7) + boxTris.addVertex(6) + boxTris.addVertex(4) + boxTris.addVertex(7) boxTris.closePrimitive() - + boxTris.addVertex(9) - boxTris.addVertex(10) - boxTris.addVertex(8) - boxTris.addVertex(11) + boxTris.addVertex(10) + boxTris.addVertex(8) + boxTris.addVertex(11) boxTris.closePrimitive() - + boxTris.addVertex(13) - boxTris.addVertex(14) - boxTris.addVertex(12) - boxTris.addVertex(15) + boxTris.addVertex(14) + boxTris.addVertex(12) + boxTris.addVertex(15) boxTris.closePrimitive() - + boxTris.addVertex(16) #(17) - boxTris.addVertex(17) #(18) - boxTris.addVertex(19) #(16) - boxTris.addVertex(18) #(19) + boxTris.addVertex(17) #(18) + boxTris.addVertex(19) #(16) + boxTris.addVertex(18) #(19) boxTris.closePrimitive() - + boxTris.addVertex(21) - boxTris.addVertex(22) - boxTris.addVertex(20) - boxTris.addVertex(23) + boxTris.addVertex(22) + boxTris.addVertex(20) + boxTris.addVertex(23) boxTris.closePrimitive() - + boxGeom=Geom(boxVertexData) boxGeom.addPrimitive(boxTris) - - + + attachNode.addGeom(boxGeom) return boxGeom - + def addBoxGeom(rootNode, sizeX, sizeY, sizeZ, color = Vec4(1.0, 1.0, 1.0, 1.0), darken = 0): global GEO_ID GN=GeomNode("Box %s" % (GEO_ID)) @@ -308,25 +308,25 @@ def addBoxGeom(rootNode, sizeX, sizeY, sizeZ, color = Vec4(1.0, 1.0, 1.0, 1.0), nodePathGeom = rootNode.attachNewNode(GN) geo = addBox(GN, sizeX, sizeY, sizeZ, color, darken) return nodePathGeom, GN, geo - - + + def addArrow(attachNode, sizeX, sizeY, color = Vec4(1.0, 1.0, 1.0, 1.0), layer = 0): targetGN=GeomNode("Arrow Geom") sX = sizeX / 2.0 sY = sizeY / 2.0 - + color1 = color color2 = color color3 = color gFormat = GeomVertexFormat.getV3n3cp() boxVertexData = GeomVertexData("vertices", gFormat, Geom.UHDynamic) - + boxVertexWriter = GeomVertexWriter(boxVertexData, "vertex") boxNormalWriter = GeomVertexWriter(boxVertexData, "normal") boxColorWriter = GeomVertexWriter(boxVertexData, "color") - + boxVertexWriter.addData3f(-sX, sY, 0.0) boxNormalWriter.addData3f(0, 0, 1) boxColorWriter.addData4f(color[0], color[1], color[2], color[3]) @@ -342,15 +342,15 @@ def addArrow(attachNode, sizeX, sizeY, color = Vec4(1.0, 1.0, 1.0, 1.0), layer = boxVertexWriter.addData3f(sX, sY, 0.0) boxNormalWriter.addData3f(0, 0, 1) boxColorWriter.addData4f(color[0], color[1], color[2], color[3]) - + boxTris=GeomTristrips(Geom.UHStatic) # trianglestrip obejcet - + boxTris.addVertex(1) - boxTris.addVertex(2) - boxTris.addVertex(0) - boxTris.addVertex(3) + boxTris.addVertex(2) + boxTris.addVertex(0) + boxTris.addVertex(3) boxTris.closePrimitive() - + boxVertexWriter.addData3f(-sX * 2.0, sY, 0.0) boxNormalWriter.addData3f(0, 0, 1) boxColorWriter.addData4f(color[0], color[1], color[2], color[3]) @@ -362,20 +362,20 @@ def addArrow(attachNode, sizeX, sizeY, color = Vec4(1.0, 1.0, 1.0, 1.0), layer = boxVertexWriter.addData3f(0.0, sY * 2.0, 0.0) boxNormalWriter.addData3f(0, 0, 1) boxColorWriter.addData4f(color[0], color[1], color[2], color[3]) - + boxTris.addVertex(4) - boxTris.addVertex(5) - boxTris.addVertex(6) + boxTris.addVertex(5) + boxTris.addVertex(6) boxTris.closePrimitive() boxGeom=Geom(boxVertexData) boxGeom.addPrimitive(boxTris) - - + + attachNode.addGeom(boxGeom) return boxGeom - + def addArrowGeom(rootNode, sizeX, sizeY, color = Vec4(1.0, 1.0, 1.0, 1.0), layer = 0): global GEO_ID GN=GeomNode("Arrow %s" % (GEO_ID)) diff --git a/direct/src/showutil/Effects.py b/direct/src/showutil/Effects.py index 19f9b40515..effaa426c6 100644 --- a/direct/src/showutil/Effects.py +++ b/direct/src/showutil/Effects.py @@ -63,26 +63,26 @@ def createBounce(nodeObj, numBounces, startValues, totalTime, amplitude, self.notify.warning( "createBounceIvals called with invalid parameter") return - + result = Sequence() - + # calculate how long, in seconds, each bounce should last bounceTime = totalTime/float(numBounces) currTime = bounceTime currAmplitude = amplitude - + # determine the how much of a change in value the first bounce - # will produce based on the given start value and amplitude + # will produce based on the given start value and amplitude # if ((bounceType == SX_BOUNCE) or (bounceType == TX_BOUNCE) or (bounceType == H_BOUNCE)): - index = 0 + index = 0 elif ((bounceType == SY_BOUNCE) or (bounceType == TY_BOUNCE) or (bounceType == P_BOUNCE)): - index = 1 + index = 1 elif ((bounceType == SZ_BOUNCE) or (bounceType == TZ_BOUNCE) or (bounceType == R_BOUNCE)): - index = 2 + index = 2 currBounceVal = startValues[index] # create a lerp interval for each bounce, making sure to @@ -106,7 +106,7 @@ def createBounce(nodeObj, numBounces, startValues, totalTime, amplitude, newVec3 = Vec3(startValues) newVec3.setCell(index, currBounceVal) print "### newVec3 = ", newVec3 - + # create the right type of lerp if ((bounceType == SX_BOUNCE) or (bounceType == SY_BOUNCE) or (bounceType == SZ_BOUNCE)): diff --git a/direct/src/showutil/Rope.py b/direct/src/showutil/Rope.py index 9b804cf0d8..1e65411684 100644 --- a/direct/src/showutil/Rope.py +++ b/direct/src/showutil/Rope.py @@ -12,7 +12,7 @@ class Rope(NodePath): showRope = ConfigVariableBool('show-rope', True, \ "Set this to false to deactivate the display of ropes.") - + def __init__(self, name = 'Rope'): self.ropeNode = RopeNode(name) self.curve = NurbsCurveEvaluator() @@ -22,7 +22,7 @@ class Rope(NodePath): self.order = 0 self.verts = [] self.knots = None - + def setup(self, order, verts, knots = None): """This must be called to define the shape of the curve initially, and may be called again as needed to adjust the @@ -65,7 +65,7 @@ class Rope(NodePath): of the first (order - 1) and last (order - 1) values the same, and the intermediate values incrementing by 1. """ - + self.order = order self.verts = verts self.knots = knots @@ -76,7 +76,7 @@ class Rope(NodePath): """Recomputes the curve after its properties have changed. Normally it is not necessary for the user to call this directly.""" - + if not self.showRope: return numVerts = len(self.verts) @@ -93,7 +93,7 @@ class Rope(NodePath): vcd = self.ropeNode.getVertexColorDimension() vtd = self.ropeNode.getVertexThicknessDimension() - + for i in range(numVerts): v = self.verts[i] if isinstance(v, types.TupleType): @@ -105,7 +105,7 @@ class Rope(NodePath): point = v.get('point', defaultPoint) color = v.get('color', defaultColor) thickness = v.get('thickness', defaultThickness) - + if isinstance(point, types.TupleType): if (len(point) >= 4): self.curve.setVertex(i, VBase4(point[0], point[1], point[2], point[3])) @@ -133,7 +133,7 @@ class Rope(NodePath): """Returns a list of len points, evenly distributed in parametric space on the rope, in the coordinate space of the Rope itself.""" - + result = self.curve.evaluate(self) startT = result.getStartT() sizeT = result.getEndT() - startT diff --git a/direct/src/showutil/TexMemWatcher.py b/direct/src/showutil/TexMemWatcher.py index 5de8ecb138..d4d91ae1d3 100644 --- a/direct/src/showutil/TexMemWatcher.py +++ b/direct/src/showutil/TexMemWatcher.py @@ -86,7 +86,7 @@ class TexMemWatcher(DirectObject): # self.limit) to allocate for packing. This controls the # value assigned to self.quantize in repack(). self.maxHeight = base.config.GetInt('tex-mem-max-height', 300) - + # The total number of texture bytes tracked, including overflow. self.totalSize = 0 @@ -96,7 +96,7 @@ class TexMemWatcher(DirectObject): # The total number of Q-units placed, not including overflow. self.placedQSize = 0 - + # If no GSG is specified, use the main GSG. if gsg is None: gsg = base.win.getGsg() @@ -134,7 +134,7 @@ class TexMemWatcher(DirectObject): # regular pipe. if not self.pipe: self.pipe = base.pipe - + self.win = base.graphicsEngine.makeOutput(self.pipe, name, 0, fbprops, props, flags) assert self.win @@ -168,7 +168,7 @@ class TexMemWatcher(DirectObject): self.setupCanvas() # Now start handling up the actual stuff in the scene. - + self.background = None self.nextTexRecordKey = 0 self.rollover = None @@ -191,7 +191,7 @@ class TexMemWatcher(DirectObject): self.render2d.setDepthWrite(False) self.render2d.setTwoSided(True) self.render2d.setBin('unsorted', 0) - + # Create a DisplayRegion and an associated camera. dr = self.win.makeDisplayRegion() cam = Camera('cam2d') @@ -229,7 +229,7 @@ class TexMemWatcher(DirectObject): """ Creates the "canvas", which is the checkerboard area where texture memory is laid out. The canvas has its own DisplayRegion. """ - + self.canvasRoot = NodePath('canvasRoot') self.canvasRoot.setDepthTest(False) self.canvasRoot.setDepthWrite(False) @@ -237,7 +237,7 @@ class TexMemWatcher(DirectObject): self.canvasRoot.setBin('unsorted', 0) self.canvas = self.canvasRoot.attachNewNode('canvas') - + # Create a DisplayRegion and an associated camera. self.canvasDR = self.win.makeDisplayRegion() self.canvasDR.setSort(-10) @@ -281,7 +281,7 @@ class TexMemWatcher(DirectObject): def makeCanvasBackground(self): if self.canvasBackground: self.canvasBackground.removeNode() - + self.canvasBackground = self.canvasRoot.attachNewNode('canvasBackground', -100) cm = CardMaker('background') @@ -300,16 +300,16 @@ class TexMemWatcher(DirectObject): """ Indicates the texture memory limit. If limit is None or unspecified, the limit is taken from the GSG, if any; or there is no limit. """ - + self.__doSetLimit(limit) self.reconfigureWindow() - + def __doSetLimit(self, limit): """ Internal implementation of setLimit(). """ self.limit = limit self.lruLimit = False self.dynamicLimit = False - + if not limit: # If no limit was specified, use the specified graphics # memory limit, if any. @@ -344,7 +344,7 @@ class TexMemWatcher(DirectObject): if top != self.top: self.top = top self.makeCanvasBackground() - + self.canvasLens.setFilmSize(1, self.top) self.canvasLens.setFilmOffset(0.5, self.top / 2.0) # lens covers 0..1 in x and y @@ -381,7 +381,7 @@ class TexMemWatcher(DirectObject): # User closed window. self.cleanup() return - + size = (props.getXSize(), props.getYSize()) if size != self.winSize: self.winSize = size @@ -421,7 +421,7 @@ class TexMemWatcher(DirectObject): def setRollover(self, tr, pi): """ Sets the highlighted texture (due to mouse rollover) to the indicated texture, or None to clear it. """ - + self.rollover = tr if self.rollover: self.statusText.setText(tr.tex.getName()) @@ -449,7 +449,7 @@ class TexMemWatcher(DirectObject): return # Now isolate. - + self.canvas.hide() # Disable the red bar at the top. self.canvasBackground.setColor(1, 1, 1, 1, 1) @@ -583,7 +583,7 @@ class TexMemWatcher(DirectObject): # neverVisited list. if tex in neverVisited: del neverVisited[tex] - + size = 0 if tex.getResident(pgo): size = tex.getDataSizeBytes(pgo) @@ -645,7 +645,7 @@ class TexMemWatcher(DirectObject): self.texRecordsByKey[tr.key] = tr return task.again - + def repack(self): """ Repacks all of the current textures. """ @@ -664,7 +664,7 @@ class TexMemWatcher(DirectObject): pgo = self.gsg.getPreparedObjects() totalSize = 0 - + for tex in self.gsg.getPreparedTextures(): if tex.getResident(pgo): size = tex.getDataSizeBytes(pgo) @@ -695,7 +695,7 @@ class TexMemWatcher(DirectObject): # There should be a little buffer on the top so we can see if # we overflow. y /= self.top - + r = float(y) / float(x) # Region size @@ -708,7 +708,7 @@ class TexMemWatcher(DirectObject): self.quantize = int(math.ceil(h / self.maxHeight)) else: self.quantize = 1 - + w = max(int(w / self.quantize + 0.5), 1) h = max(int(h / self.quantize + 0.5), 1) self.w = w @@ -731,7 +731,7 @@ class TexMemWatcher(DirectObject): # packing effectiveness. texRecords = self.texRecordsByTex.values() texRecords.sort(key = lambda tr: (tr.tw, tr.th), reverse = True) - + for tr in texRecords: self.placeTexture(tr) @@ -781,7 +781,7 @@ class TexMemWatcher(DirectObject): # error. Make it correspondingly smaller, so we can # place it anyway. tr.area = availableQSize - + if shouldFit: # Look for a single rectangular hole to hold this piece. tp = self.findHole(tr.area, tr.w, tr.h) @@ -872,7 +872,7 @@ class TexMemWatcher(DirectObject): # Make a new tp that has the right area. tp = TexPlacement(l, l + tw, b, b + th) - + ta = float(max(tw, th)) / float(min(tw, th)) if ta == aspect: return tp @@ -907,7 +907,7 @@ class TexMemWatcher(DirectObject): tp = self.findLargestHole() if not tp: break - + l, r, b, t = tp.p tpArea = (r - l) * (t - b) if tpArea >= area: @@ -962,12 +962,12 @@ class TexMemWatcher(DirectObject): continue lastBitmask = bm - + tuples = self.findEmptyRuns(bm) newTuples = tuples.difference(lastTuples) for l, r in newTuples: - # Find out how high we can go with this bitmask. + # Find out how high we can go with this bitmask. mask = BitArray.range(l, r - l) t = b + 1 while t < self.h and (self.bitmasks[t] & mask).isZero(): @@ -1006,7 +1006,7 @@ class TexMemWatcher(DirectObject): b = len(self.bitmasks) while b > self.h and self.bitmasks[b - 1].isZero(): b -= 1 - + tp = TexPlacement(0, w, b, b + h) return tp @@ -1021,7 +1021,7 @@ class TexMemWatcher(DirectObject): # Off the top. Just leave it here. tp = TexPlacement(0, w, b, b + h) return tp - + # Separate this row into (l, r) tuples. bm = self.bitmasks[b] if bm == lastBitmask: @@ -1039,7 +1039,7 @@ class TexMemWatcher(DirectObject): # Is this region wide enough? if r - l < w: continue - + # Is it tall enough? r = l + w mask = BitArray.range(l, r - l) @@ -1154,13 +1154,13 @@ class TexRecord: cx = (l + r) * 0.5 cy = (b + t) * 0.5 shrinkMat = Mat4.translateMat(-cx, 0, -cy) * Mat4.scaleMat(0.9) * Mat4.translateMat(cx, 0, cy) - + cm = CardMaker('backing') cm.setFrame(l, r, b, t) cm.setColor(0.1, 0.3, 0.5, 1) c = backing.attachNewNode(cm.generate()) c.setMat(shrinkMat) - + cm = CardMaker('card') cm.setFrame(l, r, b, t) if p.rotated: @@ -1232,7 +1232,7 @@ class TexPlacement: l, r, b, t = self.p mask = BitArray.range(l, r - l) - + for yi in range(b, t): assert (bitmasks[yi] & mask).isZero() bitmasks[yi] |= mask @@ -1243,7 +1243,7 @@ class TexPlacement: l, r, b, t = self.p mask = ~BitArray.range(l, r - l) - + for yi in range(b, t): assert (bitmasks[yi] | mask).isAllOn() bitmasks[yi] &= mask @@ -1254,7 +1254,7 @@ class TexPlacement: l, r, b, t = self.p mask = BitArray.range(l, r - l) - + for yi in range(b, t): if not (bitmasks[yi] & mask).isZero(): return True diff --git a/direct/src/showutil/TexViewer.py b/direct/src/showutil/TexViewer.py index 7d325afdfc..46d8c1bb43 100644 --- a/direct/src/showutil/TexViewer.py +++ b/direct/src/showutil/TexViewer.py @@ -30,7 +30,7 @@ class TexViewer(DirectObject): ls.drawTo(l, 0, t) ls.drawTo(l, 0, b) cards.attachNewNode(ls.create()) - + # And the "simple", reduced-resolution version goes on the # right. diff --git a/direct/src/task/FrameProfiler.py b/direct/src/task/FrameProfiler.py index 88d7cd5040..b524dbf1c1 100755 --- a/direct/src/task/FrameProfiler.py +++ b/direct/src/task/FrameProfiler.py @@ -50,7 +50,7 @@ class FrameProfiler: def destroy(self): self._enableFC.set(False) self._enableFC.destroy() - + def _setEnabled(self, enabled): if enabled: self.notify.info('frame profiler started') @@ -97,7 +97,7 @@ class FrameProfiler: time -= jitter jitter = None self._jitter = jitter - + sessionId = serialNum() session = taskMgr.getProfileSession('FrameProfile-%s' % sessionId) self._id2session[sessionId] = session diff --git a/direct/src/task/TaskProfiler.py b/direct/src/task/TaskProfiler.py index 83058e6736..ceb83b2e15 100755 --- a/direct/src/task/TaskProfiler.py +++ b/direct/src/task/TaskProfiler.py @@ -104,7 +104,7 @@ class TaskProfiler: tracker.destroy() del self._namePrefix2tracker del self._task - + @staticmethod def GetDefaultSpikeThreshold(): return config.GetFloat('profile-task-spike-threshold', 5.) @@ -142,7 +142,7 @@ class TaskProfiler: taskMgr.remove(self._taskName) del self._taskName self.notify.info('task profiler stopped') - + def _doProfileTasks(self, task=None): # gather data from the previous frame # set up for the next frame diff --git a/direct/src/task/Timer.py b/direct/src/task/Timer.py index 7474deb652..fb773a7c42 100644 --- a/direct/src/task/Timer.py +++ b/direct/src/task/Timer.py @@ -31,7 +31,7 @@ class Timer: def startCallback(self, t, callback): if (self.started): self.stop() - self.callback = callback + self.callback = callback self.finalT = t self.startT = globalClock.getFrameTime() self.currT = 0.0 @@ -70,7 +70,7 @@ class Timer: def __timerTask(self, task): t = globalClock.getFrameTime() - te = t - self.startT + te = t - self.startT self.currT = te if (te >= self.finalT): if (self.callback != None): diff --git a/direct/src/tkpanels/AnimPanel.py b/direct/src/tkpanels/AnimPanel.py index e68f52fced..c48320efab 100644 --- a/direct/src/tkpanels/AnimPanel.py +++ b/direct/src/tkpanels/AnimPanel.py @@ -56,7 +56,7 @@ class AnimPanel(AppShell): # Execute option callbacks - self.initialiseoptions(AnimPanel) + self.initialiseoptions(AnimPanel) # We need to know when AnimPanel is closed self.destroyCallBack = None @@ -131,7 +131,7 @@ class AnimPanel(AppShell): width = 4, command = self.resetAllToZero) self.toStartButton.pack(side = LEFT, expand = 1, fill = X) - + self.toPreviousFrameButton = self.createcomponent( 'toPreviousFrame', (), None, Button, (controlFrame,), @@ -153,7 +153,7 @@ class AnimPanel(AppShell): text = 'Stop', width = 8, command = self.stopActorControls) self.stopButton.pack(side = LEFT, expand = 1, fill = X) - + self.toNextFrameButton = self.createcomponent( 'toNextFrame', (), None, Button, (controlFrame,), @@ -194,7 +194,7 @@ class AnimPanel(AppShell): controlFrame.pack(fill = X) - def createActorControls(self): + def createActorControls(self): # Create a frame to hold all the actor controls self.actorFrame = Frame(self.interior()) # Create a control for each actor @@ -351,24 +351,24 @@ class AnimPanel(AppShell): def resetAllToEnd(self): for actorControl in self.actorControlList: actorControl.resetToEnd() - + def nextFrame(self): for actorControl in self.actorControlList: actorControl.nextFrame() - + def previousFrame(self): for actorControl in self.actorControlList: actorControl.previousFrame() - - def setDestroyCallBack(self, callBack): + + def setDestroyCallBack(self, callBack): self.destroyCallBack = callBack - - def destroy(self): - # First clean up - taskMgr.remove(self.id + '_UpdateTask') - self.destroyCallBack() + + def destroy(self): + # First clean up + taskMgr.remove(self.id + '_UpdateTask') + self.destroyCallBack() self.destroyCallBack = None - AppShell.destroy(self) + AppShell.destroy(self) class ActorControl(Pmw.MegaWidget): def __init__(self, parent = None, **kw): @@ -437,7 +437,7 @@ class ActorControl(Pmw.MegaWidget): command = self.resetToZero) labelMenu.add_command(label = 'Jump To End Time', command = self.resetToEnd) - + # Now associate menu with menubutton self._label['menu'] = labelMenu self._label.pack(side = LEFT, fill = X) @@ -598,7 +598,7 @@ class ActorControl(Pmw.MegaWidget): self.currT = self.currT + deltaT if fLoop and self.duration: # If its looping compute modulo - loopT = self.currT % self.duration + loopT = self.currT % self.duration self.goToT(loopT) else: if (self.currT > self.maxSeconds): @@ -645,7 +645,7 @@ class ActorControl(Pmw.MegaWidget): # This flag forces self.currT to be updated to new value self.fOneShot = 1 self.goToT(self.duration) - + def nextFrame(self): """ There needed to be a better way to select an exact frame number @@ -653,7 +653,7 @@ class ActorControl(Pmw.MegaWidget): """ self.fOneShot = 1 self.goToT((self.currT+(1/self.fps))%self.duration) - + def previousFrame(self): """ There needed to be a better way to select an exact frame number diff --git a/direct/src/tkpanels/DirectSessionPanel.py b/direct/src/tkpanels/DirectSessionPanel.py index a197cd385f..54a515895d 100644 --- a/direct/src/tkpanels/DirectSessionPanel.py +++ b/direct/src/tkpanels/DirectSessionPanel.py @@ -195,10 +195,10 @@ class DirectSessionPanel(AppShell): framePane.pack(expand = 1, fill = BOTH) mainFrame.pack(fill = 'both', expand = 1) - + # Put this here so it isn't called right away notebook['raisecommand'] = self.updateInfo - + def createEnvPage(self, envPage): bkgrdFrame = Frame(envPage, borderwidth = 2, relief = 'sunken') @@ -607,7 +607,7 @@ class DirectSessionPanel(AppShell): scrolledCanvas_hull_width = 250, scrolledCanvas_hull_height = 250) self.MemExp.pack(fill = BOTH, expand = 1) - + def toggleDirect(self): if self.directEnabled.get(): base.direct.enable() diff --git a/direct/src/tkpanels/Inspector.py b/direct/src/tkpanels/Inspector.py index 2ffa1a5249..47d3b4f6a6 100644 --- a/direct/src/tkpanels/Inspector.py +++ b/direct/src/tkpanels/Inspector.py @@ -48,7 +48,7 @@ def initializeInspectorMap(): 'DictionaryType': 'DictionaryInspector', 'DictType': 'DictionaryInspector', 'FileType': 'Inspector', - 'FloatType': 'Inspector', + 'FloatType': 'Inspector', 'FunctionType': 'FunctionInspector', 'Instance methodType': 'InstanceMethodInspector', 'InstanceType': 'InstanceInspector', @@ -68,7 +68,7 @@ def initializeInspectorMap(): for each in notFinishedTypes: _InspectorMap[each] = 'Inspector' - + ### Classes class Inspector: @@ -88,7 +88,7 @@ class Inspector: for each in keys: self._partsList.append(each) #if not callable(getattr(self.object, each)): - # self._partsList.append(each) + # self._partsList.append(each) def initializePartNames(self): self._partNames = ['up'] + [str(each) for each in self._partsList] @@ -102,7 +102,7 @@ class Inspector: def selectedPart(self): return self.partNumber(self.getLastPartNumber()) - + def namedParts(self): return dir(self.object) @@ -131,16 +131,16 @@ class Inspector: return inspectorFor(part) def privatePartNumber(self, partNumber): - return self._partsList[partNumber - 1] + return self._partsList[partNumber - 1] def partNames(self): return self._partNames - + def objectType(self): return type(self.object) ### - + class ModuleInspector(Inspector): def namedParts(self): return ['__dict__'] @@ -159,7 +159,7 @@ class InstanceInspector(Inspector): return ['__class__'] + dir(self.object) ### - + class FunctionInspector(Inspector): def title(self): return self.object.__name__ + "()" @@ -198,7 +198,7 @@ class DictionaryInspector(Inspector): return self.object[key] else: return getattr(self.object, key) - + class SequenceInspector(Inspector): def initializePartsList(self): Inspector.initializePartsList(self) @@ -214,7 +214,7 @@ class SequenceInspector(Inspector): return self.object[index] else: return getattr(self.object, index) - + class SliceInspector(Inspector): def namedParts(self): return ['start', 'stop', 'step'] @@ -288,7 +288,7 @@ class InspectorWindow: self.commandWidget.component('text').bind( '', self.evalCommand) self.textPane.pack(expand = 1, fill = BOTH) - + def createMenus(self): self.menuBar = Menu(self.top) self.top.config(menu=self.menuBar) @@ -348,8 +348,8 @@ class InspectorWindow: inspector = self.inspectorForSelectedPart() if inspector == None: return - InspectorWindow(inspector).open() - + InspectorWindow(inspector).open() + def pop(self): if len(self.inspectors) > 1: self.inspectors = self.inspectors[:-1] @@ -438,7 +438,7 @@ class InspectorWindow: label = item, command = lambda p = part, f = func: f(p)) return popupMenu - + diff --git a/direct/src/tkpanels/NotifyPanel.py b/direct/src/tkpanels/NotifyPanel.py index 76d139daad..f1b8a0720b 100644 --- a/direct/src/tkpanels/NotifyPanel.py +++ b/direct/src/tkpanels/NotifyPanel.py @@ -56,7 +56,7 @@ class NotifyPanel: items = categoryNames, selectioncommand = self.setActivePandaCategory) self.categoryList.pack(expand = 1, fill = 'both') - + # Severity frame Label(severityFrame, text = 'Severity:', font=('MSSansSerif', 10, 'bold'), diff --git a/direct/src/tkpanels/ParticlePanel.py b/direct/src/tkpanels/ParticlePanel.py index b2daba120c..f07e9c4102 100644 --- a/direct/src/tkpanels/ParticlePanel.py +++ b/direct/src/tkpanels/ParticlePanel.py @@ -45,7 +45,7 @@ class ParticlePanel(AppShell): else: # Make sure particles are enabled base.enableParticles() - + # Or create a new one if none given particles = Particles.Particles() particles.setBirthRate(0.02) @@ -559,7 +559,7 @@ class ParticlePanel(AppShell): rendererGeomBlendPage = rendererGeomNotebook.add('Blend') rendererGeomScalePage = rendererGeomNotebook.add('Scale') rendererGeomInterpolationPage = rendererGeomNotebook.add('Interpolate') - + ############################################################################ # Blend tab p = Frame(rendererGeomBlendPage) @@ -594,7 +594,7 @@ class ParticlePanel(AppShell): # Scale tab p = Frame(rendererGeomScalePage) p.pack(fill = X) - + self.createCheckbutton( p, 'Geom Renderer', 'X Scale', ("On: x scale is interpolated over particle's life; " + @@ -610,10 +610,10 @@ class ParticlePanel(AppShell): ("On: z scale is interpolated over particle's life; " + "Off: stays as start_Z_Scale"), self.toggleRendererGeomZScale, 0, side = LEFT) - + p = Frame(rendererGeomScalePage) p.pack(fill = X) - + self.createFloater(p, 'Geom Renderer', 'Initial X Scale', 'Initial X scaling factor', @@ -772,7 +772,7 @@ class ParticlePanel(AppShell): ################################################################################## p = Frame(rendererSpriteScalePage) p.pack(fill = X) - + self.createCheckbutton( p, 'Sprite Renderer', 'X Scale', ("On: x scale is interpolated over particle's life; " + @@ -1638,7 +1638,7 @@ class ParticlePanel(AppShell): self.getVariable('Renderer', 'Alpha Mode').set(aMode) userAlpha = renderer.getUserAlpha() self.getWidget('Renderer', 'User Alpha').set(userAlpha) - + if isinstance(renderer, LineParticleRenderer): headColor = renderer.getHeadColor() * 255.0 self.getWidget('Line Renderer', 'Head Color').set( @@ -1648,7 +1648,7 @@ class ParticlePanel(AppShell): [tailColor[0], tailColor[1], tailColor[2], tailColor[3]]) self.getWidget('Line Renderer', 'Line Scale Factor').set( renderer.getLineScaleFactor()) - + elif isinstance(renderer, GeomParticleRenderer): self.getVariable('Geom Renderer', 'X Scale').set( renderer.getXScaleFlag()) @@ -1713,7 +1713,7 @@ class ParticlePanel(AppShell): elif (blendMethod == BaseParticleRenderer.PPBLENDCUBIC): bMethod = "PP_BLEND_CUBIC" self.getVariable('Point Renderer', 'Blend Method').set(bMethod) - + elif isinstance(renderer, SparkleParticleRenderer): centerColor = renderer.getCenterColor() * 255.0 self.getWidget('Sparkle Renderer', 'Center Color').set( @@ -1731,7 +1731,7 @@ class ParticlePanel(AppShell): if (lifeScale == SparkleParticleRenderer.SPSCALE): lScale = "SP_SCALE" self.getVariable('Sparkle Renderer', 'Life Scale').set(lScale) - + elif isinstance(renderer, SpriteParticleRenderer): self.getWidget('Sprite Renderer','Frame Rate').set(renderer.getAnimateFramesRate(), 0) self.getVariable('Sprite Renderer','Enable Animation').set( @@ -2014,22 +2014,22 @@ class ParticlePanel(AppShell): def toggleRendererGeomZScale(self): self.particles.renderer.setZScaleFlag( self.getVariable('Geom Renderer', 'Z Scale').get()) - + def setRendererGeomInitialXScale(self, xScale): self.particles.renderer.setInitialXScale(xScale) def setRendererGeomFinalXScale(self, xScale): self.particles.renderer.setFinalXScale(xScale) - + def setRendererGeomInitialYScale(self, yScale): self.particles.renderer.setInitialYScale(yScale) def setRendererGeomFinalYScale(self, yScale): self.particles.renderer.setFinalYScale(yScale) - + def setRendererGeomInitialZScale(self, zScale): self.particles.renderer.setInitialZScale(zScale) def setRendererGeomFinalZScale(self, zScale): self.particles.renderer.setFinalZScale(zScale) - + def setRendererGeomColorBlendMethod(self, blendMethod): blendMethodStr = blendMethod incomingOperandStr = self.getVariable('Geom Renderer','Incoming Op.').get() @@ -2076,7 +2076,7 @@ class ParticlePanel(AppShell): seg = cim.getSegment(cim.addLinear()) else: seg = cim.getSegment(id) - + if(ren.__class__.__name__ == 'SpriteParticleRendererExt'): parent = self.rendererSpriteSegmentFrame segName = repr(len(self.rendererSegmentWidgetList))+':Linear' @@ -2096,7 +2096,7 @@ class ParticlePanel(AppShell): seg = cim.getSegment(cim.addStepwave()) else: seg = cim.getSegment(id) - + if(ren.__class__.__name__ == 'SpriteParticleRendererExt'): parent = self.rendererSpriteSegmentFrame segName = repr(len(self.rendererSegmentWidgetList))+':Stepwave' @@ -2116,7 +2116,7 @@ class ParticlePanel(AppShell): seg = cim.getSegment(cim.addSinusoid()) else: seg = cim.getSegment(id) - + if(ren.__class__.__name__ == 'SpriteParticleRendererExt'): parent = self.rendererSpriteSegmentFrame segName = repr(len(self.rendererSegmentWidgetList))+':Sinusoid' @@ -2144,7 +2144,7 @@ class ParticlePanel(AppShell): self.addLinearInterpolationSegment(id) elif isinstance(fun,ColorInterpolationFunctionConstant): self.addConstantInterpolationSegment(id) - + def createInterpolationSegmentFrame(self, parent, segName, seg): frame = Frame(parent, relief = RAISED, borderwidth = 2) lFrame = Frame(frame, relief = FLAT) diff --git a/direct/src/tkpanels/TaskManagerPanel.py b/direct/src/tkpanels/TaskManagerPanel.py index ab4557ffef..8030f06c2a 100644 --- a/direct/src/tkpanels/TaskManagerPanel.py +++ b/direct/src/tkpanels/TaskManagerPanel.py @@ -23,7 +23,7 @@ class TaskManagerPanel(AppShell): self.defineoptions(kw, optiondefs) self.taskMgr = taskMgr - + # Call superclass initialization function AppShell.__init__(self, parent = parent) @@ -80,7 +80,7 @@ class TaskManagerWidget(DirectObject): self._popupMenu.add_command( label = 'Remove Matching Tasks', command = self.removeMatchingTasks) - + # Controls Frame controlsFrame = Frame(parent) self.removeButton = Button(controlsFrame, text = 'Remove Task', @@ -112,7 +112,7 @@ class TaskManagerWidget(DirectObject): controlsFrame.pack(fill = X) controlsFrame.grid_columnconfigure(0, weight = 1) controlsFrame.grid_columnconfigure(1, weight = 1) - + # Add hook to spawnTaskEvents self.accept('TaskManager-spawnTask', self.spawnTaskHook) self.accept('TaskManager-removeTask', self.removeTaskHook) @@ -158,7 +158,7 @@ class TaskManagerWidget(DirectObject): taskNames.append(task.getName()) self.__taskDict[count] = task count += 1 - + if taskNames: self.taskListBox.setlist(taskNames) # And set current index (so keypresses will start with index 0) @@ -217,5 +217,5 @@ class TaskManagerWidget(DirectObject): def onDestroy(self): self.ignore('TaskManager-spawnTask') self.ignore('TaskManager-removeTask') - + diff --git a/direct/src/tkwidgets/MemoryExplorer.py b/direct/src/tkwidgets/MemoryExplorer.py index d0c5df6270..325e95b74d 100755 --- a/direct/src/tkwidgets/MemoryExplorer.py +++ b/direct/src/tkwidgets/MemoryExplorer.py @@ -14,7 +14,7 @@ class MemoryExplorer(Pmw.MegaWidget, DirectObject): #-------------------------------------------------------------------------- # Init - #-------------------------------------------------------------------------- + #-------------------------------------------------------------------------- def __init__(self, parent = None, nodePath = None, **kw): if nodePath is None: nodePath = render @@ -24,19 +24,19 @@ class MemoryExplorer(Pmw.MegaWidget, DirectObject): Pmw.MegaWidget.__init__(self, parent) self.nodePath = nodePath - self.renderItem = None + self.renderItem = None self.render2dItem = None self.buttons = [] self.labels = [] self.rootItem = None - self.btWidth = DEFAULT_BT_WIDTH - - self.createScrolledFrame() + self.btWidth = DEFAULT_BT_WIDTH + + self.createScrolledFrame() self.createScale() self.createRefreshBT() - + self.balloon = Pmw.Balloon(self.interior()) def createScrolledFrame(self): @@ -57,32 +57,32 @@ class MemoryExplorer(Pmw.MegaWidget, DirectObject): resolution = 0.1, orient = HORIZONTAL, command = self.onScaleUpdate) - + self.scaleCtrl.pack(side = LEFT, fill = BOTH, expand = 1) self.scaleCtrl.set(0.0) - + def createRefreshBT(self): self.refreshBT = Button(self.interior(), text = 'Refresh', command = self.refresh) self.refreshBT.pack(side = LEFT, fill = BOTH, expand = 1) #-------------------------------------------------------------------------- # Item Ctrls - #-------------------------------------------------------------------------- + #-------------------------------------------------------------------------- def createDefaultCtrls(self): if self.renderItem == None or self.render2dItem == None: return - + totalBytes = self.renderItem.getVertexBytes()+self.render2dItem.getVertexBytes() - + self.addChildCtrl(self.renderItem, totalBytes) self.addChildCtrl(self.render2dItem, totalBytes) self.setTitle("ALL", totalBytes) - - def setTitle(self, parent, bytes): - self.frame["label_text"] = "[%s] - %s bytes" % (parent, bytes) - def resetCtrls(self): + def setTitle(self, parent, bytes): + self.frame["label_text"] = "[%s] - %s bytes" % (parent, bytes) + + def resetCtrls(self): for button in self.buttons: self.balloon.unbind(button) button.destroy() @@ -92,8 +92,8 @@ class MemoryExplorer(Pmw.MegaWidget, DirectObject): label.destroy() self.labels = [] - def getNewButton(self, width, ratio): - newBT = Button(self.frame.interior(), + def getNewButton(self, width, ratio): + newBT = Button(self.frame.interior(), anchor = W, width = width) @@ -114,12 +114,12 @@ class MemoryExplorer(Pmw.MegaWidget, DirectObject): self.onSelfButtonLClick, self.onSelfButtonRClick, item) - + def addChildCtrl(self, item, totalBytes): self.addLabel("%s [+%s] : %s bytes" % (item.getName(), item.getNumChildren(), item.getVertexBytes())) - + bt = self.addButton(item.getVertexBytes(), totalBytes, self.onChildButtonLClick, @@ -138,34 +138,34 @@ class MemoryExplorer(Pmw.MegaWidget, DirectObject): def callbackL(event): funcLClick(item) - + def callbackR(event): funcRClick(item) bt.bind("", callbackL) bt.bind("", callbackR) - + bt.pack(side = TOP, anchor = NW) self.buttons.append(bt) - self.balloon.bind(bt, item.getPathName()) + self.balloon.bind(bt, item.getPathName()) return bt def addLabel(self, label): label = Label(self.frame.interior(), text = label) label.pack(side = TOP, anchor = NW, expand = 0) - self.labels.append(label) + self.labels.append(label) def getBTWidth(self, vertexBytes, totalBytes): if totalBytes == 0: return 1 - + width = int(self.btWidth * vertexBytes / totalBytes) if width == 0: width = 1 - + return width #-------------------------------------------------------------------------- @@ -187,52 +187,52 @@ class MemoryExplorer(Pmw.MegaWidget, DirectObject): for item in self.rootItem.getChildren(): self.buttons[btIndex]['width'] = self.getBTWidth(item.getVertexBytes(), self.rootItem.getVertexBytes()) - btIndex += 1 + btIndex += 1 def updateDefaultBTWidth(self): if self.renderItem == None or self.render2dItem == None: return totalBytes = self.renderItem.getVertexBytes() + self.render2dItem.getVertexBytes() self.buttons[0]['width'] = self.getBTWidth(self.renderItem.getVertexBytes(), totalBytes) - self.buttons[1]['width'] = self.getBTWidth(self.render2dItem.getVertexBytes(), totalBytes) - + self.buttons[1]['width'] = self.getBTWidth(self.render2dItem.getVertexBytes(), totalBytes) + def onSelfButtonLClick(self, item): pass def onSelfButtonRClick(self, item): parentItem = item.getParent() self.resetCtrls() - self.addItemCtrls(parentItem) + self.addItemCtrls(parentItem) def onChildButtonLClick(self, item): if item.getNumChildren() == 0: return - + self.resetCtrls() self.addItemCtrls(item) def onChildButtonRClick(self, item): parentItem = item.getParent() - + if parentItem: - self.resetCtrls() + self.resetCtrls() self.addItemCtrls(parentItem.getParent()) def addItemCtrls(self, item): - self.rootItem = item + self.rootItem = item if item == None: self.createDefaultCtrls() else: self.addSelfCtrl(item, item.getVertexBytes()) - + for child in item.getChildren(): self.addChildCtrl(child, item.getVertexBytes()) - + self.setTitle(item.getPathName(), item.getVertexBytes()) #-------------------------------------------------------------------------- # List & Analyze - #-------------------------------------------------------------------------- + #-------------------------------------------------------------------------- def makeList(self): self.renderItem = MemoryExplorerItem(None, render) self.buildList(self.renderItem) @@ -240,7 +240,7 @@ class MemoryExplorer(Pmw.MegaWidget, DirectObject): self.render2dItem = MemoryExplorerItem(None, render2d) self.buildList(self.render2dItem) - def buildList(self, parentItem): + def buildList(self, parentItem): for nodePath in parentItem.nodePath.getChildren(): item = MemoryExplorerItem(parentItem, nodePath) parentItem.addChild(item) @@ -249,11 +249,11 @@ class MemoryExplorer(Pmw.MegaWidget, DirectObject): def analyze(self): self.renderItem.analyze() self.render2dItem.analyze() - - def refresh(self): + + def refresh(self): self.makeList() self.analyze() - + self.resetCtrls() self.createDefaultCtrls() @@ -264,10 +264,10 @@ class MemoryExplorerItem: self.parent = parent self.nodePath = nodePath self.children = [] - + self.selfVertexBytes = 0 self.childrenVertexBytes = 0 - + self.numFaces = 0 self.textureBytes = 0 @@ -303,15 +303,15 @@ class MemoryExplorerItem: def analyze(self): self.selfVertexBytes = 0 self.childrenVertexBytes = 0 - + self.numFaces = 0 self.textureBytes = 0 - + self.calcTextureBytes() - + if self.nodePath.node().isGeomNode(): geomNode = self.nodePath.node() - + for i in range(geomNode.getNumGeoms()): geom = geomNode.getGeom(i) self.calcVertexBytes(geom) @@ -332,7 +332,7 @@ class MemoryExplorerItem: self.textureBytes += tex.estimateTextureMemory() # what about shared textures by multiple nodes ? - + def calcNumFaces(self, geom): for k in range(geom.getNumPrimitives()): primitive = geom.getPrimitive(k) @@ -342,11 +342,11 @@ class MemoryExplorerItem: for child in self.children: child.analyze() self.childrenVertexBytes += child.getVertexBytes() - self.numFaces += child.numFaces + self.numFaces += child.numFaces def ls(self, indent = ""): print(indent + self.nodePath.getName() + " " + str(self.vertexBytes) + " " + str(self.numFaces) + " " + str(self.textureBytes)) indent = indent + " " for child in self.children: - child.ls(indent) + child.ls(indent) diff --git a/direct/src/tkwidgets/SceneGraphExplorer.py b/direct/src/tkwidgets/SceneGraphExplorer.py index a26f78e172..2c5c965056 100644 --- a/direct/src/tkwidgets/SceneGraphExplorer.py +++ b/direct/src/tkwidgets/SceneGraphExplorer.py @@ -136,7 +136,7 @@ class SceneGraphExplorer(Pmw.MegaWidget, DirectObject): # Remove hooks self.ignore('DIRECT_activeParent') self.ignore('SGE_Update Explorer') - + def updateSelection(self, searchKey): # [gjeon] update SGE selection with directSession sceneGraphItem = self._node.find(searchKey) diff --git a/direct/src/tkwidgets/Tree.py b/direct/src/tkwidgets/Tree.py index 45857934b8..7e864aaad3 100644 --- a/direct/src/tkwidgets/Tree.py +++ b/direct/src/tkwidgets/Tree.py @@ -60,7 +60,7 @@ class TreeNode: def setChildrenTag(self, tag, fModeChildrenTag): self.childrenTag = tag self.fModeChildrenTag = fModeChildrenTag - + def destroy(self): if self._popupMenu: self._popupMenu.destroy() @@ -135,7 +135,7 @@ class TreeNode: value = i, indicatoron = 0, command = self.popupMenuCommand) - + def popupMenu(self, event=None): if not self._popupMenu: self.createPopupMenu() @@ -146,7 +146,7 @@ class TreeNode: def popupMenuCommand(self): command = self.menuList[self.menuVar.get()] - + if (command == 'Expand All'): self.updateAll(1) elif (command == 'Collapse All'): @@ -264,7 +264,7 @@ class TreeNode: self.x, self.y = x, y self.drawicon() self.drawtext() - + if self.state != 'expanded': return y+17 # draw children @@ -273,7 +273,7 @@ class TreeNode: # IsExpandable() was mistaken; that's allowed return y+17 self.kidKeys = [] - + # [gjeon] to sort children if self.fSortChildren: def compareText(x, y): @@ -353,7 +353,7 @@ class TreeNode: self.canvas.tag_bind(id, "<1>", self.select) self.canvas.tag_bind(id, "", self.flip) self.canvas.tag_bind(id, "<3>", self.popupMenu) - + def drawtext(self): textx = self.x+20-1 texty = self.y-1 diff --git a/direct/src/wxwidgets/ViewPort.py b/direct/src/wxwidgets/ViewPort.py index 2fd21a7a41..b0d03d88c9 100755 --- a/direct/src/wxwidgets/ViewPort.py +++ b/direct/src/wxwidgets/ViewPort.py @@ -3,7 +3,7 @@ Contains classes useful for 3D viewports. Originally written by pro-rsoft, Modified by gjeon. -Modified by Summer 2010 Carnegie Mellon University ETC PandaLE team: fixed a bug in Viewport.Close +Modified by Summer 2010 Carnegie Mellon University ETC PandaLE team: fixed a bug in Viewport.Close """ __all__ = ["Viewport", "ViewportManager"] @@ -34,13 +34,13 @@ class ViewportManager: """Calls initialize() on all the viewports.""" for v in ViewportManager.viewports: v.initialize(*args, **kwargs) - + @staticmethod def updateAll(*args, **kwargs): """Calls Update() on all the viewports.""" for v in ViewportManager.viewports: v.Update(*args, **kwargs) - + @staticmethod def layoutAll(*args, **kwargs): """Calls Layout() on all the viewports.""" @@ -78,7 +78,7 @@ class Viewport(WxPandaWindow, DirectObject): if self.win: self.cam2d = base.makeCamera2d(self.win) self.cam2d.node().setCameraMask(LE_CAM_MASKS[self.name]) - + self.cam = base.camList[-1] self.camera = render.attachNewNode(self.name) #self.camera.setName(self.name) @@ -89,7 +89,7 @@ class Viewport(WxPandaWindow, DirectObject): self.camNode.setCameraMask(LE_CAM_MASKS[self.name]) self.bt = base.setupMouse(self.win, True) - self.bt.node().setPrefix('_le_%s_'%self.name[:3]) + self.bt.node().setPrefix('_le_%s_'%self.name[:3]) mw = self.bt.getParent() mk = mw.getParent() winCtrl = WindowControls( @@ -122,18 +122,18 @@ class Viewport(WxPandaWindow, DirectObject): ## self.accept("page_up", self.zoomIn) ## self.accept("page_up-repeat", self.zoomIn) #self.accept("mouse3", self.onRightDown) - + def Close(self): """Closes the viewport.""" if self.initialized: wx.Window.Close(self) #base.closeWindow(self.win) ViewportManager.viewports.remove(self) - + def onSize(self, evt): """Invoked when the viewport is resized.""" WxPandaWindow.onSize(self, evt) - + if self.win != None: newWidth = self.ClientSize.GetWidth() newHeight = self.ClientSize.GetHeight() @@ -143,7 +143,7 @@ class Viewport(WxPandaWindow, DirectObject): if dr.camNode == self.camNode: dr.updateFilmSize(newWidth, newHeight) break - + def onRightDown(self, evt = None): """Invoked when the viewport is right-clicked.""" if evt == None: @@ -154,13 +154,13 @@ class Viewport(WxPandaWindow, DirectObject): self.Update() #self.PopupMenu(self.menu, mpos) #self.menu.Destroy() - + def zoomOut(self): self.camera.setY(self.camera, -MOUSE_ZOO_SPEED) - + def zoomIn(self): self.camera.setY(self.camera, MOUSE_ZOOM_SPEED) - + @staticmethod def make(parent, vpType = None): """Safe constructor that also takes CREATENEW, VPLEFT, VPTOP, etc.""" @@ -172,7 +172,7 @@ class Viewport(WxPandaWindow, DirectObject): if vpType == VPTOP: return Viewport.makeTop(parent) if vpType == VPPERSPECTIVE: return Viewport.makePerspective(parent) raise TypeError, "Unknown viewport type: %s" % vpType - + @staticmethod def makeOrthographic(parent, name, campos): v = Viewport(name, parent) @@ -195,7 +195,7 @@ class Viewport(WxPandaWindow, DirectObject): collPlane = CollisionNode('FrontGridCol') collPlane.addSolid(CollisionPlane(Plane(0, -1, 0, 0))) collPlane.setIntoCollideMask(BitMask32.bit(21)) - v.collPlane = NodePath(collPlane) + v.collPlane = NodePath(collPlane) v.collPlane.wrtReparentTo(v.grid) #v.grid.gridBack.findAllMatches("**/+GeomNode")[0].setName("_frontViewGridBack") LE_showInOneCam(v.grid, name) @@ -208,7 +208,7 @@ class Viewport(WxPandaWindow, DirectObject): #v.grid.gridBack.findAllMatches("**/+GeomNode")[0].setName("_topViewGridBack") LE_showInOneCam(v.grid, name) return v - + @staticmethod def makePerspective(parent): v = Viewport('persp', parent) @@ -235,7 +235,7 @@ class Viewport(WxPandaWindow, DirectObject): #v.grid.gridBack.findAllMatches("**/+GeomNode")[0].setName("_perspViewGridBack") LE_showInOneCam(v.grid, 'persp') return v - + @staticmethod def makeLeft(parent): return Viewport.makeOrthographic(parent, 'left', Point3(600, 0, 0)) @staticmethod diff --git a/direct/src/wxwidgets/WxAppShell.py b/direct/src/wxwidgets/WxAppShell.py index d74eb34647..1159ff8e32 100755 --- a/direct/src/wxwidgets/WxAppShell.py +++ b/direct/src/wxwidgets/WxAppShell.py @@ -34,7 +34,7 @@ class WxAppShell(wx.Frame): self.appInit() self.__createInterface() self.Show() - + def __createInterface(self): self.__createLogWin() self.__createMenuBar() @@ -103,7 +103,7 @@ class WxAppShell(wx.Frame): # Override if you don't want to use default menus self.menuFile = wx.Menu() self.menuBar.Append(self.menuFile, "&File") - + self.menuHelp = wx.Menu() self.menuBar.Append(self.menuHelp, "&Help") diff --git a/direct/src/wxwidgets/WxPandaShell.py b/direct/src/wxwidgets/WxPandaShell.py index 76420489c7..128eea64b4 100755 --- a/direct/src/wxwidgets/WxPandaShell.py +++ b/direct/src/wxwidgets/WxPandaShell.py @@ -20,17 +20,17 @@ ID_LEFT_VIEW = 404 ID_PERSP_VIEW = 405 class WxPandaShell(WxAppShell): - """ Class for Panda3D LevelEditor """ + """ Class for Panda3D LevelEditor """ frameWidth = 800 frameHeight = 600 appversion = '1.0' appname = 'Panda3D Generic WX Frame' copyright = ('Copyright 2010 Disney Online Studios.' + '\nAll Rights Reserved.') - + MENU_TEXTS = { ID_FOUR_VIEW : ("Four Views", None), - ID_TOP_VIEW : ("Top View", None), + ID_TOP_VIEW : ("Top View", None), ID_FRONT_VIEW : ("Front View", None), ID_LEFT_VIEW : ("Left View", None), ID_PERSP_VIEW : ("Persp View", None), @@ -63,7 +63,7 @@ class WxPandaShell(WxAppShell): menuItem = self.menuView.AppendRadioItem(ID_LEFT_VIEW, self.MENU_TEXTS[ID_LEFT_VIEW][0]) self.Bind(wx.EVT_MENU, lambda p0=None, p1=2:self.onViewChange(p0, p1), menuItem) - + self.perspViewMenuItem = self.menuView.AppendRadioItem(ID_PERSP_VIEW, self.MENU_TEXTS[ID_PERSP_VIEW][0]) self.Bind(wx.EVT_MENU, lambda p0=None, p1=3:self.onViewChange(p0, p1), self.perspViewMenuItem) @@ -90,15 +90,15 @@ class WxPandaShell(WxAppShell): self.leftBarUpPane = wx.Panel(self.leftFrame) self.leftBarDownPane = wx.Panel(self.leftFrame) self.rightBarUpPane = wx.Panel(self.rightFrame) - self.rightBarDownPane = wx.Panel(self.rightFrame) + self.rightBarDownPane = wx.Panel(self.rightFrame) self.leftFrame.SplitHorizontally(self.leftBarUpPane, self.leftBarDownPane) self.rightFrame.SplitHorizontally(self.rightBarUpPane, self.rightBarDownPane) self.mainFrame.SplitVertically(self.leftFrame, self.baseFrame, 200) self.baseFrame.SplitVertically(self.viewFrame, self.rightFrame, 600) - + self.leftFrame.SetSashGravity(0.5) - self.rightFrame.SetSashGravity(0.5) + self.rightFrame.SetSashGravity(0.5) self.baseFrame.SetSashGravity(1.0) sizer = wx.BoxSizer(wx.VERTICAL) @@ -178,7 +178,7 @@ class WxPandaShell(WxAppShell): base.direct.cameraControl.useMayaCamControls = 1 base.direct.cameraControl.perspCollPlane = self.perspView.collPlane base.direct.cameraControl.perspCollPlane2 = self.perspView.collPlane2 - + for widget in base.direct.manipulationControl.widgetList: widget.setBin('gui-popup', 0) widget.setDepthTest(0) @@ -196,7 +196,7 @@ class WxPandaShell(WxAppShell): else: base.direct=None #base.closeWindow(base.win) - base.win = base.winList[3] + base.win = base.winList[3] def wxStep(self, task = None): """A step in the WX event loop. You can either call this yourself or use as task.""" @@ -212,7 +212,7 @@ class WxPandaShell(WxAppShell): self.oldLoop = wx.EventLoop.GetActive() wx.EventLoop.SetActive(self.evtLoop) taskMgr.add(self.wxStep, "evtLoopTask") - + def onViewChange(self, evt, viewIdx): for i in range(4): if viewIdx >=0 and\ @@ -222,7 +222,7 @@ class WxPandaShell(WxAppShell): base.winList[i].setActive(1) self.viewFrame.SetExpanded(viewIdx) - + def getCurrentView(self): """Function for get the current Viewport""" if self.viewFrame._expanded == -1: #four view @@ -235,7 +235,7 @@ class WxPandaShell(WxAppShell): self.currentView = self.leftView if self.viewFrame._expanded == 3: #perspect view self.currentView = self.perspView - - return self.currentView - + + return self.currentView + diff --git a/direct/src/wxwidgets/WxPandaWindow.py b/direct/src/wxwidgets/WxPandaWindow.py index 32083c83d1..6d4ccd335b 100644 --- a/direct/src/wxwidgets/WxPandaWindow.py +++ b/direct/src/wxwidgets/WxPandaWindow.py @@ -146,11 +146,11 @@ else: attribList.append(32) kw['attribList'] = attribList - + base.startWx() wxgl.GLCanvas.__init__(self, *args, **kw) self.visible = False - + # Can't share the GSG when a new wxgl.GLContext is created # automatically. gsg = None @@ -298,7 +298,7 @@ else: # Don't upcall() in this case. return - + elif cbType == CallbackGraphicsWindow.RCTEndFlip: self.SwapBuffers() @@ -322,7 +322,7 @@ else: # ensure an idle event comes in later, and check the size # again then. wx.WakeUpIdle() - + event.Skip() def onPaint(self, event): diff --git a/direct/src/wxwidgets/WxSlider.py b/direct/src/wxwidgets/WxSlider.py index 4a8c64c541..f42026ee25 100755 --- a/direct/src/wxwidgets/WxSlider.py +++ b/direct/src/wxwidgets/WxSlider.py @@ -20,7 +20,7 @@ class WxSlider(wx.Slider): intMax = 100 self.textValue = None self.updateCB = None - + if style & wx.SL_HORIZONTAL: newStyle = wx.SL_HORIZONTAL if style & wx.SL_LABELS: @@ -81,13 +81,13 @@ class WxSlider(wx.Slider): # overriding wx.Slider.Disable() wx.Slider.Disable(self) self.textValue.Disable() - + def Enable(self): # overriding wx.Slider.Enable() wx.Slider.Enable(self) self.Bind(wx.EVT_SLIDER, self.onChange) - + if not self.textValue is None: self.textValue.Enable() - self.textValue.Bind(wx.EVT_TEXT_ENTER, self.onEnter) + self.textValue.Bind(wx.EVT_TEXT_ENTER, self.onEnter) diff --git a/makepanda/getversion.py b/makepanda/getversion.py index 5d74316aec..4595c0d589 100755 --- a/makepanda/getversion.py +++ b/makepanda/getversion.py @@ -1,17 +1,17 @@ -#!/usr/bin/env python - -# This script parses the version number in dtool/PandaVersion.pp -# and returns it on the command-line. This is useful for the -# automated scripts that build the Panda3D releases. - -from makepandacore import ParsePandaVersion, ParsePluginVersion -import sys - -if '--runtime' in sys.argv: - version = ParsePluginVersion("dtool/PandaVersion.pp") -else: - version = ParsePandaVersion("dtool/PandaVersion.pp") - -version = version.strip() -sys.stdout.write(version) -sys.stdout.flush() +#!/usr/bin/env python + +# This script parses the version number in dtool/PandaVersion.pp +# and returns it on the command-line. This is useful for the +# automated scripts that build the Panda3D releases. + +from makepandacore import ParsePandaVersion, ParsePluginVersion +import sys + +if '--runtime' in sys.argv: + version = ParsePluginVersion("dtool/PandaVersion.pp") +else: + version = ParsePandaVersion("dtool/PandaVersion.pp") + +version = version.strip() +sys.stdout.write(version) +sys.stdout.flush() diff --git a/makepanda/makechm.py b/makepanda/makechm.py index a26101cb27..1127eb41f5 100755 --- a/makepanda/makechm.py +++ b/makepanda/makechm.py @@ -68,9 +68,9 @@ REFERENCEITEMS = [ ("classes.html", "Classes"), ] -def urldecode(url): - regex = re.compile("%([0-9a-hA-H][0-9a-hA-H])", re.M) - return regex.sub(lambda x: chr(int(x.group(1), 16)), url) +def urldecode(url): + regex = re.compile("%([0-9a-hA-H][0-9a-hA-H])", re.M) + return regex.sub(lambda x: chr(int(x.group(1), 16)), url) def ireplace(string, target, replacement): """Case-insensitive replace.""" @@ -142,7 +142,7 @@ def treeToHTML(tree, dirname, indent = ""): html += indent + "
    \n" html += treeToHTML(sub, dirname, indent + " ") html += indent + "
\n" - return html + return html def makeCHM(outputfile, dirname, title, special = None): """Creates a CHM file based on a directory of HTML files. See the top of this file for more info.""" @@ -256,7 +256,7 @@ if __name__ == "__main__": except: # If not, we don't care at all. pass - + # Now, make CHM's for both the manual and reference, if we have them. for lang in ["python", "cxx"]: if not os.path.isdir("manual-" + lang): @@ -267,7 +267,7 @@ if __name__ == "__main__": makeManualCHM("manual-%s.chm" % lang, "manual-" + lang, "Panda3D Manual") else: makeManualCHM("manual-%s-%s.chm" % (VERSION, lang), "manual-" + lang, "Panda3D %s Manual" % VERSION) - + if not os.path.isdir("reference-" + lang): print "No directory named 'reference-%s' found" % lang else: @@ -276,6 +276,6 @@ if __name__ == "__main__": makeReferenceCHM("reference-%s.chm" % lang, "reference-" + lang, "Panda3D Reference") else: makeReferenceCHM("reference-%s-%s.chm" % (VERSION, lang), "reference-" + lang, "Panda3D %s Reference" % VERSION) - + print "Done!" diff --git a/panda/src/iphone/ipfreeze.py b/panda/src/iphone/ipfreeze.py index 542a64ab89..5a7462eb9e 100755 --- a/panda/src/iphone/ipfreeze.py +++ b/panda/src/iphone/ipfreeze.py @@ -27,7 +27,7 @@ if __name__ == '__main__': basename = 'iphone_runappmf' #link_all_static = True link_all_static = False - + try: opts, args = getopt.getopt(sys.argv[1:], 'h') except getopt.error, msg: @@ -47,7 +47,7 @@ if __name__ == '__main__': platform = 'IPhoneSimulator' else: platform = 'IPhoneOS' - + version = '2.0' dev = '/Developer/Platforms/%s.platform/Developer' % (platform) env = 'env MACOSX_DEPLOYMENT_TARGET=10.5 PATH="%s/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"' % (dev) diff --git a/panda/src/iphone/provision.py b/panda/src/iphone/provision.py index a51aea2dd8..47a445d3cc 100755 --- a/panda/src/iphone/provision.py +++ b/panda/src/iphone/provision.py @@ -32,7 +32,7 @@ command = 'env CODESIGN_ALLOCATE="/Developer/Platforms/iPhoneOS.platform/Develop 'identity' : identity, 'app' : app, 'xcent' : xcent, - } + } print command result = os.system(command) diff --git a/panda/src/testbed/test_native_net1.py b/panda/src/testbed/test_native_net1.py index 544466aa00..0e4738e8ad 100644 --- a/panda/src/testbed/test_native_net1.py +++ b/panda/src/testbed/test_native_net1.py @@ -1,38 +1,38 @@ -from libpandaexpress import BufferedDatagramConnection -from libpandaexpress import SocketAddress -from libpandaexpress import SocketIP -from libpandaexpress import SocketTCP -from libpandaexpress import SocketTCPListen -from libpandaexpress import SocketUDPOutgoing -from libpandaexpress import SocketUDPIncoming - - -SocketIP.InitNetworkDriver(); - -addr = SocketAddress() -addr.setHost("127.0.0.1",8080) -print addr.getIpPort() - - -inbound = SocketTCPListen() -inbound.OpenForListen(addr); -##inbound.SetNonBlocking(); - -while 1 == 1: - newsession = SocketTCP() - source = SocketAddress() - if inbound.GetIncomingConnection(newsession,source) : - #newsession.SetNonBlocking(); - print source.getIpPort() - newsession.SendData("Hello From the Listener\n\r"); - - s = newsession.RecvData(10); - print s - print newsession.GetLastError() - if newsession.ErrorIsWouldBlocking(newsession.GetLastError()) : - print "Reading Would Block" - else: - print "Not A Blocking Error" - - newsession.SendData("GoodBy From the Listener\n\r"); - newsession.Close(); +from libpandaexpress import BufferedDatagramConnection +from libpandaexpress import SocketAddress +from libpandaexpress import SocketIP +from libpandaexpress import SocketTCP +from libpandaexpress import SocketTCPListen +from libpandaexpress import SocketUDPOutgoing +from libpandaexpress import SocketUDPIncoming + + +SocketIP.InitNetworkDriver(); + +addr = SocketAddress() +addr.setHost("127.0.0.1",8080) +print addr.getIpPort() + + +inbound = SocketTCPListen() +inbound.OpenForListen(addr); +##inbound.SetNonBlocking(); + +while 1 == 1: + newsession = SocketTCP() + source = SocketAddress() + if inbound.GetIncomingConnection(newsession,source) : + #newsession.SetNonBlocking(); + print source.getIpPort() + newsession.SendData("Hello From the Listener\n\r"); + + s = newsession.RecvData(10); + print s + print newsession.GetLastError() + if newsession.ErrorIsWouldBlocking(newsession.GetLastError()) : + print "Reading Would Block" + else: + print "Not A Blocking Error" + + newsession.SendData("GoodBy From the Listener\n\r"); + newsession.Close(); diff --git a/panda/src/testbed/test_native_net2.py b/panda/src/testbed/test_native_net2.py index 47a23e0501..44c197911b 100644 --- a/panda/src/testbed/test_native_net2.py +++ b/panda/src/testbed/test_native_net2.py @@ -1,49 +1,49 @@ -from libpandaexpress import BufferedDatagramConnection -from libpandaexpress import SocketAddress -from libpandaexpress import SocketIP -from libpandaexpress import SocketTCP -from libpandaexpress import SocketTCPListen -from libpandaexpress import SocketUDPOutgoing -from libpandaexpress import SocketUDPIncoming -from libpandaexpress import Datagram - -import time - - - -SocketIP.InitNetworkDriver(); - -addr = SocketAddress() -addr.setHost("127.0.0.1",6666) -print addr.getIpPort() - -MyConection = BufferedDatagramConnection(0,4096000,4096000,102400); -#help(BufferedDatagramConnection) - -MyConection.AddAddress(addr) - -dg = Datagram(); -dg.addUint8(1) -dg.addUint64(4001) -dg.addUint16(2001) -dg.addUint64(123456) - -##MyConection.SendMessage(dg); - - -dg1 = Datagram(); -dg1.addUint8(1) -dg1.addUint64(123456) -dg1.addUint64(12340) -dg1.addUint16(1000) -dg1.addUint16(54321) - - -while 1==1: - for x in range(200000): - if not MyConection.SendMessage(dg1): - print "Error Sending Message" - - MyConection.Flush(); - time.sleep(1) - print "loop" \ No newline at end of file +from libpandaexpress import BufferedDatagramConnection +from libpandaexpress import SocketAddress +from libpandaexpress import SocketIP +from libpandaexpress import SocketTCP +from libpandaexpress import SocketTCPListen +from libpandaexpress import SocketUDPOutgoing +from libpandaexpress import SocketUDPIncoming +from libpandaexpress import Datagram + +import time + + + +SocketIP.InitNetworkDriver(); + +addr = SocketAddress() +addr.setHost("127.0.0.1",6666) +print addr.getIpPort() + +MyConection = BufferedDatagramConnection(0,4096000,4096000,102400); +#help(BufferedDatagramConnection) + +MyConection.AddAddress(addr) + +dg = Datagram(); +dg.addUint8(1) +dg.addUint64(4001) +dg.addUint16(2001) +dg.addUint64(123456) + +##MyConection.SendMessage(dg); + + +dg1 = Datagram(); +dg1.addUint8(1) +dg1.addUint64(123456) +dg1.addUint64(12340) +dg1.addUint16(1000) +dg1.addUint16(54321) + + +while 1==1: + for x in range(200000): + if not MyConection.SendMessage(dg1): + print "Error Sending Message" + + MyConection.Flush(); + time.sleep(1) + print "loop" diff --git a/panda/src/testbed/test_native_net3.py b/panda/src/testbed/test_native_net3.py index 4f01aac6d3..dff516eb60 100644 --- a/panda/src/testbed/test_native_net3.py +++ b/panda/src/testbed/test_native_net3.py @@ -1,50 +1,50 @@ -from libpandaexpress import BufferedDatagramConnection -from libpandaexpress import SocketAddress -from libpandaexpress import SocketIP -from libpandaexpress import SocketTCP -from libpandaexpress import SocketTCPListen -from libpandaexpress import SocketUDPOutgoing -from libpandaexpress import SocketUDPIncoming -from libpandaexpress import Datagram - -import time - - - -SocketIP.InitNetworkDriver(); - -addr = SocketAddress() -addr.setHost("127.0.0.1",6666) -print addr.getIpPort() - -MyConection = BufferedDatagramConnection(0,4096000,4096000,102400); -#help(BufferedDatagramConnection) - -MyConection.AddAddress(addr) - -dg = Datagram(); -dg.addUint8(1) -dg.addUint64(4001) -dg.addUint16(2001) -dg.addUint64(123456) - -MyConection.SendMessage(dg); - - -dg1 = Datagram(); -dg1.addUint8(1) -dg1.addUint64(123456) -dg1.addUint64(12340) -dg1.addUint16(1000) -dg1.addUint16(54321) - - -while 1==1: - MyConection.SendMessage(dg); - ##for x in range(120000): - while MyConection.GetMessage(): - None - - MyConection.Flush(); - time.sleep(1) - print "loop" \ No newline at end of file +from libpandaexpress import BufferedDatagramConnection +from libpandaexpress import SocketAddress +from libpandaexpress import SocketIP +from libpandaexpress import SocketTCP +from libpandaexpress import SocketTCPListen +from libpandaexpress import SocketUDPOutgoing +from libpandaexpress import SocketUDPIncoming +from libpandaexpress import Datagram + +import time + + + +SocketIP.InitNetworkDriver(); + +addr = SocketAddress() +addr.setHost("127.0.0.1",6666) +print addr.getIpPort() + +MyConection = BufferedDatagramConnection(0,4096000,4096000,102400); +#help(BufferedDatagramConnection) + +MyConection.AddAddress(addr) + +dg = Datagram(); +dg.addUint8(1) +dg.addUint64(4001) +dg.addUint16(2001) +dg.addUint64(123456) + +MyConection.SendMessage(dg); + + +dg1 = Datagram(); +dg1.addUint8(1) +dg1.addUint64(123456) +dg1.addUint64(12340) +dg1.addUint16(1000) +dg1.addUint16(54321) + + +while 1==1: + MyConection.SendMessage(dg); + ##for x in range(120000): + while MyConection.GetMessage(): + None + + MyConection.Flush(); + time.sleep(1) + print "loop" diff --git a/panda/src/tinydisplay/store_pixel.py b/panda/src/tinydisplay/store_pixel.py index b9d2b8cf08..10e5151bf8 100644 --- a/panda/src/tinydisplay/store_pixel.py +++ b/panda/src/tinydisplay/store_pixel.py @@ -32,7 +32,7 @@ CodeTable = { 'mccolor' : '0xffff - zb->blend_ ## i', 'calpha' : 'zb->blend_a', 'mcalpha' : '0xffff - zb->blend_a', -} +} bitnames = 'rgba' @@ -75,7 +75,7 @@ for op_a in Operands: print >> code, "#define STORE_PIXEL_%s(fr, r) (fr)" % (b) print >> code, '#include "store_pixel.h"' print >> code, '' - + # Now, generate the table of function pointers. arraySize = '[%s][%s][16]' % (len(Operands), len(Operands)) diff --git a/panda/src/tinydisplay/ztriangle.py b/panda/src/tinydisplay/ztriangle.py index ca19a09474..e0e5f9a848 100755 --- a/panda/src/tinydisplay/ztriangle.py +++ b/panda/src/tinydisplay/ztriangle.py @@ -155,13 +155,13 @@ def closeCode(): print >> code, '};' code.close() - + def openCode(count): """ Open the code file appropriate to the current segment. We write out the generated code into a series of smaller files, instead of one mammoth file, just to make it easier on the compiler. """ - + global code, codeSeg, fnameList seg = int(NumSegments * count / OptionsCount) + 1 @@ -171,7 +171,7 @@ def openCode(count): codeSeg = seg fnameList = [] - + # Open a new file. code = open('ztriangle_code_%s.h' % (codeSeg), 'wb') print >> code, '/* This file is generated code--do not edit. See ztriangle.py. */' @@ -241,7 +241,7 @@ def writeTableEntry(ops): indent = ' ' * (len(ops) + 1) i = len(ops) numOps = len(FullOptions[i]) - + if i + 1 == len(FullOptions): # The last level: write out the actual function names. for j in range(numOps - 1): diff --git a/samples/mouse-modes/main.py b/samples/mouse-modes/main.py index c0b8ecbdef..6d924b0e9c 100755 --- a/samples/mouse-modes/main.py +++ b/samples/mouse-modes/main.py @@ -4,11 +4,11 @@ Demonstrate different mouse modes ''' # from panda3d.core import loadPrcFileData -# -# loadPrcFileData("", "notify-level-x11display debug") -# loadPrcFileData("", "notify-level-windisplay debug") # -# loadPrcFileData("", "load-display p3tinydisplay") +# loadPrcFileData("", "notify-level-x11display debug") +# loadPrcFileData("", "notify-level-windisplay debug") +# +# loadPrcFileData("", "load-display p3tinydisplay") from panda3d.core import WindowProperties, TextNode from direct.task.TaskManagerGlobal import taskMgr @@ -28,97 +28,97 @@ class App(ShowBase): text = OnscreenText(text = text, pos = (-1.3, .5-.05*i), fg=(0,1,0,1), align = TextNode.ALeft, scale = .05) return text - - + + def setup(self): # Disable the camera trackball controls. self.disableMouse() - + # control mapping of mouse movement to box movement self.mouseMagnitude = 1 self.rotateX, self.rotateY = 0, 0 - self.genLabelText("[0] Absolute mode, [1] Relative mode, [2] Confined mode", 0) - - self.base.accept('0', lambda: self.setMouseMode(WindowProperties.M_absolute)) - self.base.accept('1', lambda: self.setMouseMode(WindowProperties.M_relative)) + self.genLabelText("[0] Absolute mode, [1] Relative mode, [2] Confined mode", 0) + + self.base.accept('0', lambda: self.setMouseMode(WindowProperties.M_absolute)) + self.base.accept('1', lambda: self.setMouseMode(WindowProperties.M_relative)) self.base.accept('2', lambda: self.setMouseMode(WindowProperties.M_confined)) - - self.genLabelText("[C] Manually re-center mouse on each tick", 1) + + self.genLabelText("[C] Manually re-center mouse on each tick", 1) self.base.accept('C', lambda: self.toggleRecenter()) self.base.accept('c', lambda: self.toggleRecenter()) - - self.genLabelText("[S] Show mouse", 2) + + self.genLabelText("[S] Show mouse", 2) self.base.accept('S', lambda: self.toggleMouse()) self.base.accept('s', lambda: self.toggleMouse()) - - self.base.accept('escape', sys.exit, [0]) - - self.mouseText = self.genLabelText("", 5) - self.deltaText = self.genLabelText("", 6) + + self.base.accept('escape', sys.exit, [0]) + + self.mouseText = self.genLabelText("", 5) + self.deltaText = self.genLabelText("", 6) self.positionText = self.genLabelText("", 8) - + self.lastMouseX, self.lastMouseY = None, None - + self.hideMouse = False - + self.setMouseMode(WindowProperties.M_absolute) self.manualRecenterMouse = True # make a box to move with the mouse self.model = self.loader.loadModel("box") self.model.reparentTo(self.render) - + self.cam.setPos(0, -5, 0) self.cam.lookAt(0, 0, 0) - + self.mouseTask = taskMgr.add(self.mouseTask, "Mouse Task") - + def setMouseMode(self, mode): print("Changing mode to %s" % mode) - + self.mouseMode = mode - + wp = WindowProperties() wp.setMouseMode(mode) self.base.win.requestProperties(wp) - + # these changes may require a tick to apply self.base.taskMgr.doMethodLater(0, self.resolveMouse, "Resolve mouse setting") - + def resolveMouse(self, t): wp = self.base.win.getProperties() - + actualMode = wp.getMouseMode() if self.mouseMode != actualMode: print("ACTUAL MOUSE MODE: %s" % actualMode) - + self.mouseMode = actualMode - + self.rotateX, self.rotateY = -.5, -.5 self.lastMouseX, self.lastMouseY = None, None self.recenterMouse() def recenterMouse(self): - self.base.win.movePointer(0, + self.base.win.movePointer(0, int(self.base.win.getProperties().getXSize() / 2), int(self.base.win.getProperties().getYSize() / 2)) - + def toggleRecenter(self): print("Toggling re-center behavior") self.manualRecenterMouse = not self.manualRecenterMouse - + def toggleMouse(self): print("Toggling mouse visibility") self.hideMouse = not self.hideMouse - + wp = WindowProperties() wp.setCursorHidden(self.hideMouse) self.base.win.requestProperties(wp) - + def mouseTask(self, task): mw = self.base.mouseWatcherNode @@ -126,49 +126,49 @@ class App(ShowBase): if hasMouse: # get the window manager's idea of the mouse position x, y = mw.getMouseX(), mw.getMouseY() - + if self.lastMouseX is not None: # get the delta if self.manualRecenterMouse: # when recentering, the position IS the delta # since the center is reported as 0, 0 - dx, dy = x, y + dx, dy = x, y else: dx, dy = x - self.lastMouseX, y - self.lastMouseY else: # no data to compare with yet dx, dy = 0, 0 - + self.lastMouseX, self.lastMouseY = x, y - + else: x, y, dx, dy = 0, 0, 0, 0 if self.manualRecenterMouse: # move mouse back to center - self.recenterMouse() - self.lastMouseX, self.lastMouseY = 0, 0 - + self.recenterMouse() + self.lastMouseX, self.lastMouseY = 0, 0 + # scale position and delta to pixels for user w, h = self.win.getSize() - + self.mouseText.setText("Mode: {0}, Recenter: {1} | Mouse: {2}, {3} | hasMouse: {4}".format( self.mouseMode, self.manualRecenterMouse, - int(x*w), int(y*h), - hasMouse)) + int(x*w), int(y*h), + hasMouse)) self.deltaText.setText("Delta: {0}, {1}".format( - int(dx*w), int(dy*h))) + int(dx*w), int(dy*h))) # rotate box by delta self.rotateX += dx * 10 * self.mouseMagnitude self.rotateY += dy * 10 * self.mouseMagnitude self.positionText.setText("Model rotation: {0}, {1}".format( - int(self.rotateX*1000)/1000., int(self.rotateY*1000)/1000.)) - + int(self.rotateX*1000)/1000., int(self.rotateY*1000)/1000.)) + self.model.setH(self.rotateX) self.model.setP(self.rotateY) return Task.cont - + app = App() app.run()