From b6eee1045a4c7469f1e75b22ef0e4ecb9df76394 Mon Sep 17 00:00:00 2001 From: rdb Date: Wed, 11 Oct 2023 00:08:25 +0200 Subject: [PATCH] direct: Reduce dependence on builtins, satisfy mypy a bit more --- direct/src/directtools/DirectManipulation.py | 420 ++++++++++--------- direct/src/directtools/DirectSession.py | 98 +++-- direct/src/leveleditor/LevelEditorUIBase.py | 55 +-- direct/src/leveleditor/LevelLoader.py | 3 + direct/src/showbase/ShowBase.py | 6 +- direct/src/showbase/ShowBaseGlobal.py | 2 + direct/src/showutil/TexMemWatcher.py | 10 +- direct/src/tkpanels/DirectSessionPanel.py | 179 ++++---- direct/src/tkpanels/Inspector.py | 5 +- direct/src/tkpanels/Placer.py | 51 +-- direct/src/wxwidgets/WxPandaShell.py | 82 ++-- 11 files changed, 488 insertions(+), 423 deletions(-) diff --git a/direct/src/directtools/DirectManipulation.py b/direct/src/directtools/DirectManipulation.py index d77a7de7e3..98d48a9aa5 100644 --- a/direct/src/directtools/DirectManipulation.py +++ b/direct/src/directtools/DirectManipulation.py @@ -14,6 +14,8 @@ from panda3d.core import ( ) from direct.showbase.DirectObject import DirectObject from direct.showbase.MessengerGlobal import messenger +from direct.showbase.ShowBaseGlobal import hidden +from direct.showbase import ShowBaseGlobal from . import DirectGlobals as DG from .DirectUtil import useDirectRenderStyle from .DirectGeometry import ( @@ -28,6 +30,7 @@ from .DirectSelection import SelectionRay from direct.task import Task from direct.task.TaskManagerGlobal import taskMgr from copy import deepcopy +from typing import Optional class DirectManipulationControl(DirectObject): @@ -37,14 +40,16 @@ class DirectManipulationControl(DirectObject): self.hitPt = Point3(0) self.prevHit = Vec3(0) + self.widgetList: list[ObjectHandles] = [] + self.hitPtScale = Point3(0) # [gjeon] to be used in new LE's camera control self.prevHitScale = Vec3(0) # [gjeon] to be used in new LE's camera control self.rotationCenter = Point3(0) self.initScaleMag = 1 - self.manipRef = base.direct.group.attachNewNode('manipRef') + self.manipRef = ShowBaseGlobal.direct.group.attachNewNode('manipRef') self.hitPtDist = 0 - self.constraint = None + self.constraint: Optional[str] = None self.rotateAxis = 'x' self.lastCrankAngle = 0 self.fSetCoa = 0 @@ -91,8 +96,8 @@ class DirectManipulationControl(DirectObject): self.fGridSnap = 0 def scaleWidget(self, factor): - if hasattr(base.direct, 'widget'): - base.direct.widget.multiplyScalingFactorBy(factor) + if hasattr(ShowBaseGlobal.direct, 'widget'): + ShowBaseGlobal.direct.widget.multiplyScalingFactorBy(factor) else: self.objectHandles.multiplyScalingFactorBy(factor) @@ -127,7 +132,7 @@ class DirectManipulationControl(DirectObject): # Start out in select mode self.mode = 'select' - if base.direct.cameraControl.useMayaCamControls and modifiers == 4: + if ShowBaseGlobal.direct.cameraControl.useMayaCamControls and modifiers == 4: self.mode = 'camera' if self.fAllowSelectionOnly: @@ -137,7 +142,7 @@ class DirectManipulationControl(DirectObject): self.fScaling3D == 0: # Check for a widget hit point - entry = base.direct.iRay.pickWidget(skipFlags = DG.SKIP_WIDGET) + entry = ShowBaseGlobal.direct.iRay.pickWidget(skipFlags = DG.SKIP_WIDGET) # Did we hit a widget? if entry: # Yes! @@ -149,13 +154,13 @@ class DirectManipulationControl(DirectObject): # Nope, off the widget, no constraint self.constraint = None # [gjeon] to prohibit unwanted object movement while direct window doesn't have focus - if base.direct.cameraControl.useMayaCamControls and not base.direct.gotControl(modifiers) \ + if ShowBaseGlobal.direct.cameraControl.useMayaCamControls and not ShowBaseGlobal.direct.gotControl(modifiers) \ and not self.fAllowMarquee: return else: entry = None - if not base.direct.gotAlt(modifiers): + if not ShowBaseGlobal.direct.gotAlt(modifiers): if entry: # Check to see if we are moving the object # We are moving the object if we either wait long enough @@ -165,18 +170,18 @@ class DirectManipulationControl(DirectObject): # Or we move far enough self.moveDir = None watchMouseTask = Task.Task(self.watchMouseTask) - watchMouseTask.initX = base.direct.dr.mouseX - watchMouseTask.initY = base.direct.dr.mouseY + watchMouseTask.initX = ShowBaseGlobal.direct.dr.mouseX + watchMouseTask.initY = ShowBaseGlobal.direct.dr.mouseY taskMgr.add(watchMouseTask, 'manip-watch-mouse') else: - if base.direct.fControl: + if ShowBaseGlobal.direct.fControl: self.mode = 'move' self.manipulateObject() - elif not base.direct.fAlt and self.fAllowMarquee: + elif not ShowBaseGlobal.direct.fAlt and self.fAllowMarquee: self.moveDir = None watchMarqueeTask = Task.Task(self.watchMarqueeTask) - watchMarqueeTask.initX = base.direct.dr.mouseX - watchMarqueeTask.initY = base.direct.dr.mouseY + watchMarqueeTask.initX = ShowBaseGlobal.direct.dr.mouseX + watchMarqueeTask.initY = ShowBaseGlobal.direct.dr.mouseY taskMgr.add(watchMarqueeTask, 'manip-marquee-mouse') def switchToWorldSpaceMode(self): @@ -192,8 +197,8 @@ class DirectManipulationControl(DirectObject): return Task.done def watchMouseTask(self, state): - if (abs(state.initX - base.direct.dr.mouseX) > 0.01 or - abs(state.initY - base.direct.dr.mouseY) > 0.01): + if (abs(state.initX - ShowBaseGlobal.direct.dr.mouseX) > 0.01 or + abs(state.initY - ShowBaseGlobal.direct.dr.mouseY) > 0.01): taskMgr.remove('manip-move-wait') self.mode = 'move' self.manipulateObject() @@ -213,19 +218,19 @@ class DirectManipulationControl(DirectObject): self.marquee.removeNode() self.marquee = None - if base.direct.cameraControl.useMayaCamControls and base.direct.fAlt: + if ShowBaseGlobal.direct.cameraControl.useMayaCamControls and ShowBaseGlobal.direct.fAlt: return - if base.direct.fControl: + if ShowBaseGlobal.direct.fControl: return - endX = base.direct.dr.mouseX - endY = base.direct.dr.mouseY + endX = ShowBaseGlobal.direct.dr.mouseX + endY = ShowBaseGlobal.direct.dr.mouseY if (abs(endX - startX) < 0.01 and abs(endY - startY) < 0.01): return - self.marquee = LineNodePath(base.render2d, 'marquee', 0.5, VBase4(.8, .6, .6, 1)) + self.marquee = LineNodePath(ShowBaseGlobal.base.render2d, 'marquee', 0.5, VBase4(.8, .6, .6, 1)) self.marqueeInfo = (startX, startY, endX, endY) self.marquee.drawLines([ [(startX, 0, startY), (startX, 0, endY)], @@ -235,15 +240,17 @@ class DirectManipulationControl(DirectObject): self.marquee.create() if self.fMultiView: - DG.LE_showInOneCam(self.marquee, base.direct.camera.getName()) + DG.LE_showInOneCam(self.marquee, ShowBaseGlobal.direct.camera.getName()) def manipulationStop(self): taskMgr.remove('manipulateObject') taskMgr.remove('manip-move-wait') taskMgr.remove('manip-watch-mouse') taskMgr.remove('manip-marquee-mouse') + direct = ShowBaseGlobal.direct # depending on flag..... if self.mode == 'select': + base = ShowBaseGlobal.base # Check for object under mouse # Don't intersect with hidden or backfacing objects, as well as any # optionally specified things @@ -254,7 +261,7 @@ class DirectManipulationControl(DirectObject): if self.marquee: self.marquee.removeNode() self.marquee = None - base.direct.deselectAll() + direct.deselectAll() startX = self.marqueeInfo[0] startY = self.marqueeInfo[1] @@ -270,31 +277,31 @@ class DirectManipulationControl(DirectObject): nur = Point3(0, 0, 0) nul = Point3(0, 0, 0) - lens = base.direct.cam.node().getLens() + lens = direct.cam.node().getLens() lens.extrude((startX, startY), nul, ful) lens.extrude((endX, startY), nur, fur) lens.extrude((endX, endY), nlr, flr) lens.extrude((startX, endY), nll, fll) marqueeFrustum = BoundingHexahedron(fll, flr, fur, ful, nll, nlr, nur, nul) - marqueeFrustum.xform(base.direct.cam.getNetTransform().getMat()) + marqueeFrustum.xform(direct.cam.getNetTransform().getMat()) base.marqueeFrustum = marqueeFrustum def findTaggedNodePath(nodePath): # Select tagged object if present - for tag in base.direct.selected.tagList: + for tag in direct.selected.tagList: if nodePath.hasNetTag(tag): nodePath = nodePath.findNetTag(tag) return nodePath return None selectionList = [] - for geom in render.findAllMatches("**/+GeomNode"): + for geom in base.render.findAllMatches("**/+GeomNode"): if (skipFlags & DG.SKIP_HIDDEN) and geom.isHidden(): # Skip if hidden node continue -## elif (skipFlags & DG.SKIP_BACKFACE) and base.direct.iRay.isEntryBackfacing(): +## elif (skipFlags & DG.SKIP_BACKFACE) and direct.iRay.isEntryBackfacing(): ## # Skip, if backfacing poly ## pass elif (skipFlags & DG.SKIP_CAMERA) and \ @@ -303,7 +310,7 @@ class DirectManipulationControl(DirectObject): continue # Can pick unpickable, use the first visible node elif (skipFlags & DG.SKIP_UNPICKABLE) and \ - (geom.getName() in base.direct.iRay.unpickable): + (geom.getName() in direct.iRay.unpickable): # Skip if in unpickable list continue @@ -350,84 +357,86 @@ class DirectManipulationControl(DirectObject): selectionList.append(nodePath) for nodePath in selectionList: - base.direct.select(nodePath, 1) + direct.select(nodePath, 1) else: - entry = base.direct.iRay.pickGeom(skipFlags = skipFlags) + entry = direct.iRay.pickGeom(skipFlags = skipFlags) if entry: # Record hit point information self.hitPt.assign(entry.getSurfacePoint(entry.getFromNodePath())) self.hitPtDist = Vec3(self.hitPt).length() # Select it - base.direct.select(entry.getIntoNodePath(), base.direct.fShift) + direct.select(entry.getIntoNodePath(), direct.fShift) else: - base.direct.deselectAll() + direct.deselectAll() #elif self.mode == 'move': self.manipulateObjectCleanup() self.mode = None def manipulateObjectCleanup(self): + direct = ShowBaseGlobal.direct if self.fScaling3D or self.fScaling1D: # We had been scaling, need to reset object handles - if hasattr(base.direct, 'widget'): - base.direct.widget.transferObjectHandlesScale() + if hasattr(direct, 'widget'): + direct.widget.transferObjectHandlesScale() else: self.objectHandles.transferObjectHandlesScale() self.fScaling3D = 0 self.fScaling1D = 0 - base.direct.selected.highlightAll() - if hasattr(base.direct, 'widget'): - base.direct.widget.showAllHandles() + direct.selected.highlightAll() + if hasattr(direct, 'widget'): + direct.widget.showAllHandles() else: self.objectHandles.showAllHandles() - if base.direct.clusterMode == 'client': - cluster( - 'base.direct.manipulationControl.objectHandles.showAllHandles()') - if hasattr(base.direct, 'widget'): - base.direct.widget.hideGuides() + if direct.clusterMode == 'client': + direct.cluster( + 'direct.manipulationControl.objectHandles.showAllHandles()') + if hasattr(direct, 'widget'): + direct.widget.hideGuides() else: self.objectHandles.hideGuides() # Restart followSelectedNodePath task self.spawnFollowSelectedNodePathTask() messenger.send('DIRECT_manipulateObjectCleanup', - [base.direct.selected.getSelectedAsList()]) + [direct.selected.getSelectedAsList()]) def spawnFollowSelectedNodePathTask(self): # If nothing selected, just return - if not base.direct.selected.last: + if not ShowBaseGlobal.direct.selected.last: return # Clear out old task to make sure taskMgr.remove('followSelectedNodePath') # Where are the object handles relative to the selected object pos = VBase3(0) hpr = VBase3(0) - decomposeMatrix(base.direct.selected.last.mCoa2Dnp, + decomposeMatrix(ShowBaseGlobal.direct.selected.last.mCoa2Dnp, VBase3(0), hpr, pos, CSDefault) # Create the task t = Task.Task(self.followSelectedNodePathTask) # Update state variables t.pos = pos t.hpr = hpr - t.base = base.direct.selected.last + t.base = ShowBaseGlobal.direct.selected.last # Spawn the task taskMgr.add(t, 'followSelectedNodePath') def followSelectedNodePathTask(self, state): - if hasattr(base.direct, "manipulationControl") and base.direct.manipulationControl.fMultiView: - for widget in base.direct.manipulationControl.widgetList: + if hasattr(ShowBaseGlobal.direct, "manipulationControl") and ShowBaseGlobal.direct.manipulationControl.fMultiView: + for widget in ShowBaseGlobal.direct.manipulationControl.widgetList: if self.worldSpaceManip: widget.setPos(state.base, state.pos) - widget.setHpr(render, VBase3(0)) + widget.setHpr(ShowBaseGlobal.base.render, VBase3(0)) else: widget.setPosHpr(state.base, state.pos, state.hpr) else: + widget = ShowBaseGlobal.direct.widget if self.worldSpaceManip: widget.setPos(state.base, state.pos) - widget.setHpr(render, VBase3(0)) + widget.setHpr(ShowBaseGlobal.base.render, VBase3(0)) else: - base.direct.widget.setPosHpr(state.base, state.pos, state.hpr) + widget.setPosHpr(state.base, state.pos, state.hpr) return Task.cont def enableManipulation(self): @@ -459,18 +468,18 @@ class DirectManipulationControl(DirectObject): self.fSetCoa = 1 - self.fSetCoa if self.fSetCoa: - if hasattr(base.direct, 'widget'): - base.direct.widget.coaModeColor() + if hasattr(ShowBaseGlobal.direct, 'widget'): + ShowBaseGlobal.direct.widget.coaModeColor() else: self.objectHandles.coaModeColor() else: - if hasattr(base.direct, 'widget'): - base.direct.widget.manipModeColor() + if hasattr(ShowBaseGlobal.direct, 'widget'): + ShowBaseGlobal.direct.widget.manipModeColor() else: self.objectHandles.manipModeColor() else: - if hasattr(base.direct, 'widget'): - base.direct.widget.disabledModeColor() + if hasattr(ShowBaseGlobal.direct, 'widget'): + ShowBaseGlobal.direct.widget.disabledModeColor() else: self.objectHandles.disabledModeColor() @@ -480,20 +489,20 @@ class DirectManipulationControl(DirectObject): def enableWidgetMove(self): self.fMovable = 1 if self.fSetCoa: - if hasattr(base.direct, 'widget'): - base.direct.widget.coaModeColor() + if hasattr(ShowBaseGlobal.direct, 'widget'): + ShowBaseGlobal.direct.widget.coaModeColor() else: self.objectHandles.coaModeColor() else: - if hasattr(base.direct, 'widget'): - base.direct.widget.manipModeColor() + if hasattr(ShowBaseGlobal.direct, 'widget'): + ShowBaseGlobal.direct.widget.manipModeColor() else: self.objectHandles.manipModeColor() def disableWidgetMove(self): self.fMovable = 0 - if hasattr(base.direct, 'widget'): - base.direct.widget.disabledModeColor() + if hasattr(ShowBaseGlobal.direct, 'widget'): + ShowBaseGlobal.direct.widget.disabledModeColor() else: self.objectHandles.disabledModeColor() @@ -519,7 +528,8 @@ class DirectManipulationControl(DirectObject): def manipulateObject(self): # Only do this if something is selected - selectedList = base.direct.selected.getSelectedAsList() + direct = ShowBaseGlobal.direct + selectedList = direct.selected.getSelectedAsList() # See if any of the selected are completely uneditable editTypes = self.getEditTypes(selectedList) if (editTypes & DG.EDIT_TYPE_UNEDITABLE) == DG.EDIT_TYPE_UNEDITABLE: @@ -533,25 +543,26 @@ class DirectManipulationControl(DirectObject): # Set manipulation flag self.fManip = 1 # Record undo point - base.direct.pushUndo(base.direct.selected) + direct.pushUndo(direct.selected) # Update object handles visibility - if hasattr(base.direct, 'widget'): - base.direct.widget.showGuides() - base.direct.widget.hideAllHandles() - base.direct.widget.showHandle(self.constraint) + if hasattr(direct, 'widget'): + direct.widget.showGuides() + direct.widget.hideAllHandles() + direct.widget.showHandle(self.constraint) else: self.objectHandles.showGuides() self.objectHandles.hideAllHandles() self.objectHandles.showHandle(self.constraint) - if base.direct.clusterMode == 'client': - oh = 'base.direct.manipulationControl.objectHandles' + if direct.clusterMode == 'client': + oh = 'direct.manipulationControl.objectHandles' + cluster = direct.cluster cluster(oh + '.showGuides()', 0) cluster(oh + '.hideAllHandles()', 0) cluster(oh + ('.showHandle("%s")'% self.constraint), 0) # Record relationship between selected nodes and widget - base.direct.selected.getWrtAll() + direct.selected.getWrtAll() # hide the bbox of the selected objects during interaction - base.direct.selected.dehighlightAll() + direct.selected.dehighlightAll() # Send event to signal start of manipulation messenger.send('DIRECT_manipulateObjectStart') # Manipulate the real object with the constraint @@ -567,14 +578,14 @@ class DirectManipulationControl(DirectObject): self.fScaleInit1 = 1 # record initial offset between widget and camera t = Task.Task(self.manipulateObjectTask) - t.fMouseX = abs(base.direct.dr.mouseX) > 0.9 - t.fMouseY = abs(base.direct.dr.mouseY) > 0.9 + t.fMouseX = abs(ShowBaseGlobal.direct.dr.mouseX) > 0.9 + t.fMouseY = abs(ShowBaseGlobal.direct.dr.mouseY) > 0.9 if t.fMouseX: t.constrainedDir = 'y' else: t.constrainedDir = 'x' # Compute widget's xy coords in screen space - t.coaCenter = getScreenXY(base.direct.widget) + t.coaCenter = getScreenXY(ShowBaseGlobal.direct.widget) # These are used to rotate about view vector if t.fMouseX and t.fMouseY: t.lastAngle = getCrankAngle(t.coaCenter) @@ -597,14 +608,14 @@ class DirectManipulationControl(DirectObject): elif type == 'ring' and not self.currEditTypes & DG.EDIT_TYPE_UNROTATABLE: self.rotate1D(state) elif type == 'scale' and not self.currEditTypes & DG.EDIT_TYPE_UNSCALABLE: - if base.direct.fShift: + if ShowBaseGlobal.direct.fShift: self.fScaling3D = 1 self.scale3D(state) else: self.fScaling1D = 1 self.scale1D(state) else: - if base.direct.fControl and not self.currEditTypes & DG.EDIT_TYPE_UNSCALABLE: + if ShowBaseGlobal.direct.fControl and not self.currEditTypes & DG.EDIT_TYPE_UNSCALABLE: if type == 'post': # [gjeon] non-uniform scaling self.fScaling1D = 1 @@ -623,16 +634,16 @@ class DirectManipulationControl(DirectObject): # No widget interaction, determine free manip mode elif self.fFreeManip and not self.useSeparateScaleHandles: # If we've been scaling and changed modes, reset object handles - if 0 and (self.fScaling1D or self.fScaling3D) and (not base.direct.fAlt): - if hasattr(base.direct, 'widget'): - base.direct.widget.transferObjectHandleScale() + if 0 and (self.fScaling1D or self.fScaling3D) and (not ShowBaseGlobal.direct.fAlt): + if hasattr(ShowBaseGlobal.direct, 'widget'): + ShowBaseGlobal.direct.widget.transferObjectHandleScale() else: self.objectHandles.transferObjectHandlesScale() self.fScaling1D = 0 self.fScaling3D = 0 # Alt key switches to a scaling mode - if base.direct.fControl and not self.currEditTypes & DG.EDIT_TYPE_UNSCALABLE: + if ShowBaseGlobal.direct.fControl and not self.currEditTypes & DG.EDIT_TYPE_UNSCALABLE: self.fScaling3D = 1 self.scale3D(state) # Otherwise, manip mode depends on where you started @@ -645,7 +656,7 @@ class DirectManipulationControl(DirectObject): elif not self.currEditTypes & DG.EDIT_TYPE_UNMOVABLE: # Mouse started in central region, xlate # Mode depends on shift key - if base.direct.fShift or base.direct.fControl: + if ShowBaseGlobal.direct.fShift or ShowBaseGlobal.direct.fControl: self.xlateCamXY(state) else: self.xlateCamXZ(state) @@ -653,11 +664,11 @@ class DirectManipulationControl(DirectObject): return Task.done if self.fSetCoa: # Update coa based on current widget position - base.direct.selected.last.mCoa2Dnp.assign( - base.direct.widget.getMat(base.direct.selected.last)) + ShowBaseGlobal.direct.selected.last.mCoa2Dnp.assign( + ShowBaseGlobal.direct.widget.getMat(ShowBaseGlobal.direct.selected.last)) else: # Move the objects with the widget - base.direct.selected.moveWrtWidgetAll() + ShowBaseGlobal.direct.selected.moveWrtWidgetAll() # Continue return Task.cont @@ -677,39 +688,41 @@ class DirectManipulationControl(DirectObject): signX = -1.0 else: signX = 1.0 - modX = math.fabs(offsetX) % base.direct.grid.gridSpacing - floorX = math.floor(math.fabs(offsetX) / base.direct.grid.gridSpacing) - if modX < base.direct.grid.gridSpacing / 2.0: - offsetX = signX * floorX * base.direct.grid.gridSpacing + modX = math.fabs(offsetX) % ShowBaseGlobal.direct.grid.gridSpacing + floorX = math.floor(math.fabs(offsetX) / ShowBaseGlobal.direct.grid.gridSpacing) + if modX < ShowBaseGlobal.direct.grid.gridSpacing / 2.0: + offsetX = signX * floorX * ShowBaseGlobal.direct.grid.gridSpacing else: - offsetX = signX * (floorX + 1) * base.direct.grid.gridSpacing + offsetX = signX * (floorX + 1) * ShowBaseGlobal.direct.grid.gridSpacing if offsetY < 0.0: signY = -1.0 else: signY = 1.0 - modY = math.fabs(offsetY) % base.direct.grid.gridSpacing - floorY = math.floor(math.fabs(offsetY) / base.direct.grid.gridSpacing) - if modY < base.direct.grid.gridSpacing / 2.0: - offsetY = signY * floorY * base.direct.grid.gridSpacing + modY = math.fabs(offsetY) % ShowBaseGlobal.direct.grid.gridSpacing + floorY = math.floor(math.fabs(offsetY) / ShowBaseGlobal.direct.grid.gridSpacing) + if modY < ShowBaseGlobal.direct.grid.gridSpacing / 2.0: + offsetY = signY * floorY * ShowBaseGlobal.direct.grid.gridSpacing else: - offsetY = signY * (floorY + 1) * base.direct.grid.gridSpacing + offsetY = signY * (floorY + 1) * ShowBaseGlobal.direct.grid.gridSpacing if offsetZ < 0.0: signZ = -1.0 else: signZ = 1.0 - modZ = math.fabs(offsetZ) % base.direct.grid.gridSpacing - floorZ = math.floor(math.fabs(offsetZ) / base.direct.grid.gridSpacing) - if modZ < base.direct.grid.gridSpacing / 2.0: - offsetZ = signZ * floorZ * base.direct.grid.gridSpacing + modZ = math.fabs(offsetZ) % ShowBaseGlobal.direct.grid.gridSpacing + floorZ = math.floor(math.fabs(offsetZ) / ShowBaseGlobal.direct.grid.gridSpacing) + if modZ < ShowBaseGlobal.direct.grid.gridSpacing / 2.0: + offsetZ = signZ * floorZ * ShowBaseGlobal.direct.grid.gridSpacing else: - offsetZ = signZ * (floorZ + 1) * base.direct.grid.gridSpacing + offsetZ = signZ * (floorZ + 1) * ShowBaseGlobal.direct.grid.gridSpacing return Point3(offsetX, offsetY, offsetZ) ### WIDGET MANIPULATION METHODS ### def xlate1D(self, state): + assert self.constraint is not None + # Constrained 1D Translation along widget axis # Compute nearest hit point along axis and try to keep # that point as close to the current mouse position as possible @@ -725,27 +738,29 @@ class DirectManipulationControl(DirectObject): # Move widget to keep hit point as close to mouse as possible offset = self.hitPt - self.prevHit - if hasattr(base.direct, "manipulationControl") and base.direct.manipulationControl.fMultiView: - for widget in base.direct.manipulationControl.widgetList: + if hasattr(ShowBaseGlobal.direct, "manipulationControl") and ShowBaseGlobal.direct.manipulationControl.fMultiView: + for widget in ShowBaseGlobal.direct.manipulationControl.widgetList: if self.fGridSnap: widget.setPos(self.gridSnapping(widget, offset)) else: widget.setPos(widget, offset) - #if base.direct.camera.getName() != 'persp': + #if ShowBaseGlobal.direct.camera.getName() != 'persp': #self.prevHit.assign(self.hitPt) else: if self.fGridSnap: - base.direct.widget.setPos(self.gridSnapping(base.direct.widget, offset)) + ShowBaseGlobal.direct.widget.setPos(self.gridSnapping(ShowBaseGlobal.direct.widget, offset)) else: - base.direct.widget.setPos(base.direct.widget, offset) + ShowBaseGlobal.direct.widget.setPos(ShowBaseGlobal.direct.widget, offset) def xlate2D(self, state): + assert self.constraint is not None + # Constrained 2D (planar) translation # Compute point of intersection of ray from eyepoint through cursor # to one of the three orthogonal planes on the widget. # This point tracks all subsequent mouse movements self.hitPt.assign(self.objectHandles.getWidgetIntersectPt( - base.direct.widget, self.constraint[:1])) + ShowBaseGlobal.direct.widget, self.constraint[:1])) # use it to see how far to move the widget if self.fHitInit: @@ -755,21 +770,23 @@ class DirectManipulationControl(DirectObject): else: offset = self.hitPt - self.prevHit - if hasattr(base.direct, "manipulationControl") and base.direct.manipulationControl.fMultiView: - for widget in base.direct.manipulationControl.widgetList: + if hasattr(ShowBaseGlobal.direct, "manipulationControl") and ShowBaseGlobal.direct.manipulationControl.fMultiView: + for widget in ShowBaseGlobal.direct.manipulationControl.widgetList: if self.fGridSnap: widget.setPos(self.gridSnapping(widget, offset)) else: widget.setPos(widget, offset) - if base.direct.camera.getName() != 'persp': + if ShowBaseGlobal.direct.camera.getName() != 'persp': self.prevHit.assign(self.hitPt) else: if self.fGridSnap: - base.direct.widget.setPos(self.gridSnapping(base.direct.widget, offset)) + ShowBaseGlobal.direct.widget.setPos(self.gridSnapping(ShowBaseGlobal.direct.widget, offset)) else: - base.direct.widget.setPos(base.direct.widget, offset) + ShowBaseGlobal.direct.widget.setPos(ShowBaseGlobal.direct.widget, offset) def rotate1D(self, state): + assert self.constraint is not None + # Constrained 1D rotation about the widget's main axis (X, Y, or Z) # Rotation depends upon circular motion of the mouse about the # projection of the widget's origin on the image plane @@ -781,7 +798,7 @@ class DirectManipulationControl(DirectObject): self.fHitInit = 0 self.rotateAxis = self.constraint[:1] self.fWidgetTop = self.widgetCheck('top?') - self.rotationCenter = getScreenXY(base.direct.widget) + self.rotationCenter = getScreenXY(ShowBaseGlobal.direct.widget) self.lastCrankAngle = getCrankAngle(self.rotationCenter) # Rotate widget based on how far cursor has swung around origin @@ -790,27 +807,29 @@ class DirectManipulationControl(DirectObject): if self.fWidgetTop: deltaAngle = -1 * deltaAngle if self.rotateAxis == 'x': - if hasattr(base.direct, "manipulationControl") and base.direct.manipulationControl.fMultiView: - for widget in base.direct.manipulationControl.widgetList: + if hasattr(ShowBaseGlobal.direct, "manipulationControl") and ShowBaseGlobal.direct.manipulationControl.fMultiView: + for widget in ShowBaseGlobal.direct.manipulationControl.widgetList: widget.setP(widget, deltaAngle) else: - base.direct.widget.setP(base.direct.widget, deltaAngle) + ShowBaseGlobal.direct.widget.setP(ShowBaseGlobal.direct.widget, deltaAngle) elif self.rotateAxis == 'y': - if hasattr(base.direct, "manipulationControl") and base.direct.manipulationControl.fMultiView: - for widget in base.direct.manipulationControl.widgetList: + if hasattr(ShowBaseGlobal.direct, "manipulationControl") and ShowBaseGlobal.direct.manipulationControl.fMultiView: + for widget in ShowBaseGlobal.direct.manipulationControl.widgetList: widget.setR(widget, deltaAngle) else: - base.direct.widget.setR(base.direct.widget, deltaAngle) + ShowBaseGlobal.direct.widget.setR(ShowBaseGlobal.direct.widget, deltaAngle) elif self.rotateAxis == 'z': - if hasattr(base.direct, "manipulationControl") and base.direct.manipulationControl.fMultiView: - for widget in base.direct.manipulationControl.widgetList: + if hasattr(ShowBaseGlobal.direct, "manipulationControl") and ShowBaseGlobal.direct.manipulationControl.fMultiView: + for widget in ShowBaseGlobal.direct.manipulationControl.widgetList: widget.setH(widget, deltaAngle) else: - base.direct.widget.setH(base.direct.widget, deltaAngle) + ShowBaseGlobal.direct.widget.setH(ShowBaseGlobal.direct.widget, deltaAngle) # Record crank angle for next time around self.lastCrankAngle = newAngle def widgetCheck(self, type): + assert self.constraint is not None + # Utility to see if we are looking at the top or bottom of # a 2D planar widget or if we are looking at a 2D planar widget # edge on @@ -818,7 +837,7 @@ class DirectManipulationControl(DirectObject): # widget's origin and one of the three principle axes axis = self.constraint[:1] # First compute vector from eye through widget origin - mWidget2Cam = base.direct.widget.getMat(base.direct.camera) + mWidget2Cam = ShowBaseGlobal.direct.widget.getMat(ShowBaseGlobal.direct.camera) # And determine where the viewpoint is relative to widget pos = VBase3(0) decomposeMatrix(mWidget2Cam, VBase3(0), VBase3(0), pos, @@ -850,19 +869,19 @@ class DirectManipulationControl(DirectObject): # Reset scaling init flag self.fScaleInit = 1 # Where is the widget relative to current camera view - vWidget2Camera = base.direct.widget.getPos(base.direct.camera) + vWidget2Camera = ShowBaseGlobal.direct.widget.getPos(ShowBaseGlobal.direct.camera) x = vWidget2Camera[0] y = vWidget2Camera[1] z = vWidget2Camera[2] # Move widget (and objects) based upon mouse motion # Scaled up accordingly based upon widget distance - dr = base.direct.dr + dr = ShowBaseGlobal.direct.dr - base.direct.widget.setX( - base.direct.camera, + ShowBaseGlobal.direct.widget.setX( + ShowBaseGlobal.direct.camera, x + 0.5 * dr.mouseDeltaX * dr.nearWidth * (y/dr.near)) - base.direct.widget.setZ( - base.direct.camera, + ShowBaseGlobal.direct.widget.setZ( + ShowBaseGlobal.direct.camera, z + 0.5 * dr.mouseDeltaY * dr.nearHeight * (y/dr.near)) def xlateCamXY(self, state): @@ -873,17 +892,17 @@ class DirectManipulationControl(DirectObject): # Reset scaling init flag self.fScaleInit = 1 # Now, where is the widget relative to current camera view - vWidget2Camera = base.direct.widget.getPos(base.direct.camera) + vWidget2Camera = ShowBaseGlobal.direct.widget.getPos(ShowBaseGlobal.direct.camera) # If this is first time around, record initial y distance if self.fHitInit: self.fHitInit = 0 # Use distance to widget to scale motion along Y self.xlateSF = Vec3(vWidget2Camera).length() # Get widget's current xy coords in screen space - coaCenter = getNearProjectionPoint(base.direct.widget) - self.deltaNearX = coaCenter[0] - base.direct.dr.nearVec[0] + coaCenter = getNearProjectionPoint(ShowBaseGlobal.direct.widget) + self.deltaNearX = coaCenter[0] - ShowBaseGlobal.direct.dr.nearVec[0] # Which way do we move the object? - if base.direct.fControl: + if ShowBaseGlobal.direct.fControl: moveDir = Vec3(vWidget2Camera) # If widget is behind camera invert vector if moveDir[1] < 0.0: @@ -892,7 +911,7 @@ class DirectManipulationControl(DirectObject): else: moveDir = Vec3(DG.Y_AXIS) # Move selected objects - dr = base.direct.dr + dr = ShowBaseGlobal.direct.dr # Scale move dir moveDir.assign(moveDir * (2.0 * dr.mouseDeltaY * self.xlateSF)) # Add it to current widget offset @@ -902,7 +921,7 @@ class DirectManipulationControl(DirectObject): (vWidget2Camera[1]/dr.near)) # Move widget - base.direct.widget.setPos(base.direct.camera, vWidget2Camera) + ShowBaseGlobal.direct.widget.setPos(ShowBaseGlobal.direct.camera, vWidget2Camera) def rotate2D(self, state): """ Virtual trackball rotation of widget """ @@ -912,17 +931,17 @@ class DirectManipulationControl(DirectObject): self.fScaleInit = 1 tumbleRate = 360 # If moving outside of center, ignore motion perpendicular to edge - if ((state.constrainedDir == 'y') and (abs(base.direct.dr.mouseX) > 0.9)): + if ((state.constrainedDir == 'y') and (abs(ShowBaseGlobal.direct.dr.mouseX) > 0.9)): deltaX = 0 - deltaY = base.direct.dr.mouseDeltaY - elif ((state.constrainedDir == 'x') and (abs(base.direct.dr.mouseY) > 0.9)): - deltaX = base.direct.dr.mouseDeltaX + deltaY = ShowBaseGlobal.direct.dr.mouseDeltaY + elif ((state.constrainedDir == 'x') and (abs(ShowBaseGlobal.direct.dr.mouseY) > 0.9)): + deltaX = ShowBaseGlobal.direct.dr.mouseDeltaX deltaY = 0 else: - deltaX = base.direct.dr.mouseDeltaX - deltaY = base.direct.dr.mouseDeltaY + deltaX = ShowBaseGlobal.direct.dr.mouseDeltaX + deltaY = ShowBaseGlobal.direct.dr.mouseDeltaY # Mouse motion edge to edge of display region results in one full turn - relHpr(base.direct.widget, base.direct.camera, deltaX * tumbleRate, + relHpr(ShowBaseGlobal.direct.widget, ShowBaseGlobal.direct.camera, deltaX * tumbleRate, -deltaY * tumbleRate, 0) def rotateAboutViewVector(self, state): @@ -935,19 +954,22 @@ class DirectManipulationControl(DirectObject): deltaAngle = angle - state.lastAngle state.lastAngle = angle # Mouse motion edge to edge of display region results in one full turn - relHpr(base.direct.widget, base.direct.camera, 0, 0, -deltaAngle) + relHpr(ShowBaseGlobal.direct.widget, ShowBaseGlobal.direct.camera, 0, 0, -deltaAngle) def scale1D(self, state): - if hasattr(base.direct, "manipulationControl") and base.direct.manipulationControl.fMultiView: + assert self.constraint is not None + + direct = ShowBaseGlobal.direct + if hasattr(direct, "manipulationControl") and direct.manipulationControl.fMultiView: self.hitPtScale.assign(self.objectHandles.getAxisIntersectPt(self.constraint[:1])) self.hitPtScale = self.objectHandles.getMat().xformVec(self.hitPtScale) if self.fScaleInit1: # First time through just record hit point self.fScaleInit1 = 0 self.prevHitScale.assign(self.hitPtScale) - self.origScale = base.direct.widget.getScale() + self.origScale = direct.widget.getScale() else: - widgetPos = base.direct.widget.getPos() + widgetPos = direct.widget.getPos() d0 = (self.prevHitScale).length() if d0 == 0: #make sure we don't divide by zero d0 = 0.001 @@ -962,7 +984,7 @@ class DirectManipulationControl(DirectObject): currScale = Vec3(currScale.getX(), currScale.getY() * d1/d0, currScale.getZ()) elif self.constraint[:1] == 'z': currScale = Vec3(currScale.getX(), currScale.getY(), currScale.getZ() * d1/d0) - base.direct.widget.setScale(currScale) + direct.widget.setScale(currScale) return # [gjeon] Constrained 1D scale of the selected node based upon up down mouse motion @@ -970,13 +992,13 @@ class DirectManipulationControl(DirectObject): self.fScaleInit = 0 self.initScaleMag = Vec3(self.objectHandles.getAxisIntersectPt(self.constraint[:1])).length() # record initial scale - self.initScale = base.direct.widget.getScale() + self.initScale = direct.widget.getScale() # Reset fHitInitFlag self.fHitInit = 1 # reset the scale of the scaling widget so the calls to # getAxisIntersectPt calculate the correct distance - base.direct.widget.setScale(1,1,1) + direct.widget.setScale(1,1,1) # Scale factor is ratio current mag with init mag if self.constraint[:1] == 'x': @@ -991,20 +1013,22 @@ class DirectManipulationControl(DirectObject): currScale = Vec3(self.initScale.getX(), self.initScale.getY(), self.initScale.getZ() * self.objectHandles.getAxisIntersectPt('z').length() / self.initScaleMag) - base.direct.widget.setScale(currScale) + direct.widget.setScale(currScale) def scale3D(self, state): - if hasattr(base.direct, "manipulationControl") and base.direct.manipulationControl.fMultiView: + direct = ShowBaseGlobal.direct + if hasattr(direct, "manipulationControl") and direct.manipulationControl.fMultiView: if self.useSeparateScaleHandles: + assert self.constraint is not None self.hitPtScale.assign(self.objectHandles.getAxisIntersectPt(self.constraint[:1])) self.hitPtScale = self.objectHandles.getMat().xformVec(self.hitPtScale) if self.fScaleInit1: # First time through just record hit point self.fScaleInit1 = 0 self.prevHitScale.assign(self.hitPtScale) - self.origScale = base.direct.widget.getScale() + self.origScale = direct.widget.getScale() else: - widgetPos = base.direct.widget.getPos() + widgetPos = direct.widget.getPos() d0 = (self.prevHitScale).length() if d0 == 0: #make sure we don't divide by zero d0 = 0.001 @@ -1014,7 +1038,7 @@ class DirectManipulationControl(DirectObject): currScale = self.origScale # 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) + direct.widget.setScale(currScale) return else: self.hitPtScale.assign(self.objectHandles.getMouseIntersectPt()) @@ -1023,9 +1047,9 @@ class DirectManipulationControl(DirectObject): # First time through just record hit point self.fScaleInit1 = 0 self.prevHitScale.assign(self.hitPtScale) - self.origScale = base.direct.widget.getScale() + self.origScale = direct.widget.getScale() else: - widgetPos = base.direct.widget.getPos() + widgetPos = direct.widget.getPos() d0 = (self.prevHitScale - widgetPos).length() if d0 == 0: #make sure we don't divide by zero d0 = 0.001 @@ -1034,20 +1058,20 @@ class DirectManipulationControl(DirectObject): d1 = 0.001 #make sure we don't set scale to zero currScale = self.origScale currScale = currScale * d1/d0 - base.direct.widget.setScale(currScale) + direct.widget.setScale(currScale) return # Scale the selected node based upon up down mouse motion # Mouse motion from edge to edge results in a factor of 4 scaling # From midpoint to edge doubles or halves objects scale if self.fScaleInit: self.fScaleInit = 0 - self.manipRef.setPos(base.direct.widget, 0, 0, 0) - self.manipRef.setHpr(base.direct.camera, 0, 0, 0) + self.manipRef.setPos(direct.widget, 0, 0, 0) + self.manipRef.setHpr(direct.camera, 0, 0, 0) self.initScaleMag = Vec3( self.objectHandles.getWidgetIntersectPt( self.manipRef, 'y')).length() # record initial scale - self.initScale = base.direct.widget.getScale() + self.initScale = direct.widget.getScale() # Reset fHitInitFlag self.fHitInit = 1 # Begin @@ -1058,29 +1082,29 @@ class DirectManipulationControl(DirectObject): self.manipRef, 'y').length() / self.initScaleMag) ) - base.direct.widget.setScale(currScale) + direct.widget.setScale(currScale) ## Utility functions ## def plantSelectedNodePath(self): """ Move selected object to intersection point of cursor on scene """ # Check for intersection - entry = base.direct.iRay.pickGeom( + entry = ShowBaseGlobal.direct.iRay.pickGeom( skipFlags = DG.SKIP_HIDDEN | DG.SKIP_BACKFACE | DG.SKIP_CAMERA) # MRM: Need to handle moving COA - if entry is not None and base.direct.selected.last is not None: + if entry is not None and ShowBaseGlobal.direct.selected.last is not None: # Record undo point - base.direct.pushUndo(base.direct.selected) + ShowBaseGlobal.direct.pushUndo(ShowBaseGlobal.direct.selected) # Record wrt matrix - base.direct.selected.getWrtAll() + ShowBaseGlobal.direct.selected.getWrtAll() # Move selected - base.direct.widget.setPos( - base.direct.camera, entry.getSurfacePoint(entry.getFromNodePath())) + ShowBaseGlobal.direct.widget.setPos( + ShowBaseGlobal.direct.camera, entry.getSurfacePoint(entry.getFromNodePath())) # Move all the selected objects with widget # Move the objects with the widget - base.direct.selected.moveWrtWidgetAll() + ShowBaseGlobal.direct.selected.moveWrtWidgetAll() # Let everyone know that something was moved messenger.send('DIRECT_manipulateObjectCleanup', - [base.direct.selected.getSelectedAsList()]) + [ShowBaseGlobal.direct.selected.getSelectedAsList()]) class ObjectHandles(NodePath, DirectObject): @@ -1089,7 +1113,7 @@ class ObjectHandles(NodePath, DirectObject): NodePath.__init__(self) # Load up object handles model and assign it to self - self.assign(base.loader.loadModel('models/misc/objectHandles')) + self.assign(ShowBaseGlobal.base.loader.loadModel('models/misc/objectHandles')) self.setName(name) self.scalingNode = NodePath(self) self.scalingNode.setName('ohScalingNode') @@ -1199,14 +1223,14 @@ class ObjectHandles(NodePath, DirectObject): def toggleWidget(self): if self.fActive: - if hasattr(base.direct, "manipulationControl") and base.direct.manipulationControl.fMultiView: - for widget in base.direct.manipulationControl.widgetList: + if hasattr(ShowBaseGlobal.direct, "manipulationControl") and ShowBaseGlobal.direct.manipulationControl.fMultiView: + for widget in ShowBaseGlobal.direct.manipulationControl.widgetList: widget.deactivate() else: self.deactivate() else: - if hasattr(base.direct, "manipulationControl") and base.direct.manipulationControl.fMultiView: - for widget in base.direct.manipulationControl.widgetList: + if hasattr(ShowBaseGlobal.direct, "manipulationControl") and ShowBaseGlobal.direct.manipulationControl.fMultiView: + for widget in ShowBaseGlobal.direct.manipulationControl.widgetList: widget.activate() widget.showWidgetIfActive() else: @@ -1222,10 +1246,10 @@ class ObjectHandles(NodePath, DirectObject): def showWidgetIfActive(self): if self.fActive: - self.reparentTo(base.direct.group) + self.reparentTo(ShowBaseGlobal.direct.group) def showWidget(self): - self.reparentTo(base.direct.group) + self.reparentTo(ShowBaseGlobal.direct.group) def hideWidget(self): self.reparentTo(hidden) @@ -1260,7 +1284,7 @@ class ObjectHandles(NodePath, DirectObject): self.xRingGroup.reparentTo(self.xHandles) elif handle == 'x-disc': self.xDiscGroup.reparentTo(self.xHandles) - elif handle == 'x-scale' and base.direct.manipulationControl.useSeparateScaleHandles: + elif handle == 'x-scale' and ShowBaseGlobal.direct.manipulationControl.useSeparateScaleHandles: self.xScaleGroup.reparentTo(self.xHandles) elif handle == 'y-post': self.yPostGroup.reparentTo(self.yHandles) @@ -1268,7 +1292,7 @@ class ObjectHandles(NodePath, DirectObject): self.yRingGroup.reparentTo(self.yHandles) elif handle == 'y-disc': self.yDiscGroup.reparentTo(self.yHandles) - elif handle == 'y-scale' and base.direct.manipulationControl.useSeparateScaleHandles: + elif handle == 'y-scale' and ShowBaseGlobal.direct.manipulationControl.useSeparateScaleHandles: self.yScaleGroup.reparentTo(self.yHandles) elif handle == 'z-post': self.zPostGroup.reparentTo(self.zHandles) @@ -1276,7 +1300,7 @@ class ObjectHandles(NodePath, DirectObject): self.zRingGroup.reparentTo(self.zHandles) elif handle == 'z-disc': self.zDiscGroup.reparentTo(self.zHandles) - elif handle == 'z-scale' and base.direct.manipulationControl.useSeparateScaleHandles: + elif handle == 'z-scale' and ShowBaseGlobal.direct.manipulationControl.useSeparateScaleHandles: self.zScaleGroup.reparentTo(self.zHandles) def disableHandles(self, handles): @@ -1420,9 +1444,9 @@ class ObjectHandles(NodePath, DirectObject): def growToFit(self): # Increase handles scale until they cover 30% of the min dimension - pos = base.direct.widget.getPos(base.direct.camera) - minDim = min(base.direct.dr.nearWidth, base.direct.dr.nearHeight) - sf = 0.15 * minDim * (pos[1]/base.direct.dr.near) + pos = ShowBaseGlobal.direct.widget.getPos(ShowBaseGlobal.direct.camera) + minDim = min(ShowBaseGlobal.direct.dr.nearWidth, ShowBaseGlobal.direct.dr.nearHeight) + sf = 0.15 * minDim * (pos[1]/ShowBaseGlobal.direct.dr.near) self.ohScalingFactor = sf sf = sf * self.directScalingFactor ival = self.scalingNode.scaleInterval(0.5, (sf, sf, sf), @@ -1624,14 +1648,14 @@ class ObjectHandles(NodePath, DirectObject): lines.setName('z-guide') def getAxisIntersectPt(self, axis): - if hasattr(base.direct, "manipulationControl") and base.direct.manipulationControl.fMultiView and\ - base.direct.camera.getName() != 'persp': + if hasattr(ShowBaseGlobal.direct, "manipulationControl") and ShowBaseGlobal.direct.manipulationControl.fMultiView and\ + ShowBaseGlobal.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) + iRay = SelectionRay(ShowBaseGlobal.direct.camera) + iRay.collider.setFromLens(ShowBaseGlobal.direct.camNode, ShowBaseGlobal.direct.dr.mouseX, ShowBaseGlobal.direct.dr.mouseY) #iRay.collideWithBitMask(1) iRay.collideWithBitMask(BitMask32.bit(21)) - iRay.ct.traverse(base.direct.grid) + iRay.ct.traverse(ShowBaseGlobal.direct.grid) if iRay.getNumEntries() == 0: del iRay @@ -1653,8 +1677,8 @@ class ObjectHandles(NodePath, DirectObject): 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)) + mCam2Widget = ShowBaseGlobal.direct.camera.getMat(ShowBaseGlobal.direct.widget) + lineDir = Vec3(mCam2Widget.xformVec(ShowBaseGlobal.direct.dr.nearVec)) lineDir.normalize() # And determine where the viewpoint is relative to widget lineOrigin = VBase3(0) @@ -1698,11 +1722,11 @@ class ObjectHandles(NodePath, DirectObject): def getMouseIntersectPt(self): # 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) + iRay = SelectionRay(ShowBaseGlobal.direct.camera) + iRay.collider.setFromLens(ShowBaseGlobal.direct.camNode, ShowBaseGlobal.direct.dr.mouseX, ShowBaseGlobal.direct.dr.mouseY) #iRay.collideWithBitMask(1) iRay.collideWithBitMask(BitMask32.bit(21)) - iRay.ct.traverse(base.direct.grid) + iRay.ct.traverse(ShowBaseGlobal.direct.grid) if iRay.getNumEntries() == 0: del iRay @@ -1713,7 +1737,7 @@ class ObjectHandles(NodePath, DirectObject): # create a temp nodePath to get the position np = NodePath('temp') - np.setPos(base.direct.camera, hitPt) + np.setPos(ShowBaseGlobal.direct.camera, hitPt) resultPt = Point3(0) resultPt.assign(np.getPos()) np.removeNode() @@ -1721,8 +1745,8 @@ class ObjectHandles(NodePath, DirectObject): return resultPt def getWidgetIntersectPt(self, nodePath, plane): - if hasattr(base.direct, "manipulationControl") and base.direct.manipulationControl.fMultiView and\ - base.direct.camera.getName() != 'persp': + if hasattr(ShowBaseGlobal.direct, "manipulationControl") and ShowBaseGlobal.direct.manipulationControl.fMultiView and\ + ShowBaseGlobal.direct.camera.getName() != 'persp': self.hitPt.assign(self.getMouseIntersectPt()) return self.hitPt @@ -1730,7 +1754,7 @@ class ObjectHandles(NodePath, DirectObject): # with the plane containing the 2D xlation or 1D rotation widgets # Calc the xfrom from camera to the nodePath - mCam2NodePath = base.direct.camera.getMat(nodePath) + mCam2NodePath = ShowBaseGlobal.direct.camera.getMat(nodePath) # And determine where the viewpoint is relative to widget lineOrigin = VBase3(0) @@ -1740,7 +1764,7 @@ class ObjectHandles(NodePath, DirectObject): # Next we find the vector from viewpoint to the widget through # the mouse's position on near plane. # This defines the intersection ray - lineDir = Vec3(mCam2NodePath.xformVec(base.direct.dr.nearVec)) + lineDir = Vec3(mCam2NodePath.xformVec(ShowBaseGlobal.direct.dr.nearVec)) lineDir.normalize() # Find the hit point if plane == 'x': diff --git a/direct/src/directtools/DirectSession.py b/direct/src/directtools/DirectSession.py index 2947b29088..651a9addec 100644 --- a/direct/src/directtools/DirectSession.py +++ b/direct/src/directtools/DirectSession.py @@ -5,6 +5,7 @@ from panda3d.core import ( ConfigVariableBool, ConfigVariableString, CSDefault, + GraphicsWindow, NodePath, Point3, TextNode, @@ -35,19 +36,33 @@ from direct.gui import OnscreenText from direct.interval.IntervalGlobal import Func, Sequence from direct.task.TaskManagerGlobal import taskMgr from direct.showbase.MessengerGlobal import messenger +from direct.showbase import ShowBaseGlobal +from direct.showbase.ShowBaseGlobal import ShowBase, hidden +import builtins + +base: ShowBase class DirectSession(DirectObject): # post this to the bboard to make sure DIRECT doesn't turn on DIRECTdisablePost = 'disableDIRECT' + cam: NodePath + camera: NodePath + oobeCamera: NodePath + def __init__(self): # Establish a global pointer to the direct object early on # so dependant classes can access it in their code - __builtins__["direct"] = base.direct = self + global direct, base + base = ShowBaseGlobal.base + base.direct = self + setattr(builtins, 'direct', self) + ShowBaseGlobal.direct = self + # These come early since they are used later on - self.group = render.attachNewNode('DIRECT') + self.group = base.render.attachNewNode('DIRECT') self.font = TextNode.getDefaultFont() self.fEnabled = 0 self.fEnabledLight = 0 @@ -57,7 +72,7 @@ class DirectSession(DirectObject): self.drList = DisplayRegionList() self.iRayList = [x.iRay for x in self.drList] self.dr = self.drList[0] - self.win = base.win + self.win: GraphicsWindow = base.win self.camera = base.camera self.cam = base.cam self.camNode = base.camNode @@ -70,7 +85,7 @@ class DirectSession(DirectObject): self.useObjectHandles() self.grid = DirectGrid() self.grid.disable() - self.lights = DirectLights(base.direct.group) + self.lights = DirectLights(self.group) # Create some default lights self.lights.createDefaultLights() # But turn them off @@ -308,13 +323,16 @@ class DirectSession(DirectObject): if base.wantTk: from direct.tkpanels import DirectSessionPanel self.panel = DirectSessionPanel.DirectSessionPanel(parent = base.tkRoot) - try: + + clusterMode: str + if hasattr(builtins, 'clusterMode'): # Has the clusterMode been set externally (i.e. via the # bootstrap application? - self.clusterMode = clusterMode - except NameError: + clusterMode = builtins.clusterMode + else: # Has the clusterMode been set via a config variable? - self.clusterMode = ConfigVariableString("cluster-mode", '').value + clusterMode = ConfigVariableString("cluster-mode", '').value + self.clusterMode = clusterMode if self.clusterMode == 'client': from direct.cluster.ClusterClient import createClusterClient @@ -325,7 +343,7 @@ class DirectSession(DirectObject): else: from direct.cluster.ClusterClient import DummyClusterClient self.cluster = DummyClusterClient() - __builtins__['cluster'] = self.cluster + setattr(builtins, 'cluster', self.cluster) def addPassThroughKey(self,key): @@ -412,10 +430,10 @@ class DirectSession(DirectObject): if self.oobeMode: # Position a target point to lerp the oobe camera to - base.direct.cameraControl.camManipRef.setPosHpr(self.trueCamera, 0, 0, 0, 0, 0, 0) + self.cameraControl.camManipRef.setPosHpr(self.trueCamera, 0, 0, 0, 0, 0, 0) ival = self.oobeCamera.posHprInterval( 2.0, pos = Point3(0), hpr = Vec3(0), - other = base.direct.cameraControl.camManipRef, + other = self.cameraControl.camManipRef, blendType = 'easeInOut') ival = Sequence(ival, Func(self.endOOBE), name = 'oobeTransition') ival.start() @@ -432,20 +450,20 @@ class DirectSession(DirectObject): # Put camera under new oobe camera self.cam.reparentTo(self.oobeCamera) # Position a target point to lerp the oobe camera to - base.direct.cameraControl.camManipRef.setPos( + self.cameraControl.camManipRef.setPos( self.trueCamera, Vec3(-2, -20, 5)) - base.direct.cameraControl.camManipRef.lookAt(self.trueCamera) + self.cameraControl.camManipRef.lookAt(self.trueCamera) ival = self.oobeCamera.posHprInterval( 2.0, pos = Point3(0), hpr = Vec3(0), - other = base.direct.cameraControl.camManipRef, + other = self.cameraControl.camManipRef, blendType = 'easeInOut') ival = Sequence(ival, Func(self.beginOOBE), name = 'oobeTransition') ival.start() def beginOOBE(self): # Make sure we've reached our final destination - self.oobeCamera.setPosHpr(base.direct.cameraControl.camManipRef, 0, 0, 0, 0, 0, 0) - base.direct.camera = self.oobeCamera + self.oobeCamera.setPosHpr(self.cameraControl.camManipRef, 0, 0, 0, 0, 0, 0) + self.camera = self.oobeCamera self.oobeMode = 1 def endOOBE(self): @@ -453,7 +471,7 @@ class DirectSession(DirectObject): self.oobeCamera.setPosHpr(self.trueCamera, 0, 0, 0, 0, 0, 0) # Disable OOBE mode. self.cam.reparentTo(self.trueCamera) - base.direct.camera = self.trueCamera + self.camera = self.trueCamera # Get rid of ancillary node paths self.oobeVis.reparentTo(hidden) self.oobeCamera.reparentTo(hidden) @@ -501,7 +519,7 @@ class DirectSession(DirectObject): def inputHandler(self, input): if not hasattr(self, 'oobeMode') or self.oobeMode == 0: # [gjeon] change current camera dr, iRay, mouseWatcher accordingly to support multiple windows - if base.direct.manipulationControl.fMultiView: + if self.manipulationControl.fMultiView: # handling orphan events if self.fMouse1 and 'mouse1' not in input or\ self.fMouse2 and 'mouse2' not in input or\ @@ -518,7 +536,7 @@ class DirectSession(DirectObject): return if (self.fMouse1 or self.fMouse2 or self.fMouse3) and\ - input[4:7] != base.direct.camera.getName()[:3] and\ + input[4:7] != self.camera.getName()[:3] and\ input.endswith('-up'): # to handle orphan events return @@ -551,14 +569,14 @@ class DirectSession(DirectObject): self.cam = NodePath(winCtrl.camNode) self.camNode = winCtrl.camNode if hasattr(winCtrl, 'grid'): - base.direct.grid = winCtrl.grid - base.direct.dr = base.direct.drList[base.camList.index(NodePath(winCtrl.camNode))] - base.direct.iRay = base.direct.dr.iRay + self.grid = winCtrl.grid + self.dr = self.drList[base.camList.index(NodePath(winCtrl.camNode))] + self.iRay = self.dr.iRay base.mouseWatcher = winCtrl.mouseWatcher base.mouseWatcherNode = winCtrl.mouseWatcher.node() - base.direct.dr.mouseUpdate() + self.dr.mouseUpdate() DG.LE_showInOneCam(self.selectedNPReadout, self.camera.getName()) - base.direct.widget = base.direct.manipulationControl.widgetList[base.camList.index(NodePath(winCtrl.camNode))] + self.widget = self.manipulationControl.widgetList[base.camList.index(NodePath(winCtrl.camNode))] input = input[8:] # get rid of camera prefix if self.fAlt and 'alt' not in input and not input.endswith('-up'): @@ -683,20 +701,18 @@ class DirectSession(DirectObject): if not taskMgr.hasTaskNamed('resizeObjectHandles'): dnp = self.selected.last if dnp: - direct = base.direct - if self.manipulationControl.fMultiView: for i in range(3): - sf = 30.0 * direct.drList[i].orthoFactor + sf = 30.0 * self.drList[i].orthoFactor self.manipulationControl.widgetList[i].setDirectScalingFactor(sf) nodeCamDist = Vec3(dnp.getPos(base.camList[3])).length() - sf = 0.075 * nodeCamDist * math.tan(deg2Rad(direct.drList[3].fovV)) + sf = 0.075 * nodeCamDist * math.tan(deg2Rad(self.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)) + nodeCamDist = Vec3(dnp.getPos(self.camera)).length() + sf = 0.075 * nodeCamDist * math.tan(deg2Rad(self.drList.getCurrentDr().fovV)) self.widget.setDirectScalingFactor(sf) return Task.cont @@ -755,7 +771,7 @@ class DirectSession(DirectObject): messenger.send('DIRECT_selectedNodePath_fMulti_fTag_fLEPane', [dnp, fMultiSelect, fSelectTag, fLEPane]) def followSelectedNodePathTask(self, state): - mCoa2Render = state.dnp.mCoa2Dnp * state.dnp.getMat(render) + mCoa2Render = state.dnp.mCoa2Dnp * state.dnp.getMat(base.render) decomposeMatrix(mCoa2Render, self.scale, self.hpr, self.pos, CSDefault) @@ -874,7 +890,7 @@ class DirectSession(DirectObject): if nodePath == 'None Given': # If nothing specified, try selected node path nodePath = self.selected.last - base.direct.select(nodePath) + self.select(nodePath) def fitTask(state, self = self): self.cameraControl.fitOnWidget() @@ -1061,7 +1077,7 @@ class DirectSession(DirectObject): def useObjectHandles(self): self.widget = self.manipulationControl.objectHandles - self.widget.reparentTo(base.direct.group) + self.widget.reparentTo(self.group) def hideSelectedNPReadout(self): self.selectedNPReadout.reparentTo(hidden) @@ -1167,14 +1183,14 @@ class DisplayRegionContext(DirectObject): self.camLens.setFov(hfov, vfov) def getWidth(self): - prop = base.direct.win.getProperties() + prop = ShowBaseGlobal.direct.win.getProperties() if prop.hasSize(): return prop.getXSize() else: return 640 def getHeight(self): - prop = base.direct.win.getProperties() + prop = ShowBaseGlobal.direct.win.getProperties() if prop.hasSize(): return prop.getYSize() else: @@ -1208,9 +1224,10 @@ class DisplayRegionContext(DirectObject): # Values for this frame # This ranges from -1 to 1 - if base.mouseWatcherNode and base.mouseWatcherNode.hasMouse(): - self.mouseX = base.mouseWatcherNode.getMouseX() - self.mouseY = base.mouseWatcherNode.getMouseY() + mouseWatcherNode = base.mouseWatcherNode + if mouseWatcherNode and mouseWatcherNode.hasMouse(): + self.mouseX = mouseWatcherNode.getMouseX() + self.mouseY = mouseWatcherNode.getMouseY() self.mouseX = (self.mouseX-self.originX)*self.scaleX self.mouseY = (self.mouseY-self.originY)*self.scaleY # Delta percent of window the mouse moved @@ -1262,6 +1279,9 @@ class DisplayRegionList(DirectObject): def __len__(self): return len(self.displayRegionList) + def __iter__(self): + return iter(self.displayRegionList) + def updateContext(self): self.contextTask(None) @@ -1296,7 +1316,7 @@ class DisplayRegionList(DirectObject): def getCurrentDr(self): if not self.tryToGetCurrentDr: - return base.direct.dr + return ShowBaseGlobal.direct.dr for dr in self.displayRegionList: if (dr.mouseX >= -1.0 and dr.mouseX <= 1.0 and dr.mouseY >= -1.0 and dr.mouseY <= 1.0): diff --git a/direct/src/leveleditor/LevelEditorUIBase.py b/direct/src/leveleditor/LevelEditorUIBase.py index 126bbf9f6b..87ccbb02ff 100755 --- a/direct/src/leveleditor/LevelEditorUIBase.py +++ b/direct/src/leveleditor/LevelEditorUIBase.py @@ -7,6 +7,7 @@ from direct.wxwidgets.WxPandaShell import WxPandaShell from direct.wxwidgets.WxSlider import WxSlider from direct.directtools.DirectSelection import SelectionRay from direct.showbase.MessengerGlobal import messenger +from direct.showbase import ShowBaseGlobal #from ViewPort import * from . import ObjectGlobals as OG @@ -88,7 +89,7 @@ class PandaTextDropTarget(wx.TextDropTarget): np = NodePath('temp') np.setPos(self.view.camera, hitPt) - if base.direct.manipulationControl.fGridSnap: + if ShowBaseGlobal.direct.manipulationControl.fGridSnap: snappedPos = self.view.grid.computeSnapPoint(np.getPos()) np.setPos(snappedPos) @@ -98,10 +99,10 @@ class PandaTextDropTarget(wx.TextDropTarget): # transform newobj to cursor position obj = self.editor.objectMgr.findObjectByNodePath(newobj) - action = ActionTransformObj(self.editor, obj[OG.OBJ_UID], Mat4(np.getMat())) - self.editor.actionMgr.push(action) + action2 = ActionTransformObj(self.editor, obj[OG.OBJ_UID], Mat4(np.getMat())) + self.editor.actionMgr.push(action2) np.remove() - action() + action2() iRay.collisionNodePath.removeNode() del iRay @@ -250,13 +251,13 @@ class LevelEditorUIBase(WxPandaShell): WxPandaShell.createMenu(self) def onGraphEditor(self, e): - if base.direct.selected.last is None: + if ShowBaseGlobal.direct.selected.last is None: dlg = wx.MessageDialog(None, 'Please select a object first.', 'NOTICE', wx.OK) dlg.ShowModal() dlg.Destroy() self.graphEditorMenuItem.Check(False) else: - currentObj = self.editor.objectMgr.findObjectByNodePath(base.direct.selected.last) + currentObj = self.editor.objectMgr.findObjectByNodePath(ShowBaseGlobal.direct.selected.last) self.graphEditorUI = GraphEditorUI(self, self.editor, currentObj) self.graphEditorUI.Show() self.graphEditorMenuItem.Check(True) @@ -298,7 +299,7 @@ class LevelEditorUIBase(WxPandaShell): degreeUI = CurveDegreeUI(self, -1, 'Curve Degree') degreeUI.ShowModal() degreeUI.Destroy() - base.direct.manipulationControl.disableManipulation() + ShowBaseGlobal.direct.manipulationControl.disableManipulation() self.editCurveMenuItem.Check(False) def onEditCurve(self, e): @@ -313,15 +314,15 @@ class LevelEditorUIBase(WxPandaShell): self.createCurveMenuItem.Check(False) self.onEditCurve(None) else: - if base.direct.selected.last is None: + if ShowBaseGlobal.direct.selected.last is None: dlg = wx.MessageDialog(None, 'Please select a curve first.', 'NOTICE', wx.OK) dlg.ShowModal() dlg.Destroy() self.editCurveMenuItem.Check(False) - if base.direct.selected.last is not None: - base.direct.manipulationControl.enableManipulation() + if ShowBaseGlobal.direct.selected.last is not None: + ShowBaseGlobal.direct.manipulationControl.enableManipulation() self.createCurveMenuItem.Check(False) - self.curveObj = self.editor.objectMgr.findObjectByNodePath(base.direct.selected.last) + self.curveObj = self.editor.objectMgr.findObjectByNodePath(ShowBaseGlobal.direct.selected.last) if self.curveObj[OG.OBJ_DEF].name == '__Curve__': self.editor.mode = self.editor.EDIT_CURVE_MODE self.editor.updateStatusReadout('Please press ENTER to end the curve editing.') @@ -339,8 +340,8 @@ class LevelEditorUIBase(WxPandaShell): def updateMenu(self): hotKeyDict = {} - for hotKey in base.direct.hotKeyMap.keys(): - desc = base.direct.hotKeyMap[hotKey] + for hotKey in ShowBaseGlobal.direct.hotKeyMap.keys(): + desc = ShowBaseGlobal.direct.hotKeyMap[hotKey] hotKeyDict[desc[1]] = hotKey for id in self.MENU_TEXTS.keys(): @@ -401,16 +402,16 @@ class LevelEditorUIBase(WxPandaShell): else: mpos = evt.GetPosition() - base.direct.fMouse3 = 0 + ShowBaseGlobal.direct.fMouse3 = 0 self.PopupMenu(self.contextMenu, mpos) def onKeyDownEvent(self, evt): if evt.GetKeyCode() == wx.WXK_ALT: - base.direct.fAlt = 1 + ShowBaseGlobal.direct.fAlt = 1 elif evt.GetKeyCode() == wx.WXK_CONTROL: - base.direct.fControl = 1 + ShowBaseGlobal.direct.fControl = 1 elif evt.GetKeyCode() == wx.WXK_SHIFT: - base.direct.fShift = 1 + ShowBaseGlobal.direct.fShift = 1 elif evt.GetKeyCode() == wx.WXK_UP: messenger.send('arrow_up') elif evt.GetKeyCode() == wx.WXK_DOWN: @@ -428,11 +429,11 @@ class LevelEditorUIBase(WxPandaShell): def onKeyUpEvent(self, evt): if evt.GetKeyCode() == wx.WXK_ALT: - base.direct.fAlt = 0 + ShowBaseGlobal.direct.fAlt = 0 elif evt.GetKeyCode() == wx.WXK_CONTROL: - base.direct.fControl = 0 + ShowBaseGlobal.direct.fControl = 0 elif evt.GetKeyCode() == wx.WXK_SHIFT: - base.direct.fShift = 0 + ShowBaseGlobal.direct.fShift = 0 elif evt.GetKeyCode() == wx.WXK_UP: messenger.send('arrow_up-up') elif evt.GetKeyCode() == wx.WXK_DOWN: @@ -473,8 +474,8 @@ class LevelEditorUIBase(WxPandaShell): input = 'control-%s'%chr(evt.GetKeyCode()) elif evt.GetKeyCode() < 256: input = chr(evt.GetKeyCode()) - if input in base.direct.hotKeyMap.keys(): - keyDesc = base.direct.hotKeyMap[input] + if input in ShowBaseGlobal.direct.hotKeyMap.keys(): + keyDesc = ShowBaseGlobal.direct.hotKeyMap[input] messenger.send(keyDesc[1]) def reset(self): @@ -533,12 +534,12 @@ class LevelEditorUIBase(WxPandaShell): def toggleGridSnap(self, evt): if self.gridSnapMenuItem.IsChecked(): - base.direct.manipulationControl.fGridSnap = 1 + ShowBaseGlobal.direct.manipulationControl.fGridSnap = 1 for grid in [self.perspView.grid, self.topView.grid, self.frontView.grid, self.leftView.grid]: grid.fXyzSnap = 1 else: - base.direct.manipulationControl.fGridSnap = 0 + ShowBaseGlobal.direct.manipulationControl.fGridSnap = 0 for grid in [self.perspView.grid, self.topView.grid, self.frontView.grid, self.leftView.grid]: grid.fXyzSnap = 0 @@ -589,7 +590,7 @@ class LevelEditorUIBase(WxPandaShell): self.contextMenu.AppendSeparator() def replaceObject(self, evt, all=False): - currObj = self.editor.objectMgr.findObjectByNodePath(base.direct.selected.last) + currObj = self.editor.objectMgr.findObjectByNodePath(ShowBaseGlobal.direct.selected.last) if currObj is None: print('No valid object is selected for replacement') return @@ -636,13 +637,13 @@ class GridSizeUI(wx.Dialog): vbox.Add(okButton, 1, wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM, 5) self.SetSizer(vbox) - base.le.ui.bindKeyEvents(False) + ShowBaseGlobal.base.le.ui.bindKeyEvents(False) def onApply(self, evt): newSize = self.gridSizeSlider.GetValue() newSpacing = self.gridSpacingSlider.GetValue() self.parent.updateGrids(newSize, newSpacing) - base.le.ui.bindKeyEvents(True) + ShowBaseGlobal.base.le.ui.bindKeyEvents(True) self.Destroy() diff --git a/direct/src/leveleditor/LevelLoader.py b/direct/src/leveleditor/LevelLoader.py index 34a843dd61..cc5fb13c90 100755 --- a/direct/src/leveleditor/LevelLoader.py +++ b/direct/src/leveleditor/LevelLoader.py @@ -25,6 +25,9 @@ class LevelLoader(LevelLoaderBase): def initLoader(self): self.defaultPath = os.path.dirname(__file__) + + from direct.showbase import ShowBaseGlobal + base = ShowBaseGlobal.base base.objectPalette = ObjectPalette() base.protoPalette = ProtoPalette() base.objectHandler = ObjectHandler(None) diff --git a/direct/src/showbase/ShowBase.py b/direct/src/showbase/ShowBase.py index df2630c636..05d7612339 100644 --- a/direct/src/showbase/ShowBase.py +++ b/direct/src/showbase/ShowBase.py @@ -141,7 +141,7 @@ import importlib from direct.showbase import ExceptionVarDump from . import DirectObject from . import SfxPlayer -from typing import ClassVar +from typing import ClassVar, Optional if __debug__: from direct.showbase import GarbageReport from direct.directutil import DeltaProfiler @@ -166,6 +166,10 @@ class ShowBase(DirectObject.DirectObject): notify: ClassVar[Notifier] = directNotify.newCategory("ShowBase") guiItems: ClassVar[dict] + render2d: NodePath + aspect2d: NodePath + pixel2d: NodePath + def __init__(self, fStartDirect=True, windowType=None): """Opens a window, sets up a 3-D and several 2-D scene graphs, and everything else needed to render the scene graph to the window. diff --git a/direct/src/showbase/ShowBaseGlobal.py b/direct/src/showbase/ShowBaseGlobal.py index 58e7e69f58..a9fd35c51a 100644 --- a/direct/src/showbase/ShowBaseGlobal.py +++ b/direct/src/showbase/ShowBaseGlobal.py @@ -61,6 +61,8 @@ aspect2d = render2d.attachNewNode(PGTop("aspect2d")) #: A dummy scene graph that is not being rendered by anything. hidden = NodePath("hidden") +direct: "DirectSession" + # Set direct notify categories now that we have config directNotify.setDconfigLevels() diff --git a/direct/src/showutil/TexMemWatcher.py b/direct/src/showutil/TexMemWatcher.py index 3135c76b05..2ddd54cc59 100644 --- a/direct/src/showutil/TexMemWatcher.py +++ b/direct/src/showutil/TexMemWatcher.py @@ -22,6 +22,7 @@ from panda3d.core import ( WindowProperties, ) from direct.showbase.DirectObject import DirectObject +from direct.showbase import ShowBaseGlobal from direct.task.TaskManagerGlobal import taskMgr import math import copy @@ -109,7 +110,7 @@ class TexMemWatcher(DirectObject): # This is the maximum number of bitmask rows (within # 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) + self.maxHeight = ConfigVariableInt('tex-mem-max-height', 300).value # The total number of texture bytes tracked, including overflow. self.totalSize = 0 @@ -122,6 +123,7 @@ class TexMemWatcher(DirectObject): self.placedQSize = 0 # If no GSG is specified, use the main GSG. + base = ShowBaseGlobal.base if gsg is None: gsg = base.win.getGsg() elif isinstance(gsg, GraphicsOutput): @@ -150,7 +152,7 @@ class TexMemWatcher(DirectObject): # Set this to tinydisplay if you're running on a machine with # limited texture memory. That way you won't compete for # texture memory with the main scene. - moduleName = base.config.GetString('tex-mem-pipe', '') + moduleName = ConfigVariableString('tex-mem-pipe', '').value if moduleName: self.pipe = base.makeModulePipe(moduleName) @@ -202,7 +204,7 @@ class TexMemWatcher(DirectObject): # How frequently should the texture memory window check for # state changes? - updateInterval = base.config.GetDouble("tex-mem-update-interval", 0.5) + updateInterval = ConfigVariableDouble("tex-mem-update-interval", 0.5).value self.task = taskMgr.doMethodLater(updateInterval, self.updateTextures, 'TexMemWatcher') self.setLimit(limit) @@ -380,7 +382,7 @@ class TexMemWatcher(DirectObject): self.cleanedUp = True # Remove the window. - base.graphicsEngine.removeWindow(self.win) + self.win.engine.removeWindow(self.win) self.win = None self.gsg = None self.pipe = None diff --git a/direct/src/tkpanels/DirectSessionPanel.py b/direct/src/tkpanels/DirectSessionPanel.py index b3e521deea..95eaad784d 100644 --- a/direct/src/tkpanels/DirectSessionPanel.py +++ b/direct/src/tkpanels/DirectSessionPanel.py @@ -20,6 +20,7 @@ from direct.tkwidgets import VectorWidgets from direct.tkwidgets import SceneGraphExplorer from direct.tkwidgets import MemoryExplorer from direct.task.TaskManagerGlobal import taskMgr +from direct.showbase import ShowBaseGlobal from .TaskManagerPanel import TaskManagerWidget import Pmw import tkinter as tk @@ -44,8 +45,8 @@ class DirectSessionPanel(AppShell): AppShell.__init__(self, parent) # Active light - if len(base.direct.lights) > 0: - name = base.direct.lights.getNameList()[0] + if len(ShowBaseGlobal.direct.lights) > 0: + name = ShowBaseGlobal.direct.lights.getNameList()[0] self.lightMenu.selectitem(name) self.selectLightNamed(name) else: @@ -62,14 +63,14 @@ class DirectSessionPanel(AppShell): # Initialize state # Dictionary keeping track of all node paths selected so far self.nodePathDict = {} - self.nodePathDict['widget'] = base.direct.widget + self.nodePathDict['widget'] = ShowBaseGlobal.direct.widget self.nodePathNames = ['widget'] # Dictionary keeping track of all jb node paths selected so far self.jbNodePathDict = {} self.jbNodePathDict['none'] = 'No Node Path' - self.jbNodePathDict['widget'] = base.direct.widget - self.jbNodePathDict['camera'] = base.direct.camera + self.jbNodePathDict['widget'] = ShowBaseGlobal.direct.widget + self.jbNodePathDict['camera'] = ShowBaseGlobal.direct.camera self.jbNodePathNames = ['camera', 'selected', 'none'] # Set up event hooks @@ -93,7 +94,7 @@ class DirectSessionPanel(AppShell): self.menuBar.addmenu('DIRECT', 'Direct Session Panel Operations') self.directEnabled = tk.BooleanVar() - self.directEnabled.set(1) + self.directEnabled.set(True) self.menuBar.addmenuitem('DIRECT', 'checkbutton', 'DIRECT Enabled', label = 'Enable', @@ -101,7 +102,7 @@ class DirectSessionPanel(AppShell): command = self.toggleDirect) self.directGridEnabled = tk.BooleanVar() - self.directGridEnabled.set(base.direct.grid.isEnabled()) + self.directGridEnabled.set(ShowBaseGlobal.direct.grid.isEnabled()) self.menuBar.addmenuitem('DIRECT', 'checkbutton', 'DIRECT Grid Enabled', label = 'Enable Grid', @@ -111,16 +112,16 @@ class DirectSessionPanel(AppShell): self.menuBar.addmenuitem('DIRECT', 'command', 'Toggle Object Handles Visability', label = 'Toggle Widget Viz', - command = base.direct.toggleWidgetVis) + command = ShowBaseGlobal.direct.toggleWidgetVis) self.menuBar.addmenuitem( 'DIRECT', 'command', 'Toggle Widget Move/COA Mode', label = 'Toggle Widget Mode', - command = base.direct.manipulationControl.toggleObjectHandlesMode) + command = ShowBaseGlobal.direct.manipulationControl.toggleObjectHandlesMode) self.directWidgetOnTop = tk.BooleanVar() - self.directWidgetOnTop.set(0) + self.directWidgetOnTop.set(False) self.menuBar.addmenuitem('DIRECT', 'checkbutton', 'DIRECT Widget On Top', label = 'Widget On Top', @@ -130,7 +131,7 @@ class DirectSessionPanel(AppShell): self.menuBar.addmenuitem('DIRECT', 'command', 'Deselect All', label = 'Deselect All', - command = base.direct.deselectAll) + command = ShowBaseGlobal.direct.deselectAll) # Get a handle to the menu frame menuFrame = self.menuFrame @@ -150,8 +151,8 @@ class DirectSessionPanel(AppShell): self.bind(self.nodePathMenu, 'Select node path to manipulate') self.undoButton = tk.Button(menuFrame, text = 'Undo', - command = base.direct.undo) - if base.direct.undoList: + command = ShowBaseGlobal.direct.undo) + if ShowBaseGlobal.direct.undoList: self.undoButton['state'] = 'normal' else: self.undoButton['state'] = 'disabled' @@ -159,8 +160,8 @@ class DirectSessionPanel(AppShell): self.bind(self.undoButton, 'Undo last operation') self.redoButton = tk.Button(menuFrame, text = 'Redo', - command = base.direct.redo) - if base.direct.redoList: + command = ShowBaseGlobal.direct.redo) + if ShowBaseGlobal.direct.redoList: self.redoButton['state'] = 'normal' else: self.redoButton['state'] = 'disabled' @@ -177,7 +178,7 @@ class DirectSessionPanel(AppShell): # Scene Graph Explorer self.SGE = SceneGraphExplorer.SceneGraphExplorer( - sgeFrame, nodePath = render, + sgeFrame, nodePath = ShowBaseGlobal.base.render, scrolledCanvas_hull_width = 250, scrolledCanvas_hull_height = 300) self.SGE.pack(fill = tk.BOTH, expand = 1) @@ -218,7 +219,7 @@ class DirectSessionPanel(AppShell): tk.Label(drFrame, text = 'Display Region', font=('MSSansSerif', 14, 'bold')).pack(expand = 0) - nameList = ['Display Region ' + repr(x) for x in range(len(base.direct.drList))] + nameList = ['Display Region ' + repr(x) for x in range(len(ShowBaseGlobal.direct.drList))] self.drMenu = Pmw.ComboBox( drFrame, labelpos = tk.W, label_text = 'Display Region:', entry_width = 20, @@ -264,7 +265,7 @@ class DirectSessionPanel(AppShell): frame = tk.Frame(fovFrame) self.lockedFov = tk.BooleanVar() - self.lockedFov.set(1) + self.lockedFov.set(True) self.lockedFovButton = tk.Checkbutton( frame, text = 'Locked', @@ -289,25 +290,25 @@ class DirectSessionPanel(AppShell): self.toggleBackfaceButton = tk.Button( toggleFrame, text = 'Backface', - command = base.toggleBackface) + command = ShowBaseGlobal.base.toggleBackface) self.toggleBackfaceButton.pack(side = tk.LEFT, fill = tk.X, expand = 1) self.toggleLightsButton = tk.Button( toggleFrame, text = 'Lights', - command = base.direct.lights.toggle) + command = ShowBaseGlobal.direct.lights.toggle) self.toggleLightsButton.pack(side = tk.LEFT, fill = tk.X, expand = 1) self.toggleTextureButton = tk.Button( toggleFrame, text = 'Texture', - command = base.toggleTexture) + command = ShowBaseGlobal.base.toggleTexture) self.toggleTextureButton.pack(side = tk.LEFT, fill = tk.X, expand = 1) self.toggleWireframeButton = tk.Button( toggleFrame, text = 'Wireframe', - command = base.toggleWireframe) + command = ShowBaseGlobal.base.toggleWireframe) self.toggleWireframeButton.pack(fill = tk.X, expand = 1) toggleFrame.pack(side = tk.LEFT, fill = tk.X, expand = 1) @@ -354,7 +355,7 @@ class DirectSessionPanel(AppShell): mainSwitchFrame.pack(fill = tk.X, expand = 0) # Widget to select a light to configure - nameList = base.direct.lights.getNameList() + nameList = ShowBaseGlobal.direct.lights.getNameList() lightMenuFrame = tk.Frame(lightFrame) self.lightMenu = Pmw.ComboBox( @@ -510,36 +511,36 @@ class DirectSessionPanel(AppShell): gridPage, text = 'Grid Spacing', min = 0.1, - value = base.direct.grid.getGridSpacing()) - self.gridSpacing['command'] = base.direct.grid.setGridSpacing + value = ShowBaseGlobal.direct.grid.getGridSpacing()) + self.gridSpacing['command'] = ShowBaseGlobal.direct.grid.setGridSpacing self.gridSpacing.pack(fill = tk.X, expand = 0) self.gridSize = Floater.Floater( gridPage, text = 'Grid Size', min = 1.0, - value = base.direct.grid.getGridSize()) - self.gridSize['command'] = base.direct.grid.setGridSize + value = ShowBaseGlobal.direct.grid.getGridSize()) + self.gridSize['command'] = ShowBaseGlobal.direct.grid.setGridSize self.gridSize.pack(fill = tk.X, expand = 0) self.gridSnapAngle = Dial.AngleDial( gridPage, text = 'Snap Angle', style = 'mini', - value = base.direct.grid.getSnapAngle()) - self.gridSnapAngle['command'] = base.direct.grid.setSnapAngle + value = ShowBaseGlobal.direct.grid.getSnapAngle()) + self.gridSnapAngle['command'] = ShowBaseGlobal.direct.grid.setSnapAngle self.gridSnapAngle.pack(fill = tk.X, expand = 0) def createDevicePage(self, devicePage): tk.Label(devicePage, text = 'DEVICES', font=('MSSansSerif', 14, 'bold')).pack(expand = 0) - if base.direct.joybox is not None: + if ShowBaseGlobal.direct.joybox is not None: joyboxFrame = tk.Frame(devicePage, borderwidth = 2, relief = 'sunken') tk.Label(joyboxFrame, text = 'Joybox', font=('MSSansSerif', 14, 'bold')).pack(expand = 0) self.enableJoybox = tk.BooleanVar() - self.enableJoybox.set(1) + self.enableJoybox.set(True) self.enableJoyboxButton = tk.Checkbutton( joyboxFrame, text = 'Enabled/Disabled', @@ -581,7 +582,7 @@ class DirectSessionPanel(AppShell): hull_relief = tk.RIDGE, hull_borderwidth = 2, min = 1.0, max = 100.0) self.jbXyzSF['command'] = ( - lambda v: base.direct.joybox.setXyzMultiplier(v)) + lambda v: ShowBaseGlobal.direct.joybox.setXyzMultiplier(v)) self.jbXyzSF.pack(fill = tk.X, expand = 0) self.bind(self.jbXyzSF, 'Set joybox XYZ speed multiplier') @@ -592,7 +593,7 @@ class DirectSessionPanel(AppShell): hull_relief = tk.RIDGE, hull_borderwidth = 2, min = 1.0, max = 100.0) self.jbHprSF['command'] = ( - lambda v: base.direct.joybox.setHprMultiplier(v)) + lambda v: ShowBaseGlobal.direct.joybox.setHprMultiplier(v)) self.jbHprSF.pack(fill = tk.X, expand = 0) self.bind(self.jbHprSF, 'Set joybox HPR speed multiplier') @@ -604,30 +605,30 @@ class DirectSessionPanel(AppShell): def createMemPage(self, memPage): self.MemExp = MemoryExplorer.MemoryExplorer( - memPage, nodePath = render, + memPage, nodePath = ShowBaseGlobal.base.render, scrolledCanvas_hull_width = 250, scrolledCanvas_hull_height = 250) self.MemExp.pack(fill = tk.BOTH, expand = 1) def toggleDirect(self): if self.directEnabled.get(): - base.direct.enable() + ShowBaseGlobal.direct.enable() else: - base.direct.disable() + ShowBaseGlobal.direct.disable() def toggleDirectGrid(self): if self.directGridEnabled.get(): - base.direct.grid.enable() + ShowBaseGlobal.direct.grid.enable() else: - base.direct.grid.disable() + ShowBaseGlobal.direct.grid.disable() def toggleWidgetOnTop(self): if self.directWidgetOnTop.get(): - base.direct.widget.setBin('gui-popup', 0) - base.direct.widget.setDepthTest(0) + ShowBaseGlobal.direct.widget.setBin('gui-popup', 0) + ShowBaseGlobal.direct.widget.setDepthTest(0) else: - base.direct.widget.clearBin() - base.direct.widget.setDepthTest(1) + ShowBaseGlobal.direct.widget.clearBin() + ShowBaseGlobal.direct.widget.setDepthTest(1) def selectedNodePathHook(self, nodePath): # Make sure node path is in nodePathDict @@ -657,7 +658,7 @@ class DirectSessionPanel(AppShell): # Did we finally get something? if nodePath is not None: # Yes, select it! - base.direct.select(nodePath) + ShowBaseGlobal.direct.select(nodePath) def addNodePath(self, nodePath): self.addNodePathToDict(nodePath, self.nodePathNames, @@ -665,25 +666,25 @@ class DirectSessionPanel(AppShell): def selectJBModeNamed(self, name): if name == 'Joe Mode': - base.direct.joybox.joeMode() + ShowBaseGlobal.direct.joybox.joeMode() elif name == 'Drive Mode': - base.direct.joybox.driveMode() + ShowBaseGlobal.direct.joybox.driveMode() elif name == 'Orbit Mode': - base.direct.joybox.orbitMode() + ShowBaseGlobal.direct.joybox.orbitMode() elif name == 'Look At Mode': - base.direct.joybox.lookAtMode() + ShowBaseGlobal.direct.joybox.lookAtMode() elif name == 'Look Around Mode': - base.direct.joybox.lookAroundMode() + ShowBaseGlobal.direct.joybox.lookAroundMode() elif name == 'Walkthru Mode': - base.direct.joybox.walkthruMode() + ShowBaseGlobal.direct.joybox.walkthruMode() elif name == 'Demo Mode': - base.direct.joybox.demoMode() + ShowBaseGlobal.direct.joybox.demoMode() elif name == 'HPRXYZ Mode': - base.direct.joybox.hprXyzMode() + ShowBaseGlobal.direct.joybox.hprXyzMode() def selectJBNodePathNamed(self, name): if name == 'selected': - nodePath = base.direct.selected.last + nodePath = ShowBaseGlobal.direct.selected.last # Add Combo box entry for this selected object self.addJBNodePath(nodePath) else: @@ -708,9 +709,9 @@ class DirectSessionPanel(AppShell): if nodePath is not None: # Yes, select it! if nodePath == 'No Node Path': - base.direct.joybox.setNodePath(None) + ShowBaseGlobal.direct.joybox.setNodePath(None) else: - base.direct.joybox.setNodePath(nodePath) + ShowBaseGlobal.direct.joybox.setNodePath(nodePath) def addJBNodePath(self, nodePath): self.addNodePathToDict(nodePath, self.jbNodePathNames, @@ -741,14 +742,13 @@ class DirectSessionPanel(AppShell): self.setBackgroundColorVec((r, g, b)) def setBackgroundColorVec(self, color): - base.setBackgroundColor(color[0]/255.0, - color[1]/255.0, - color[2]/255.0) + ShowBaseGlobal.base.setBackgroundColor( + color[0] / 255.0, color[1] / 255.0, color[2] / 255.0) def selectDisplayRegionNamed(self, name): if name.find('Display Region ') >= 0: drIndex = int(name[-1:]) - self.activeDisplayRegion = base.direct.drList[drIndex] + self.activeDisplayRegion = ShowBaseGlobal.direct.drList[drIndex] else: self.activeDisplayRegion = None # Make sure info is current @@ -758,13 +758,13 @@ class DirectSessionPanel(AppShell): dr = self.activeDisplayRegion if dr: dr.camLens.setNear(near) - cluster('base.camLens.setNear(%f)' % near, 0) + ShowBaseGlobal.direct.cluster('base.camLens.setNear(%f)' % near, 0) def setFar(self, far): dr = self.activeDisplayRegion if dr: dr.camLens.setFar(far) - cluster('base.camLens.setFar(%f)' % far, 0) + ShowBaseGlobal.direct.cluster('base.camLens.setFar(%f)' % far, 0) def setHFov(self, hFov): dr = self.activeDisplayRegion @@ -802,10 +802,10 @@ class DirectSessionPanel(AppShell): # Lights # def selectLightNamed(self, name): # See if light exists - self.activeLight = base.direct.lights[name] + self.activeLight = ShowBaseGlobal.direct.lights[name] # If not...create new one if self.activeLight is None: - self.activeLight = base.direct.lights.create(name) + self.activeLight = ShowBaseGlobal.direct.lights.create(name) # Do we have a valid light at this point? if self.activeLight: light = self.activeLight.getLight() @@ -820,28 +820,28 @@ class DirectSessionPanel(AppShell): else: # Restore valid data listbox = self.lightMenu.component('scrolledlist') - listbox.setlist(base.direct.lights.getNameList()) - if len(base.direct.lights) > 0: - self.lightMenu.selectitem(base.direct.lights.getNameList()[0]) + listbox.setlist(ShowBaseGlobal.direct.lights.getNameList()) + if len(ShowBaseGlobal.direct.lights) > 0: + self.lightMenu.selectitem(ShowBaseGlobal.direct.lights.getNameList()[0]) # Make sure info is current self.updateLightInfo() def addAmbient(self): - return base.direct.lights.create('ambient') + return ShowBaseGlobal.direct.lights.create('ambient') def addDirectional(self): - return base.direct.lights.create('directional') + return ShowBaseGlobal.direct.lights.create('directional') def addPoint(self): - return base.direct.lights.create('point') + return ShowBaseGlobal.direct.lights.create('point') def addSpot(self): - return base.direct.lights.create('spot') + return ShowBaseGlobal.direct.lights.create('spot') def addLight(self, light): # Make list reflect current list of lights listbox = self.lightMenu.component('scrolledlist') - listbox.setlist(base.direct.lights.getNameList()) + listbox.setlist(ShowBaseGlobal.direct.lights.getNameList()) # Select the newly added light self.lightMenu.selectitem(light.getName()) # And show corresponding page @@ -849,16 +849,16 @@ class DirectSessionPanel(AppShell): def toggleLights(self): if self.enableLights.get(): - base.direct.lights.allOn() + ShowBaseGlobal.direct.lights.allOn() else: - base.direct.lights.allOff() + ShowBaseGlobal.direct.lights.allOff() def toggleActiveLight(self): if self.activeLight: if self.lightActive.get(): - base.direct.lights.setOn(self.activeLight) + ShowBaseGlobal.direct.lights.setOn(self.activeLight) else: - base.direct.lights.setOff(self.activeLight) + ShowBaseGlobal.direct.lights.setOff(self.activeLight) def setLightColor(self, color): if self.activeLight: @@ -893,22 +893,22 @@ class DirectSessionPanel(AppShell): ## GRID CONTROLS ## def toggleGrid(self): if self.enableGrid.get(): - base.direct.grid.enable() + ShowBaseGlobal.direct.grid.enable() else: - base.direct.grid.disable() + ShowBaseGlobal.direct.grid.disable() def toggleXyzSnap(self): - base.direct.grid.setXyzSnap(self.xyzSnap.get()) + ShowBaseGlobal.direct.grid.setXyzSnap(self.xyzSnap.get()) def toggleHprSnap(self): - base.direct.grid.setHprSnap(self.hprSnap.get()) + ShowBaseGlobal.direct.grid.setHprSnap(self.hprSnap.get()) ## DEVICE CONTROLS def toggleJoybox(self): if self.enableJoybox.get(): - base.direct.joybox.enable() + ShowBaseGlobal.direct.joybox.enable() else: - base.direct.joybox.disable() + ShowBaseGlobal.direct.joybox.disable() ## UPDATE INFO ## def updateInfo(self, page = 'Environment'): @@ -920,7 +920,7 @@ class DirectSessionPanel(AppShell): self.updateGridInfo() def updateEnvironmentInfo(self): - bkgrdColor = base.getBackgroundColor() * 255.0 + bkgrdColor = ShowBaseGlobal.base.getBackgroundColor() * 255.0 self.backgroundColor.set([bkgrdColor[0], bkgrdColor[1], bkgrdColor[2], @@ -936,6 +936,7 @@ class DirectSessionPanel(AppShell): def updateLightInfo(self, page = None): # Set main lighting button + render = ShowBaseGlobal.base.render self.enableLights.set( render.node().hasAttrib(LightAttrib.getClassType())) @@ -974,16 +975,16 @@ class DirectSessionPanel(AppShell): self.pQuadraticAttenuation.set(att[2], 0) def updateGridInfo(self): - self.enableGrid.set(base.direct.grid.isEnabled()) - self.xyzSnap.set(base.direct.grid.getXyzSnap()) - self.hprSnap.set(base.direct.grid.getHprSnap()) - self.gridSpacing.set(base.direct.grid.getGridSpacing(), 0) - self.gridSize.set(base.direct.grid.getGridSize(), 0) - self.gridSnapAngle.set(base.direct.grid.getSnapAngle(), 0) + self.enableGrid.set(ShowBaseGlobal.direct.grid.isEnabled()) + self.xyzSnap.set(ShowBaseGlobal.direct.grid.getXyzSnap()) + self.hprSnap.set(ShowBaseGlobal.direct.grid.getHprSnap()) + self.gridSpacing.set(ShowBaseGlobal.direct.grid.getGridSpacing(), 0) + self.gridSize.set(ShowBaseGlobal.direct.grid.getGridSize(), 0) + self.gridSnapAngle.set(ShowBaseGlobal.direct.grid.getSnapAngle(), 0) # UNDO/REDO def pushUndo(self, fResetRedo = 1): - base.direct.pushUndo([self['nodePath']]) + ShowBaseGlobal.direct.pushUndo([self['nodePath']]) def undoHook(self, nodePathList = []): pass @@ -997,7 +998,7 @@ class DirectSessionPanel(AppShell): self.undoButton.configure(state = 'disabled') def pushRedo(self): - base.direct.pushRedo([self['nodePath']]) + ShowBaseGlobal.direct.pushRedo([self['nodePath']]) def redoHook(self, nodePathList = []): pass diff --git a/direct/src/tkpanels/Inspector.py b/direct/src/tkpanels/Inspector.py index 15cc04dc46..707bc038c3 100644 --- a/direct/src/tkpanels/Inspector.py +++ b/direct/src/tkpanels/Inspector.py @@ -31,6 +31,8 @@ def inspect(anObject): ### private +_InspectorMap: dict[str, str] + def inspectorFor(anObject): typeName = type(anObject).__name__.capitalize() + 'Type' @@ -396,7 +398,8 @@ class InspectorWindow: self.listWidget.component('listbox').focus_set() def showHelp(self): - help = tk.Toplevel(base.tkRoot) + from direct.showbase import ShowBaseGlobal + help = tk.Toplevel(ShowBaseGlobal.base.tkRoot) help.title("Inspector Help") frame = tk.Frame(help) frame.pack() diff --git a/direct/src/tkpanels/Placer.py b/direct/src/tkpanels/Placer.py index 6fdf0767f1..2549fee2a1 100644 --- a/direct/src/tkpanels/Placer.py +++ b/direct/src/tkpanels/Placer.py @@ -9,6 +9,7 @@ from direct.tkwidgets import Dial from direct.tkwidgets import Floater from direct.directtools.DirectGlobals import ZERO_VEC, UNIT_VEC from direct.showbase.MessengerGlobal import messenger +from direct.showbase import ShowBaseGlobal from direct.task.TaskManagerGlobal import taskMgr import Pmw import tkinter as tk @@ -28,7 +29,7 @@ class Placer(AppShell): INITOPT = Pmw.INITOPT optiondefs = ( ('title', self.appname, None), - ('nodePath', base.direct.camera, None), + ('nodePath', ShowBaseGlobal.direct.camera, None), ) self.defineoptions(kw, optiondefs) @@ -39,23 +40,23 @@ class Placer(AppShell): def appInit(self): # Initialize state - self.tempCS = base.direct.group.attachNewNode('placerTempCS') - self.orbitFromCS = base.direct.group.attachNewNode( + self.tempCS = ShowBaseGlobal.direct.group.attachNewNode('placerTempCS') + self.orbitFromCS = ShowBaseGlobal.direct.group.attachNewNode( 'placerOrbitFromCS') - self.orbitToCS = base.direct.group.attachNewNode('placerOrbitToCS') + self.orbitToCS = ShowBaseGlobal.direct.group.attachNewNode('placerOrbitToCS') self.refCS = self.tempCS # Dictionary keeping track of all node paths manipulated so far self.nodePathDict = {} - self.nodePathDict['camera'] = base.direct.camera - self.nodePathDict['widget'] = base.direct.widget + self.nodePathDict['camera'] = ShowBaseGlobal.direct.camera + self.nodePathDict['widget'] = ShowBaseGlobal.direct.widget self.nodePathNames = ['camera', 'widget', 'selected'] self.refNodePathDict = {} self.refNodePathDict['parent'] = self['nodePath'].getParent() self.refNodePathDict['render'] = render - self.refNodePathDict['camera'] = base.direct.camera - self.refNodePathDict['widget'] = base.direct.widget + self.refNodePathDict['camera'] = ShowBaseGlobal.direct.camera + self.refNodePathDict['widget'] = ShowBaseGlobal.direct.widget self.refNodePathNames = ['parent', 'self', 'render', 'camera', 'widget', 'selected'] @@ -103,12 +104,12 @@ class Placer(AppShell): 'Placer', 'command', 'Toggle widget visability', label = 'Toggle Widget Vis', - command = base.direct.toggleWidgetVis) + command = ShowBaseGlobal.direct.toggleWidgetVis) self.menuBar.addmenuitem( 'Placer', 'command', 'Toggle widget manipulation mode', label = 'Toggle Widget Mode', - command = base.direct.manipulationControl.toggleObjectHandlesMode) + command = ShowBaseGlobal.direct.manipulationControl.toggleObjectHandlesMode) # Get a handle to the menu frame menuFrame = self.menuFrame @@ -145,8 +146,8 @@ class Placer(AppShell): self.bind(self.refNodePathMenu, 'Select relative node path') self.undoButton = tk.Button(menuFrame, text = 'Undo', - command = base.direct.undo) - if base.direct.undoList: + command = ShowBaseGlobal.direct.undo) + if ShowBaseGlobal.direct.undoList: self.undoButton['state'] = 'normal' else: self.undoButton['state'] = 'disabled' @@ -154,8 +155,8 @@ class Placer(AppShell): self.bind(self.undoButton, 'Undo last operation') self.redoButton = tk.Button(menuFrame, text = 'Redo', - command = base.direct.redo) - if base.direct.redoList: + command = ShowBaseGlobal.direct.redo) + if ShowBaseGlobal.direct.redoList: self.redoButton['state'] = 'normal' else: self.redoButton['state'] = 'disabled' @@ -394,7 +395,7 @@ class Placer(AppShell): # Add Combo box entry for the initial node path self.addNodePath(nodePath) elif name == 'selected': - nodePath = base.direct.selected.last + nodePath = ShowBaseGlobal.direct.selected.last # Add Combo box entry for this selected object self.addNodePath(nodePath) else: @@ -417,7 +418,7 @@ class Placer(AppShell): else: if name == 'widget': # Record relationship between selected nodes and widget - base.direct.selected.getWrtAll() + ShowBaseGlobal.direct.selected.getWrtAll() # Update active node path self.setActiveNodePath(nodePath) @@ -449,7 +450,7 @@ class Placer(AppShell): if name == 'self': nodePath = self.tempCS elif name == 'selected': - nodePath = base.direct.selected.last + nodePath = ShowBaseGlobal.direct.selected.last # Add Combo box entry for this selected object self.addRefNodePath(nodePath) elif name == 'parent': @@ -560,13 +561,13 @@ class Placer(AppShell): elif self.movementMode == 'Orbit:': self.xformOrbit(value, axis) if self.nodePathMenu.get() == 'widget': - if base.direct.manipulationControl.fSetCoa: + if ShowBaseGlobal.direct.manipulationControl.fSetCoa: # Update coa based on current widget position - base.direct.selected.last.mCoa2Dnp.assign( - base.direct.widget.getMat(base.direct.selected.last)) + ShowBaseGlobal.direct.selected.last.mCoa2Dnp.assign( + ShowBaseGlobal.direct.widget.getMat(ShowBaseGlobal.direct.selected.last)) else: # Move the objects with the widget - base.direct.selected.moveWrtWidgetAll() + ShowBaseGlobal.direct.selected.moveWrtWidgetAll() def xformStart(self, data): # Record undo point @@ -575,7 +576,7 @@ class Placer(AppShell): if self.nodePathMenu.get() == 'widget': taskMgr.remove('followSelectedNodePath') # Record relationship between selected nodes and widget - base.direct.selected.getWrtAll() + ShowBaseGlobal.direct.selected.getWrtAll() # Record initial state self.deltaHpr = self['nodePath'].getHpr(self.refCS) # Update placer to reflect new state @@ -590,7 +591,7 @@ class Placer(AppShell): # If moving widget restart follow task if self.nodePathMenu.get() == 'widget': # Restart followSelectedNodePath task - base.direct.manipulationControl.spawnFollowSelectedNodePathTask() + ShowBaseGlobal.direct.manipulationControl.spawnFollowSelectedNodePathTask() def xformRelative(self, value, axis): nodePath = self['nodePath'] @@ -729,7 +730,7 @@ class Placer(AppShell): self.xformStop(None) def pushUndo(self, fResetRedo = 1): - base.direct.pushUndo([self['nodePath']]) + ShowBaseGlobal.direct.pushUndo([self['nodePath']]) def undoHook(self, nodePathList = []): # Reflect new changes @@ -744,7 +745,7 @@ class Placer(AppShell): self.undoButton.configure(state = 'disabled') def pushRedo(self): - base.direct.pushRedo([self['nodePath']]) + ShowBaseGlobal.direct.pushRedo([self['nodePath']]) def redoHook(self, nodePathList = []): # Reflect new changes diff --git a/direct/src/wxwidgets/WxPandaShell.py b/direct/src/wxwidgets/WxPandaShell.py index 44790bd653..09e15add96 100755 --- a/direct/src/wxwidgets/WxPandaShell.py +++ b/direct/src/wxwidgets/WxPandaShell.py @@ -9,6 +9,8 @@ from direct.task.TaskManagerGlobal import taskMgr from .WxAppShell import WxAppShell from .ViewPort import Viewport, ViewportManager +from typing import Optional + ID_FOUR_VIEW = 401 ID_TOP_VIEW = 402 ID_FRONT_VIEW = 403 @@ -25,7 +27,7 @@ class WxPandaShell(WxAppShell): copyright = ('Copyright 2010 Disney Online Studios.' + '\nAll Rights Reserved.') - MENU_TEXTS = { + MENU_TEXTS: dict[int, tuple[str, Optional[str]]] = { ID_FOUR_VIEW: ("Four Views", None), ID_TOP_VIEW: ("Top View", None), ID_FRONT_VIEW: ("Front View", None), @@ -114,6 +116,7 @@ class WxPandaShell(WxAppShell): self.wxStep() ViewportManager.initializeAll() # Position the camera + base = ShowBaseGlobal.base if base.trackball is not None: base.trackball.node().setPos(0, 30, 0) base.trackball.node().setHpr(0, 15, 0) @@ -125,33 +128,34 @@ class WxPandaShell(WxAppShell): # initializing direct if self.fStartDirect: base.startDirect(fWantTk = 0, fWantWx = 0) + direct = ShowBaseGlobal.direct - base.direct.disableMouseEvents() - newMouseEvents = ["_le_per_%s"%x for x in base.direct.mouseEvents] +\ - ["_le_fro_%s"%x for x in base.direct.mouseEvents] +\ - ["_le_lef_%s"%x for x in base.direct.mouseEvents] +\ - ["_le_top_%s"%x for x in base.direct.mouseEvents] - base.direct.mouseEvents = newMouseEvents - base.direct.enableMouseEvents() + direct.disableMouseEvents() + newMouseEvents = ["_le_per_%s"%x for x in direct.mouseEvents] +\ + ["_le_fro_%s"%x for x in direct.mouseEvents] +\ + ["_le_lef_%s"%x for x in direct.mouseEvents] +\ + ["_le_top_%s"%x for x in direct.mouseEvents] + direct.mouseEvents = newMouseEvents + direct.enableMouseEvents() - base.direct.disableKeyEvents() - keyEvents = ["_le_per_%s"%x for x in base.direct.keyEvents] +\ - ["_le_fro_%s"%x for x in base.direct.keyEvents] +\ - ["_le_lef_%s"%x for x in base.direct.keyEvents] +\ - ["_le_top_%s"%x for x in base.direct.keyEvents] - base.direct.keyEvents = keyEvents - base.direct.enableKeyEvents() + direct.disableKeyEvents() + keyEvents = ["_le_per_%s"%x for x in direct.keyEvents] +\ + ["_le_fro_%s"%x for x in direct.keyEvents] +\ + ["_le_lef_%s"%x for x in direct.keyEvents] +\ + ["_le_top_%s"%x for x in direct.keyEvents] + direct.keyEvents = keyEvents + direct.enableKeyEvents() - base.direct.disableModifierEvents() - modifierEvents = ["_le_per_%s"%x for x in base.direct.modifierEvents] +\ - ["_le_fro_%s"%x for x in base.direct.modifierEvents] +\ - ["_le_lef_%s"%x for x in base.direct.modifierEvents] +\ - ["_le_top_%s"%x for x in base.direct.modifierEvents] - base.direct.modifierEvents = modifierEvents - base.direct.enableModifierEvents() + direct.disableModifierEvents() + modifierEvents = ["_le_per_%s"%x for x in direct.modifierEvents] +\ + ["_le_fro_%s"%x for x in direct.modifierEvents] +\ + ["_le_lef_%s"%x for x in direct.modifierEvents] +\ + ["_le_top_%s"%x for x in direct.modifierEvents] + direct.modifierEvents = modifierEvents + direct.enableModifierEvents() - base.direct.cameraControl.lockRoll = True - base.direct.setFScaleWidgetByCam(1) + direct.cameraControl.lockRoll = True + direct.setFScaleWidgetByCam(1) unpickables = [ "z-guide", @@ -172,31 +176,31 @@ class WxPandaShell(WxAppShell): "Sphere",] for unpickable in unpickables: - base.direct.addUnpickable(unpickable) + direct.addUnpickable(unpickable) - base.direct.manipulationControl.optionalSkipFlags |= SKIP_UNPICKABLE - base.direct.manipulationControl.fAllowMarquee = 1 - base.direct.manipulationControl.supportMultiView() - base.direct.cameraControl.useMayaCamControls = 1 - base.direct.cameraControl.perspCollPlane = self.perspView.collPlane - base.direct.cameraControl.perspCollPlane2 = self.perspView.collPlane2 + direct.manipulationControl.optionalSkipFlags |= SKIP_UNPICKABLE + direct.manipulationControl.fAllowMarquee = 1 + direct.manipulationControl.supportMultiView() + direct.cameraControl.useMayaCamControls = 1 + direct.cameraControl.perspCollPlane = self.perspView.collPlane + direct.cameraControl.perspCollPlane2 = self.perspView.collPlane2 - for widget in base.direct.manipulationControl.widgetList: + for widget in direct.manipulationControl.widgetList: widget.setBin('gui-popup', 0) widget.setDepthTest(0) # [gjeon] to intercept messages here - base.direct.ignore('DIRECT-delete') - base.direct.ignore('DIRECT-select') - base.direct.ignore('DIRECT-preDeselectAll') - base.direct.ignore('DIRECT-toggleWidgetVis') - base.direct.fIgnoreDirectOnlyKeyMap = 1 + direct.ignore('DIRECT-delete') + direct.ignore('DIRECT-select') + direct.ignore('DIRECT-preDeselectAll') + direct.ignore('DIRECT-toggleWidgetVis') + direct.fIgnoreDirectOnlyKeyMap = 1 # [gjeon] do not use the old way of finding current DR - base.direct.drList.tryToGetCurrentDr = False + direct.drList.tryToGetCurrentDr = False else: - base.direct=None + base.direct = None #base.closeWindow(base.win) base.win = base.winList[3]