tabs to spaces

This commit is contained in:
David Rose 2001-08-21 03:45:07 +00:00
parent 7a30c9e26d
commit 43a83a5e96
54 changed files with 1872 additions and 1872 deletions

View File

@ -403,14 +403,14 @@ class Actor(PandaObject, NodePath):
return self.__hasLOD
def update(self, lod=0):
""" update(lod)
"""
if (lod < len(self.__partBundleDict.values())):
partBundles = self.__partBundleDict.values()[lod].values()
for partBundle in partBundles:
partBundle.node().update()
else:
self.notify.warning('update() - no lod: %d' % lod)
""" update(lod)
"""
if (lod < len(self.__partBundleDict.values())):
partBundles = self.__partBundleDict.values()[lod].values()
for partBundle in partBundles:
partBundle.node().update()
else:
self.notify.warning('update() - no lod: %d' % lod)
def getFrameRate(self, animName=None, partName=None):
"""getFrameRate(self, string, string=None)
@ -507,21 +507,21 @@ class Actor(PandaObject, NodePath):
return None
def getNumFrames(self, animName=None, partName=None):
""" getNumFrames(animName, partName)
"""
lodName = self.__animControlDict.keys()[0]
if (partName == None):
partName = self.__animControlDict[lodName].keys()[0]
if (animName == None):
animName = self.getCurrentAnim(partName)
if (self.__animControlDict[lodName].has_key(partName)):
animControl = self.getAnimControl(animName, partName, lodName)
if (animControl != None):
return animControl.getNumFrames()
else:
Actor.notify.error('no anim control!')
else:
Actor.notify.warning('no part named: %s' % (partName))
""" getNumFrames(animName, partName)
"""
lodName = self.__animControlDict.keys()[0]
if (partName == None):
partName = self.__animControlDict[lodName].keys()[0]
if (animName == None):
animName = self.getCurrentAnim(partName)
if (self.__animControlDict[lodName].has_key(partName)):
animControl = self.getAnimControl(animName, partName, lodName)
if (animControl != None):
return animControl.getNumFrames()
else:
Actor.notify.error('no anim control!')
else:
Actor.notify.warning('no part named: %s' % (partName))
def getCurrentAnim(self, partName=None):
"""getCurrentAnim(self, string=None)
@ -930,19 +930,19 @@ class Actor(PandaObject, NodePath):
animControl = self.getAnimControl(animName, thisPart,
thisLod)
if (animControl != None):
if (fromFrame == None):
if (fromFrame == None):
animControl.play()
else:
animControl.play(fromFrame, toFrame)
else:
animControl.play(fromFrame, toFrame)
else:
animControl = self.getAnimControl(animName, partName,
thisLod)
if (animControl != None):
if (fromFrame == None):
animControl.play()
else:
animControl.play(fromFrame, toFrame)
if (fromFrame == None):
animControl.play()
else:
animControl.play(fromFrame, toFrame)
def loop(self, animName, restart=1, partName=None):
@ -981,7 +981,7 @@ class Actor(PandaObject, NodePath):
animControl = self.getAnimControl(animName, thisPart,
thisLod)
if (animControl != None):
animControl.pingpong(restart, fromFrame, toFrame)
animControl.pingpong(restart, fromFrame, toFrame)
else:
# loop a specific part
animControl = self.getAnimControl(animName, partName,

View File

@ -21,7 +21,7 @@ class DistributedActor(DistributedNode.DistributedNode, Actor.Actor):
def disable(self):
# remove all anims, on all parts and all lods
if (not self.isEmpty()):
if (not self.isEmpty()):
Actor.Actor.unloadAnims(self, None, None, None)
DistributedNode.DistributedNode.disable(self)

View File

@ -10,8 +10,8 @@ class DirectCameraControl(PandaObject):
# Create the grid
self.startT = 0.0
self.startF = 0
self.orthoViewRoll = 0.0
self.lastView = 0
self.orthoViewRoll = 0.0
self.lastView = 0
self.coa = Point3(0,100,0)
self.coaMarker = loader.loadModel('models/misc/sphere')
self.coaMarker.setName('DirectCameraCOAMarker')
@ -24,7 +24,7 @@ class DirectCameraControl(PandaObject):
self.nullHitPointCount = 0
self.cqEntries = []
self.coaMarkerRef = direct.group.attachNewNode('coaMarkerRef')
self.camManipRef = direct.group.attachNewNode('camManipRef')
self.camManipRef = direct.group.attachNewNode('camManipRef')
t = CAM_MOVE_DURATION
self.actionEvents = [
['DIRECT_mouse2', self.mouseFlyStart],
@ -63,7 +63,7 @@ class DirectCameraControl(PandaObject):
def mouseFlyStart(self):
# Record undo point
direct.pushUndo([direct.camera])
# Where are we in the display region?
# Where are we in the display region?
if ((abs(direct.dr.mouseX) < 0.9) and (abs(direct.dr.mouseY) < 0.9)):
# MOUSE IS IN CENTRAL REGION
# Hide the marker for this kind of motion
@ -84,7 +84,7 @@ class DirectCameraControl(PandaObject):
self.spawnMouseRotateTask()
def mouseFlyStop(self):
taskMgr.removeTasksNamed('manipulateCamera')
taskMgr.removeTasksNamed('manipulateCamera')
stopT = globalClock.getFrameTime()
deltaT = stopT - self.startT
stopF = globalClock.getFrameCount()
@ -110,7 +110,7 @@ class DirectCameraControl(PandaObject):
def spawnXZTranslateOrHPanYZoom(self):
# Kill any existing tasks
taskMgr.removeTasksNamed('manipulateCamera')
taskMgr.removeTasksNamed('manipulateCamera')
# Spawn the new task
t = Task.Task(self.XZTranslateOrHPanYZoomTask)
# For HPanYZoom
@ -120,20 +120,20 @@ class DirectCameraControl(PandaObject):
def spawnXZTranslateOrHPPan(self):
# Kill any existing tasks
taskMgr.removeTasksNamed('manipulateCamera')
taskMgr.removeTasksNamed('manipulateCamera')
# Spawn new task
taskMgr.spawnMethodNamed(self.XZTranslateOrHPPanTask,
'manipulateCamera')
def spawnXZTranslate(self):
# Kill any existing tasks
taskMgr.removeTasksNamed('manipulateCamera')
taskMgr.removeTasksNamed('manipulateCamera')
# Spawn new task
taskMgr.spawnMethodNamed(self.XZTranslateTask, 'manipulateCamera')
def spawnHPanYZoom(self):
# Kill any existing tasks
taskMgr.removeTasksNamed('manipulateCamera')
taskMgr.removeTasksNamed('manipulateCamera')
# Spawn new task
t = Task.Task(self.HPanYZoomTask)
coaDist = Vec3(self.coaMarker.getPos(direct.camera)).length()
@ -142,7 +142,7 @@ class DirectCameraControl(PandaObject):
def spawnHPPan(self):
# Kill any existing tasks
taskMgr.removeTasksNamed('manipulateCamera')
taskMgr.removeTasksNamed('manipulateCamera')
# Spawn new task
taskMgr.spawnMethodNamed(self.HPPanTask, 'manipulateCamera')
@ -206,10 +206,10 @@ class DirectCameraControl(PandaObject):
def spawnMouseRotateTask(self):
# Kill any existing tasks
taskMgr.removeTasksNamed('manipulateCamera')
taskMgr.removeTasksNamed('manipulateCamera')
# Set at markers position in render coordinates
self.camManipRef.setPos(self.coaMarkerPos)
self.camManipRef.setHpr(direct.camera, ZERO_POINT)
self.camManipRef.setPos(self.coaMarkerPos)
self.camManipRef.setHpr(direct.camera, ZERO_POINT)
t = Task.Task(self.mouseRotateTask)
if abs(direct.dr.mouseX) > 0.9:
t.constrainedDir = 'y'
@ -246,14 +246,14 @@ class DirectCameraControl(PandaObject):
def spawnMouseRollTask(self):
# Kill any existing tasks
taskMgr.removeTasksNamed('manipulateCamera')
taskMgr.removeTasksNamed('manipulateCamera')
# Set at markers position in render coordinates
self.camManipRef.setPos(self.coaMarkerPos)
self.camManipRef.setHpr(direct.camera, ZERO_POINT)
self.camManipRef.setPos(self.coaMarkerPos)
self.camManipRef.setHpr(direct.camera, ZERO_POINT)
t = Task.Task(self.mouseRollTask)
t.coaCenter = getScreenXY(self.coaMarker)
t.lastAngle = getCrankAngle(t.coaCenter)
t.wrtMat = direct.camera.getMat( self.camManipRef )
t.wrtMat = direct.camera.getMat( self.camManipRef )
taskMgr.spawnTaskNamed(t, 'manipulateCamera')
def mouseRollTask(self, state):
@ -384,19 +384,19 @@ class DirectCameraControl(PandaObject):
self.updateCoaMarkerSize()
def uprightCam(self):
taskMgr.removeTasksNamed('manipulateCamera')
taskMgr.removeTasksNamed('manipulateCamera')
# Record undo point
direct.pushUndo([direct.camera])
# Pitch camera till upright
currH = direct.camera.getH()
direct.camera.lerpHpr(currH, 0, 0,
direct.camera.lerpHpr(currH, 0, 0,
CAM_MOVE_DURATION,
other = render,
blendType = 'easeInOut',
task = 'manipulateCamera')
def orbitUprightCam(self):
taskMgr.removeTasksNamed('manipulateCamera')
taskMgr.removeTasksNamed('manipulateCamera')
# Record undo point
direct.pushUndo([direct.camera])
# Transform camera z axis to render space
@ -421,10 +421,10 @@ class DirectCameraControl(PandaObject):
self.camManipRef.setPos(self.coaMarker, Vec3(0))
self.camManipRef.setHpr(render, rotAngle, 0, 0)
# Reparent Cam to ref Coordinate system
parent = direct.camera.getParent()
direct.camera.wrtReparentTo(self.camManipRef)
parent = direct.camera.getParent()
direct.camera.wrtReparentTo(self.camManipRef)
# Rotate ref CS to final orientation
t = self.camManipRef.lerpHpr(rotAngle, orbitAngle, 0,
t = self.camManipRef.lerpHpr(rotAngle, orbitAngle, 0,
CAM_MOVE_DURATION,
other = render,
blendType = 'easeInOut',
@ -434,22 +434,22 @@ class DirectCameraControl(PandaObject):
t.uponDeath = self.reparentCam
def centerCam(self):
self.centerCamIn(1.0)
self.centerCamIn(1.0)
def centerCamNow(self):
self.centerCamIn(0.)
def centerCamIn(self, t):
taskMgr.removeTasksNamed('manipulateCamera')
taskMgr.removeTasksNamed('manipulateCamera')
# Record undo point
direct.pushUndo([direct.camera])
# Determine marker location
markerToCam = self.coaMarker.getPos( direct.camera )
dist = Vec3(markerToCam - ZERO_POINT).length()
scaledCenterVec = Y_AXIS * dist
delta = markerToCam - scaledCenterVec
self.camManipRef.setPosHpr(direct.camera, Point3(0), Point3(0))
t = direct.camera.lerpPos(Point3(delta),
dist = Vec3(markerToCam - ZERO_POINT).length()
scaledCenterVec = Y_AXIS * dist
delta = markerToCam - scaledCenterVec
self.camManipRef.setPosHpr(direct.camera, Point3(0), Point3(0))
t = direct.camera.lerpPos(Point3(delta),
CAM_MOVE_DURATION,
other = self.camManipRef,
blendType = 'easeInOut',
@ -457,16 +457,16 @@ class DirectCameraControl(PandaObject):
t.uponDeath = self.updateCoaMarkerSizeOnDeath
def zoomCam(self, zoomFactor, t):
taskMgr.removeTasksNamed('manipulateCamera')
taskMgr.removeTasksNamed('manipulateCamera')
# Record undo point
direct.pushUndo([direct.camera])
# Find a point zoom factor times the current separation
# Find a point zoom factor times the current separation
# of the widget and cam
zoomPtToCam = self.coaMarker.getPos(direct.camera) * zoomFactor
# Put a target nodePath there
self.camManipRef.setPos(direct.camera, zoomPtToCam)
# Move to that point
t = direct.camera.lerpPos(ZERO_POINT,
# Put a target nodePath there
self.camManipRef.setPos(direct.camera, zoomPtToCam)
# Move to that point
t = direct.camera.lerpPos(ZERO_POINT,
CAM_MOVE_DURATION,
other = self.camManipRef,
blendType = 'easeInOut',
@ -526,20 +526,20 @@ class DirectCameraControl(PandaObject):
def swingCamAboutWidget(self, degrees, t):
# Remove existing camera manipulation task
taskMgr.removeTasksNamed('manipulateCamera')
taskMgr.removeTasksNamed('manipulateCamera')
# Record undo point
direct.pushUndo([direct.camera])
# Coincident with widget
# Coincident with widget
self.camManipRef.setPos(self.coaMarker, ZERO_POINT)
# But aligned with render space
self.camManipRef.setHpr(ZERO_POINT)
# But aligned with render space
self.camManipRef.setHpr(ZERO_POINT)
parent = direct.camera.getParent()
direct.camera.wrtReparentTo(self.camManipRef)
parent = direct.camera.getParent()
direct.camera.wrtReparentTo(self.camManipRef)
manipTask = self.camManipRef.lerpHpr(VBase3(degrees,0,0),
manipTask = self.camManipRef.lerpHpr(VBase3(degrees,0,0),
CAM_MOVE_DURATION,
blendType = 'easeInOut',
task = 'manipulateCamera')
@ -576,9 +576,9 @@ class DirectCameraControl(PandaObject):
# Move a target there
self.camManipRef.setPos(direct.camera, deltaMove)
parent = direct.camera.getParent()
direct.camera.wrtReparentTo(self.camManipRef)
fitTask = direct.camera.lerpPos(Point3(0,0,0),
parent = direct.camera.getParent()
direct.camera.wrtReparentTo(self.camManipRef)
fitTask = direct.camera.lerpPos(Point3(0,0,0),
CAM_MOVE_DURATION,
blendType = 'easeInOut',
task = 'manipulateCamera')
@ -620,8 +620,8 @@ class DirectCameraControl(PandaObject):
return Task.cont
def enableMouseFly(self):
# disable C++ fly interface
base.disableMouse()
# disable C++ fly interface
base.disableMouse()
# Enable events
for event in self.actionEvents:
self.accept(event[0], event[1], extraArgs = event[2:])
@ -631,10 +631,10 @@ class DirectCameraControl(PandaObject):
def disableMouseFly(self):
# Hide the marker
self.coaMarker.reparentTo(hidden)
# Ignore events
# Ignore events
for event in self.actionEvents:
self.ignore(event[0])
base.enableMouse()
base.enableMouse()
def removeManipulateCameraTask(self):
taskMgr.removeTasksNamed('manipulateCamera')

View File

@ -9,42 +9,42 @@ class DirectGrid(NodePath,PandaObject):
# Don't wireframe or light
useDirectRenderStyle(self)
# Load up grid parts to initialize grid object
# Polygon used to mark grid plane
self.gridBack = loader.loadModel('models/misc/gridBack')
self.gridBack.reparentTo(self)
self.gridBack.setColor(0.5,0.5,0.5,0.5)
# Load up grid parts to initialize grid object
# Polygon used to mark grid plane
self.gridBack = loader.loadModel('models/misc/gridBack')
self.gridBack.reparentTo(self)
self.gridBack.setColor(0.5,0.5,0.5,0.5)
# Grid Lines
# Grid Lines
self.lines = self.attachNewNode('gridLines')
self.minorLines = LineNodePath(self.lines)
self.minorLines = LineNodePath(self.lines)
self.minorLines.lineNode.setName('minorLines')
self.minorLines.setColor(VBase4(0.3,0.55,1,1))
self.minorLines.setThickness(1)
self.minorLines.setColor(VBase4(0.3,0.55,1,1))
self.minorLines.setThickness(1)
self.majorLines = LineNodePath(self.lines)
self.majorLines = LineNodePath(self.lines)
self.majorLines.lineNode.setName('majorLines')
self.majorLines.setColor(VBase4(0.3,0.55,1,1))
self.majorLines.setThickness(5)
self.majorLines.setColor(VBase4(0.3,0.55,1,1))
self.majorLines.setThickness(5)
self.centerLines = LineNodePath(self.lines)
self.centerLines = LineNodePath(self.lines)
self.centerLines.lineNode.setName('centerLines')
self.centerLines.setColor(VBase4(1,0,0,0))
self.centerLines.setThickness(3)
self.centerLines.setColor(VBase4(1,0,0,0))
self.centerLines.setThickness(3)
# Small marker to hilight snap-to-grid point
self.snapMarker = loader.loadModel('models/misc/sphere')
self.snapMarker.node().setName('gridSnapMarker')
self.snapMarker.reparentTo(self)
self.snapMarker.setColor(1,0,0,1)
self.snapMarker.setScale(0.3)
# Small marker to hilight snap-to-grid point
self.snapMarker = loader.loadModel('models/misc/sphere')
self.snapMarker.node().setName('gridSnapMarker')
self.snapMarker.reparentTo(self)
self.snapMarker.setColor(1,0,0,1)
self.snapMarker.setScale(0.3)
self.snapPos = Point3(0)
# Initialize Grid characteristics
# Initialize Grid characteristics
self.fXyzSnap = 1
self.fHprSnap = 1
self.gridSize = 100.0
self.gridSpacing = 5.0
self.gridSize = 100.0
self.gridSpacing = 5.0
self.snapAngle = 15.0
self.enable()
@ -67,15 +67,15 @@ class DirectGrid(NodePath,PandaObject):
return self.fEnabled
def updateGrid(self):
# Update grid lines based upon current grid spacing and grid size
# First reset existing grid lines
self.minorLines.reset()
self.majorLines.reset()
self.centerLines.reset()
# Update grid lines based upon current grid spacing and grid size
# First reset existing grid lines
self.minorLines.reset()
self.majorLines.reset()
self.centerLines.reset()
# Now redraw lines
numLines = math.ceil(self.gridSize/self.gridSpacing)
scaledSize = numLines * self.gridSpacing
# Now redraw lines
numLines = math.ceil(self.gridSize/self.gridSpacing)
scaledSize = numLines * self.gridSpacing
center = self.centerLines
minor = self.minorLines
@ -125,11 +125,11 @@ class DirectGrid(NodePath,PandaObject):
ROUND_TO(self.snapPos[1], self.gridSpacing),
ROUND_TO(self.snapPos[2], self.gridSpacing))
# Move snap marker to this point
self.snapMarker.setPos(self.snapPos)
# Return the hit point
return self.snapPos
# Move snap marker to this point
self.snapMarker.setPos(self.snapPos)
# Return the hit point
return self.snapPos
def computeSnapAngle(self, angle):
return ROUND_TO(angle, self.snapAngle)
@ -148,9 +148,9 @@ class DirectGrid(NodePath,PandaObject):
return self.gridSpacing
def setGridSize(self, size):
# Set size of grid back and redraw lines
# Set size of grid back and redraw lines
self.gridSize = size
self.updateGrid()
self.updateGrid()
def getGridSize(self):
return self.gridSize

View File

@ -138,12 +138,12 @@ class DirectManipulationControl(PandaObject):
return Task.cont
def enableManipulation(self):
# Accept events
# Accept events
for event in self.actionEvents:
self.accept(event[0], event[1], extraArgs = event[2:])
def disableManipulation(self):
# Ignore events
# Ignore events
for event in self.actionEvents:
self.ignore(event[0])
@ -276,7 +276,7 @@ class DirectManipulationControl(PandaObject):
self.fHitInit = 0
self.prevHit.assign(self.hitPt)
else:
offset = self.hitPt - self.prevHit
offset = self.hitPt - self.prevHit
direct.widget.setPos(direct.widget, offset)
def rotate1D(self, state):
@ -466,7 +466,7 @@ class DirectManipulationControl(PandaObject):
## Utility functions ##
def plantSelectedNodePath(self):
""" Move selected object to intersection point of cursor on scene """
""" Move selected object to intersection point of cursor on scene """
# Check for intersection
node, hitPt, hitPtDist = direct.iRay.pickGeom(
fIntersectUnpickable = 1)
@ -747,25 +747,25 @@ class ObjectHandles(NodePath,PandaObject):
def createObjectHandleLines(self):
# X post
self.xPost = self.xPostGroup.attachNewNode('x-post-visible')
lines = LineNodePath(self.xPost)
lines.setColor(VBase4(1,0,0,1))
lines.setThickness(5)
lines.moveTo(0,0,0)
lines = LineNodePath(self.xPost)
lines.setColor(VBase4(1,0,0,1))
lines.setThickness(5)
lines.moveTo(0,0,0)
lines.drawTo(1.5,0,0)
lines.create()
lines = LineNodePath(self.xPost)
lines.setColor(VBase4(1,0,0,1))
lines.setThickness(1.5)
lines.moveTo(0,0,0)
lines = LineNodePath(self.xPost)
lines.setColor(VBase4(1,0,0,1))
lines.setThickness(1.5)
lines.moveTo(0,0,0)
lines.drawTo(-1.5,0,0)
lines.create()
# X ring
# X ring
self.xRing = self.xRingGroup.attachNewNode('x-ring-visible')
lines = LineNodePath(self.xRing)
lines.setColor(VBase4(1,0,0,1))
lines.setThickness(3)
lines.moveTo(0,1,0)
lines = LineNodePath(self.xRing)
lines.setColor(VBase4(1,0,0,1))
lines.setThickness(3)
lines.moveTo(0,1,0)
for ang in range(15, 370, 15):
lines.drawTo(0,
math.cos(deg2Rad(ang)),
@ -774,25 +774,25 @@ class ObjectHandles(NodePath,PandaObject):
# Y post
self.yPost = self.yPostGroup.attachNewNode('y-post-visible')
lines = LineNodePath(self.yPost)
lines.setColor(VBase4(0,1,0,1))
lines.setThickness(5)
lines.moveTo(0,0,0)
lines = LineNodePath(self.yPost)
lines.setColor(VBase4(0,1,0,1))
lines.setThickness(5)
lines.moveTo(0,0,0)
lines.drawTo(0,1.5,0)
lines.create()
lines = LineNodePath(self.yPost)
lines.setColor(VBase4(0,1,0,1))
lines.setThickness(1.5)
lines.moveTo(0,0,0)
lines = LineNodePath(self.yPost)
lines.setColor(VBase4(0,1,0,1))
lines.setThickness(1.5)
lines.moveTo(0,0,0)
lines.drawTo(0,-1.5,0)
lines.create()
# Y ring
# Y ring
self.yRing = self.yRingGroup.attachNewNode('y-ring-visible')
lines = LineNodePath(self.yRing)
lines.setColor(VBase4(0,1,0,1))
lines.setThickness(3)
lines.moveTo(1,0,0)
lines = LineNodePath(self.yRing)
lines.setColor(VBase4(0,1,0,1))
lines.setThickness(3)
lines.moveTo(1,0,0)
for ang in range(15, 370, 15):
lines.drawTo(math.cos(deg2Rad(ang)),
0,
@ -801,25 +801,25 @@ class ObjectHandles(NodePath,PandaObject):
# Z post
self.zPost = self.zPostGroup.attachNewNode('z-post-visible')
lines = LineNodePath(self.zPost)
lines.setColor(VBase4(0,0,1,1))
lines.setThickness(5)
lines.moveTo(0,0,0)
lines = LineNodePath(self.zPost)
lines.setColor(VBase4(0,0,1,1))
lines.setThickness(5)
lines.moveTo(0,0,0)
lines.drawTo(0,0,1.5)
lines.create()
lines = LineNodePath(self.zPost)
lines.setColor(VBase4(0,0,1,1))
lines.setThickness(1.5)
lines.moveTo(0,0,0)
lines = LineNodePath(self.zPost)
lines.setColor(VBase4(0,0,1,1))
lines.setThickness(1.5)
lines.moveTo(0,0,0)
lines.drawTo(0,0,-1.5)
lines.create()
# Z ring
# Z ring
self.zRing = self.zRingGroup.attachNewNode('z-ring-visible')
lines = LineNodePath(self.zRing)
lines.setColor(VBase4(0,0,1,1))
lines.setThickness(3)
lines.moveTo(1,0,0)
lines = LineNodePath(self.zRing)
lines.setColor(VBase4(0,0,1,1))
lines.setThickness(3)
lines.moveTo(1,0,0)
for ang in range(15, 370, 15):
lines.drawTo(math.cos(deg2Rad(ang)),
math.sin(deg2Rad(ang)),
@ -829,28 +829,28 @@ class ObjectHandles(NodePath,PandaObject):
def createGuideLines(self):
self.guideLines = self.attachNewNode('guideLines')
# X guide lines
lines = LineNodePath(self.guideLines)
lines.setColor(VBase4(1,0,0,1))
lines.setThickness(0.5)
lines.moveTo(-500,0,0)
lines = LineNodePath(self.guideLines)
lines.setColor(VBase4(1,0,0,1))
lines.setThickness(0.5)
lines.moveTo(-500,0,0)
lines.drawTo(500,0,0)
lines.create()
lines.node().setName('x-guide')
# Y guide lines
lines = LineNodePath(self.guideLines)
lines.setColor(VBase4(0,1,0,1))
lines.setThickness(0.5)
lines.moveTo(0,-500,0)
lines = LineNodePath(self.guideLines)
lines.setColor(VBase4(0,1,0,1))
lines.setThickness(0.5)
lines.moveTo(0,-500,0)
lines.drawTo(0,500,0)
lines.create()
lines.node().setName('y-guide')
# Z guide lines
lines = LineNodePath(self.guideLines)
lines.setColor(VBase4(0,0,1,1))
lines.setThickness(0.5)
lines.moveTo(0,0,-500)
lines = LineNodePath(self.guideLines)
lines.setColor(VBase4(0,0,1,1))
lines.setThickness(0.5)
lines.moveTo(0,0,-500)
lines.drawTo(0,0,500)
lines.create()
lines.node().setName('z-guide')

View File

@ -60,12 +60,12 @@ class SelectedNodePaths(PandaObject):
def select(self, nodePath, fMultiSelect = 0):
""" Select the specified node path. Multiselect as required """
# Do nothing if nothing selected
# Do nothing if nothing selected
if not nodePath:
print 'Nothing selected!!'
return None
# Reset selected objects and highlight if multiSelect is false
# Reset selected objects and highlight if multiSelect is false
if not fMultiSelect:
self.deselectAll()
@ -208,17 +208,17 @@ class SelectedNodePaths(PandaObject):
self.forEachSelectedNodePathDo(DirectNodePath.dehighlight)
def removeSelected(self):
selected = self.last
selected = self.last
if selected:
selected.remove()
__builtin__.last = self.last = None
def removeAll(self):
# Remove all selected nodePaths from the Scene Graph
# Remove all selected nodePaths from the Scene Graph
self.forEachSelectedNodePathDo(NodePath.remove)
def toggleVisSelected(self):
selected = self.last
selected = self.last
# Toggle visibility of selected node paths
if selected:
selected.toggleVis()
@ -228,7 +228,7 @@ class SelectedNodePaths(PandaObject):
self.forEachSelectedNodePathDo(NodePath.toggleVis)
def isolateSelected(self):
selected = self.last
selected = self.last
if selected:
selected.isolate()
@ -271,7 +271,7 @@ class DirectBoundingBox:
lines = LineNodePath(hidden)
lines.node().setName('bboxLines')
lines.setColor( VBase4( 1., 0., 0., 1. ) )
lines.setThickness( 0.5 )
lines.setThickness( 0.5 )
minX = self.min[0]
minY = self.min[1]
@ -281,29 +281,29 @@ class DirectBoundingBox:
maxZ = self.max[2]
# Bottom face
lines.moveTo( minX, minY, minZ )
lines.drawTo( maxX, minY, minZ )
lines.drawTo( maxX, maxY, minZ )
lines.drawTo( minX, maxY, minZ )
lines.drawTo( minX, minY, minZ )
lines.moveTo( minX, minY, minZ )
lines.drawTo( maxX, minY, minZ )
lines.drawTo( maxX, maxY, minZ )
lines.drawTo( minX, maxY, minZ )
lines.drawTo( minX, minY, minZ )
# Front Edge/Top face
lines.drawTo( minX, minY, maxZ )
lines.drawTo( maxX, minY, maxZ )
lines.drawTo( maxX, maxY, maxZ )
lines.drawTo( minX, maxY, maxZ )
lines.drawTo( minX, minY, maxZ )
# Front Edge/Top face
lines.drawTo( minX, minY, maxZ )
lines.drawTo( maxX, minY, maxZ )
lines.drawTo( maxX, maxY, maxZ )
lines.drawTo( minX, maxY, maxZ )
lines.drawTo( minX, minY, maxZ )
# Three remaining edges
lines.moveTo( maxX, minY, minZ )
lines.drawTo( maxX, minY, maxZ )
lines.moveTo( maxX, maxY, minZ )
lines.drawTo( maxX, maxY, maxZ )
lines.moveTo( minX, maxY, minZ )
lines.drawTo( minX, maxY, maxZ )
# Three remaining edges
lines.moveTo( maxX, minY, minZ )
lines.drawTo( maxX, minY, maxZ )
lines.moveTo( maxX, maxY, minZ )
lines.drawTo( maxX, maxY, maxZ )
lines.moveTo( minX, maxY, minZ )
lines.drawTo( minX, maxY, maxZ )
# Create and return bbox lines
lines.create()
lines.create()
# Make sure bbox is never lit or drawn in wireframe
useDirectRenderStyle(lines)
@ -321,26 +321,26 @@ class DirectBoundingBox:
maxZ = self.max[2]
# Bottom face
ls.setVertex( 0, minX, minY, minZ )
ls.setVertex( 1, maxX, minY, minZ )
ls.setVertex( 2, maxX, maxY, minZ )
ls.setVertex( 3, minX, maxY, minZ )
ls.setVertex( 4, minX, minY, minZ )
ls.setVertex( 0, minX, minY, minZ )
ls.setVertex( 1, maxX, minY, minZ )
ls.setVertex( 2, maxX, maxY, minZ )
ls.setVertex( 3, minX, maxY, minZ )
ls.setVertex( 4, minX, minY, minZ )
# Front Edge/Top face
ls.setVertex( 5, minX, minY, maxZ )
ls.setVertex( 6, maxX, minY, maxZ )
ls.setVertex( 7, maxX, maxY, maxZ )
ls.setVertex( 8, minX, maxY, maxZ )
ls.setVertex( 9, minX, minY, maxZ )
# Front Edge/Top face
ls.setVertex( 5, minX, minY, maxZ )
ls.setVertex( 6, maxX, minY, maxZ )
ls.setVertex( 7, maxX, maxY, maxZ )
ls.setVertex( 8, minX, maxY, maxZ )
ls.setVertex( 9, minX, minY, maxZ )
# Three remaining edges
ls.setVertex( 10, maxX, minY, minZ )
ls.setVertex( 11, maxX, minY, maxZ )
ls.setVertex( 12, maxX, maxY, minZ )
ls.setVertex( 13, maxX, maxY, maxZ )
ls.setVertex( 14, minX, maxY, minZ )
ls.setVertex( 15, minX, maxY, maxZ )
# Three remaining edges
ls.setVertex( 10, maxX, minY, minZ )
ls.setVertex( 11, maxX, minY, maxZ )
ls.setVertex( 12, maxX, maxY, minZ )
ls.setVertex( 13, maxX, maxY, maxZ )
ls.setVertex( 14, minX, maxY, minZ )
ls.setVertex( 15, minX, maxY, maxZ )
def getBounds(self):
# Get a node path's bounds

View File

@ -8,40 +8,40 @@ class Mopath(PandaObject):
nameIndex = 1
def __init__(self, name = None):
if (name == None):
name = 'mopath%d' % self.nameIndex
self.nameIndex = self.nameIndex + 1
self.name = name
self.reset()
if (name == None):
name = 'mopath%d' % self.nameIndex
self.nameIndex = self.nameIndex + 1
self.name = name
self.reset()
def getMaxT(self):
return self.maxT
return self.maxT
def loadFile(self, filename):
nodePath = loader.loadModel(filename)
nodePath = loader.loadModel(filename)
if nodePath:
self.__extractCurves(nodePath)
if (self.xyzNurbsCurve != None):
self.maxT = self.xyzNurbsCurve.getMaxT()
elif (self.hprNurbsCurve != None):
self.maxT = self.hprNurbsCurve.getMaxT()
elif (self.tNurbsCurve != None):
self.maxT = self.tNurbsCurve.getMaxT()
else:
print 'Mopath: no valid curves in file: %s' % filename
if (self.xyzNurbsCurve != None):
self.maxT = self.xyzNurbsCurve.getMaxT()
elif (self.hprNurbsCurve != None):
self.maxT = self.hprNurbsCurve.getMaxT()
elif (self.tNurbsCurve != None):
self.maxT = self.tNurbsCurve.getMaxT()
else:
print 'Mopath: no valid curves in file: %s' % filename
nodePath.removeNode()
else:
print 'Mopath: no data in file: %s' % filename
else:
print 'Mopath: no data in file: %s' % filename
def reset(self):
self.maxT = 0.0
self.loop = 0
self.xyzNurbsCurve = None
self.hprNurbsCurve = None
self.tNurbsCurve = None
self.node = None
self.maxT = 0.0
self.loop = 0
self.xyzNurbsCurve = None
self.hprNurbsCurve = None
self.tNurbsCurve = None
self.node = None
def __extractCurves(self, nodePath):
node = nodePath.node()
@ -50,70 +50,70 @@ class Mopath(PandaObject):
self.xyzNurbsCurve = node
elif node.getCurveType() == PCTHPR:
self.hprNurbsCurve = node
elif node.getCurveType() == PCTNONE:
if (self.xyzNurbsCurve == None):
self.xyzNurbsCurve = node
else:
print 'Mopath: got a PCT_NONE curve and an XYZ Curve!'
elif (node.getCurveType() == PCTT):
self.tNurbsCurve = node
elif node.getCurveType() == PCTNONE:
if (self.xyzNurbsCurve == None):
self.xyzNurbsCurve = node
else:
print 'Mopath: got a PCT_NONE curve and an XYZ Curve!'
elif (node.getCurveType() == PCTT):
self.tNurbsCurve = node
else:
# Iterate over children if any
for child in nodePath.getChildrenAsList():
self.__extractCurves(child)
def getFinalState(self):
""" getFinalState()
"""
pos = Point3(0)
if (self.xyzNurbsCurve != None):
self.xyzNurbsCurve.getPoint(self.maxT, pos)
hpr = Point3(0)
if (self.hprNurbsCurve != None):
self.hprNurbsCurve.getPoint(self.maxT, hpr)
return (pos, hpr)
""" getFinalState()
"""
pos = Point3(0)
if (self.xyzNurbsCurve != None):
self.xyzNurbsCurve.getPoint(self.maxT, pos)
hpr = Point3(0)
if (self.hprNurbsCurve != None):
self.hprNurbsCurve.getPoint(self.maxT, hpr)
return (pos, hpr)
def goTo(self, node, time):
if (self.xyzNurbsCurve == None) and (self.hprNurbsCurve == None):
print 'Mopath: Mopath has no curves'
return
self.playbackTime = CLAMP(time, 0.0, self.maxT)
if (self.xyzNurbsCurve != None):
pos = Point3(0)
self.xyzNurbsCurve.getPoint(self.playbackTime, pos)
node.setPos(pos)
if (self.hprNurbsCurve != None):
hpr = Point3(0)
self.hprNurbsCurve.getPoint(self.playbackTime, hpr)
node.setHpr(hpr)
if (self.xyzNurbsCurve == None) and (self.hprNurbsCurve == None):
print 'Mopath: Mopath has no curves'
return
self.playbackTime = CLAMP(time, 0.0, self.maxT)
if (self.xyzNurbsCurve != None):
pos = Point3(0)
self.xyzNurbsCurve.getPoint(self.playbackTime, pos)
node.setPos(pos)
if (self.hprNurbsCurve != None):
hpr = Point3(0)
self.hprNurbsCurve.getPoint(self.playbackTime, hpr)
node.setHpr(hpr)
def play(self, node, time = 0.0, loop = 0):
if (self.xyzNurbsCurve == None) and (self.hprNurbsCurve == None):
print 'Mopath: Mopath has no curves'
return
self.node = node
self.loop = loop
self.stop()
t = taskMgr.spawnMethodNamed(self.__playTask, self.name + '-play')
t.currentTime = time
t.lastTime = globalClock.getFrameTime()
if (self.xyzNurbsCurve == None) and (self.hprNurbsCurve == None):
print 'Mopath: Mopath has no curves'
return
self.node = node
self.loop = loop
self.stop()
t = taskMgr.spawnMethodNamed(self.__playTask, self.name + '-play')
t.currentTime = time
t.lastTime = globalClock.getFrameTime()
def stop(self):
taskMgr.removeTasksNamed(self.name + '-play')
taskMgr.removeTasksNamed(self.name + '-play')
def __playTask(self, state):
time = globalClock.getFrameTime()
dTime = time - state.lastTime
state.lastTime = time
if (self.loop):
cTime = (state.currentTime + dTime) % self.maxT
else:
cTime = state.currentTime + dTime
if ((self.loop == 0) and (cTime > self.maxT)):
self.stop()
messenger.send(self.name + '-done')
self.node = None
return Task.done
self.goTo(self.node, cTime)
state.currentTime = cTime
return Task.cont
time = globalClock.getFrameTime()
dTime = time - state.lastTime
state.lastTime = time
if (self.loop):
cTime = (state.currentTime + dTime) % self.maxT
else:
cTime = state.currentTime + dTime
if ((self.loop == 0) and (cTime > self.maxT)):
self.stop()
messenger.send(self.name + '-done')
self.node = None
return Task.done
self.goTo(self.node, cTime)
state.currentTime = cTime
return Task.cont

View File

@ -5,7 +5,7 @@ import DirectNotifyGlobal
import ClientDistUpdate
class ClientDistClass:
def __init__(self, dcClass):
self.number = dcClass.getNumber()
self.name = dcClass.getName()

View File

@ -177,7 +177,7 @@ class ClientRepository(DirectObject.DirectObject):
if self.doId2do.has_key(doId):
# If so, just update it.
distObj = self.doId2do[doId]
distObj.generate()
distObj.generate()
distObj.updateRequiredFields(cdc, di)
distObj.announceGenerate()
@ -190,7 +190,7 @@ class ClientRepository(DirectObject.DirectObject):
self.doId2do[doId] = distObj
self.doId2cdc[doId] = cdc
# and update it.
distObj.generate()
distObj.generate()
distObj.updateRequiredFields(cdc, di)
distObj.announceGenerate()
@ -205,7 +205,7 @@ class ClientRepository(DirectObject.DirectObject):
self.doId2cdc[doId] = cdc
# Update the required fields
distObj.generateInit() # Only called when constructed
distObj.generate()
distObj.generate()
distObj.updateRequiredFields(cdc, di)
distObj.announceGenerate()
@ -216,7 +216,7 @@ class ClientRepository(DirectObject.DirectObject):
if self.doId2do.has_key(doId):
# If so, just update it.
distObj = self.doId2do[doId]
distObj.generate()
distObj.generate()
distObj.updateRequiredOtherFields(cdc, di)
distObj.announceGenerate()
@ -229,7 +229,7 @@ class ClientRepository(DirectObject.DirectObject):
self.doId2do[doId] = distObj
self.doId2cdc[doId] = cdc
# and update it.
distObj.generate()
distObj.generate()
distObj.updateRequiredOtherFields(cdc, di)
distObj.announceGenerate()
@ -244,7 +244,7 @@ class ClientRepository(DirectObject.DirectObject):
self.doId2cdc[doId] = cdc
# Update the required fields
distObj.generateInit() # Only called when constructed
distObj.generate()
distObj.generate()
distObj.updateRequiredOtherFields(cdc, di)
distObj.announceGenerate()

View File

@ -1,6 +1,6 @@
"""MsgTypes module: contains distributed object message types"""
CLIENT_OBJECT_UPDATE_FIELD = 24
CLIENT_OBJECT_UPDATE_FIELD = 24
CLIENT_OBJECT_UPDATE_FIELD_RESP = 24
CLIENT_OBJECT_DISABLE_RESP = 25
CLIENT_OBJECT_DELETE_RESP = 27

View File

@ -175,7 +175,7 @@ def subclass(type1, type2):
"""
# If the types are the same, return 0
if type1 == type2:
return 0
return 0
# If you have no args, sort you first
elif (type1 == 0):
return 1
@ -183,7 +183,7 @@ def subclass(type1, type2):
return -1
# If class1 inherits from class2 return 1
elif inheritsFrom(type1, type2):
return 1
return 1
# If class2 inherits from class1 return -1
elif inheritsFrom(type2, type1):
return -1

View File

@ -86,8 +86,8 @@ class FSM(DirectObject):
self.__states = states
def addState(self, state):
"""addState(state)"""
self.__states.append(state)
"""addState(state)"""
self.__states.append(state)
def getInitialState(self):
"""getInitialState(self)"""

View File

@ -14,63 +14,63 @@ class StateData(DirectObject):
def __init__(self, doneEvent):
"""__init__(self, Event)
"""
self.doneEvent = doneEvent
self.doneStatus = None
self.isLoaded = 0
self.isEntered = 0
return None
self.doneEvent = doneEvent
self.doneStatus = None
self.isLoaded = 0
self.isEntered = 0
return None
def cleanup(self):
"""cleanup(self)
"""
self.unload()
return None
"""cleanup(self)
"""
self.unload()
return None
def enter(self):
"""enter(self)
"""
# Use isEntered to avoid redundant entry work
if self.isEntered == 1:
return None
self.isEntered = 1
# Use isLoaded to avoid redundant loading
if self.isLoaded == 0:
self.load()
self.notify.debug('enter()')
return None
"""
# Use isEntered to avoid redundant entry work
if self.isEntered == 1:
return None
self.isEntered = 1
# Use isLoaded to avoid redundant loading
if self.isLoaded == 0:
self.load()
self.notify.debug('enter()')
return None
def exit(self):
"""exit(self)
"""
if self.isEntered == 0:
return None
self.isEntered = 0
self.notify.debug('exit()')
return None
"""exit(self)
"""
if self.isEntered == 0:
return None
self.isEntered = 0
self.notify.debug('exit()')
return None
def load(self):
"""load(self)
"""
if self.isLoaded == 1:
return None
self.isLoaded = 1
self.notify.debug('load()')
return None
"""load(self)
"""
if self.isLoaded == 1:
return None
self.isLoaded = 1
self.notify.debug('load()')
return None
def unload(self):
"""unload(self)
"""
if self.isLoaded == 0:
return None
self.isLoaded = 0
self.exit()
self.notify.debug('unload()')
return None
"""unload(self)
"""
if self.isLoaded == 0:
return None
self.isLoaded = 0
self.exit()
self.notify.debug('unload()')
return None
def getDoneStatus(self):
"""getDoneStatus(self)
"""
return self.doneStatus
"""getDoneStatus(self)
"""
return self.doneStatus

View File

@ -12,15 +12,15 @@ class Background(DirectObject):
self.background = GuiBackground.GuiBackground(name, self.item,
self.label)
self.managed = 0
return None
return None
def cleanup(self):
"""cleanup(self)
"""
"""cleanup(self)
"""
if (self.managed):
self.unmanage()
self.background = None
return None
return None
def __str__(self):
return "Background: %s behind %s" % (self.name, self.item )

View File

@ -11,15 +11,15 @@ class Collection(DirectObject):
self.collection = GuiCollection.GuiCollection(self.name)
self.items= []
self.managed = 0
return None
return None
def cleanup(self):
"""cleanup(self)
"""
"""cleanup(self)
"""
if (self.managed):
self.unmanage()
self.collection = None
return None
return None
def __str__(self):
return "Collection: %s = %s" % (self.name, self.items)

View File

@ -25,7 +25,7 @@ class DialogBox(OnscreenPanel.OnscreenPanel):
def __init__(self, message = "", doneEvent = None, style = NoButtons,
font = getDefaultFont(), wordwrap = 12, okButtonText = "OK",
cancelButtonText = "Cancel"):
"""___init___(self, Event, string="", int, model, int=12)"""
"""___init___(self, Event, string="", int, model, int=12)"""
# Sanity check
if (doneEvent == None) and (style != NoButtons):
@ -48,8 +48,8 @@ class DialogBox(OnscreenPanel.OnscreenPanel):
drawOrder = 32000, font = self.font,
bg = (0.8, 0.8, 0.8, 1.0))
# create a message
self.makeText(self.message, wordwrap = self.wordwrap, scale = 0.08,
# create a message
self.makeText(self.message, wordwrap = self.wordwrap, scale = 0.08,
pos = (0.0, 0.25))
if (self.style == TwoChoice):
@ -75,39 +75,39 @@ class DialogBox(OnscreenPanel.OnscreenPanel):
"Sanity check"
self.notify.error("No such style as: " + str(self.style))
return None
return None
def show(self):
"""show(self)
"""
"""show(self)
"""
base.transitions.fadeScreen()
OnscreenPanel.OnscreenPanel.show(self)
return None
return None
def hide(self):
"""hide(self)
"""
"""hide(self)
"""
base.transitions.noTransitions()
OnscreenPanel.OnscreenPanel.hide(self)
return None
return None
def cleanup(self):
"""unload(self)
"""
self.hide()
"""unload(self)
"""
self.hide()
OnscreenPanel.OnscreenPanel.cleanup(self)
return None
return None
# def handleRollover(self):
# return None
# return None
def handleOk(self, okButton, item):
assert(self.style != NoButtons)
if (okButton == item):
self.doneStatus = "ok"
self.doneStatus = "ok"
messenger.send(self.__doneEvent)
def handleCancel(self, cancelButton, item):

View File

@ -97,48 +97,48 @@ class DirectGuiBase(PandaObject.PandaObject):
self._hookDict = {}
# To avoid doing things redundantly during initialisation
self.fInit = 1
# Mapping from each megawidget option to a list of information
# about the option
# - default value
# - current value
# - function to call when the option is initialised in the
# call to initialiseoptions() in the constructor or
# modified via configure(). If this is INITOPT, the
# option is an initialisation option (an option that can
# be set by the call to the constructor but can not be
# used with configure).
# This mapping is not initialised here, but in the call to
# defineoptions() which precedes construction of this base class.
#
# self._optionInfo = {}
# Mapping from each megawidget option to a list of information
# about the option
# - default value
# - current value
# - function to call when the option is initialised in the
# call to initialiseoptions() in the constructor or
# modified via configure(). If this is INITOPT, the
# option is an initialisation option (an option that can
# be set by the call to the constructor but can not be
# used with configure).
# This mapping is not initialised here, but in the call to
# defineoptions() which precedes construction of this base class.
#
# self._optionInfo = {}
# Mapping from each component name to a tuple of information
# about the component.
# - component widget instance
# - configure function of widget instance
# - the class of the widget (Frame, EntryField, etc)
# - cget function of widget instance
# - the name of the component group of this component, if any
self.__componentInfo = {}
# Mapping from each component name to a tuple of information
# about the component.
# - component widget instance
# - configure function of widget instance
# - the class of the widget (Frame, EntryField, etc)
# - cget function of widget instance
# - the name of the component group of this component, if any
self.__componentInfo = {}
# Mapping from alias names to the names of components or
# sub-components.
self.__componentAliases = {}
# Mapping from alias names to the names of components or
# sub-components.
self.__componentAliases = {}
# Contains information about the keywords provided to the
# constructor. It is a mapping from the keyword to a tuple
# containing:
# - value of keyword
# - a boolean indicating if the keyword has been used.
# A keyword is used if, during the construction of a megawidget,
# - it is defined in a call to defineoptions() or addoptions(), or
# - it references, by name, a component of the megawidget, or
# - it references, by group, at least one component
# At the end of megawidget construction, a call is made to
# initialiseoptions() which reports an error if there are
# unused options given to the constructor.
#
# self._constructorKeywords = {}
# Contains information about the keywords provided to the
# constructor. It is a mapping from the keyword to a tuple
# containing:
# - value of keyword
# - a boolean indicating if the keyword has been used.
# A keyword is used if, during the construction of a megawidget,
# - it is defined in a call to defineoptions() or addoptions(), or
# - it references, by name, a component of the megawidget, or
# - it references, by group, at least one component
# At the end of megawidget construction, a call is made to
# initialiseoptions() which reports an error if there are
# unused options given to the constructor.
#
# self._constructorKeywords = {}
# List of dynamic component groups. If a group is included in
# this list, then it not an error if a keyword argument for
@ -153,10 +153,10 @@ class DirectGuiBase(PandaObject.PandaObject):
def defineoptions(self, keywords, optionDefs, dynamicGroups = ()):
""" defineoptions(keywords, optionDefs, dynamicGroups = {}) """
# Create options, providing the default value and the method
# to call when the value is changed. If any option created by
# base classes has the same name as one in <optionDefs>, the
# base class's value and function will be overriden.
# Create options, providing the default value and the method
# to call when the value is changed. If any option created by
# base classes has the same name as one in <optionDefs>, the
# base class's value and function will be overriden.
# keywords is a dictionary of keyword/value pairs from the constructor
# optionDefs is a dictionary of default options for the widget
@ -164,15 +164,15 @@ class DirectGuiBase(PandaObject.PandaObject):
# specify options even though no components of this group have
# been created
# This should be called before the constructor of the base
# class, so that default values defined in the derived class
# override those in the base class.
if not hasattr(self, '_constructorKeywords'):
tmp = {}
for option, value in keywords.items():
tmp[option] = [value, 0]
# This should be called before the constructor of the base
# class, so that default values defined in the derived class
# override those in the base class.
if not hasattr(self, '_constructorKeywords'):
tmp = {}
for option, value in keywords.items():
tmp[option] = [value, 0]
self._constructorKeywords = tmp
self._optionInfo = {}
self._optionInfo = {}
# Initialize dictionary of dynamic groups
if not hasattr(self, '_dynamicGroups'):
self._dynamicGroups = ()
@ -182,19 +182,19 @@ class DirectGuiBase(PandaObject.PandaObject):
def addoptions(self, optionDefs):
""" addoptions(optionDefs) - add option def to option info """
# Add additional options, providing the default value and the
# method to call when the value is changed. See
# "defineoptions" for more details
# Add additional options, providing the default value and the
# method to call when the value is changed. See
# "defineoptions" for more details
# optimisations:
optionInfo = self._optionInfo
optionInfo_has_key = optionInfo.has_key
keywords = self._constructorKeywords
keywords_has_key = keywords.has_key
FUNCTION = _OPT_FUNCTION
# optimisations:
optionInfo = self._optionInfo
optionInfo_has_key = optionInfo.has_key
keywords = self._constructorKeywords
keywords_has_key = keywords.has_key
FUNCTION = _OPT_FUNCTION
for name, default, function in optionDefs:
if '_' not in name:
for name, default, function in optionDefs:
if '_' not in name:
# The option will already exist if it has been defined
# in a derived class. In this case, do not override the
# default value of the option or the callback function
@ -212,13 +212,13 @@ class DirectGuiBase(PandaObject.PandaObject):
elif optionInfo[name][FUNCTION] is None:
# Only override function if not defined by derived class
optionInfo[name][FUNCTION] = function
else:
# This option is of the form "component_option". If this is
# not already defined in self._constructorKeywords add it.
# This allows a derived class to override the default value
# of an option of a component of a base class.
if not keywords_has_key(name):
keywords[name] = [default, 0]
else:
# This option is of the form "component_option". If this is
# not already defined in self._constructorKeywords add it.
# This allows a derived class to override the default value
# of an option of a component of a base class.
if not keywords_has_key(name):
keywords[name] = [default, 0]
def initialiseoptions(self, myClass):
"""
@ -227,36 +227,36 @@ class DirectGuiBase(PandaObject.PandaObject):
"""
# This is to make sure this method class is only called by
# the most specific class in the class hierarchy
if self.__class__ is myClass:
# Call the configuration callback function for every option.
FUNCTION = _OPT_FUNCTION
if self.__class__ is myClass:
# Call the configuration callback function for every option.
FUNCTION = _OPT_FUNCTION
self.fInit = 1
for info in self._optionInfo.values():
func = info[FUNCTION]
if func is not None and func is not INITOPT:
func()
for info in self._optionInfo.values():
func = info[FUNCTION]
if func is not None and func is not INITOPT:
func()
self.fInit = 0
# Now check if anything is left over
unusedOptions = []
keywords = self._constructorKeywords
for name in keywords.keys():
used = keywords[name][1]
if not used:
unusedOptions = []
keywords = self._constructorKeywords
for name in keywords.keys():
used = keywords[name][1]
if not used:
# This keyword argument has not been used. If it
# does not refer to a dynamic group, mark it as
# unused.
index = string.find(name, '_')
if index < 0 or name[:index] not in self._dynamicGroups:
unusedOptions.append(name)
self._constructorKeywords = {}
if len(unusedOptions) > 0:
if len(unusedOptions) == 1:
text = 'Unknown option "'
else:
text = 'Unknown options "'
raise KeyError, text + string.join(unusedOptions, ', ') + \
'" for ' + myClass.__name__
self._constructorKeywords = {}
if len(unusedOptions) > 0:
if len(unusedOptions) == 1:
text = 'Unknown option "'
else:
text = 'Unknown options "'
raise KeyError, text + string.join(unusedOptions, ', ') + \
'" for ' + myClass.__name__
# Can now call post init func
self.postInitialiseFunc()
@ -268,7 +268,7 @@ class DirectGuiBase(PandaObject.PandaObject):
isinitoption(option)
Is this opition one that can only be specified at construction?
"""
return self._optionInfo[option][_OPT_FUNCTION] is INITOPT
return self._optionInfo[option][_OPT_FUNCTION] is INITOPT
def options(self):
"""
@ -276,155 +276,155 @@ class DirectGuiBase(PandaObject.PandaObject):
Print out a list of available widget options.
Does not include subcomponent options.
"""
options = []
if hasattr(self, '_optionInfo'):
for option, info in self._optionInfo.items():
isinit = info[_OPT_FUNCTION] is INITOPT
default = info[_OPT_DEFAULT]
options.append((option, default, isinit))
options.sort()
return options
options = []
if hasattr(self, '_optionInfo'):
for option, info in self._optionInfo.items():
isinit = info[_OPT_FUNCTION] is INITOPT
default = info[_OPT_DEFAULT]
options.append((option, default, isinit))
options.sort()
return options
def configure(self, option=None, **kw):
"""
configure(option = None)
Query or configure the megawidget options.
Query or configure the megawidget options.
"""
#
# If not empty, *kw* is a dictionary giving new
# values for some of the options of this gui item
# For options defined for this widget, set
# the value of the option to the new value and call the
# configuration callback function, if any.
#
# If *option* is None, return all gui item configuration
# options and settings. Options are returned as standard 3
# element tuples
#
# If *option* is a string, return the 3 element tuple for the
# given configuration option.
#
# If not empty, *kw* is a dictionary giving new
# values for some of the options of this gui item
# For options defined for this widget, set
# the value of the option to the new value and call the
# configuration callback function, if any.
#
# If *option* is None, return all gui item configuration
# options and settings. Options are returned as standard 3
# element tuples
#
# If *option* is a string, return the 3 element tuple for the
# given configuration option.
# First, deal with the option queries.
if len(kw) == 0:
# This configure call is querying the values of one or all options.
# Return 3-tuples:
# (optionName, default, value)
if option is None:
rtn = {}
for option, config in self._optionInfo.items():
rtn[option] = (option,
# First, deal with the option queries.
if len(kw) == 0:
# This configure call is querying the values of one or all options.
# Return 3-tuples:
# (optionName, default, value)
if option is None:
rtn = {}
for option, config in self._optionInfo.items():
rtn[option] = (option,
config[_OPT_DEFAULT],
config[_OPT_VALUE])
return rtn
else:
config = self._optionInfo[option]
return (option, config[_OPT_DEFAULT], config[_OPT_VALUE])
return rtn
else:
config = self._optionInfo[option]
return (option, config[_OPT_DEFAULT], config[_OPT_VALUE])
# optimizations:
optionInfo = self._optionInfo
optionInfo_has_key = optionInfo.has_key
componentInfo = self.__componentInfo
componentInfo_has_key = componentInfo.has_key
componentAliases = self.__componentAliases
componentAliases_has_key = componentAliases.has_key
VALUE = _OPT_VALUE
FUNCTION = _OPT_FUNCTION
# optimizations:
optionInfo = self._optionInfo
optionInfo_has_key = optionInfo.has_key
componentInfo = self.__componentInfo
componentInfo_has_key = componentInfo.has_key
componentAliases = self.__componentAliases
componentAliases_has_key = componentAliases.has_key
VALUE = _OPT_VALUE
FUNCTION = _OPT_FUNCTION
# This will contain a list of options in *kw* which
# are known to this gui item.
directOptions = []
# This will contain a list of options in *kw* which
# are known to this gui item.
directOptions = []
# This will contain information about the options in
# *kw* of the form <component>_<option>, where
# <component> is a component of this megawidget. It is a
# dictionary whose keys are the configure method of each
# component and whose values are a dictionary of options and
# values for the component.
indirectOptions = {}
indirectOptions_has_key = indirectOptions.has_key
# This will contain information about the options in
# *kw* of the form <component>_<option>, where
# <component> is a component of this megawidget. It is a
# dictionary whose keys are the configure method of each
# component and whose values are a dictionary of options and
# values for the component.
indirectOptions = {}
indirectOptions_has_key = indirectOptions.has_key
for option, value in kw.items():
if optionInfo_has_key(option):
# This is one of the options of this gui item.
# Check it is an initialisation option.
if optionInfo[option][FUNCTION] is INITOPT:
for option, value in kw.items():
if optionInfo_has_key(option):
# This is one of the options of this gui item.
# Check it is an initialisation option.
if optionInfo[option][FUNCTION] is INITOPT:
print 'Cannot configure initialisation option "' \
+ option + '" for ' + self.__class__.__name__
break
#raise KeyError, \
# 'Cannot configure initialisation option "' \
# + option + '" for ' + self.__class__.__name__
optionInfo[option][VALUE] = value
directOptions.append(option)
#raise KeyError, \
# 'Cannot configure initialisation option "' \
# + option + '" for ' + self.__class__.__name__
optionInfo[option][VALUE] = value
directOptions.append(option)
else:
index = string.find(option, '_')
if index >= 0:
# This option may be of the form <component>_<option>.
index = string.find(option, '_')
if index >= 0:
# This option may be of the form <component>_<option>.
# e.g. if alias ('efEntry', 'entryField_entry')
# and option = efEntry_width
# component = efEntry, componentOption = width
component = option[:index]
componentOption = option[(index + 1):]
component = option[:index]
componentOption = option[(index + 1):]
# Expand component alias
if componentAliases_has_key(component):
# Expand component alias
if componentAliases_has_key(component):
# component = entryField, subcomponent = entry
component, subComponent = componentAliases[component]
if subComponent is not None:
component, subComponent = componentAliases[component]
if subComponent is not None:
# componentOption becomes entry_width
componentOption = subComponent + '_' \
+ componentOption
componentOption = subComponent + '_' \
+ componentOption
# Expand option string to write on error
# Expand option string to write on error
# option = entryField_entry_width
option = component + '_' + componentOption
option = component + '_' + componentOption
# Does this component exist
if componentInfo_has_key(component):
# Get the configure func for the named component
if componentInfo_has_key(component):
# Get the configure func for the named component
# component = entryField
componentConfigFuncs = [componentInfo[component][1]]
else:
# Check if this is a group name and configure all
# components in the group.
componentConfigFuncs = []
componentConfigFuncs = [componentInfo[component][1]]
else:
# Check if this is a group name and configure all
# components in the group.
componentConfigFuncs = []
# For each component
for info in componentInfo.values():
for info in componentInfo.values():
# Check if it is a member of this group
if info[4] == component:
if info[4] == component:
# Yes, append its config func
componentConfigFuncs.append(info[1])
componentConfigFuncs.append(info[1])
if len(componentConfigFuncs) == 0 and \
component not in self._dynamicGroups:
raise KeyError, 'Unknown option "' + option + \
'" for ' + self.__class__.__name__
raise KeyError, 'Unknown option "' + option + \
'" for ' + self.__class__.__name__
# Add the configure method(s) (may be more than
# one if this is configuring a component group)
# and option/value to dictionary.
for componentConfigFunc in componentConfigFuncs:
if not indirectOptions_has_key(componentConfigFunc):
indirectOptions[componentConfigFunc] = {}
# Add the configure method(s) (may be more than
# one if this is configuring a component group)
# and option/value to dictionary.
for componentConfigFunc in componentConfigFuncs:
if not indirectOptions_has_key(componentConfigFunc):
indirectOptions[componentConfigFunc] = {}
# Create a dictionary of keyword/values keyed
# on configuration function
indirectOptions[componentConfigFunc][componentOption] \
= value
else:
raise KeyError, 'Unknown option "' + option + \
'" for ' + self.__class__.__name__
indirectOptions[componentConfigFunc][componentOption] \
= value
else:
raise KeyError, 'Unknown option "' + option + \
'" for ' + self.__class__.__name__
# Call the configure methods for any components.
# Call the configure methods for any components.
# Pass in the dictionary of keyword/values created above
map(apply, indirectOptions.keys(),
((),) * len(indirectOptions), indirectOptions.values())
map(apply, indirectOptions.keys(),
((),) * len(indirectOptions), indirectOptions.values())
# Call the configuration callback function for each option.
for option in directOptions:
info = optionInfo[option]
func = info[_OPT_FUNCTION]
if func is not None:
func()
# Call the configuration callback function for each option.
for option in directOptions:
info = optionInfo[option]
func = info[_OPT_FUNCTION]
if func is not None:
func()
# Allow index style references
def __setitem__(self, key, value):
@ -433,111 +433,111 @@ class DirectGuiBase(PandaObject.PandaObject):
def cget(self, option):
"""
cget(option)
Get current configuration setting for this option
Get current configuration setting for this option
"""
# Return the value of an option, for example myWidget['font'].
if self._optionInfo.has_key(option):
return self._optionInfo[option][_OPT_VALUE]
else:
index = string.find(option, '_')
if index >= 0:
component = option[:index]
componentOption = option[(index + 1):]
# Return the value of an option, for example myWidget['font'].
if self._optionInfo.has_key(option):
return self._optionInfo[option][_OPT_VALUE]
else:
index = string.find(option, '_')
if index >= 0:
component = option[:index]
componentOption = option[(index + 1):]
# Expand component alias
if self.__componentAliases.has_key(component):
component, subComponent = self.__componentAliases[
# Expand component alias
if self.__componentAliases.has_key(component):
component, subComponent = self.__componentAliases[
component]
if subComponent is not None:
componentOption = subComponent + '_' + componentOption
if subComponent is not None:
componentOption = subComponent + '_' + componentOption
# Expand option string to write on error
option = component + '_' + componentOption
# Expand option string to write on error
option = component + '_' + componentOption
if self.__componentInfo.has_key(component):
# Call cget on the component.
componentCget = self.__componentInfo[component][3]
return componentCget(componentOption)
else:
# If this is a group name, call cget for one of
# the components in the group.
for info in self.__componentInfo.values():
if info[4] == component:
componentCget = info[3]
return componentCget(componentOption)
if self.__componentInfo.has_key(component):
# Call cget on the component.
componentCget = self.__componentInfo[component][3]
return componentCget(componentOption)
else:
# If this is a group name, call cget for one of
# the components in the group.
for info in self.__componentInfo.values():
if info[4] == component:
componentCget = info[3]
return componentCget(componentOption)
# Option not found
raise KeyError, 'Unknown option "' + option + \
'" for ' + self.__class__.__name__
raise KeyError, 'Unknown option "' + option + \
'" for ' + self.__class__.__name__
# Allow index style refererences
__getitem__ = cget
def createcomponent(self, componentName, componentAliases, componentGroup,
widgetClass, *widgetArgs, **kw):
"""
"""
Create a component (during construction or later) for this widget.
"""
# Check for invalid component name
if '_' in componentName:
raise ValueError, \
if '_' in componentName:
raise ValueError, \
'Component name "%s" must not contain "_"' % componentName
# Get construction keywords
if hasattr(self, '_constructorKeywords'):
keywords = self._constructorKeywords
else:
keywords = {}
if hasattr(self, '_constructorKeywords'):
keywords = self._constructorKeywords
else:
keywords = {}
for alias, component in componentAliases:
# Create aliases to the component and its sub-components.
index = string.find(component, '_')
if index < 0:
for alias, component in componentAliases:
# Create aliases to the component and its sub-components.
index = string.find(component, '_')
if index < 0:
# Just a shorter name for one of this widget's components
self.__componentAliases[alias] = (component, None)
else:
self.__componentAliases[alias] = (component, None)
else:
# An alias for a component of one of this widget's components
mainComponent = component[:index]
subComponent = component[(index + 1):]
self.__componentAliases[alias] = (mainComponent, subComponent)
mainComponent = component[:index]
subComponent = component[(index + 1):]
self.__componentAliases[alias] = (mainComponent, subComponent)
# Remove aliases from the constructor keyword arguments by
# replacing any keyword arguments that begin with *alias*
# with corresponding keys beginning with *component*.
alias = alias + '_'
aliasLen = len(alias)
for option in keywords.keys():
if len(option) > aliasLen and option[:aliasLen] == alias:
newkey = component + '_' + option[aliasLen:]
keywords[newkey] = keywords[option]
del keywords[option]
# Remove aliases from the constructor keyword arguments by
# replacing any keyword arguments that begin with *alias*
# with corresponding keys beginning with *component*.
alias = alias + '_'
aliasLen = len(alias)
for option in keywords.keys():
if len(option) > aliasLen and option[:aliasLen] == alias:
newkey = component + '_' + option[aliasLen:]
keywords[newkey] = keywords[option]
del keywords[option]
# Find any keyword arguments for this component
componentPrefix = componentName + '_'
nameLen = len(componentPrefix)
for option in keywords.keys():
if len(option) > nameLen and option[:nameLen] == componentPrefix:
# The keyword argument refers to this component, so add
# this to the options to use when constructing the widget.
kw[option[nameLen:]] = keywords[option][0]
componentPrefix = componentName + '_'
nameLen = len(componentPrefix)
for option in keywords.keys():
if len(option) > nameLen and option[:nameLen] == componentPrefix:
# The keyword argument refers to this component, so add
# this to the options to use when constructing the widget.
kw[option[nameLen:]] = keywords[option][0]
# And delete it from main construction keywords
del keywords[option]
else:
# Check if this keyword argument refers to the group
# of this component. If so, add this to the options
# to use when constructing the widget. Mark the
# keyword argument as being used, but do not remove it
# since it may be required when creating another
# component.
index = string.find(option, '_')
if index >= 0 and componentGroup == option[:index]:
rest = option[(index + 1):]
kw[rest] = keywords[option][0]
keywords[option][1] = 1
del keywords[option]
else:
# Check if this keyword argument refers to the group
# of this component. If so, add this to the options
# to use when constructing the widget. Mark the
# keyword argument as being used, but do not remove it
# since it may be required when creating another
# component.
index = string.find(option, '_')
if index >= 0 and componentGroup == option[:index]:
rest = option[(index + 1):]
kw[rest] = keywords[option][0]
keywords[option][1] = 1
# Return None if no widget class is specified
if widgetClass is None:
return None
if widgetClass is None:
return None
# Get arguments for widget constructor
if len(widgetArgs) == 1 and type(widgetArgs[0]) == types.TupleType:
# Arguments to the constructor can be specified as either
@ -545,63 +545,63 @@ class DirectGuiBase(PandaObject.PandaObject):
# single tuple argument.
widgetArgs = widgetArgs[0]
# Create the widget
widget = apply(widgetClass, widgetArgs, kw)
componentClass = widget.__class__.__name__
self.__componentInfo[componentName] = (widget, widget.configure,
componentClass, widget.cget, componentGroup)
return widget
widget = apply(widgetClass, widgetArgs, kw)
componentClass = widget.__class__.__name__
self.__componentInfo[componentName] = (widget, widget.configure,
componentClass, widget.cget, componentGroup)
return widget
def component(self, name):
# Return a component widget of the megawidget given the
# component's name
# This allows the user of a megawidget to access and configure
# widget components directly.
# Return a component widget of the megawidget given the
# component's name
# This allows the user of a megawidget to access and configure
# widget components directly.
# Find the main component and any subcomponents
index = string.find(name, '_')
if index < 0:
component = name
remainingComponents = None
else:
component = name[:index]
remainingComponents = name[(index + 1):]
# Find the main component and any subcomponents
index = string.find(name, '_')
if index < 0:
component = name
remainingComponents = None
else:
component = name[:index]
remainingComponents = name[(index + 1):]
# Expand component alias
# Expand component alias
# Example entry which is an alias for entryField_entry
if self.__componentAliases.has_key(component):
if self.__componentAliases.has_key(component):
# component = entryField, subComponent = entry
component, subComponent = self.__componentAliases[component]
if subComponent is not None:
if remainingComponents is None:
component, subComponent = self.__componentAliases[component]
if subComponent is not None:
if remainingComponents is None:
# remainingComponents = entry
remainingComponents = subComponent
else:
remainingComponents = subComponent + '_' \
+ remainingComponents
remainingComponents = subComponent
else:
remainingComponents = subComponent + '_' \
+ remainingComponents
# Get the component from __componentInfo dictionary
widget = self.__componentInfo[component][0]
if remainingComponents is None:
widget = self.__componentInfo[component][0]
if remainingComponents is None:
# Not looking for subcomponent
return widget
else:
return widget
else:
# Recursive call on subcomponent
return widget.component(remainingComponents)
return widget.component(remainingComponents)
def components(self):
# Return a list of all components.
names = self.__componentInfo.keys()
names.sort()
return names
# Return a list of all components.
names = self.__componentInfo.keys()
names.sort()
return names
def hascomponent(self, component):
return component in self.__componentInfo.keys()
def destroycomponent(self, name):
# Remove a megawidget component.
# This command is for use by megawidget designers to destroy a
# megawidget component.
self.__componentInfo[name][0].destroy()
del self.__componentInfo[name]
# Remove a megawidget component.
# This command is for use by megawidget designers to destroy a
# megawidget component.
self.__componentInfo[name][0].destroy()
del self.__componentInfo[name]
def destroy(self):
# Clean out any hooks

View File

@ -9,72 +9,72 @@ from ShowBaseGlobal import *
class ForceAcknowledge(StateData.StateData):
def __init__(self, doneEvent, message):
"""___init___(self, Event)"""
StateData.StateData.__init__(self, doneEvent)
return None
"""___init___(self, Event)"""
StateData.StateData.__init__(self, doneEvent)
return None
def enter(self, message):
"""enter(self, string)
"""
if self.isLoaded == 0:
self.load()
"""enter(self, string)
"""
if self.isLoaded == 0:
self.load()
if self.text:
self.text.setText(message)
self.text.reparentTo(aspect2d)
if self.text:
self.text.setText(message)
self.text.reparentTo(aspect2d)
if self.okButton:
self.okButton.manage()
self.accept("ForceAcknowledge-ok", self.__handleOk)
return None
if self.okButton:
self.okButton.manage()
self.accept("ForceAcknowledge-ok", self.__handleOk)
return None
def exit(self):
"""exit(self)
"""
if self.isLoaded == 0:
return None
"""exit(self)
"""
if self.isLoaded == 0:
return None
self.ignore("ForceAcknowledge-ok")
self.ignore("ForceAcknowledge-ok")
self.text.reparentTo(hidden)
self.okButton.unmanage()
return None
self.text.reparentTo(hidden)
self.okButton.unmanage()
return None
def load(self):
"""load(self)
"""
if self.isLoaded == 1:
return None
"""load(self)
"""
if self.isLoaded == 1:
return None
# create a message
self.text = OnscreenText.OnscreenText(parent = hidden,
# create a message
self.text = OnscreenText.OnscreenText(parent = hidden,
scale = 0.08,
pos = (0.0, 0.25))
# create a button
self.okButton = Button.Button("ForceAcknowledge", "OK",
# create a button
self.okButton = Button.Button("ForceAcknowledge", "OK",
event = "ForceAcknowledge-ok")
self.okButton.setPos(0.0, -0.5)
self.okButton.button.setPriority(self.okButton.button,
self.okButton.setPos(0.0, -0.5)
self.okButton.button.setPriority(self.okButton.button,
GuiItem.PHighest)
self.isLoaded = 1
return None
def unload(self):
"""unload(self)
"""
if self.isLoaded == 0:
return None
self.exit()
self.isLoaded = 1
return None
# GUI
self.okButton.cleanup()
self.okButton = None
self.isLoaded = 0
return None
def unload(self):
"""unload(self)
"""
if self.isLoaded == 0:
return None
self.exit()
# GUI
self.okButton.cleanup()
self.okButton = None
self.isLoaded = 0
return None
def __handleOk(self, item):
if (item == self.okButton.button):
self.doneStatus = "ok"
self.doneStatus = "ok"
messenger.send(self.doneEvent)

View File

@ -13,15 +13,15 @@ class Frame(DirectObject):
self.offset = 0
self.frame = GuiFrame.GuiFrame(name)
self.items = []
return None
return None
def cleanup(self):
"""cleanup(self)
"""
"""cleanup(self)
"""
if (self.managed):
self.frame.unmanage()
self.frame = None
return None
return None
def __str__(self):
return "Frame: %s = %s" % (self.name, self.items)

View File

@ -47,7 +47,7 @@ class ListBox(DirectObject):
self.items = []
return None
return None
def addItem(self, item, label, event = None, param = None):
if event:
@ -85,7 +85,7 @@ class ListBox(DirectObject):
self.up.cleanup()
self.down.cleanup()
self.listBox = None
return None
return None
def __str__(self):
return "ListBox: %s" % (self.name)

View File

@ -90,7 +90,7 @@ class OnscreenGeom(PandaObject, NodePath):
return self
def configure(self, option=None, **kw):
for option, value in kw.items():
for option, value in kw.items():
# Use option string to access setter function
try:
setter = eval('self.set' +
@ -111,7 +111,7 @@ class OnscreenGeom(PandaObject, NodePath):
apply(self.configure, (), {key: value})
def cget(self, option):
# Get current configuration setting.
# Get current configuration setting.
# This is for compatability with DirectGui functions
getter = eval('self.get' + string.upper(option[0]) + option[1:])
return getter()

View File

@ -110,7 +110,7 @@ class OnscreenImage(PandaObject, NodePath):
return self
def configure(self, option=None, **kw):
for option, value in kw.items():
for option, value in kw.items():
# Use option string to access setter function
try:
setter = eval('self.set' +
@ -131,7 +131,7 @@ class OnscreenImage(PandaObject, NodePath):
apply(self.configure, (), {key: value})
def cget(self, option):
# Get current configuration setting.
# Get current configuration setting.
# This is for compatability with DirectGui functions
getter = eval('self.get' + string.upper(option[0]) + option[1:])
return getter()

View File

@ -202,17 +202,17 @@ class OnscreenText(PandaObject, NodePath):
# Otherwise, we can throw it away.
self.textNode = textNode.generate()
self.isClean = 0
self.isClean = 0
# Set ourselves up as the NodePath that points to this node.
self.assign(parent.attachNewNode(self.textNode, sort))
def cleanup(self):
"""cleanup(self)
"""
self.textNode = None
if self.isClean == 0:
self.isClean = 1
"""cleanup(self)
"""
self.textNode = None
if self.isClean == 0:
self.isClean = 1
if self.hasArcs():
self.removeNode()
@ -333,7 +333,7 @@ class OnscreenText(PandaObject, NodePath):
return
# Freeze text node prior to making changes
self.freeze()
for option, value in kw.items():
for option, value in kw.items():
# Use option string to access setter function
try:
setter = eval('self.set' +
@ -351,7 +351,7 @@ class OnscreenText(PandaObject, NodePath):
apply(self.configure, (), {key: value})
def cget(self, option):
# Get current configuration setting.
# Get current configuration setting.
# This is for compatability with DirectGui functions
getter = eval('self.get' + string.upper(option[0]) + option[1:])
return getter()

View File

@ -29,8 +29,8 @@ class PickList(PandaObject.PandaObject):
# display the menu
self.__displayChoices(choiceList, scale, width, drawOrder, font)
self.isClean = 0
return None
self.isClean = 0
return None
def owns(self, item):
for x in self.choiceList:
@ -39,15 +39,15 @@ class PickList(PandaObject.PandaObject):
return None
def cleanup(self):
"""cleanup(self)
"""
if self.isClean == 0:
self.isClean = 1
"""cleanup(self)
"""
if self.isClean == 0:
self.isClean = 1
self.disable()
self.frame.unmanage()
self.frame = None
self.choiceList = []
return None
self.frame = None
self.choiceList = []
return None
# accessing
def getName(self):
@ -98,19 +98,19 @@ class PickList(PandaObject.PandaObject):
# set up the frame
self.frame.makeVertical()
return None
return None
def manage(self):
self.enable()
self.frame.manage()
for x in self.choiceList:
x.startBehavior()
return None
return None
def unmanage(self):
self.disable()
self.frame.unmanage()
return None
return None
def enable(self):
# turn the buttons on

View File

@ -111,15 +111,15 @@ class ScrollingLabel(PandaObject.PandaObject):
# refresh the frame
self.frame.recompute()
return None
return None
def cleanup(self):
"""cleanup(self)
"""
"""cleanup(self)
"""
# ignore events
self.ignore("left-button")
self.ignore("right-button")
self.ignore(self.eventName + "-rollover")
self.ignore(self.eventName + "-rollover")
self.setKeyFocus(0)
# remove gui items
@ -127,16 +127,16 @@ class ScrollingLabel(PandaObject.PandaObject):
self.frame = None
self.items = None
self.label = None
self.label = None
self.title.cleanup()
self.title = None
self.title = None
self.itemSign.cleanup()
self.itemSign = None
self.itemSign = None
self.leftButton.cleanup()
self.leftButton = None
self.leftButton = None
self.rightButton.cleanup()
self.rightButton = None
return None
self.rightButton = None
return None
# accessing
def getTitle(self):
@ -218,7 +218,7 @@ class ScrollingLabel(PandaObject.PandaObject):
self.leftButton.startBehavior()
self.rightButton.startBehavior()
return None
return None
def unmanage(self):
# ignore keyboard hits
@ -228,12 +228,12 @@ class ScrollingLabel(PandaObject.PandaObject):
# ignore events
self.ignore("left-button")
self.ignore("right-button")
self.ignore(self.eventName + "-rollover")
self.ignore(self.eventName + "-rollover")
self.setKeyFocus(0)
self.frame.unmanage()
return None
return None
def handleLeftButton(self, item):
# update the current item and the scroll label

View File

@ -29,15 +29,15 @@ class Sign(DirectObject):
self.sign = GuiSign.GuiSign(self.name, self.label)
self.managed = 0
return None
return None
def cleanup(self):
"""cleanup(self)
"""
"""cleanup(self)
"""
if (self.managed):
self.unmanage()
self.sign = None
return None
return None
def __str__(self):
return "sign: %s contains label: %s" % (self.name, self.label)

View File

@ -31,52 +31,52 @@ class ActorInterval(Interval):
id = 'Actor-%d' % ActorInterval.animNum
ActorInterval.animNum += 1
# Record class specific variables
self.actor = actor
self.animName = animName
self.actor = actor
self.animName = animName
self.loop = loop
self.frameRate = self.actor.getFrameRate(self.animName)
self.numFrames = self.actor.getNumFrames(self.animName)
self.numFrames = self.actor.getNumFrames(self.animName)
# Compute start time
self.startTime = startTime
# If no name specified, use id as name
if (name == None):
name = id
if (name == None):
name = id
# Compute duration if no duration specified
reverse = 0
reverse = 0
if duration == 0.0:
if (endTime == None):
duration = max(self.actor.getDuration(self.animName) - \
startTime, 0.0)
else:
duration = endTime - startTime
if (duration < 0.0):
duration = -duration
if (endTime == None):
self.finishTime = self.startTime + duration
else:
self.finishTime = endTime
if (self.startTime > self.finishTime):
reverse = 1
if (endTime == None):
duration = max(self.actor.getDuration(self.animName) - \
startTime, 0.0)
else:
duration = endTime - startTime
if (duration < 0.0):
duration = -duration
if (endTime == None):
self.finishTime = self.startTime + duration
else:
self.finishTime = endTime
if (self.startTime > self.finishTime):
reverse = 1
# Initialize superclass
Interval.__init__(self, name, duration, reverse=reverse)
Interval.__init__(self, name, duration, reverse=reverse)
# Update stopEvent
self.stopEvent = id + '_stopEvent'
if self.loop:
self.stopEventList = [self.stopEvent]
def calcFrame(self, t):
segmentLength = abs(self.finishTime - self.startTime)
offset = t % segmentLength
# Handle boundary case where we want to set the final frame
if (t == self.getDuration() and offset < 0.0001):
offset = segmentLength
segmentLength = abs(self.finishTime - self.startTime)
offset = t % segmentLength
# Handle boundary case where we want to set the final frame
if (t == self.getDuration() and offset < 0.0001):
offset = segmentLength
# Compute current frame based upon current time
if (self.reverse == 0):
if (self.reverse == 0):
floatFrame = self.frameRate * (self.startTime + offset)
else:
negOffset = (self.startTime - self.finishTime) - offset
floatFrame = self.frameRate * (self.finishTime + negOffset)
else:
negOffset = (self.startTime - self.finishTime) - offset
floatFrame = self.frameRate * (self.finishTime + negOffset)
# Need max to avoid frame = -1 when t = 0
frame = max(0, int(math.ceil(floatFrame)) - 1)
# Modulo in case of looping anim
@ -93,21 +93,21 @@ class ActorInterval(Interval):
return frame
def updateFunc(self, t, event=IVAL_NONE):
""" updateFunc(t, event)
Go to time t
"""
if (self.actor.isEmpty()):
self.notify.warning('updateFunc() - %s empty actor!' % self.name)
return
""" updateFunc(t, event)
Go to time t
"""
if (self.actor.isEmpty()):
self.notify.warning('updateFunc() - %s empty actor!' % self.name)
return
# Update animation based upon current time
# Pose or stop anim
if (t >= self.getDuration()):
if (t >= self.getDuration()):
self.actor.stop()
frame = self.goToT(self.getDuration())
if self.loop:
self.ignore(self.stopEvent)
# Print debug information
self.notify.debug(
self.notify.debug(
'updateFunc() - %s stoping at frame: ' % self.name +
'%d Num frames: %d' % (frame, self.numFrames))
elif self.loop == 1:

View File

@ -22,11 +22,11 @@ class FunctionInterval(Interval):
"""__init__(function, name = None)
"""
# Record instance variables
self.function = function
self.function = function
# Create a unique name for the interval if necessary
if (name == None):
name = 'FunctionInterval-%d' % FunctionInterval.functionIntervalNum
FunctionInterval.functionIntervalNum += 1
if (name == None):
name = 'FunctionInterval-%d' % FunctionInterval.functionIntervalNum
FunctionInterval.functionIntervalNum += 1
# Record any arguments
self.extraArgs = extraArgs
# Initialize superclass
@ -34,12 +34,12 @@ class FunctionInterval(Interval):
# function to be called. If false, IVAL_INIT calls have no effect
# Event, Accept, Ignore intervals default to fOpenEnded = 0
# Parent, Pos, Hpr, etc intervals default to fOpenEnded = 1
Interval.__init__(self, name, duration = 0.0, openEnded = openEnded)
Interval.__init__(self, name, duration = 0.0, openEnded = openEnded)
def updateFunc(self, t, event = IVAL_NONE):
""" updateFunc(t, event)
Go to time t
"""
""" updateFunc(t, event)
Go to time t
"""
# Evaluate the function
apply(self.function, self.extraArgs)
# Print debug information
@ -55,7 +55,7 @@ class EventInterval(FunctionInterval):
def sendFunc(event = event, sentArgs = sentArgs):
messenger.send(event, sentArgs)
# Create function interval
FunctionInterval.__init__(self, sendFunc, name = event,
FunctionInterval.__init__(self, sendFunc, name = event,
openEnded = 0)
### FunctionInterval subclass for accepting hooks ###
@ -70,7 +70,7 @@ class AcceptInterval(FunctionInterval):
if (name == None):
name = 'Accept-' + event
# Create function interval
FunctionInterval.__init__(self, acceptFunc, name = name,
FunctionInterval.__init__(self, acceptFunc, name = name,
openEnded = 0)
### FunctionInterval subclass for ignoring events ###
@ -82,10 +82,10 @@ class IgnoreInterval(FunctionInterval):
def ignoreFunc(dirObj = dirObj, event = event):
dirObj.ignore(event)
# Determine name
if (name == None):
name = 'Ignore-' + event
if (name == None):
name = 'Ignore-' + event
# Create function interval
FunctionInterval.__init__(self, ignoreFunc, name = name,
FunctionInterval.__init__(self, ignoreFunc, name = name,
openEnded = 0)
### Function Interval subclass for adjusting scene graph hierarchy ###
@ -99,11 +99,11 @@ class ParentInterval(FunctionInterval):
def reparentFunc(nodePath = nodePath, parent = parent):
nodePath.reparentTo(parent)
# Determine name
if (name == None):
name = 'ParentInterval-%d' % ParentInterval.parentIntervalNum
ParentInterval.parentIntervalNum += 1
if (name == None):
name = 'ParentInterval-%d' % ParentInterval.parentIntervalNum
ParentInterval.parentIntervalNum += 1
# Create function interval
FunctionInterval.__init__(self, reparentFunc, name = name)
FunctionInterval.__init__(self, reparentFunc, name = name)
### Function Interval subclass for adjusting scene graph hierarchy ###
class WrtParentInterval(FunctionInterval):
@ -116,12 +116,12 @@ class WrtParentInterval(FunctionInterval):
def wrtReparentFunc(nodePath = nodePath, parent = parent):
nodePath.wrtReparentTo(parent)
# Determine name
if (name == None):
name = ('WrtParentInterval-%d' %
if (name == None):
name = ('WrtParentInterval-%d' %
WrtParentInterval.wrtParentIntervalNum)
WrtParentInterval.wrtParentIntervalNum += 1
WrtParentInterval.wrtParentIntervalNum += 1
# Create function interval
FunctionInterval.__init__(self, wrtReparentFunc, name = name)
FunctionInterval.__init__(self, wrtReparentFunc, name = name)
### Function Interval subclasses for instantaneous pose changes ###
class PosInterval(FunctionInterval):
@ -139,9 +139,9 @@ class PosInterval(FunctionInterval):
else:
np.setPos(pos)
# Determine name
if (name == None):
name = 'PosInterval-%d' % PosInterval.posIntervalNum
PosInterval.posIntervalNum += 1
if (name == None):
name = 'PosInterval-%d' % PosInterval.posIntervalNum
PosInterval.posIntervalNum += 1
# Create function interval
FunctionInterval.__init__(self, posFunc, name = name)
@ -160,9 +160,9 @@ class HprInterval(FunctionInterval):
else:
np.setHpr(hpr)
# Determine name
if (name == None):
name = 'HprInterval-%d' % HprInterval.hprIntervalNum
HprInterval.hprIntervalNum += 1
if (name == None):
name = 'HprInterval-%d' % HprInterval.hprIntervalNum
HprInterval.hprIntervalNum += 1
# Create function interval
FunctionInterval.__init__(self, hprFunc, name = name)
@ -181,9 +181,9 @@ class ScaleInterval(FunctionInterval):
else:
np.setScale(scale)
# Determine name
if (name == None):
name = 'ScaleInterval-%d' % ScaleInterval.scaleIntervalNum
ScaleInterval.scaleIntervalNum += 1
if (name == None):
name = 'ScaleInterval-%d' % ScaleInterval.scaleIntervalNum
ScaleInterval.scaleIntervalNum += 1
# Create function interval
FunctionInterval.__init__(self, scaleFunc, name = name)
@ -202,9 +202,9 @@ class PosHprInterval(FunctionInterval):
else:
np.setPosHpr(pos, hpr)
# Determine name
if (name == None):
name = 'PosHprInterval-%d' % PosHprInterval.posHprIntervalNum
PosHprInterval.posHprIntervalNum += 1
if (name == None):
name = 'PosHprInterval-%d' % PosHprInterval.posHprIntervalNum
PosHprInterval.posHprIntervalNum += 1
# Create function interval
FunctionInterval.__init__(self, posHprFunc, name = name)
@ -224,10 +224,10 @@ class PosHprScaleInterval(FunctionInterval):
else:
np.setPosHprScale(pos, hpr, scale)
# Determine name
if (name == None):
name = ('PosHprScale-%d' %
if (name == None):
name = ('PosHprScale-%d' %
PosHprScaleInterval.posHprScaleIntervalNum)
PosHprScaleInterval.posHprScaleIntervalNum += 1
PosHprScaleInterval.posHprScaleIntervalNum += 1
# Create function interval
FunctionInterval.__init__(self, posHprScaleFunc, name = name)

View File

@ -24,25 +24,25 @@ class Interval(DirectObject):
def __init__(self, name, duration, openEnded=1, reverse=0):
"""__init__(name, duration, openEnded, reverse)
"""
self.name = name
self.duration = duration
self.curr_t = 0.0
self.prev_t = 0.0
self.name = name
self.duration = duration
self.curr_t = 0.0
self.prev_t = 0.0
self.stopEventList = []
self.setTHooks = []
# Set true if interval responds to setT(t): t>duration
self.fOpenEnded = openEnded
self.reverse = reverse
self.reverse = reverse
def getName(self):
""" getName()
"""
return self.name
""" getName()
"""
return self.name
def getDuration(self):
""" getDuration()
"""
return self.duration
""" getDuration()
"""
return self.duration
def setfOpenEnded(self, openEnded):
""" setfOpenEnded(openEnded)
@ -55,11 +55,11 @@ class Interval(DirectObject):
return self.fOpenEnded
def setT(self, t, event = IVAL_NONE):
""" setT(t, event)
Go to time t
"""
""" setT(t, event)
Go to time t
"""
# Update current time
self.curr_t = t
self.curr_t = t
# Perform interval actions
self.updateFunc(t, event)
# Call setT Hook
@ -79,9 +79,9 @@ class Interval(DirectObject):
pass
def setFinalT(self):
""" setFinalT()
"""
self.setT(self.getDuration(), event=IVAL_DONE)
""" setFinalT()
"""
self.setT(self.getDuration(), event=IVAL_DONE)
def play(self, t0=0.0, duration=0.0, scale=1.0):
""" play(t0, duration)
@ -93,18 +93,18 @@ class Interval(DirectObject):
# Kill ongoing play task
taskMgr.removeTasksNamed(self.name + '-play')
# Start new one
self.offset = t0
self.offset = t0
self.startT = self.clock.getFrameTime()
assert(scale > 0.0)
self.scale = scale
self.firstTime = 1
assert(scale > 0.0)
self.scale = scale
self.firstTime = 1
if (duration == 0.0):
# If no play duration specified, use duration of Interval
self.endTime = self.duration
else:
# Otherwise use min of interval duration and offset + play duration
self.endTime = min(self.duration, self.offset + duration)
assert(t0 <= self.endTime)
assert(t0 <= self.endTime)
# Spawn task
taskMgr.spawnMethodNamed(self.__playTask, self.name + '-play')
@ -125,10 +125,10 @@ class Interval(DirectObject):
taskMgr.removeTasksNamed(self.name + '-play')
# No more looping.
self.ignore(self.name + '-loop')
return self.curr_t
return self.curr_t
def isPlaying(self):
return taskMgr.hasTaskNamed(self.name + '-play')
return taskMgr.hasTaskNamed(self.name + '-play')
def __playTask(self, task):
""" __playTask(task)
@ -155,12 +155,12 @@ class Interval(DirectObject):
return Task.done
def __repr__(self, indent=0):
""" __repr__(indent)
"""
space = ''
for l in range(indent):
space = space + ' '
return (space + self.name + ' dur: %.2f' % self.duration)
""" __repr__(indent)
"""
space = ''
for l in range(indent):
space = space + ' '
return (space + self.name + ' dur: %.2f' % self.duration)
def popupControls(self, tl = None):
""" popupControls()

View File

@ -39,9 +39,9 @@ donaldSteerTrack = Track([donaldSteerInterval, donaldLoopInterval],
# Make the dock lerp up so that it's up when the boat reaches the end of
# its mopath
dockLerp = LerpPosHprInterval(dock, 5.0,
pos=Point3(0, 0, -5),
hpr=Vec3(0, 0, 0),
name='dock-lerp')
pos=Point3(0, 0, -5),
hpr=Vec3(0, 0, 0),
name='dock-lerp')
# We need the dock's state to be defined before the lerp
dockPos = PosHprInterval(dock, dock.getPos(), dock.getHpr(), 1.0, 'dockpos')
dockUpTime = BOAT_END - dockLerp.getDuration()

View File

@ -14,21 +14,21 @@ class LerpInterval(Interval):
"""
# Record instance variables
self.lerp = None
self.functorFunc = functorFunc
self.blendType = self.getBlend(blendType)
self.functorFunc = functorFunc
self.blendType = self.getBlend(blendType)
# Initialize superclass
Interval.__init__(self, name, duration)
Interval.__init__(self, name, duration)
def updateFunc(self, t, event = IVAL_NONE):
""" updateFunc(t, event)
"""
""" updateFunc(t, event)
"""
# Check to see if we need to create the lerp
if (event == IVAL_INIT):
self.lerp = Lerp(self.functorFunc(), self.duration,
self.lerp = Lerp(self.functorFunc(), self.duration,
self.blendType)
# Make sure lerp exists
if (not self.lerp):
self.lerp = Lerp(self.functorFunc(), self.duration,
if (not self.lerp):
self.lerp = Lerp(self.functorFunc(), self.duration,
self.blendType)
# Evaluate the lerp
self.lerp.setT(t)
@ -49,71 +49,71 @@ class LerpInterval(Interval):
return LerpBlendHelpers.noBlend
else:
raise Exception(
'Error: LerpInterval.__getBlend: Unknown blend type')
'Error: LerpInterval.__getBlend: Unknown blend type')
class LerpPosInterval(LerpInterval):
# Name counter
lerpPosNum = 1
# Class methods
def __init__(self, node, duration, pos, startPos=None,
other=None, blendType='noBlend', name=None):
""" __init__(node, duration, pos, startPos, other, blendType, name)
"""
def functorFunc(node=node, pos=pos, startPos=startPos,
other=other):
assert(not node.isEmpty())
other=None, blendType='noBlend', name=None):
""" __init__(node, duration, pos, startPos, other, blendType, name)
"""
def functorFunc(node=node, pos=pos, startPos=startPos,
other=other):
assert(not node.isEmpty())
if callable(pos):
# This may be a thunk that returns a point.
pos = pos()
if (other != None):
# lerp wrt other
if (startPos == None):
# lerp wrt other
if (startPos == None):
startPos = node.getPos(other)
functor = PosLerpFunctor(node, startPos, pos, other)
functor = PosLerpFunctor(node, startPos, pos, other)
else:
if (startPos == None):
startPos = node.getPos()
functor = PosLerpFunctor(node, startPos, pos)
return functor
if (startPos == None):
startPos = node.getPos()
functor = PosLerpFunctor(node, startPos, pos)
return functor
# Generate unique name if necessary
if (name == None):
name = 'LerpPosInterval-%d' % LerpPosInterval.lerpPosNum
LerpPosInterval.lerpPosNum += 1
if (name == None):
name = 'LerpPosInterval-%d' % LerpPosInterval.lerpPosNum
LerpPosInterval.lerpPosNum += 1
# Initialize superclass
LerpInterval.__init__(self, name, duration, functorFunc, blendType)
LerpInterval.__init__(self, name, duration, functorFunc, blendType)
class LerpHprInterval(LerpInterval):
# Name counter
lerpHprNum = 1
# Class methods
def __init__(self, node, duration, hpr, startHpr=None,
other=None, blendType='noBlend', name=None):
""" __init__(node, duration, hpr, startHpr, other, blendType, name)
"""
def functorFunc(node=node, hpr=hpr, startHpr=startHpr,
other=other):
assert(not node.isEmpty())
other=None, blendType='noBlend', name=None):
""" __init__(node, duration, hpr, startHpr, other, blendType, name)
"""
def functorFunc(node=node, hpr=hpr, startHpr=startHpr,
other=other):
assert(not node.isEmpty())
if callable(hpr):
# This may be a thunk that returns a point.
hpr = hpr()
if (other != None):
# lerp wrt other
if (startHpr == None):
# lerp wrt other
if (startHpr == None):
startHpr = node.getHpr(other)
functor = HprLerpFunctor(node, startHpr, hpr, other)
functor = HprLerpFunctor(node, startHpr, hpr, other)
else:
if (startHpr == None):
startHpr = node.getHpr()
functor = HprLerpFunctor(node, startHpr, hpr)
return functor
if (startHpr == None):
startHpr = node.getHpr()
functor = HprLerpFunctor(node, startHpr, hpr)
return functor
# Generate unique name if necessary
if (name == None):
name = 'LerpHprInterval-%d' % LerpHprInterval.lerpHprNum
LerpHprInterval.lerpHprNum += 1
if (name == None):
name = 'LerpHprInterval-%d' % LerpHprInterval.lerpHprNum
LerpHprInterval.lerpHprNum += 1
# Initialize superclass
LerpInterval.__init__(self, name, duration, functorFunc, blendType)
LerpInterval.__init__(self, name, duration, functorFunc, blendType)
class LerpScaleInterval(LerpInterval):
@ -121,32 +121,32 @@ class LerpScaleInterval(LerpInterval):
lerpScaleNum = 1
# Class methods
def __init__(self, node, duration, scale, startScale=None,
other=None, blendType='noBlend', name=None):
""" __init__(node, duration, scale, startScale, other, blendType, name)
"""
def functorFunc(node=node, scale=scale,
other=None, blendType='noBlend', name=None):
""" __init__(node, duration, scale, startScale, other, blendType, name)
"""
def functorFunc(node=node, scale=scale,
startScale=startScale, other=other):
assert(not node.isEmpty())
assert(not node.isEmpty())
if callable(scale):
# This may be a thunk that returns a point.
scale = scale()
if (other != None):
# lerp wrt other
if (startScale == None):
# lerp wrt other
if (startScale == None):
startScale = node.getScale(other)
functor = ScaleLerpFunctor(node, startScale, scale, other)
functor = ScaleLerpFunctor(node, startScale, scale, other)
else:
if (startScale == None):
startScale = node.getScale()
functor = ScaleLerpFunctor(node, startScale, scale)
return functor
if (startScale == None):
startScale = node.getScale()
functor = ScaleLerpFunctor(node, startScale, scale)
return functor
# Generate unique name if necessary
if (name == None):
name = 'LerpScaleInterval-%d' % LerpScaleInterval.lerpScaleNum
LerpScaleInterval.lerpScaleNum += 1
if (name == None):
name = 'LerpScaleInterval-%d' % LerpScaleInterval.lerpScaleNum
LerpScaleInterval.lerpScaleNum += 1
# Initialize superclass
LerpInterval.__init__(self, name, duration, functorFunc, blendType)
LerpInterval.__init__(self, name, duration, functorFunc, blendType)
class LerpPosHprInterval(LerpInterval):
# Interval counter
@ -154,13 +154,13 @@ class LerpPosHprInterval(LerpInterval):
lerpPosHprNum = 1
def __init__(self, node, duration, pos, hpr, startPos=None,
startHpr=None, other=None, blendType='noBlend', name=None):
""" __init__(node, duration, pos, hpr, startPos, startHpr,
other, blendType, name)
"""
def functorFunc(node=node, pos=pos, hpr=hpr,
startPos=startPos, startHpr=startHpr, other=other):
assert(not node.isEmpty())
startHpr=None, other=None, blendType='noBlend', name=None):
""" __init__(node, duration, pos, hpr, startPos, startHpr,
other, blendType, name)
"""
def functorFunc(node=node, pos=pos, hpr=hpr,
startPos=startPos, startHpr=startHpr, other=other):
assert(not node.isEmpty())
if callable(pos):
# This may be a thunk that returns a point.
pos = pos()
@ -168,30 +168,30 @@ class LerpPosHprInterval(LerpInterval):
# This may be a thunk that returns a point.
hpr = hpr()
if (other != None):
# lerp wrt other
if (startPos == None):
startPos = node.getPos(other)
if (startHpr == None):
startHpr = node.getHpr(other)
functor = PosHprLerpFunctor(
# lerp wrt other
if (startPos == None):
startPos = node.getPos(other)
if (startHpr == None):
startHpr = node.getHpr(other)
functor = PosHprLerpFunctor(
node, startPos, pos,
startHpr, hpr, other)
else:
if (startPos == None):
startPos = node.getPos()
if (startHpr == None):
startHpr = node.getHpr()
functor = PosHprLerpFunctor(
if (startPos == None):
startPos = node.getPos()
if (startHpr == None):
startHpr = node.getHpr()
functor = PosHprLerpFunctor(
node, startPos, pos,
startHpr, hpr)
return functor
return functor
# Generate unique name if necessary
if (name == None):
name = 'LerpPosHpr-%d' % LerpPosHprInterval.lerpPosHprNum
LerpPosHprInterval.lerpPosHprNum += 1
if (name == None):
name = 'LerpPosHpr-%d' % LerpPosHprInterval.lerpPosHprNum
LerpPosHprInterval.lerpPosHprNum += 1
# Initialize superclass
LerpInterval.__init__(self, name, duration, functorFunc, blendType)
LerpInterval.__init__(self, name, duration, functorFunc, blendType)
class LerpPosHprScaleInterval(LerpInterval):
# Interval counter
@ -200,14 +200,14 @@ class LerpPosHprScaleInterval(LerpInterval):
def __init__(self, node, duration, pos, hpr, scale,
startPos=None, startHpr=None, startScale=None,
other=None, blendType='noBlend', name=None):
""" __init__(node, duration, pos, hpr, scale,
""" __init__(node, duration, pos, hpr, scale,
startPos, startHpr, startScale,
other, blendType, name)
"""
def functorFunc(node=node, pos=pos, hpr=hpr, scale=scale,
startPos=startPos, startHpr=startHpr,
"""
def functorFunc(node=node, pos=pos, hpr=hpr, scale=scale,
startPos=startPos, startHpr=startHpr,
startScale=startScale, other=other):
assert(not node.isEmpty())
assert(not node.isEmpty())
if callable(pos):
# This may be a thunk that returns a point.
pos = pos()
@ -218,34 +218,34 @@ class LerpPosHprScaleInterval(LerpInterval):
# This may be a thunk that returns a point.
scale = scale()
if (other != None):
# lerp wrt other
if (startPos == None):
startPos = node.getPos(other)
if (startHpr == None):
startHpr = node.getHpr(other)
if (startScale == None):
startScale = node.getScale(other)
functor = PosHprScaleLerpFunctor(
# lerp wrt other
if (startPos == None):
startPos = node.getPos(other)
if (startHpr == None):
startHpr = node.getHpr(other)
if (startScale == None):
startScale = node.getScale(other)
functor = PosHprScaleLerpFunctor(
node, startPos, pos, startHpr, hpr,
startScale, scale, other)
else:
if (startPos == None):
startPos = node.getPos()
if (startHpr == None):
startHpr = node.getHpr()
if (startScale == None):
startScale = node.getScale()
functor = PosHprScaleLerpFunctor(
if (startPos == None):
startPos = node.getPos()
if (startHpr == None):
startHpr = node.getHpr()
if (startScale == None):
startScale = node.getScale()
functor = PosHprScaleLerpFunctor(
node, startPos, pos, startHpr, hpr, startScale, scale)
return functor
return functor
# Generate unique name if necessary
if (name == None):
name = ('LerpPosHprScale-%d' %
if (name == None):
name = ('LerpPosHprScale-%d' %
LerpPosHprScaleInterval.lerpPosHprScaleNum)
LerpPosHprScaleInterval.lerpPosHprScaleNum += 1
LerpPosHprScaleInterval.lerpPosHprScaleNum += 1
# Initialize superclass
LerpInterval.__init__(self, name, duration, functorFunc, blendType)
LerpInterval.__init__(self, name, duration, functorFunc, blendType)
# Class used to execute a function over time. Function can access fromData
# and toData to perform blend. If fromData and toData not specified, will
@ -261,26 +261,26 @@ class LerpFunctionInterval(Interval):
"""__init__(function, duration, fromData, toData, name)
"""
# Record instance variables
self.function = function
self.function = function
self.fromData = fromData
self.toData = toData
self.blendType = self.getBlend(blendType)
self.blendType = self.getBlend(blendType)
self.extraArgs = extraArgs
# Generate unique name if necessary
if (name == None):
name = ('LerpFunctionInterval-%d' %
if (name == None):
name = ('LerpFunctionInterval-%d' %
LerpFunctionInterval.lerpFunctionIntervalNum)
LerpFunctionInterval.lerpFunctionIntervalNum += 1
# Initialize superclass
Interval.__init__(self, name, duration)
Interval.__init__(self, name, duration)
def updateFunc(self, t, event = IVAL_NONE):
""" updateFunc(t, event)
"""
""" updateFunc(t, event)
"""
# Evaluate the function
if (t >= self.duration):
# Set to end value
apply(self.function, [self.toData] + self.extraArgs)
apply(self.function, [self.toData] + self.extraArgs)
elif self.duration == 0.0:
# Zero duration, just use endpoint
apply(self.function, [self.toData] + self.extraArgs)
@ -308,5 +308,5 @@ class LerpFunctionInterval(Interval):
return LerpBlendHelpers.noBlend
else:
raise Exception(
'Error: LerpInterval.__getBlend: Unknown blend type')
'Error: LerpInterval.__getBlend: Unknown blend type')

View File

@ -13,21 +13,21 @@ class MopathInterval(Interval):
def __init__(self, mopath, node, name=None):
"""__init__(mopath, node, name)
"""
self.mopath = mopath
self.node = node
self.mopath = mopath
self.node = node
# Generate unique name if necessary
if (name == None):
name = 'Mopath-%d' % MopathInterval.mopathNum
MopathInterval.mopathNum += 1
if (name == None):
name = 'Mopath-%d' % MopathInterval.mopathNum
MopathInterval.mopathNum += 1
# Compute duration
duration = self.mopath.getMaxT()
duration = self.mopath.getMaxT()
# Initialize superclass
Interval.__init__(self, name, duration)
Interval.__init__(self, name, duration)
def updateFunc(self, t, event = IVAL_NONE):
""" updateFunc(t, event)
Go to time t
"""
""" updateFunc(t, event)
Go to time t
"""
self.mopath.goTo(self.node, t)
# Print debug information
self.notify.debug('updateFunc() - %s: t = %f' % (self.name, t))

View File

@ -11,15 +11,15 @@ class MultiTrack(Interval):
"""__init__(trackList, name)
"""
# Record track list
self.tlist = trackList
self.tlist = trackList
# Generate name if necessary
if (name == None):
name = 'MultiTrack-%d' % MultiTrack.multiTrackNum
MultiTrack.multiTrackNum = MultiTrack.multiTrackNum + 1
if (name == None):
name = 'MultiTrack-%d' % MultiTrack.multiTrackNum
MultiTrack.multiTrackNum = MultiTrack.multiTrackNum + 1
# Duration is max of all track durations
duration = self.__computeDuration()
duration = self.__computeDuration()
# Initialize superclass
Interval.__init__(self, name, duration)
Interval.__init__(self, name, duration)
# Update stopEventList after initialization
# It is the union of the stopEventLists of all tracks in the MultiTrack
for t in self.tlist:
@ -30,21 +30,21 @@ class MultiTrack(Interval):
return self.tlist[item]
def __computeDuration(self):
""" __computeDuration()
Returns the duration of the longest Track
"""
duration = 0.0
for t in self.tlist:
dur = t.getDuration()
if (dur > duration):
duration = dur
return duration
""" __computeDuration()
Returns the duration of the longest Track
"""
duration = 0.0
for t in self.tlist:
dur = t.getDuration()
if (dur > duration):
duration = dur
return duration
def updateFunc(self, t, event = IVAL_NONE):
""" updateFunc(t, event)
Go to time t
"""
for track in self.tlist:
""" updateFunc(t, event)
Go to time t
"""
for track in self.tlist:
# Compare time with track's end times
if (event == IVAL_INIT) or (event == IVAL_DONE):
# always call setT if INIT or DONE event
@ -58,11 +58,11 @@ class MultiTrack(Interval):
# Print out representation of MultiTrack
def __repr__(self, indent=0):
""" __repr__(indent)
"""
str = Interval.__repr__(self, indent) + '\n'
for t in self.tlist:
str = str + t.__repr__(indent+1)
""" __repr__(indent)
"""
str = Interval.__repr__(self, indent) + '\n'
for t in self.tlist:
str = str + t.__repr__(indent+1)
return str

View File

@ -11,8 +11,8 @@ class WaitInterval(Interval):
"""__init__(duration, name)
"""
# Generate unique name if necessary
if (name == None):
name = 'Wait-%d' % WaitInterval.waitNum
WaitInterval.waitNum += 1
if (name == None):
name = 'Wait-%d' % WaitInterval.waitNum
WaitInterval.waitNum += 1
# Initialize superclass
Interval.__init__(self, name, duration)
Interval.__init__(self, name, duration)

View File

@ -36,30 +36,30 @@ class PieMenu(NodePath, PandaObject):
def removePieMenuTask(self):
taskMgr.removeTasksNamed('pieMenuTask')
self.reparentTo(hidden)
self.lines.reset()
self.reparentTo(hidden)
self.lines.reset()
def spawnPieMenuTask(self):
# Make sure no errant tasks lying around
taskMgr.removeTasksNamed('pieMenuTask')
# Make sure no errant tasks lying around
taskMgr.removeTasksNamed('pieMenuTask')
# Where did the user press the button?
self.originX = direct.dr.mouseX
self.originY = direct.dr.mouseY
# Where did the user press the button?
self.originX = direct.dr.mouseX
self.originY = direct.dr.mouseY
# Pop up menu
self.reparentTo(render2d)
self.setPos(self.originX,0.0,self.originY)
# Pop up menu
self.reparentTo(render2d)
self.setPos(self.originX,0.0,self.originY)
# Compensate for window aspect ratio
self.setScale(1.0, 1.0,1.0)
#direct.dr.width/float(direct.dr.height))
# Start drawing the selection line
self.lines.reset()
self.lines.moveTo(0,0,0)
self.lines.drawTo(0,0,0)
self.lines.create()
# Start drawing the selection line
self.lines.reset()
self.lines.moveTo(0,0,0)
self.lines.drawTo(0,0,0)
self.lines.create()
# Spawn task to update line and select new texture
# Spawn task to update line and select new texture
self.currItem = -1
t = Task.Task(self.pieMenuTask)
taskMgr.spawnTaskNamed(t, 'pieMenuTask')
@ -104,14 +104,14 @@ class PieMenu(NodePath, PandaObject):
return Task.cont
def setInitialState(self,state):
self.initialState = state
self.initialState = state
def getInitialState(self):
return self.initialState
def setItemOffset(self,newOffset):
self.itemOffset = newOffset
self.itemOffset = newOffset
def setUpdateOnlyOnChange(self,flag):
self.fUpdateOnlyOnChange = flag
self.fUpdateOnlyOnChange = flag

View File

@ -11,57 +11,57 @@ class ForceGroup(DirectObject):
id = 1
def __init__(self, name=None):
"""__init__(self)"""
"""__init__(self)"""
if (name == None):
self.name = 'ForceGroup-%d' % ForceGroup.id
ForceGroup.id += 1
else:
self.name = name
if (name == None):
self.name = 'ForceGroup-%d' % ForceGroup.id
ForceGroup.id += 1
else:
self.name = name
self.node = ForceNode.ForceNode(self.name)
self.nodePath = hidden.attachNewNode(self.node)
self.node = ForceNode.ForceNode(self.name)
self.nodePath = hidden.attachNewNode(self.node)
self.fEnabled = 0
self.particleEffect = None
self.particleEffect = None
def cleanup(self):
for f in self.asList():
self.removeForce(f)
self.nodePath.removeNode()
self.node = None
self.particleEffect = None
for f in self.asList():
self.removeForce(f)
self.nodePath.removeNode()
self.node = None
self.particleEffect = None
def enable(self):
"""enable(self)
Convenience function to enable all forces in force group"""
for i in range(self.node.getNumForces()):
f = self.node.getForce(i)
f.setActive(1)
"""enable(self)
Convenience function to enable all forces in force group"""
for i in range(self.node.getNumForces()):
f = self.node.getForce(i)
f.setActive(1)
self.fEnabled = 1
def disable(self):
"""disable(self)
Convenience function to disable all forces in force group"""
for i in range(self.node.getNumForces()):
f = self.node.getForce(i)
f.setActive(0)
"""disable(self)
Convenience function to disable all forces in force group"""
for i in range(self.node.getNumForces()):
f = self.node.getForce(i)
f.setActive(0)
self.fEnabled = 0
def isEnabled(self):
return self.fEnabled
def addForce(self, force):
"""addForce(self, force)"""
self.node.addForce(force)
if (self.particleEffect):
self.particleEffect.addForce(force)
"""addForce(self, force)"""
self.node.addForce(force)
if (self.particleEffect):
self.particleEffect.addForce(force)
def removeForce(self, force):
"""removeForce(self, force)"""
self.node.removeForce(force)
if (self.particleEffect != None):
self.particleEffect.removeForce(force)
"""removeForce(self, force)"""
self.node.removeForce(force)
if (self.particleEffect != None):
self.particleEffect.removeForce(force)
# Get/set
def getName(self):
@ -76,63 +76,63 @@ class ForceGroup(DirectObject):
# Utility functions
def __getitem__(self, index):
"""__getItem__(self, index)"""
"""__getItem__(self, index)"""
numForces = self.node.getNumForces()
if numForces == 0:
raise IndexError
if ((index < 0) | (index >= self.node.getNumForces())):
raise IndexError
return self.node.getForce(index)
return self.node.getForce(index)
def __len__(self):
"""__len__(self)"""
return self.node.getNumForces()
"""__len__(self)"""
return self.node.getNumForces()
def asList(self):
"""asList(self)"""
l = []
for i in range(self.node.getNumForces()):
l.append(self.node.getForce(i))
return l
"""asList(self)"""
l = []
for i in range(self.node.getNumForces()):
l.append(self.node.getForce(i))
return l
def printParams(self, file = sys.stdout, targ = 'self'):
"""printParams(file, targ)"""
file.write('# Force parameters\n')
for i in range(self.node.getNumForces()):
f = self.node.getForce(i)
fname = 'force%d' % i
if isinstance(f, LinearForce):
amplitude = f.getAmplitude()
massDependent = f.getMassDependent()
if isinstance(f, LinearCylinderVortexForce):
file.write(fname + ' = LinearCylinderVortexForce(%.4f, %.4f, %.4f, %.4f, %d)\n' % (f.getRadius(), f.getLength(), f.getCoef(), amplitude, massDependent))
elif isinstance(f, LinearDistanceForce):
radius = f.getRadius()
falloffType = f.getFalloffType()
ftype = 'FTONEOVERR'
if (falloffType == LinearDistanceForce.FTONEOVERR):
ftype = 'FTONEOVERR'
elif (falloffType == LinearDistanceForce.FTONEOVERRSQUARED):
ftype = 'FTONEOVERRSQUARED'
elif (falloffType == LinearDistanceForce.FTONEOVERRCUBED):
ftype = 'FTONEOVERRCUBED'
forceCenter = f.getForceCenter()
if isinstance(f, LinearSinkForce):
file.write(fname + ' = LinearSinkForce(Point3(%.4f, %.4f, %.4f), LinearDistanceForce.%s, %.4f, %.4f, %d)\n' % (forceCenter[0], forceCenter[1], forceCenter[2], ftype, radius, amplitude, massDependent))
elif isinstance(f, LinearSourceForce):
file.write(fname + ' = LinearSourceForce(Point3(%.4f, %.4f, %.4f), LinearDistanceForce.%s, %.4f, %.4f, %d)\n' % (forceCenter[0], forceCenter[1], forceCenter[2], ftype, radius, amplitude, massDependent))
elif isinstance(f, LinearFrictionForce):
file.write(fname + ' = LinearFrictionForce(%.4f, %.4f, %d)\n' % (f.getCoef(), amplitude, massDependent))
elif isinstance(f, LinearJitterForce):
file.write(fname + ' = LinearJitterForce(%.4f, %d)\n' % (amplitude, massDependent))
elif isinstance(f, LinearNoiseForce):
file.write(fname + ' = LinearNoiseForce(%.4f, %d)\n' % (amplitude, massDependent))
elif isinstance(f, LinearVectorForce):
vec = f.getLocalVector()
file.write(fname + ' = LinearVectorForce(Vec3(%.4f, %.4f, %.4f), %.4f, %d)\n' % (vec[0], vec[1], vec[2], amplitude, massDependent))
elif isinstance(f, AngularForce):
if isinstance(f, AngularVectorForce):
vec = f.getLocalVector()
file.write(fname + ' = AngularVectorForce(Vec3(%.4f, %.4f, %.4f))\n' % (vec[0], vec[1], vec[2]))
file.write(fname + '.setActive(%d)\n' % f.getActive())
file.write(targ + '.addForce(%s)\n' % fname)
"""printParams(file, targ)"""
file.write('# Force parameters\n')
for i in range(self.node.getNumForces()):
f = self.node.getForce(i)
fname = 'force%d' % i
if isinstance(f, LinearForce):
amplitude = f.getAmplitude()
massDependent = f.getMassDependent()
if isinstance(f, LinearCylinderVortexForce):
file.write(fname + ' = LinearCylinderVortexForce(%.4f, %.4f, %.4f, %.4f, %d)\n' % (f.getRadius(), f.getLength(), f.getCoef(), amplitude, massDependent))
elif isinstance(f, LinearDistanceForce):
radius = f.getRadius()
falloffType = f.getFalloffType()
ftype = 'FTONEOVERR'
if (falloffType == LinearDistanceForce.FTONEOVERR):
ftype = 'FTONEOVERR'
elif (falloffType == LinearDistanceForce.FTONEOVERRSQUARED):
ftype = 'FTONEOVERRSQUARED'
elif (falloffType == LinearDistanceForce.FTONEOVERRCUBED):
ftype = 'FTONEOVERRCUBED'
forceCenter = f.getForceCenter()
if isinstance(f, LinearSinkForce):
file.write(fname + ' = LinearSinkForce(Point3(%.4f, %.4f, %.4f), LinearDistanceForce.%s, %.4f, %.4f, %d)\n' % (forceCenter[0], forceCenter[1], forceCenter[2], ftype, radius, amplitude, massDependent))
elif isinstance(f, LinearSourceForce):
file.write(fname + ' = LinearSourceForce(Point3(%.4f, %.4f, %.4f), LinearDistanceForce.%s, %.4f, %.4f, %d)\n' % (forceCenter[0], forceCenter[1], forceCenter[2], ftype, radius, amplitude, massDependent))
elif isinstance(f, LinearFrictionForce):
file.write(fname + ' = LinearFrictionForce(%.4f, %.4f, %d)\n' % (f.getCoef(), amplitude, massDependent))
elif isinstance(f, LinearJitterForce):
file.write(fname + ' = LinearJitterForce(%.4f, %d)\n' % (amplitude, massDependent))
elif isinstance(f, LinearNoiseForce):
file.write(fname + ' = LinearNoiseForce(%.4f, %d)\n' % (amplitude, massDependent))
elif isinstance(f, LinearVectorForce):
vec = f.getLocalVector()
file.write(fname + ' = LinearVectorForce(Vec3(%.4f, %.4f, %.4f), %.4f, %d)\n' % (vec[0], vec[1], vec[2], amplitude, massDependent))
elif isinstance(f, AngularForce):
if isinstance(f, AngularVectorForce):
vec = f.getLocalVector()
file.write(fname + ' = AngularVectorForce(Vec3(%.4f, %.4f, %.4f))\n' % (vec[0], vec[1], vec[2]))
file.write(fname + '.setActive(%d)\n' % f.getActive())
file.write(targ + '.addForce(%s)\n' % fname)

View File

@ -3,24 +3,24 @@ import ForceGroup
class GlobalForceGroup(ForceGroup.ForceGroup):
def __init__(self, name = None):
"""__init__(self)"""
ForceGroup.ForceGroup.__init__(self, name)
"""__init__(self)"""
ForceGroup.ForceGroup.__init__(self, name)
def addForce(self, force):
"""addForce(self, force)"""
ForceGroup.ForceGroup.addForce(force)
if (force.isLinear() == 0):
# Physics manager will need an angular integrator
base.addAngularIntegrator()
if (force.isLinear() == 1):
physicsMgr.addLinearForce(force)
else:
physicsMgr.addAngularForce(force)
"""addForce(self, force)"""
ForceGroup.ForceGroup.addForce(force)
if (force.isLinear() == 0):
# Physics manager will need an angular integrator
base.addAngularIntegrator()
if (force.isLinear() == 1):
physicsMgr.addLinearForce(force)
else:
physicsMgr.addAngularForce(force)
def removeForce(self, force):
"""removeForce(self, force)"""
ForceGroup.ForceGroup.removeForce(force)
if (force.isLinear() == 1):
physicsMgr.removeLinearForce(force)
else:
physicsMgr.removeAngularForce(force)
"""removeForce(self, force)"""
ForceGroup.ForceGroup.removeForce(force)
if (force.isLinear() == 1):
physicsMgr.removeLinearForce(force)
else:
physicsMgr.removeAngularForce(force)

View File

@ -11,52 +11,52 @@ class ParticleEffect(NodePath):
pid = 1
def __init__(self, name=None, particles=None):
"""__init__()"""
NodePath.__init__(self)
if (name == None):
name = 'particle-effect-%d' % ParticleEffect.pid
ParticleEffect.pid += 1
"""__init__()"""
NodePath.__init__(self)
if (name == None):
name = 'particle-effect-%d' % ParticleEffect.pid
ParticleEffect.pid += 1
self.assign(hidden.attachNewNode(name))
# Record particle effect name
self.name = name
self.name = name
# Enabled flag
self.fEnabled = 0
# Dictionary of particles and forceGroups
self.particlesDict = {}
self.forceGroupDict = {}
self.particlesDict = {}
self.forceGroupDict = {}
# The effect's particle system
if (particles != None):
self.addParticles(particles)
if (particles != None):
self.addParticles(particles)
def cleanup(self):
for f in self.forceGroupDict.values():
f.cleanup()
for p in self.particlesDict.values():
p.cleanup()
forceGroupDict = {}
particlesDict = {}
self.removeNode()
for f in self.forceGroupDict.values():
f.cleanup()
for p in self.particlesDict.values():
p.cleanup()
forceGroupDict = {}
particlesDict = {}
self.removeNode()
def reset(self):
self.removeAllForces()
self.removeAllParticles()
self.forceGroupDict = {}
self.particlesDict = {}
self.removeAllForces()
self.removeAllParticles()
self.forceGroupDict = {}
self.particlesDict = {}
def enable(self):
"""enable()"""
for f in self.forceGroupDict.values():
f.enable()
for p in self.particlesDict.values():
p.enable()
"""enable()"""
for f in self.forceGroupDict.values():
f.enable()
for p in self.particlesDict.values():
p.enable()
self.fEnabled = 1
def disable(self):
"""disable()"""
for f in self.forceGroupDict.values():
f.disable()
for p in self.particlesDict.values():
p.disable()
"""disable()"""
for f in self.forceGroupDict.values():
f.disable()
for p in self.particlesDict.values():
p.disable()
self.fEnabled = 0
def isEnabled(self):
@ -67,65 +67,65 @@ class ParticleEffect(NodePath):
return self.fEnabled
def addForceGroup(self, forceGroup):
"""addForceGroup(forceGroup)"""
forceGroup.nodePath.reparentTo(self)
forceGroup.particleEffect = self
self.forceGroupDict[forceGroup.getName()] = forceGroup
"""addForceGroup(forceGroup)"""
forceGroup.nodePath.reparentTo(self)
forceGroup.particleEffect = self
self.forceGroupDict[forceGroup.getName()] = forceGroup
# Associate the force group with all particles
for f in forceGroup.asList():
self.addForce(f)
# Associate the force group with all particles
for f in forceGroup.asList():
self.addForce(f)
def addForce(self, force):
"""addForce(force)"""
for p in self.particlesDict.values():
p.addForce(force)
"""addForce(force)"""
for p in self.particlesDict.values():
p.addForce(force)
def removeForceGroup(self, forceGroup):
"""removeForceGroup(forceGroup)"""
# Remove forces from all particles
for f in forceGroup.asList():
self.removeForce(f)
"""removeForceGroup(forceGroup)"""
# Remove forces from all particles
for f in forceGroup.asList():
self.removeForce(f)
forceGroup.nodePath.reparentTo(hidden)
forceGroup.particleEffect = None
del self.forceGroupDict[forceGroup.getName()]
forceGroup.nodePath.reparentTo(hidden)
forceGroup.particleEffect = None
del self.forceGroupDict[forceGroup.getName()]
def removeForce(self, force):
"""removeForce(force)"""
for p in self.particlesDict.values():
p.removeForce(force)
"""removeForce(force)"""
for p in self.particlesDict.values():
p.removeForce(force)
def removeAllForces(self):
for fg in self.forceGroupDict.values():
self.removeForceGroup(fg)
for fg in self.forceGroupDict.values():
self.removeForceGroup(fg)
def addParticles(self, particles):
"""addParticles(particles)"""
particles.nodePath.reparentTo(self)
self.particlesDict[particles.getName()] = particles
"""addParticles(particles)"""
particles.nodePath.reparentTo(self)
self.particlesDict[particles.getName()] = particles
# Associate all forces in all force groups with the particles
for fg in self.forceGroupDict.values():
for f in fg.asList():
particles.addForce(f)
# Associate all forces in all force groups with the particles
for fg in self.forceGroupDict.values():
for f in fg.asList():
particles.addForce(f)
def removeParticles(self, particles):
"""removeParticles(particles)"""
if (particles == None):
self.notify.warning('removeParticles() - particles == None!')
return
particles.nodePath.reparentTo(hidden)
del self.particlesDict[particles.getName()]
# Remove all forces from the particles
for fg in self.forceGroupDict.values():
for f in fg.asList():
particles.removeForce(f)
"""removeParticles(particles)"""
if (particles == None):
self.notify.warning('removeParticles() - particles == None!')
return
particles.nodePath.reparentTo(hidden)
del self.particlesDict[particles.getName()]
# Remove all forces from the particles
for fg in self.forceGroupDict.values():
for f in fg.asList():
particles.removeForce(f)
def removeAllParticles(self):
for p in self.particlesDict.values():
self.removeParticles(p)
for p in self.particlesDict.values():
self.removeParticles(p)
def getParticlesList(self):
"""getParticles()"""
@ -157,8 +157,8 @@ class ParticleEffect(NodePath):
# Add a blank line
f.write('\n')
# Make sure we start with a clean slate
f.write('self.reset()\n')
# Make sure we start with a clean slate
f.write('self.reset()\n')
pos = self.getPos()
hpr = self.getHpr()
@ -171,30 +171,30 @@ class ParticleEffect(NodePath):
(scale[0], scale[1], scale[2]))
# Save all the particles to file
num = 0
for p in self.particlesDict.values():
target = 'p%d' % num
num = num + 1
f.write(target + ' = Particles.Particles(\'%s\')\n' % p.getName())
p.printParams(f, target)
f.write('self.addParticles(%s)\n' % target)
num = 0
for p in self.particlesDict.values():
target = 'p%d' % num
num = num + 1
f.write(target + ' = Particles.Particles(\'%s\')\n' % p.getName())
p.printParams(f, target)
f.write('self.addParticles(%s)\n' % target)
# Save all the forces to file
num = 0
for fg in self.forceGroupDict.values():
target = 'f%d' % num
num = num + 1
f.write(target + ' = ForceGroup.ForceGroup(\'%s\')\n' % \
fg.getName())
fg.printParams(f, target)
f.write('self.addForceGroup(%s)\n' % target)
# Save all the forces to file
num = 0
for fg in self.forceGroupDict.values():
target = 'f%d' % num
num = num + 1
f.write(target + ' = ForceGroup.ForceGroup(\'%s\')\n' % \
fg.getName())
fg.printParams(f, target)
f.write('self.addForceGroup(%s)\n' % target)
# Close the file
f.close()
def loadConfig(self, filename):
"""loadConfig(filename)"""
execfile(filename.toOsSpecific())
"""loadConfig(filename)"""
execfile(filename.toOsSpecific())

View File

@ -33,113 +33,113 @@ class Particles(ParticleSystem.ParticleSystem):
id = 1
def __init__(self, name=None, poolSize=1024):
"""__init__(name, poolSize)"""
"""__init__(name, poolSize)"""
if (name == None):
self.name = 'particles-%d' % Particles.id
Particles.id += 1
else:
self.name = name
ParticleSystem.ParticleSystem.__init__(self, poolSize)
self.setBirthRate(0.02)
self.setLitterSize(10)
self.setLitterSpread(0)
if (name == None):
self.name = 'particles-%d' % Particles.id
Particles.id += 1
else:
self.name = name
ParticleSystem.ParticleSystem.__init__(self, poolSize)
self.setBirthRate(0.02)
self.setLitterSize(10)
self.setLitterSpread(0)
# Set up a physical node
self.node = PhysicalNode(self.name)
self.nodePath = hidden.attachNewNode(self.node)
self.setRenderParent(self.node)
self.node.addPhysical(self)
# Set up a physical node
self.node = PhysicalNode(self.name)
self.nodePath = hidden.attachNewNode(self.node)
self.setRenderParent(self.node)
self.node.addPhysical(self)
self.factory = None
self.factoryType = "undefined"
self.setFactory("PointParticleFactory")
self.renderer = None
self.rendererType = "undefined"
self.setRenderer("PointParticleRenderer")
self.emitter = None
self.emitterType = "undefined"
self.setEmitter("SphereVolumeEmitter")
self.factory = None
self.factoryType = "undefined"
self.setFactory("PointParticleFactory")
self.renderer = None
self.rendererType = "undefined"
self.setRenderer("PointParticleRenderer")
self.emitter = None
self.emitterType = "undefined"
self.setEmitter("SphereVolumeEmitter")
# Enable particles by default
self.fEnabled = 0
#self.enable()
# Enable particles by default
self.fEnabled = 0
#self.enable()
def cleanup(self):
self.disable()
self.clearLinearForces()
self.clearAngularForces()
self.setRenderParent(self.node)
self.node.removePhysical(self)
self.nodePath.removeNode()
self.node = None
self.factory = None
self.renderer = None
self.emitter = None
self.disable()
self.clearLinearForces()
self.clearAngularForces()
self.setRenderParent(self.node)
self.node.removePhysical(self)
self.nodePath.removeNode()
self.node = None
self.factory = None
self.renderer = None
self.emitter = None
def enable(self):
"""enable()"""
if (self.fEnabled == 0):
physicsMgr.attachPhysical(self)
particleMgr.attachParticlesystem(self)
"""enable()"""
if (self.fEnabled == 0):
physicsMgr.attachPhysical(self)
particleMgr.attachParticlesystem(self)
self.fEnabled = 1
def disable(self):
"""disable()"""
if (self.fEnabled == 1):
physicsMgr.removePhysical(self)
particleMgr.removeParticlesystem(self)
"""disable()"""
if (self.fEnabled == 1):
physicsMgr.removePhysical(self)
particleMgr.removeParticlesystem(self)
self.fEnabled = 0
def isEnabled(self):
return self.fEnabled
def getNode(self):
return self.node
return self.node
def setFactory(self, type):
"""setFactory(type)"""
if (self.factoryType == type):
return None
if (self.factory):
self.factory = None
self.factoryType = type
if (type == "PointParticleFactory"):
self.factory = PointParticleFactory.PointParticleFactory()
elif (type == "ZSpinParticleFactory"):
self.factory = ZSpinParticleFactory.ZSpinParticleFactory()
elif (type == "OrientedParticleFactory"):
self.factory = OrientedParticleFactory.OrientedParticleFactory()
else:
print "unknown factory type: %s" % type
return None
self.factory.setLifespanBase(0.5)
ParticleSystem.ParticleSystem.setFactory(self, self.factory)
"""setFactory(type)"""
if (self.factoryType == type):
return None
if (self.factory):
self.factory = None
self.factoryType = type
if (type == "PointParticleFactory"):
self.factory = PointParticleFactory.PointParticleFactory()
elif (type == "ZSpinParticleFactory"):
self.factory = ZSpinParticleFactory.ZSpinParticleFactory()
elif (type == "OrientedParticleFactory"):
self.factory = OrientedParticleFactory.OrientedParticleFactory()
else:
print "unknown factory type: %s" % type
return None
self.factory.setLifespanBase(0.5)
ParticleSystem.ParticleSystem.setFactory(self, self.factory)
def setRenderer(self, type):
"""setRenderer(type)"""
if (self.rendererType == type):
return None
if (self.renderer):
self.renderer = None
self.rendererType = type
if (type == "PointParticleRenderer"):
self.renderer = PointParticleRenderer.PointParticleRenderer()
self.renderer.setPointSize(1.0)
elif (type == "LineParticleRenderer"):
self.renderer = LineParticleRenderer.LineParticleRenderer()
elif (type == "GeomParticleRenderer"):
self.renderer = GeomParticleRenderer.GeomParticleRenderer()
npath = hidden.attachNewNode(NamedNode('default-geom'))
"""setRenderer(type)"""
if (self.rendererType == type):
return None
if (self.renderer):
self.renderer = None
self.rendererType = type
if (type == "PointParticleRenderer"):
self.renderer = PointParticleRenderer.PointParticleRenderer()
self.renderer.setPointSize(1.0)
elif (type == "LineParticleRenderer"):
self.renderer = LineParticleRenderer.LineParticleRenderer()
elif (type == "GeomParticleRenderer"):
self.renderer = GeomParticleRenderer.GeomParticleRenderer()
npath = hidden.attachNewNode(NamedNode('default-geom'))
# This was moved here because we do not want to download
# the direct tools with toontown.
import DirectSelection
bbox = DirectSelection.DirectBoundingBox(npath)
self.renderer.setGeomNode(bbox.lines.node())
elif (type == "SparkleParticleRenderer"):
self.renderer = SparkleParticleRenderer.SparkleParticleRenderer()
elif (type == "SpriteParticleRenderer"):
self.renderer = SpriteParticleRenderer.SpriteParticleRenderer()
bbox = DirectSelection.DirectBoundingBox(npath)
self.renderer.setGeomNode(bbox.lines.node())
elif (type == "SparkleParticleRenderer"):
self.renderer = SparkleParticleRenderer.SparkleParticleRenderer()
elif (type == "SpriteParticleRenderer"):
self.renderer = SpriteParticleRenderer.SpriteParticleRenderer()
if (self.renderer.getSourceType() ==
SpriteParticleRenderer.SpriteParticleRenderer.STTexture):
t = loader.loadTexture('phase_3/maps/eyes.jpg')
@ -151,58 +151,58 @@ class Particles(ParticleSystem.ParticleSystem):
# Use default model file and node
# See SpriteParticleRenderer-extensions.py
self.renderer.setTextureFromNode()
else:
print "unknown renderer type: %s" % type
return None
ParticleSystem.ParticleSystem.setRenderer(self, self.renderer)
else:
print "unknown renderer type: %s" % type
return None
ParticleSystem.ParticleSystem.setRenderer(self, self.renderer)
def setEmitter(self, type):
"""setEmitter(type)"""
if (self.emitterType == type):
return None
if (self.emitter):
self.emitter = None
self.emitterType = type
if (type == "BoxEmitter"):
self.emitter = BoxEmitter.BoxEmitter()
elif (type == "DiscEmitter"):
self.emitter = DiscEmitter.DiscEmitter()
elif (type == "LineEmitter"):
self.emitter = LineEmitter.LineEmitter()
elif (type == "PointEmitter"):
self.emitter = PointEmitter.PointEmitter()
elif (type == "RectangleEmitter"):
self.emitter = RectangleEmitter.RectangleEmitter()
elif (type == "RingEmitter"):
self.emitter = RingEmitter.RingEmitter()
elif (type == "SphereSurfaceEmitter"):
self.emitter = SphereSurfaceEmitter.SphereSurfaceEmitter()
elif (type == "SphereVolumeEmitter"):
self.emitter = SphereVolumeEmitter.SphereVolumeEmitter()
self.emitter.setRadius(1.0)
elif (type == "TangentRingEmitter"):
self.emitter = TangentRingEmitter.TangentRingEmitter()
else:
print "unknown emitter type: %s" % type
return None
ParticleSystem.ParticleSystem.setEmitter(self, self.emitter)
"""setEmitter(type)"""
if (self.emitterType == type):
return None
if (self.emitter):
self.emitter = None
self.emitterType = type
if (type == "BoxEmitter"):
self.emitter = BoxEmitter.BoxEmitter()
elif (type == "DiscEmitter"):
self.emitter = DiscEmitter.DiscEmitter()
elif (type == "LineEmitter"):
self.emitter = LineEmitter.LineEmitter()
elif (type == "PointEmitter"):
self.emitter = PointEmitter.PointEmitter()
elif (type == "RectangleEmitter"):
self.emitter = RectangleEmitter.RectangleEmitter()
elif (type == "RingEmitter"):
self.emitter = RingEmitter.RingEmitter()
elif (type == "SphereSurfaceEmitter"):
self.emitter = SphereSurfaceEmitter.SphereSurfaceEmitter()
elif (type == "SphereVolumeEmitter"):
self.emitter = SphereVolumeEmitter.SphereVolumeEmitter()
self.emitter.setRadius(1.0)
elif (type == "TangentRingEmitter"):
self.emitter = TangentRingEmitter.TangentRingEmitter()
else:
print "unknown emitter type: %s" % type
return None
ParticleSystem.ParticleSystem.setEmitter(self, self.emitter)
def addForce(self, force):
"""addForce(force)"""
if (force.isLinear()):
self.addLinearForce(force)
else:
self.addAngularForce(force)
"""addForce(force)"""
if (force.isLinear()):
self.addLinearForce(force)
else:
self.addAngularForce(force)
def removeForce(self, force):
"""removeForce(force)"""
if (force == None):
self.notify.warning('removeForce() - force == None!')
return
if (force.isLinear()):
self.removeLinearForce(force)
else:
self.removeAngularForce(force)
"""removeForce(force)"""
if (force == None):
self.notify.warning('removeForce() - force == None!')
return
if (force.isLinear()):
self.removeLinearForce(force)
else:
self.removeAngularForce(force)
def setRenderNodePath(self, nodePath):
self.setRenderParent(nodePath.node())
@ -222,11 +222,11 @@ class Particles(ParticleSystem.ParticleSystem):
return self.renderer
def printParams(self, file = sys.stdout, targ = 'self'):
"""printParams(file, targ)"""
file.write('# Particles parameters\n')
file.write(targ + '.setFactory(\"' + self.factoryType + '\")\n')
file.write(targ + '.setRenderer(\"' + self.rendererType + '\")\n')
file.write(targ + '.setEmitter(\"' + self.emitterType + '\")\n')
"""printParams(file, targ)"""
file.write('# Particles parameters\n')
file.write(targ + '.setFactory(\"' + self.factoryType + '\")\n')
file.write(targ + '.setRenderer(\"' + self.rendererType + '\")\n')
file.write(targ + '.setEmitter(\"' + self.emitterType + '\")\n')
# System parameters
file.write(targ + ('.setPoolSize(%d)\n' %
@ -243,106 +243,106 @@ class Particles(ParticleSystem.ParticleSystem):
self.getLocalVelocityFlag()))
file.write(targ + ('.setSystemGrowsOlderFlag(%d)\n' %
self.getSystemGrowsOlderFlag()))
file.write('# Factory parameters\n')
file.write(targ + ('.factory.setLifespanBase(%.4f)\n' %
file.write('# Factory parameters\n')
file.write(targ + ('.factory.setLifespanBase(%.4f)\n' %
self.factory.getLifespanBase()))
file.write(targ + '.factory.setLifespanSpread(%.4f)\n' % \
self.factory.getLifespanSpread())
file.write(targ + '.factory.setMassBase(%.4f)\n' % \
self.factory.getMassBase())
file.write(targ + '.factory.setMassSpread(%.4f)\n' % \
self.factory.getMassSpread())
file.write(targ + '.factory.setTerminalVelocityBase(%.4f)\n' % \
self.factory.getTerminalVelocityBase())
file.write(targ + '.factory.setTerminalVelocitySpread(%.4f)\n' % \
self.factory.getTerminalVelocitySpread())
if (self.factoryType == "PointParticleFactory"):
file.write('# Point factory parameters\n')
elif (self.factoryType == "ZSpinParticleFactory"):
file.write('# Z Spin factory parameters\n')
file.write(targ + '.factory.setInitialAngle(%.4f)\n' % \
self.factory.getInitialAngle())
file.write(targ + '.factory.setFinalAngle(%.4f)\n' % \
self.factory.getFinalAngle())
file.write(targ + '.factory.setInitialAngleSpread(%.4f)\n' % \
self.factory.getInitialAngleSpread())
file.write(targ + '.factory.setFinalAngleSpread(%.4f)\n' % \
self.factory.getFinalAngleSpread())
elif (self.factoryType == "OrientedParticleFactory"):
file.write('# Oriented factory parameters\n')
file.write(targ + '.factory.setInitialOrientation(%.4f)\n' % \
self.factory.getInitialOrientation())
file.write(targ + '.factory.setFinalOrientation(%.4f)\n' % \
self.factory.getFinalOrientation())
file.write(targ + '.factory.setLifespanSpread(%.4f)\n' % \
self.factory.getLifespanSpread())
file.write(targ + '.factory.setMassBase(%.4f)\n' % \
self.factory.getMassBase())
file.write(targ + '.factory.setMassSpread(%.4f)\n' % \
self.factory.getMassSpread())
file.write(targ + '.factory.setTerminalVelocityBase(%.4f)\n' % \
self.factory.getTerminalVelocityBase())
file.write(targ + '.factory.setTerminalVelocitySpread(%.4f)\n' % \
self.factory.getTerminalVelocitySpread())
if (self.factoryType == "PointParticleFactory"):
file.write('# Point factory parameters\n')
elif (self.factoryType == "ZSpinParticleFactory"):
file.write('# Z Spin factory parameters\n')
file.write(targ + '.factory.setInitialAngle(%.4f)\n' % \
self.factory.getInitialAngle())
file.write(targ + '.factory.setFinalAngle(%.4f)\n' % \
self.factory.getFinalAngle())
file.write(targ + '.factory.setInitialAngleSpread(%.4f)\n' % \
self.factory.getInitialAngleSpread())
file.write(targ + '.factory.setFinalAngleSpread(%.4f)\n' % \
self.factory.getFinalAngleSpread())
elif (self.factoryType == "OrientedParticleFactory"):
file.write('# Oriented factory parameters\n')
file.write(targ + '.factory.setInitialOrientation(%.4f)\n' % \
self.factory.getInitialOrientation())
file.write(targ + '.factory.setFinalOrientation(%.4f)\n' % \
self.factory.getFinalOrientation())
file.write('# Renderer parameters\n')
alphaMode = self.renderer.getAlphaMode()
aMode = "PRALPHANONE"
if (alphaMode == BaseParticleRenderer.BaseParticleRenderer.PRALPHANONE):
aMode = "PRALPHANONE"
elif (alphaMode ==
BaseParticleRenderer.BaseParticleRenderer.PRALPHAOUT):
aMode = "PRALPHAOUT"
elif (alphaMode ==
BaseParticleRenderer.BaseParticleRenderer.PRALPHAIN):
aMode = "PRALPHAIN"
elif (alphaMode ==
BaseParticleRenderer.BaseParticleRenderer.PRALPHAUSER):
aMode = "PRALPHAUSER"
file.write(targ + '.renderer.setAlphaMode(BaseParticleRenderer.' + aMode + ')\n')
file.write(targ + '.renderer.setUserAlpha(%.2f)\n' % \
self.renderer.getUserAlpha())
if (self.rendererType == "Point"):
file.write('# Point parameters\n')
file.write(targ + '.renderer.setPointSize(%.2f)\n' % \
self.renderer.getPointSize())
sColor = self.renderer.getStartColor()
file.write((targ + '.renderer.setStartColor(Vec4(%.2f, %.2f, %.2f, %.2f))\n' % (sColor[0], sColor[1], sColor[2], sColor[3])))
sColor = self.renderer.getEndColor()
file.write((targ + '.renderer.setEndColor(Vec4(%.2f, %.2f, %.2f, %.2f))\n' % (sColor[0], sColor[1], sColor[2], sColor[3])))
blendType = self.renderer.getBlendType()
bType = "PPONECOLOR"
if (blendType == PointParticleRenderer.PointParticleRenderer.PPONECOLOR):
bType = "PPONECOLOR"
elif (blendType == PointParticleRenderer.PointParticleRenderer.PPBLENDLIFE):
bType = "PPBLENDLIFE"
elif (blendType == PointParticleRenderer.PointParticleRenderer.PPBLENDVEL):
bType = "PPBLENDVEL"
file.write(targ + '.renderer.setBlendType(PointParticleRenderer.' + bType + ')\n')
blendMethod = self.renderer.getBlendMethod()
bMethod = "PPNOBLEND"
if (blendMethod == BaseParticleRenderer.BaseParticleRenderer.PPNOBLEND):
bMethod = "PPNOBLEND"
elif (blendMethod == BaseParticleRenderer.BaseParticleRenderer.PPBLENDLINEAR):
bMethod = "PPBLENDLINEAR"
elif (blendMethod == BaseParticleRenderer.BaseParticleRenderer.PPBLENDCUBIC):
bMethod = "PPBLENDCUBIC"
file.write(targ + '.renderer.setBlendMethod(BaseParticleRenderer.' + bMethod + ')\n')
elif (self.rendererType == "LineParticleRenderer"):
file.write('# Line parameters\n')
sColor = self.renderer.getHeadColor()
file.write((targ + '.renderer.setHeadColor(Vec4(%.2f, %.2f, %.2f, %.2f))\n' % (sColor[0], sColor[1], sColor[2], sColor[3])))
sColor = self.renderer.getTailColor()
file.write((targ + '.renderer.setTailColor(Vec4(%.2f, %.2f, %.2f, %.2f))\n' % (sColor[0], sColor[1], sColor[2], sColor[3])))
elif (self.rendererType == "GeomParticleRenderer"):
file.write('# Geom parameters\n')
node = self.renderer.getGeomNode()
file.write(targ + '.renderer.setGeomNode(' + node.getName() + ')\n')
elif (self.rendererType == "SparkleParticleRenderer"):
file.write('# Sparkle parameters\n')
sColor = self.renderer.getCenterColor()
file.write((targ + '.renderer.setCenterColor(Vec4(%.2f, %.2f, %.2f, %.2f))\n' % (sColor[0], sColor[1], sColor[2], sColor[3])))
sColor = self.renderer.getEdgeColor()
file.write((targ + '.renderer.setEdgeColor(Vec4(%.2f, %.2f, %.2f, %.2f))\n' % (sColor[0], sColor[1], sColor[2], sColor[3])))
file.write(targ + '.renderer.setBirthRadius(%.4f)\n' % self.renderer.getBirthRadius())
file.write(targ + '.renderer.setDeathRadius(%.4f)\n' % self.renderer.getDeathRadius())
lifeScale = self.renderer.getLifeScale()
lScale = "SPNOSCALE"
if (lifeScale == SparkleParticleRenderer.SparkleParticleRenderer.SPSCALE):
lScale = "SPSCALE"
file.write(targ + '.renderer.setLifeScale(SparkleParticleRenderer.' + lScale + ')\n')
elif (self.rendererType == "SpriteParticleRenderer"):
file.write('# Sprite parameters\n')
file.write('# Renderer parameters\n')
alphaMode = self.renderer.getAlphaMode()
aMode = "PRALPHANONE"
if (alphaMode == BaseParticleRenderer.BaseParticleRenderer.PRALPHANONE):
aMode = "PRALPHANONE"
elif (alphaMode ==
BaseParticleRenderer.BaseParticleRenderer.PRALPHAOUT):
aMode = "PRALPHAOUT"
elif (alphaMode ==
BaseParticleRenderer.BaseParticleRenderer.PRALPHAIN):
aMode = "PRALPHAIN"
elif (alphaMode ==
BaseParticleRenderer.BaseParticleRenderer.PRALPHAUSER):
aMode = "PRALPHAUSER"
file.write(targ + '.renderer.setAlphaMode(BaseParticleRenderer.' + aMode + ')\n')
file.write(targ + '.renderer.setUserAlpha(%.2f)\n' % \
self.renderer.getUserAlpha())
if (self.rendererType == "Point"):
file.write('# Point parameters\n')
file.write(targ + '.renderer.setPointSize(%.2f)\n' % \
self.renderer.getPointSize())
sColor = self.renderer.getStartColor()
file.write((targ + '.renderer.setStartColor(Vec4(%.2f, %.2f, %.2f, %.2f))\n' % (sColor[0], sColor[1], sColor[2], sColor[3])))
sColor = self.renderer.getEndColor()
file.write((targ + '.renderer.setEndColor(Vec4(%.2f, %.2f, %.2f, %.2f))\n' % (sColor[0], sColor[1], sColor[2], sColor[3])))
blendType = self.renderer.getBlendType()
bType = "PPONECOLOR"
if (blendType == PointParticleRenderer.PointParticleRenderer.PPONECOLOR):
bType = "PPONECOLOR"
elif (blendType == PointParticleRenderer.PointParticleRenderer.PPBLENDLIFE):
bType = "PPBLENDLIFE"
elif (blendType == PointParticleRenderer.PointParticleRenderer.PPBLENDVEL):
bType = "PPBLENDVEL"
file.write(targ + '.renderer.setBlendType(PointParticleRenderer.' + bType + ')\n')
blendMethod = self.renderer.getBlendMethod()
bMethod = "PPNOBLEND"
if (blendMethod == BaseParticleRenderer.BaseParticleRenderer.PPNOBLEND):
bMethod = "PPNOBLEND"
elif (blendMethod == BaseParticleRenderer.BaseParticleRenderer.PPBLENDLINEAR):
bMethod = "PPBLENDLINEAR"
elif (blendMethod == BaseParticleRenderer.BaseParticleRenderer.PPBLENDCUBIC):
bMethod = "PPBLENDCUBIC"
file.write(targ + '.renderer.setBlendMethod(BaseParticleRenderer.' + bMethod + ')\n')
elif (self.rendererType == "LineParticleRenderer"):
file.write('# Line parameters\n')
sColor = self.renderer.getHeadColor()
file.write((targ + '.renderer.setHeadColor(Vec4(%.2f, %.2f, %.2f, %.2f))\n' % (sColor[0], sColor[1], sColor[2], sColor[3])))
sColor = self.renderer.getTailColor()
file.write((targ + '.renderer.setTailColor(Vec4(%.2f, %.2f, %.2f, %.2f))\n' % (sColor[0], sColor[1], sColor[2], sColor[3])))
elif (self.rendererType == "GeomParticleRenderer"):
file.write('# Geom parameters\n')
node = self.renderer.getGeomNode()
file.write(targ + '.renderer.setGeomNode(' + node.getName() + ')\n')
elif (self.rendererType == "SparkleParticleRenderer"):
file.write('# Sparkle parameters\n')
sColor = self.renderer.getCenterColor()
file.write((targ + '.renderer.setCenterColor(Vec4(%.2f, %.2f, %.2f, %.2f))\n' % (sColor[0], sColor[1], sColor[2], sColor[3])))
sColor = self.renderer.getEdgeColor()
file.write((targ + '.renderer.setEdgeColor(Vec4(%.2f, %.2f, %.2f, %.2f))\n' % (sColor[0], sColor[1], sColor[2], sColor[3])))
file.write(targ + '.renderer.setBirthRadius(%.4f)\n' % self.renderer.getBirthRadius())
file.write(targ + '.renderer.setDeathRadius(%.4f)\n' % self.renderer.getDeathRadius())
lifeScale = self.renderer.getLifeScale()
lScale = "SPNOSCALE"
if (lifeScale == SparkleParticleRenderer.SparkleParticleRenderer.SPSCALE):
lScale = "SPSCALE"
file.write(targ + '.renderer.setLifeScale(SparkleParticleRenderer.' + lScale + ')\n')
elif (self.rendererType == "SpriteParticleRenderer"):
file.write('# Sprite parameters\n')
if (self.renderer.getSourceType() ==
SpriteParticleRenderer.SpriteParticleRenderer.STTexture):
tex = self.renderer.getTexture()
@ -351,88 +351,88 @@ class Particles(ParticleSystem.ParticleSystem):
modelName = self.renderer.getSourceFileName()
nodeName = self.renderer.getSourceNodeName()
file.write(targ + '.renderer.setTextureFromNode("%s", "%s")\n' % (modelName, nodeName))
sColor = self.renderer.getColor()
file.write((targ + '.renderer.setColor(Vec4(%.2f, %.2f, %.2f, %.2f))\n' % (sColor[0], sColor[1], sColor[2], sColor[3])))
file.write(targ + '.renderer.setXScaleFlag(%d)\n' % self.renderer.getXScaleFlag())
file.write(targ + '.renderer.setYScaleFlag(%d)\n' % self.renderer.getYScaleFlag())
file.write(targ + '.renderer.setAnimAngleFlag(%d)\n' % self.renderer.getAnimAngleFlag())
file.write(targ + '.renderer.setInitialXScale(%.4f)\n' % self.renderer.getInitialXScale())
file.write(targ + '.renderer.setFinalXScale(%.4f)\n' % self.renderer.getFinalXScale())
file.write(targ + '.renderer.setInitialYScale(%.4f)\n' % self.renderer.getInitialYScale())
file.write(targ + '.renderer.setFinalYScale(%.4f)\n' % self.renderer.getFinalYScale())
file.write(targ + '.renderer.setNonanimatedTheta(%.4f)\n' % self.renderer.getNonanimatedTheta())
blendMethod = self.renderer.getAlphaBlendMethod()
bMethod = "PPNOBLEND"
if (blendMethod == BaseParticleRenderer.BaseParticleRenderer.PPNOBLEND):
bMethod = "PPNOBLEND"
elif (blendMethod == BaseParticleRenderer.BaseParticleRenderer.PPBLENDLINEAR):
bMethod = "PPBLENDLINEAR"
elif (blendMethod == BaseParticleRenderer.BaseParticleRenderer.PPBLENDCUBIC):
bMethod = "PPBLENDCUBIC"
file.write(targ + '.renderer.setAlphaBlendMethod(BaseParticleRenderer.' + bMethod + ')\n')
file.write(targ + '.renderer.setAlphaDisable(%d)\n' % self.renderer.getAlphaDisable())
sColor = self.renderer.getColor()
file.write((targ + '.renderer.setColor(Vec4(%.2f, %.2f, %.2f, %.2f))\n' % (sColor[0], sColor[1], sColor[2], sColor[3])))
file.write(targ + '.renderer.setXScaleFlag(%d)\n' % self.renderer.getXScaleFlag())
file.write(targ + '.renderer.setYScaleFlag(%d)\n' % self.renderer.getYScaleFlag())
file.write(targ + '.renderer.setAnimAngleFlag(%d)\n' % self.renderer.getAnimAngleFlag())
file.write(targ + '.renderer.setInitialXScale(%.4f)\n' % self.renderer.getInitialXScale())
file.write(targ + '.renderer.setFinalXScale(%.4f)\n' % self.renderer.getFinalXScale())
file.write(targ + '.renderer.setInitialYScale(%.4f)\n' % self.renderer.getInitialYScale())
file.write(targ + '.renderer.setFinalYScale(%.4f)\n' % self.renderer.getFinalYScale())
file.write(targ + '.renderer.setNonanimatedTheta(%.4f)\n' % self.renderer.getNonanimatedTheta())
blendMethod = self.renderer.getAlphaBlendMethod()
bMethod = "PPNOBLEND"
if (blendMethod == BaseParticleRenderer.BaseParticleRenderer.PPNOBLEND):
bMethod = "PPNOBLEND"
elif (blendMethod == BaseParticleRenderer.BaseParticleRenderer.PPBLENDLINEAR):
bMethod = "PPBLENDLINEAR"
elif (blendMethod == BaseParticleRenderer.BaseParticleRenderer.PPBLENDCUBIC):
bMethod = "PPBLENDCUBIC"
file.write(targ + '.renderer.setAlphaBlendMethod(BaseParticleRenderer.' + bMethod + ')\n')
file.write(targ + '.renderer.setAlphaDisable(%d)\n' % self.renderer.getAlphaDisable())
file.write('# Emitter parameters\n')
emissionType = self.emitter.getEmissionType()
eType = "ETEXPLICIT"
if (emissionType == BaseParticleEmitter.BaseParticleEmitter.ETEXPLICIT):
eType = "ETEXPLICIT"
elif (emissionType == BaseParticleEmitter.BaseParticleEmitter.ETRADIATE):
eType = "ETRADIATE"
elif (emissionType == BaseParticleEmitter.BaseParticleEmitter.ETCUSTOM):
eType = "ETCUSTOM"
file.write(targ + '.emitter.setEmissionType(BaseParticleEmitter.' + eType + ')\n')
file.write(targ + '.emitter.setAmplitude(%.4f)\n' % self.emitter.getAmplitude())
file.write(targ + '.emitter.setAmplitudeSpread(%.4f)\n' % self.emitter.getAmplitudeSpread())
oForce = self.emitter.getOffsetForce()
file.write((targ + '.emitter.setOffsetForce(Vec3(%.4f, %.4f, %.4f))\n' % (oForce[0], oForce[1], oForce[2])))
oForce = self.emitter.getExplicitLaunchVector()
file.write((targ + '.emitter.setExplicitLaunchVector(Vec3(%.4f, %.4f, %.4f))\n' % (oForce[0], oForce[1], oForce[2])))
orig = self.emitter.getRadiateOrigin()
file.write((targ + '.emitter.setRadiateOrigin(Point3(%.4f, %.4f, %.4f))\n' % (orig[0], orig[1], orig[2])))
if (self.emitterType == "BoxEmitter"):
file.write('# Box parameters\n')
bound = self.emitter.getMinBound()
file.write((targ + '.emitter.setMinBound(Point3(%.4f, %.4f, %.4f))\n' % (bound[0], bound[1], bound[2])))
bound = self.emitter.getMaxBound()
file.write((targ + '.emitter.setMaxBound(Point3(%.4f, %.4f, %.4f))\n' % (bound[0], bound[1], bound[2])))
elif (self.emitterType == "DiscEmitter"):
file.write('# Disc parameters\n')
file.write(targ + '.emitter.setRadius(%.4f)\n' % self.emitter.getRadius())
if (eType == "ETCUSTOM"):
file.write(targ + '.emitter.setOuterAngle(%.4f)\n' % self.emitter.getOuterAngle())
file.write(targ + '.emitter.setInnerAngle(%.4f)\n' % self.emitter.getInnerAngle())
file.write(targ + '.emitter.setOuterMagnitude(%.4f)\n' % self.emitter.getOuterMagnitude())
file.write(targ + '.emitter.setInnerMagnitude(%.4f)\n' % self.emitter.getInnerMagnitude())
file.write(targ + '.emitter.setCubicLerping(%d)\n' % self.emitter.getCubicLerping())
file.write('# Emitter parameters\n')
emissionType = self.emitter.getEmissionType()
eType = "ETEXPLICIT"
if (emissionType == BaseParticleEmitter.BaseParticleEmitter.ETEXPLICIT):
eType = "ETEXPLICIT"
elif (emissionType == BaseParticleEmitter.BaseParticleEmitter.ETRADIATE):
eType = "ETRADIATE"
elif (emissionType == BaseParticleEmitter.BaseParticleEmitter.ETCUSTOM):
eType = "ETCUSTOM"
file.write(targ + '.emitter.setEmissionType(BaseParticleEmitter.' + eType + ')\n')
file.write(targ + '.emitter.setAmplitude(%.4f)\n' % self.emitter.getAmplitude())
file.write(targ + '.emitter.setAmplitudeSpread(%.4f)\n' % self.emitter.getAmplitudeSpread())
oForce = self.emitter.getOffsetForce()
file.write((targ + '.emitter.setOffsetForce(Vec3(%.4f, %.4f, %.4f))\n' % (oForce[0], oForce[1], oForce[2])))
oForce = self.emitter.getExplicitLaunchVector()
file.write((targ + '.emitter.setExplicitLaunchVector(Vec3(%.4f, %.4f, %.4f))\n' % (oForce[0], oForce[1], oForce[2])))
orig = self.emitter.getRadiateOrigin()
file.write((targ + '.emitter.setRadiateOrigin(Point3(%.4f, %.4f, %.4f))\n' % (orig[0], orig[1], orig[2])))
if (self.emitterType == "BoxEmitter"):
file.write('# Box parameters\n')
bound = self.emitter.getMinBound()
file.write((targ + '.emitter.setMinBound(Point3(%.4f, %.4f, %.4f))\n' % (bound[0], bound[1], bound[2])))
bound = self.emitter.getMaxBound()
file.write((targ + '.emitter.setMaxBound(Point3(%.4f, %.4f, %.4f))\n' % (bound[0], bound[1], bound[2])))
elif (self.emitterType == "DiscEmitter"):
file.write('# Disc parameters\n')
file.write(targ + '.emitter.setRadius(%.4f)\n' % self.emitter.getRadius())
if (eType == "ETCUSTOM"):
file.write(targ + '.emitter.setOuterAngle(%.4f)\n' % self.emitter.getOuterAngle())
file.write(targ + '.emitter.setInnerAngle(%.4f)\n' % self.emitter.getInnerAngle())
file.write(targ + '.emitter.setOuterMagnitude(%.4f)\n' % self.emitter.getOuterMagnitude())
file.write(targ + '.emitter.setInnerMagnitude(%.4f)\n' % self.emitter.getInnerMagnitude())
file.write(targ + '.emitter.setCubicLerping(%d)\n' % self.emitter.getCubicLerping())
elif (self.emitterType == "LineEmitter"):
file.write('# Line parameters\n')
point = self.emitter.getEndpoint1()
file.write((targ + '.emitter.setEndpoint1(Point3(%.4f, %.4f, %.4f))\n' % (point[0], point[1], point[2])))
point = self.emitter.getEndpoint2()
file.write((targ + '.emitter.setEndpoint2(Point3(%.4f, %.4f, %.4f))\n' % (point[0], point[1], point[2])))
elif (self.emitterType == "PointEmitter"):
file.write('# Point parameters\n')
point = self.emitter.getLocation()
file.write((targ + '.emitter.setLocation(Point3(%.4f, %.4f, %.4f))\n' % (point[0], point[1], point[2])))
elif (self.emitterType == "RectangleEmitter"):
file.write('# Rectangle parameters\n')
bound = self.emitter.getMinBound()
file.write((targ + '.emitter.setMinBound(Point2(%.4f, %.4f))\n' % (point[0], point[1])))
bound = self.emitter.getMaxBound()
file.write((targ + '.emitter.setMaxBound(Point2(%.4f, %.4f))\n' % (point[0], point[1])))
elif (self.emitterType == "RingEmitter"):
file.write('# Ring parameters\n')
file.write(targ + '.emitter.setRadius(%.4f)\n' % self.emitter.getRadius())
if (eType == "ETCUSTOM"):
file.write(targ + '.emitter.setAngle(%.4f)\n' % self.emitter.getAngle())
elif (self.emitterType == "SphereSurfaceEmitter"):
file.write('# Sphere Surface parameters\n')
file.write(targ + '.emitter.setRadius(%.4f)\n' % self.emitter.getRadius())
elif (self.emitterType == "SphereVolumeEmitter"):
file.write('# Sphere Volume parameters\n')
file.write(targ + '.emitter.setRadius(%.4f)\n' % self.emitter.getRadius())
elif (self.emitterType == "TangentRingEmitter"):
file.write('# Tangent Ring parameters\n')
file.write(targ + '.emitter.setRadius(%.4f)\n' % self.emitter.getRadius())
elif (self.emitterType == "LineEmitter"):
file.write('# Line parameters\n')
point = self.emitter.getEndpoint1()
file.write((targ + '.emitter.setEndpoint1(Point3(%.4f, %.4f, %.4f))\n' % (point[0], point[1], point[2])))
point = self.emitter.getEndpoint2()
file.write((targ + '.emitter.setEndpoint2(Point3(%.4f, %.4f, %.4f))\n' % (point[0], point[1], point[2])))
elif (self.emitterType == "PointEmitter"):
file.write('# Point parameters\n')
point = self.emitter.getLocation()
file.write((targ + '.emitter.setLocation(Point3(%.4f, %.4f, %.4f))\n' % (point[0], point[1], point[2])))
elif (self.emitterType == "RectangleEmitter"):
file.write('# Rectangle parameters\n')
bound = self.emitter.getMinBound()
file.write((targ + '.emitter.setMinBound(Point2(%.4f, %.4f))\n' % (point[0], point[1])))
bound = self.emitter.getMaxBound()
file.write((targ + '.emitter.setMaxBound(Point2(%.4f, %.4f))\n' % (point[0], point[1])))
elif (self.emitterType == "RingEmitter"):
file.write('# Ring parameters\n')
file.write(targ + '.emitter.setRadius(%.4f)\n' % self.emitter.getRadius())
if (eType == "ETCUSTOM"):
file.write(targ + '.emitter.setAngle(%.4f)\n' % self.emitter.getAngle())
elif (self.emitterType == "SphereSurfaceEmitter"):
file.write('# Sphere Surface parameters\n')
file.write(targ + '.emitter.setRadius(%.4f)\n' % self.emitter.getRadius())
elif (self.emitterType == "SphereVolumeEmitter"):
file.write('# Sphere Volume parameters\n')
file.write(targ + '.emitter.setRadius(%.4f)\n' % self.emitter.getRadius())
elif (self.emitterType == "TangentRingEmitter"):
file.write('# Tangent Ring parameters\n')
file.write(targ + '.emitter.setRadius(%.4f)\n' % self.emitter.getRadius())

View File

@ -404,7 +404,7 @@ class InstallTarget(FullExeTarget):
f.write(txt)
f.close()
dispatch = {
dispatch = {
'PYZ': PYZTarget,
'CARCHIVE': ArchiveTarget,
'COLLECT': CollectTarget,
@ -417,22 +417,22 @@ dispatch = {
def makeTarget(cfg, section):
return dispatch[cfg.get(section, 'type')](cfg, section, optcnvrts)
optdefaults = { 'type':'PYZ',
'script':'', # INSTALL (opt) & STANDALONE (required)
'zlib':'', # INSTALL, STANDALONE, COLLECT
'bindepends':'', # INSTALL, COLLECT
'misc':'', # INSTALL. COLLECT
'includetk': '0', # INSTALL, COLLECT
optdefaults = { 'type':'PYZ',
'script':'', # INSTALL (opt) & STANDALONE (required)
'zlib':'', # INSTALL, STANDALONE, COLLECT
'bindepends':'', # INSTALL, COLLECT
'misc':'', # INSTALL. COLLECT
'includetk': '0', # INSTALL, COLLECT
'userunw': '0', # STANDALONE
'dependencies':'', # PYZ
'directories':'', # PYZ
'excludes':'', # PYZ, INSTALL, COLLECT
'expatterns': '',
'dependencies':'', # PYZ
'directories':'', # PYZ
'excludes':'', # PYZ, INSTALL, COLLECT
'expatterns': '',
'exstdlib' : '0',
'extypes' : '',
'includes':'', # PYZ
'packages':'', # PYZ
'destdir':'', # COLLECT
'includes':'', # PYZ
'packages':'', # PYZ
'destdir':'', # COLLECT
'pathprefix' : '',
'trees' : '',
'debug' : '0',

View File

@ -52,10 +52,10 @@ class Archive:
Check to see if the file object self.lib actually has a file
we understand.
"""
self.lib.seek(self.start) #default - magic is at start of file
self.lib.seek(self.start) #default - magic is at start of file
if self.lib.read(len(self.MAGIC)) != self.MAGIC:
raise RuntimeError, "%s is not a valid %s archive file" \
% (self.path, self.__class__.__name__)
% (self.path, self.__class__.__name__)
if self.lib.read(len(self.pymagic)) != self.pymagic:
raise RuntimeError, "%s has version mismatch to dll" % (self.path)
@ -171,7 +171,7 @@ class Archive:
ispkg = self.os.path.splitext(self.os.path.basename(pth))[0] == '__init__'
self.toc[nm] = (ispkg, self.lib.tell())
f = open(entry[1], 'rb')
f.seek(8) #skip magic and timestamp
f.seek(8) #skip magic and timestamp
self.lib.write(f.read())
def save_toc(self, tocpos):
@ -239,7 +239,7 @@ class ZlibArchive(Archive):
pth = entry[1]
ispkg = self.os.path.splitext(self.os.path.basename(pth))[0] == '__init__'
f = open(pth, 'rb')
f.seek(8) #skip magic and timestamp
f.seek(8) #skip magic and timestamp
obj = zlib.compress(f.read(), self.LEVEL)
self.toc[nm] = (ispkg, self.lib.tell(), len(obj))
self.lib.write(obj)

View File

@ -51,10 +51,10 @@ class Archive:
Check to see if the file object self.lib actually has a file
we understand.
"""
self.lib.seek(self.start) #default - magic is at start of file
self.lib.seek(self.start) #default - magic is at start of file
if self.lib.read(len(self.MAGIC)) != self.MAGIC:
raise RuntimeError, "%s is not a valid %s archive file" \
% (self.path, self.__class__.__name__)
% (self.path, self.__class__.__name__)
if self.lib.read(len(self.pymagic)) != self.pymagic:
raise RuntimeError, "%s has version mismatch to dll" % (self.path)
@ -165,7 +165,7 @@ class Archive:
## ispkg = self.os.path.splitext(self.os.path.basename(pth))[0] == '__init__'
## self.toc[nm] = (ispkg, self.lib.tell())
## f = open(entry[1], 'rb')
## f.seek(8) #skip magic and timestamp
## f.seek(8) #skip magic and timestamp
## self.lib.write(f.read())
##
## def save_toc(self, tocpos):
@ -219,7 +219,7 @@ class ZlibArchive(Archive):
## pth = entry[1]
## ispkg = self.os.path.splitext(self.os.path.basename(pth))[0] == '__init__'
## f = open(pth, 'rb')
## f.seek(8) #skip magic and timestamp
## f.seek(8) #skip magic and timestamp
## obj = zlib.compress(f.read(), self.LEVEL)
## self.toc[nm] = (ispkg, self.lib.tell(), len(obj))
## self.lib.write(obj)

View File

@ -38,7 +38,7 @@ class CTOC:
entrylen = struct.calcsize(self.ENTRYSTRUCT)
rslt = []
for (dpos, dlen, ulen, flag, typcd, nm) in self.data:
nmlen = len(nm) + 1 # add 1 for a '\0'
nmlen = len(nm) + 1 # add 1 for a '\0'
rslt.append(struct.pack(self.ENTRYSTRUCT+`nmlen`+'s',
nmlen+entrylen, dpos, dlen, ulen, flag, typcd, nm+'\0'))
return string.join(rslt, '')
@ -104,10 +104,10 @@ class CArchive(archive.Archive):
else:
self.lib.seek(-self.TRLLEN, 2)
(magic, totallen, tocpos, toclen) = struct.unpack(self.TRLSTRUCT,
self.lib.read(self.TRLLEN))
self.lib.read(self.TRLLEN))
if magic != self.MAGIC:
raise RuntimeError, "%s is not a valid %s archive file" \
% (self.path, self.__class__.__name__)
% (self.path, self.__class__.__name__)
self.pkgstart = filelen - totallen
if self.len:
if totallen != self.len or self.pkgstart != self.start:

View File

@ -36,7 +36,7 @@ class CTOC:
## entrylen = struct.calcsize(self.ENTRYSTRUCT)
## rslt = []
## for (dpos, dlen, ulen, flag, typcd, nm) in self.data:
## nmlen = len(nm) + 1 # add 1 for a '\0'
## nmlen = len(nm) + 1 # add 1 for a '\0'
## rslt.append(struct.pack(self.ENTRYSTRUCT+`nmlen`+'s',
## nmlen+entrylen, dpos, dlen, ulen, flag, typcd, nm+'\0'))
## return string.join(rslt, '')
@ -79,10 +79,10 @@ class CArchive(archive_rt.Archive):
else:
self.lib.seek(-self.TRLLEN, 2)
(magic, totallen, tocpos, toclen) = struct.unpack(self.TRLSTRUCT,
self.lib.read(self.TRLLEN))
self.lib.read(self.TRLLEN))
if magic != self.MAGIC:
raise RuntimeError, "%s is not a valid %s archive file" \
% (self.path, self.__class__.__name__)
% (self.path, self.__class__.__name__)
self.pkgstart = filelen - totallen
if self.len:
if totallen != self.len or self.pkgstart != self.start:

View File

@ -16,7 +16,7 @@ __version__ = '0.3'
import imp
import sys
import strop
import __builtin__ ### why this instead of just using __builtins__ ??
import __builtin__ ### why this instead of just using __builtins__ ??
# for the DirectoryImporter
import struct

View File

@ -30,7 +30,7 @@ class Transitions:
"""
self.noTransitions()
self.fade.reparentTo(aspect2d)
self.fade.reparentTo(aspect2d)
if (t == 0):
# Fade in immediately with no lerp
@ -67,7 +67,7 @@ class Transitions:
"""
self.noTransitions()
self.fade.reparentTo(aspect2d)
self.fade.reparentTo(aspect2d)
if (t == 0):
# Fade out immediately with no lerp
@ -115,8 +115,8 @@ class Transitions:
"""
Removes any current fade tasks and parents the fade polygon away
"""
taskMgr.removeTasksNamed(self.fadeTaskName)
self.fade.reparentTo(hidden)
taskMgr.removeTasksNamed(self.fadeTaskName)
self.fade.reparentTo(hidden)
def irisInLerpDone(self, task):
# This is a helper function to the fadeIn sequence
@ -131,7 +131,7 @@ class Transitions:
scale lerp is finished, it parents the iris polygon to hidden.
If block is true, does not execute lerp, but returns the sequence.
"""
self.noTransitions()
self.noTransitions()
if (t == 0):
self.iris.reparentTo(hidden)
@ -172,7 +172,7 @@ class Transitions:
lerp is finished, it leaves the iris polygon covering the
aspect2d plane until you irisIn or call noIris.
"""
self.noTransitions()
self.noTransitions()
if (t == 0):
self.iris.reparentTo(hidden)
else:
@ -212,8 +212,8 @@ class Transitions:
"""
Removes any current iris tasks and parents the iris polygon away
"""
taskMgr.removeTasksNamed(self.irisTaskName)
self.iris.reparentTo(hidden)
taskMgr.removeTasksNamed(self.irisTaskName)
self.iris.reparentTo(hidden)
# Actually we need to remove the fade to, because the iris effect uses it
self.noFade()
@ -222,5 +222,5 @@ class Transitions:
"""
This call should immediately remove any and all transitions running
"""
self.noFade()
self.noIris()
self.noFade()
self.noIris()

View File

@ -367,10 +367,10 @@ class TaskManager:
return len(removedTasks)
def hasTaskNamed(self, taskName):
for task in self.taskList:
if (task.name == taskName):
return 1
return 0
for task in self.taskList:
if (task.name == taskName):
return 1
return 0
def removeTasksMatching(self, taskPattern):
"""removeTasksMatching(self, string taskPattern)

View File

@ -4,72 +4,72 @@ import Task
class Timer:
def __init__(self):
""" __init__()
"""
self.clock = ClockObject.ClockObject.getGlobalClock()
self.finalT = 0.0
self.currT = 0.0
self.name = 'default-timer'
self.started = 0
""" __init__()
"""
self.clock = ClockObject.ClockObject.getGlobalClock()
self.finalT = 0.0
self.currT = 0.0
self.name = 'default-timer'
self.started = 0
def start(self, t, name):
""" start(t, name)
"""
if (self.started):
self.stop()
self.finalT = t
self.name = name
self.startT = self.clock.getFrameTime()
self.currT = 0.0
taskMgr.spawnMethodNamed(self.__timerTask, self.name + '-run')
self.started = 1
""" start(t, name)
"""
if (self.started):
self.stop()
self.finalT = t
self.name = name
self.startT = self.clock.getFrameTime()
self.currT = 0.0
taskMgr.spawnMethodNamed(self.__timerTask, self.name + '-run')
self.started = 1
def stop(self):
""" stop()
"""
if (not self.started):
return 0.0
taskMgr.removeTasksNamed(self.name + '-run')
self.started = 0
return self.currT
""" stop()
"""
if (not self.started):
return 0.0
taskMgr.removeTasksNamed(self.name + '-run')
self.started = 0
return self.currT
def resume(self):
""" resume()
"""
assert(self.currT <= self.finalT)
assert(self.started == 0)
self.start(self.finalT - self.currT, self.name)
""" resume()
"""
assert(self.currT <= self.finalT)
assert(self.started == 0)
self.start(self.finalT - self.currT, self.name)
def restart(self):
""" restart()
"""
self.start(self.finalT, self.name)
""" restart()
"""
self.start(self.finalT, self.name)
def isStarted(self):
""" isStarted()
"""
return self.started
""" isStarted()
"""
return self.started
def addT(self, t):
""" addT(t)
"""
self.finalT = self.finalT + t
""" addT(t)
"""
self.finalT = self.finalT + t
def setT(self, t):
""" setT(t)
"""
self.finalT = t
""" setT(t)
"""
self.finalT = t
def getT(self):
""" getT()
"""
return (self.finalT - self.currT)
""" getT()
"""
return (self.finalT - self.currT)
def __timerTask(self, task):
t = self.clock.getFrameTime()
te = t - self.startT
self.currT = te
if (te >= self.finalT):
messenger.send(self.name)
return Task.done
return Task.cont
t = self.clock.getFrameTime()
te = t - self.startT
self.currT = te
if (te >= self.finalT):
messenger.send(self.name)
return Task.done
return Task.cont

View File

@ -139,7 +139,7 @@ class DirectSessionPanel(AppShell):
self.bind(self.redoButton, 'Redo last operation')
# The master frame for the dials
mainFrame = Frame(interior)
mainFrame = Frame(interior)
# Paned widget for dividing two halves
framePane = Pmw.PanedWidget(mainFrame, orient = HORIZONTAL)

View File

@ -81,9 +81,9 @@ class MopathRecorder(AppShell, PandaObject):
self.tangentMarker.setColor(1,0,1,1)
self.tangentMarker.setName('Tangent Marker')
self.tangentLines = LineNodePath(self.tangentGroup)
self.tangentLines.setColor(VBase4(1,0,1,1))
self.tangentLines.setThickness(1)
self.tangentLines.moveTo(0,0,0)
self.tangentLines.setColor(VBase4(1,0,1,1))
self.tangentLines.setThickness(1)
self.tangentLines.moveTo(0,0,0)
self.tangentLines.drawTo(0,0,0)
self.tangentLines.create()
# Active node path dictionary
@ -169,7 +169,7 @@ class MopathRecorder(AppShell, PandaObject):
self.accept(event, method)
def createInterface(self):
interior = self.interior()
interior = self.interior()
# FILE MENU
# Get a handle on the file menu so commands can be inserted
# before quit item
@ -546,27 +546,27 @@ class MopathRecorder(AppShell, PandaObject):
initialValue = 5.0,
command = self.setTickScale, side = TOP)
widget.component('hull')['relief'] = RIDGE
self.createColorEntry(
self.createColorEntry(
sfFrame, 'Style', 'Path Color',
'Color of curve',
command = self.setPathColor,
initialValue = [255.0,255.0,255.0,255.0])
self.createColorEntry(
self.createColorEntry(
sfFrame, 'Style', 'Knot Color',
'Color of knots',
command = self.setKnotColor,
initialValue = [0,0,255.0,255.0])
self.createColorEntry(
self.createColorEntry(
sfFrame, 'Style', 'CV Color',
'Color of CVs',
command = self.setCvColor,
initialValue = [255.0,0,0,255.0])
self.createColorEntry(
self.createColorEntry(
sfFrame, 'Style', 'Tick Color',
'Color of Ticks',
command = self.setTickColor,
initialValue = [255.0,0,0,255.0])
self.createColorEntry(
self.createColorEntry(
sfFrame, 'Style', 'Hull Color',
'Color of Hull',
command = self.setHullColor,

View File

@ -37,7 +37,7 @@ class ParticlePanel(AppShell):
self.particleEffect = particleEffect
else:
# Or create a new one if none given
particles = Particles.Particles()
particles = Particles.Particles()
pe = ParticleEffect.ParticleEffect('effect-1', particles)
self.particleEffect = pe
pe.reparentTo(render)
@ -478,14 +478,14 @@ class ParticlePanel(AppShell):
command = self.setRendererUserAlpha)
self.rendererNotebook = Pmw.NoteBook(rendererPage, tabpos = None)
# Line page #
linePage = self.rendererNotebook.add('LineParticleRenderer')
self.createColorEntry(linePage, 'Line Renderer', 'Head Color',
'Head color of line',
command = self.setRendererLineHeadColor)
self.createColorEntry(linePage, 'Line Renderer', 'Tail Color',
'Tail color of line',
command = self.setRendererLineTailColor)
# Line page #
linePage = self.rendererNotebook.add('LineParticleRenderer')
self.createColorEntry(linePage, 'Line Renderer', 'Head Color',
'Head color of line',
command = self.setRendererLineHeadColor)
self.createColorEntry(linePage, 'Line Renderer', 'Tail Color',
'Tail color of line',
command = self.setRendererLineTailColor)
# Geom page #
geomPage = self.rendererNotebook.add('GeomParticleRenderer')
f = Frame(geomPage)
@ -1106,30 +1106,30 @@ class ParticlePanel(AppShell):
self.getVariable('System', 'System Grows Older').set(
self.particles.getSystemGrowsOlderFlag())
def setSystemPoolSize(self, value):
self.particles.setPoolSize(int(value))
self.particles.setPoolSize(int(value))
def setSystemBirthRate(self, value):
self.particles.setBirthRate(value)
self.particles.setBirthRate(value)
def setSystemLitterSize(self, value):
self.particles.setLitterSize(int(value))
self.particles.setLitterSize(int(value))
def setSystemLitterSpread(self, value):
self.particles.setLitterSpread(int(value))
self.particles.setLitterSpread(int(value))
def setSystemLifespan(self, value):
self.particles.setSystemLifespan(value)
self.particles.setSystemLifespan(value)
def toggleSystemLocalVelocity(self):
self.particles.setLocalVelocityFlag(
self.particles.setLocalVelocityFlag(
self.getVariable('System', 'Render Space Velocities').get())
def toggleSystemGrowsOlder(self):
self.particles.setSystemGrowsOlderFlag(
self.particles.setSystemGrowsOlderFlag(
self.getVariable('System', 'System Grows Older').get())
def setSystemPos(self, pos):
self.particles.nodePath.setPos(Vec3(pos[0], pos[1], pos[2]))
self.particles.nodePath.setPos(Vec3(pos[0], pos[1], pos[2]))
def setSystemHpr(self, pos):
self.particles.nodePath.setHpr(Vec3(pos[0], pos[1], pos[2]))
self.particles.nodePath.setHpr(Vec3(pos[0], pos[1], pos[2]))
## FACTORY PAGE ##
def selectFactoryType(self, type):
self.factoryNotebook.selectpage(type)
self.particles.setFactory(type)
self.particles.setFactory(type)
self.updateFactoryWidgets()
def selectFactoryPage(self):
@ -1152,32 +1152,32 @@ class ParticlePanel(AppShell):
terminalVelocitySpread, 0)
def setFactoryLifeSpan(self, value):
self.particles.factory.setLifespanBase(value)
self.particles.factory.setLifespanBase(value)
def setFactoryLifeSpanSpread(self, value):
self.particles.factory.setLifespanSpread(value)
self.particles.factory.setLifespanSpread(value)
def setFactoryParticleMass(self, value):
self.particles.factory.setMassBase(value)
self.particles.factory.setMassBase(value)
def setFactoryParticleMassSpread(self, value):
self.particles.factory.setMassSpread(value)
self.particles.factory.setMassSpread(value)
def setFactoryTerminalVelocity(self, value):
self.particles.factory.setTerminalVelocityBase(value)
self.particles.factory.setTerminalVelocityBase(value)
def setFactoryTerminalVelocitySpread(self, value):
self.particles.factory.setTerminalVelocitySpread(value)
self.particles.factory.setTerminalVelocitySpread(value)
# Point Page #
# Z Spin Page #
def setFactoryZSpinInitialAngle(self, angle):
self.particles.factory.setInitialAngle(angle)
self.particles.factory.setInitialAngle(angle)
def setFactoryZSpinInitialAngleSpread(self, spread):
self.particles.factory.setInitialAngleSpread(spread)
self.particles.factory.setInitialAngleSpread(spread)
def setFactoryZSpinFinalAngle(self, angle):
self.particles.factory.setFinalAngle(angle)
self.particles.factory.setFinalAngle(angle)
def setFactoryZSpinFinalAngleSpread(self, spread):
self.particles.factory.setFinalAngleSpread(spread)
self.particles.factory.setFinalAngleSpread(spread)
## EMITTER PAGE ##
def selectEmitterType(self, type):
self.emitterNotebook.selectpage(type)
self.particles.setEmitter(type)
self.particles.setEmitter(type)
self.updateEmitterWidgets()
def selectEmitterPage(self):
@ -1314,63 +1314,63 @@ class ParticlePanel(AppShell):
# Box #
def setEmitterBoxPoint1(self, point):
self.particles.emitter.setMinBound(Point3(point[0],
self.particles.emitter.setMinBound(Point3(point[0],
point[1],
point[2]))
def setEmitterBoxPoint2(self, point):
self.particles.emitter.setMaxBound(Point3(point[0],
self.particles.emitter.setMaxBound(Point3(point[0],
point[1],
point[2]))
# Disc #
def setEmitterDiscRadius(self, radius):
self.particles.emitter.setRadius(radius)
self.particles.emitter.setRadius(radius)
def setEmitterDiscInnerAngle(self, angle):
self.particles.emitter.setInnerAngle(angle)
self.particles.emitter.setInnerAngle(angle)
def setEmitterDiscInnerVelocity(self, velocity):
self.particles.emitter.setInnerMagnitude(velocity)
def setEmitterDiscOuterAngle(self, angle):
self.particles.emitter.setOuterAngle(angle)
self.particles.emitter.setOuterAngle(angle)
def setEmitterDiscOuterVelocity(self, velocity):
self.particles.emitter.setOuterMagnitude(velocity)
def toggleEmitterDiscCubicLerping(self):
self.particles.emitter.setCubicLerping(
self.particles.emitter.setCubicLerping(
self.getVariable('Disc Emitter', 'Cubic Lerping').get())
# Line #
def setEmitterLinePoint1(self, point):
self.particles.emitter.setEndpoint1(Point3(point[0],
self.particles.emitter.setEndpoint1(Point3(point[0],
point[1],
point[2]))
def setEmitterLinePoint2(self, point):
self.particles.emitter.setEndpoint2(Point3(point[0],
self.particles.emitter.setEndpoint2(Point3(point[0],
point[1],
point[2]))
# Point #
def setEmitterPointPosition(self, pos):
self.particles.emitter.setLocation(Point3(pos[0], pos[1], pos[2]))
self.particles.emitter.setLocation(Point3(pos[0], pos[1], pos[2]))
# Rectangle #
def setEmitterRectanglePoint1(self, point):
self.particles.emitter.setMinBound(Point2(point[0], point[1]))
self.particles.emitter.setMinBound(Point2(point[0], point[1]))
def setEmitterRectanglePoint2(self, point):
self.particles.emitter.setMaxBound(Point2(point[0], point[1]))
self.particles.emitter.setMaxBound(Point2(point[0], point[1]))
# Ring #
def setEmitterRingRadius(self, radius):
self.particles.emitter.setRadius(radius)
self.particles.emitter.setRadius(radius)
def setEmitterRingLaunchAngle(self, angle):
self.particles.emitter.setAngle(angle)
self.particles.emitter.setAngle(angle)
# Sphere surface #
def setEmitterSphereSurfaceRadius(self, radius):
self.particles.emitter.setRadius(radius)
self.particles.emitter.setRadius(radius)
# Sphere volume #
def setEmitterSphereVolumeRadius(self, radius):
self.particles.emitter.setRadius(radius)
self.particles.emitter.setRadius(radius)
# Tangent ring #
def setEmitterTangentRingRadius(self, radius):
self.particles.emitter.setRadius(radius)
self.particles.emitter.setRadius(radius)
## RENDERER PAGE ##
def selectRendererType(self, type):
self.rendererNotebook.selectpage(type)
self.particles.setRenderer(type)
self.particles.setRenderer(type)
self.updateRendererWidgets()
def updateRendererWidgets(self):
@ -1406,21 +1406,21 @@ class ParticlePanel(AppShell):
self.getWidget('Point Renderer', 'End Color').set(
[endColor[0], endColor[1], endColor[2], endColor[3]])
blendType = renderer.getBlendType()
if (blendType == PointParticleRenderer.PPONECOLOR):
bType = "PP_ONE_COLOR"
elif (blendType == PointParticleRenderer.PPBLENDLIFE):
bType = "PP_BLEND_LIFE"
elif (blendType == PointParticleRenderer.PPBLENDVEL):
bType = "PP_BLEND_VEL"
if (blendType == PointParticleRenderer.PPONECOLOR):
bType = "PP_ONE_COLOR"
elif (blendType == PointParticleRenderer.PPBLENDLIFE):
bType = "PP_BLEND_LIFE"
elif (blendType == PointParticleRenderer.PPBLENDVEL):
bType = "PP_BLEND_VEL"
self.getVariable('Point Renderer', 'Blend Type').set(bType)
blendMethod = renderer.getBlendMethod()
bMethod = "PP_NO_BLEND"
if (blendMethod == BaseParticleRenderer.PPNOBLEND):
bMethod = "PP_NO_BLEND"
elif (blendMethod == BaseParticleRenderer.PPBLENDLINEAR):
bMethod = "PP_BLEND_LINEAR"
elif (blendMethod == BaseParticleRenderer.PPBLENDCUBIC):
bMethod = "PP_BLEND_CUBIC"
bMethod = "PP_NO_BLEND"
if (blendMethod == BaseParticleRenderer.PPNOBLEND):
bMethod = "PP_NO_BLEND"
elif (blendMethod == BaseParticleRenderer.PPBLENDLINEAR):
bMethod = "PP_BLEND_LINEAR"
elif (blendMethod == BaseParticleRenderer.PPBLENDCUBIC):
bMethod = "PP_BLEND_CUBIC"
self.getVariable('Point Renderer', 'Blend Method').set(bMethod)
elif isinstance(renderer, SparkleParticleRenderer):
centerColor = renderer.getCenterColor() * 255.0
@ -1435,15 +1435,15 @@ class ParticlePanel(AppShell):
deathRadius = renderer.getDeathRadius()
self.getWidget('Sparkle Renderer', 'Death Radius').set(deathRadius)
lifeScale = renderer.getLifeScale()
lScale = "SP_NO_SCALE"
if (lifeScale == SparkleParticleRenderer.SPSCALE):
lScale = "SP_SCALE"
lScale = "SP_NO_SCALE"
if (lifeScale == SparkleParticleRenderer.SPSCALE):
lScale = "SP_SCALE"
self.getVariable('Sparkle Renderer', 'Life Scale').set(lScale)
elif isinstance(renderer, SpriteParticleRenderer):
color = renderer.getColor() * 255.0
texture = renderer.getTexture()
if (texture != None):
self.rendererSpriteTexture.set(texture.getName())
if (texture != None):
self.rendererSpriteTexture.set(texture.getName())
fileName = renderer.getSourceFileName()
if fileName != None:
self.rendererSpriteFile.set(fileName)
@ -1472,13 +1472,13 @@ class ParticlePanel(AppShell):
self.getWidget('Sprite Renderer', 'Non Animated Theta').set(
nonanimatedTheta)
blendMethod = renderer.getAlphaBlendMethod()
bMethod = "PP_NO_BLEND"
if (blendMethod == BaseParticleRenderer.PPNOBLEND):
bMethod = "PP_NO_BLEND"
elif (blendMethod == BaseParticleRenderer.PPBLENDLINEAR):
bMethod = "PP_BLEND_LINEAR"
elif (blendMethod == BaseParticleRenderer.PPBLENDCUBIC):
bMethod = "PP_BLEND_CUBIC"
bMethod = "PP_NO_BLEND"
if (blendMethod == BaseParticleRenderer.PPNOBLEND):
bMethod = "PP_NO_BLEND"
elif (blendMethod == BaseParticleRenderer.PPBLENDLINEAR):
bMethod = "PP_BLEND_LINEAR"
elif (blendMethod == BaseParticleRenderer.PPBLENDCUBIC):
bMethod = "PP_BLEND_CUBIC"
self.getVariable('Sprite Renderer', 'Alpha Disable').set(
renderer.getAlphaDisable())
@ -1504,30 +1504,30 @@ class ParticlePanel(AppShell):
# Line #
def setRendererLineHeadColor(self, color):
self.particles.renderer.setHeadColor(
self.particles.renderer.setHeadColor(
Vec4(color[0]/255.0, color[1]/255.0,
color[2]/255.0, color[3]/255.0))
def setRendererLineTailColor(self, color):
self.particles.renderer.setTailColor(
self.particles.renderer.setTailColor(
Vec4(color[0]/255.0, color[1]/255.0,
color[2]/255.0, color[3]/255.0))
# Geom #
def setRendererGeomNode(self, event):
node = None
nodePath = loader.loadModel(self.rendererGeomNode.get())
nodePath = loader.loadModel(self.rendererGeomNode.get())
if nodePath != None:
node = nodePath.node()
if (node != None):
if (node != None):
self.particles.renderer.setGeomNode(node)
# Point #
def setRendererPointSize(self, size):
self.particles.renderer.setPointSize(size)
self.particles.renderer.setPointSize(size)
def setRendererPointStartColor(self, color):
self.particles.renderer.setStartColor(
self.particles.renderer.setStartColor(
Vec4(color[0]/255.0, color[1]/255.0,
color[2]/255.0, color[3]/255.0))
def setRendererPointEndColor(self, color):
self.particles.renderer.setEndColor(
self.particles.renderer.setEndColor(
Vec4(color[0]/255.0, color[1]/255.0,
color[2]/255.0, color[3]/255.0))
def rendererPointSelectBlendType(self, blendType):
@ -1537,7 +1537,7 @@ class ParticlePanel(AppShell):
bType = PointParticleRenderer.PPBLENDLIFE
elif blendType == "PP_BLEND_VEL":
bType = PointParticleRenderer.PPBLENDVEL
self.particles.renderer.setBlendType(bType)
self.particles.renderer.setBlendType(bType)
def rendererPointSelectBlendMethod(self, blendMethod):
if blendMethod == "PP_NO_BLEND":
bMethod = BaseParticleRenderer.PPNOBLEND
@ -1545,26 +1545,26 @@ class ParticlePanel(AppShell):
bMethod = BaseParticleRenderer.PPBLENDLINEAR
elif blendMethod == "PP_BLEND_CUBIC":
bMethod = BaseParticleRenderer.PPBLENDCUBIC
self.particles.renderer.setBlendMethod(bMethod)
self.particles.renderer.setBlendMethod(bMethod)
# Sparkle #
def setRendererSparkleCenterColor(self, color):
self.particles.renderer.setCenterColor(
self.particles.renderer.setCenterColor(
Vec4(color[0]/255.0, color[1]/255.0,
color[2]/255.0, color[3]/255.0))
def setRendererSparkleEdgeColor(self, color):
self.particles.renderer.setEdgeColor(
self.particles.renderer.setEdgeColor(
Vec4(color[0]/255.0, color[1]/255.0,
color[2]/255.0, color[3]/255.0))
def setRendererSparkleBirthRadius(self, radius):
self.particles.renderer.setBirthRadius(radius)
self.particles.renderer.setBirthRadius(radius)
def setRendererSparkleDeathRadius(self, radius):
self.particles.renderer.setDeathRadius(radius)
self.particles.renderer.setDeathRadius(radius)
def setRendererSparkleLifeScale(self, lifeScaleMethod):
if lifeScaleMethod == 'SP_NO_SCALE':
lScale = SparkleParticleRenderer.SPNOSCALE
else:
lScale = SparkleParticleRenderer.SPSCALE
self.particles.renderer.setLifeScale(lScale)
self.particles.renderer.setLifeScale(lScale)
# Sprite #
def setSpriteSourceType(self):
if self.rendererSpriteSourceType.get() == SpriteParticleRenderer.STTexture:
@ -1592,24 +1592,24 @@ class ParticlePanel(AppShell):
self.particles.renderer.setTextureFromNode(
self.rendererSpriteFile.get(), self.rendererSpriteNode.get())
def toggleRendererSpriteXScale(self):
self.particles.renderer.setXScaleFlag(
self.particles.renderer.setXScaleFlag(
self.getVariable('Sprite Renderer', 'X Scale').get())
def toggleRendererSpriteYScale(self):
self.particles.renderer.setYScaleFlag(
self.particles.renderer.setYScaleFlag(
self.getVariable('Sprite Renderer', 'Y Scale').get())
def toggleRendererSpriteAnimAngle(self):
self.particles.renderer.setAnimAngleFlag(
self.particles.renderer.setAnimAngleFlag(
self.getVariable('Sprite Renderer', 'Anim Angle').get())
def setRendererSpriteInitialXScale(self, xScale):
self.particles.renderer.setInitialXScale(xScale)
self.particles.renderer.setInitialXScale(xScale)
def setRendererSpriteFinalXScale(self, xScale):
self.particles.renderer.setFinalXScale(xScale)
self.particles.renderer.setFinalXScale(xScale)
def setRendererSpriteInitialYScale(self, yScale):
self.particles.renderer.setInitialYScale(yScale)
self.particles.renderer.setInitialYScale(yScale)
def setRendererSpriteFinalYScale(self, yScale):
self.particles.renderer.setFinalYScale(yScale)
self.particles.renderer.setFinalYScale(yScale)
def setRendererSpriteNonAnimatedTheta(self, theta):
self.particles.renderer.setNonanimatedTheta(theta)
self.particles.renderer.setNonanimatedTheta(theta)
def setRendererSpriteBlendMethod(self, blendMethod):
print blendMethod
if blendMethod == 'PP_NO_BLEND':
@ -1620,9 +1620,9 @@ class ParticlePanel(AppShell):
bMethod = BaseParticleRenderer.PPBLENDCUBIC
else:
bMethod = BaseParticleRenderer.PPNOBLEND
self.particles.renderer.setAlphaBlendMethod(bMethod)
self.particles.renderer.setAlphaBlendMethod(bMethod)
def toggleRendererSpriteAlphaDisable(self):
self.particles.renderer.setAlphaDisable(
self.particles.renderer.setAlphaDisable(
self.getVariable('Sprite Renderer', 'Alpha Disable').get())
## FORCEGROUP COMMANDS ##

View File

@ -160,28 +160,28 @@ class Placer(AppShell):
self.bind(self.redoButton, 'Redo last operation')
# The master frame for the dials
dialFrame = Frame(interior)
dialFrame = Frame(interior)
dialFrame.pack(fill = 'both', expand = 1)
# Create and pack the Pos Controls
posGroup = Pmw.Group(dialFrame,
# Create and pack the Pos Controls
posGroup = Pmw.Group(dialFrame,
tag_pyclass = Menubutton,
tag_text = 'Position',
tag_font=('MSSansSerif', 14, 'bold'),
tag_activebackground = '#909090',
ring_relief = 'flat')
posMenubutton = posGroup.component('tag')
posMenubutton = posGroup.component('tag')
self.bind(posMenubutton, 'Position menu operations')
posMenu = Menu(posMenubutton)
posMenu.add_command(label = 'Set to zero', command = self.zeroPos)
posMenu.add_command(label = 'Reset initial',
posMenu = Menu(posMenubutton)
posMenu.add_command(label = 'Set to zero', command = self.zeroPos)
posMenu.add_command(label = 'Reset initial',
command = self.resetPos)
posMenubutton['menu'] = posMenu
posGroup.pack(side='left', fill = 'both', expand = 1)
posMenubutton['menu'] = posMenu
posGroup.pack(side='left', fill = 'both', expand = 1)
posInterior = posGroup.interior()
# Create the dials
self.posX = self.createcomponent('posX', (), None,
self.posX = self.createcomponent('posX', (), None,
Floater.Floater, (posInterior,),
text = 'X',
initialValue = 0.0,
@ -195,7 +195,7 @@ class Placer(AppShell):
self.posX.onRelease = self.xformStop
self.posX.pack(expand=1,fill='both')
self.posY = self.createcomponent('posY', (), None,
self.posY = self.createcomponent('posY', (), None,
Floater.Floater, (posInterior,),
text = 'Y',
initialValue = 0.0,
@ -209,7 +209,7 @@ class Placer(AppShell):
self.posY.onRelease = self.xformStop
self.posY.pack(expand=1,fill='both')
self.posZ = self.createcomponent('posZ', (), None,
self.posZ = self.createcomponent('posZ', (), None,
Floater.Floater, (posInterior,),
text = 'Z',
initialValue = 0.0,
@ -223,24 +223,24 @@ class Placer(AppShell):
self.posZ.onRelease = self.xformStop
self.posZ.pack(expand=1,fill='both')
# Create and pack the Hpr Controls
hprGroup = Pmw.Group(dialFrame,
# Create and pack the Hpr Controls
hprGroup = Pmw.Group(dialFrame,
tag_pyclass = Menubutton,
tag_text = 'Orientation',
tag_font=('MSSansSerif', 14, 'bold'),
tag_activebackground = '#909090',
ring_relief = 'flat')
hprMenubutton = hprGroup.component('tag')
hprMenubutton = hprGroup.component('tag')
self.bind(hprMenubutton, 'Orientation menu operations')
hprMenu = Menu(hprMenubutton)
hprMenu.add_command(label = 'Set to zero', command = self.zeroHpr)
hprMenu.add_command(label = 'Reset initial', command = self.resetHpr)
hprMenubutton['menu'] = hprMenu
hprGroup.pack(side='left',fill = 'both', expand = 1)
hprMenu = Menu(hprMenubutton)
hprMenu.add_command(label = 'Set to zero', command = self.zeroHpr)
hprMenu.add_command(label = 'Reset initial', command = self.resetHpr)
hprMenubutton['menu'] = hprMenu
hprGroup.pack(side='left',fill = 'both', expand = 1)
hprInterior = hprGroup.interior()
# Create the dials
self.hprH = self.createcomponent('hprH', (), None,
# Create the dials
self.hprH = self.createcomponent('hprH', (), None,
Dial.Dial, (hprInterior,),
text = 'H', fRollover = 0,
max = 360.0, numTicks = 12,
@ -255,7 +255,7 @@ class Placer(AppShell):
self.hprH.onRelease = self.xformStop
self.hprH.pack(expand=1,fill='both')
self.hprP = self.createcomponent('hprP', (), None,
self.hprP = self.createcomponent('hprP', (), None,
Dial.Dial, (hprInterior,),
text = 'P', fRollover = 0,
max = 360.0, numTicks = 12,
@ -270,7 +270,7 @@ class Placer(AppShell):
self.hprP.onRelease = self.xformStop
self.hprP.pack(expand=1,fill='both')
self.hprR = self.createcomponent('hprR', (), None,
self.hprR = self.createcomponent('hprR', (), None,
Dial.Dial, (hprInterior,),
text = 'R', fRollover = 0,
max = 360.0, numTicks = 12,
@ -286,39 +286,39 @@ class Placer(AppShell):
self.hprR.pack(expand=1,fill='both')
# Create and pack the Scale Controls
# The available scaling modes
self.scalingMode = StringVar()
self.scalingMode.set('Scale Uniform')
# The available scaling modes
self.scalingMode = StringVar()
self.scalingMode.set('Scale Uniform')
# The scaling widgets
scaleGroup = Pmw.Group(dialFrame,
scaleGroup = Pmw.Group(dialFrame,
tag_text = 'Scale Uniform',
tag_pyclass = Menubutton,
tag_font=('MSSansSerif', 14, 'bold'),
tag_activebackground = '#909090',
ring_relief = 'flat')
self.scaleMenubutton = scaleGroup.component('tag')
self.scaleMenubutton = scaleGroup.component('tag')
self.bind(self.scaleMenubutton, 'Scale menu operations')
self.scaleMenubutton['textvariable'] = self.scalingMode
# Scaling menu
scaleMenu = Menu(self.scaleMenubutton)
scaleMenu.add_command(label = 'Set to unity',
# Scaling menu
scaleMenu = Menu(self.scaleMenubutton)
scaleMenu.add_command(label = 'Set to unity',
command = self.unitScale)
scaleMenu.add_command(label = 'Reset initial',
scaleMenu.add_command(label = 'Reset initial',
command = self.resetScale)
scaleMenu.add_radiobutton(label = 'Scale Free',
scaleMenu.add_radiobutton(label = 'Scale Free',
variable = self.scalingMode)
scaleMenu.add_radiobutton(label = 'Scale Uniform',
scaleMenu.add_radiobutton(label = 'Scale Uniform',
variable = self.scalingMode)
scaleMenu.add_radiobutton(label = 'Scale Proportional',
scaleMenu.add_radiobutton(label = 'Scale Proportional',
variable = self.scalingMode)
self.scaleMenubutton['menu'] = scaleMenu
self.scaleMenubutton['menu'] = scaleMenu
# Pack group widgets
scaleGroup.pack(side='left',fill = 'both', expand = 1)
scaleGroup.pack(side='left',fill = 'both', expand = 1)
scaleInterior = scaleGroup.interior()
# Create the dials
self.scaleX = self.createcomponent('scaleX', (), None,
# Create the dials
self.scaleX = self.createcomponent('scaleX', (), None,
Dial.Dial, (scaleInterior,),
text = 'X Scale',
initialValue = 1.0,
@ -332,7 +332,7 @@ class Placer(AppShell):
self.scaleX.onRelease = self.xformStop
self.scaleX.pack(expand=1,fill='both')
self.scaleY = self.createcomponent('scaleY', (), None,
self.scaleY = self.createcomponent('scaleY', (), None,
Dial.Dial, (scaleInterior,),
text = 'Y Scale',
initialValue = 1.0,
@ -346,7 +346,7 @@ class Placer(AppShell):
self.scaleY.onRelease = self.xformStop
self.scaleY.pack(expand=1,fill='both')
self.scaleZ = self.createcomponent('scaleZ', (), None,
self.scaleZ = self.createcomponent('scaleZ', (), None,
Dial.Dial, (scaleInterior,),
text = 'Z Scale',
initialValue = 1.0,
@ -674,7 +674,7 @@ class Placer(AppShell):
sf = value/scale[0]
elif axis == 'sy':
sf = value/scale[1]
elif axis == 'sz':
elif axis == 'sz':
sf = value/scale[2]
scale = scale * sf
self['nodePath'].setScale(scale)

View File

@ -211,9 +211,9 @@ class AppShell(Pmw.MegaWidget, PandaObject):
return None
def toggleBalloon(self):
if self.toggleBalloonVar.get():
if self.toggleBalloonVar.get():
self.__balloon.configure(state = 'both')
else:
else:
self.__balloon.configure(state = 'status')
def showAbout(self):
@ -274,7 +274,7 @@ class AppShell(Pmw.MegaWidget, PandaObject):
def messageBar(self):
# Retieve the message bar
return self.__messageBar
return self.__messageBar
# Utility functions
def buttonAdd(self, buttonName, helpMessage=None,

View File

@ -7,36 +7,36 @@ class ProgressBar:
def __init__(self, master=None, orientation="horizontal",
min=0, max=100, width=100, height=18,
doLabel=1, appearance="sunken",
fillColor="blue", background="gray",
fillColor="blue", background="gray",
labelColor="yellow", labelFont="Verdana",
labelText="", labelFormat="%d%%",
value=50, bd=2):
# preserve various values
self.master=master
self.orientation=orientation
self.min=min
self.max=max
self.width=width
self.height=height
self.doLabel=doLabel
self.fillColor=fillColor
# preserve various values
self.master=master
self.orientation=orientation
self.min=min
self.max=max
self.width=width
self.height=height
self.doLabel=doLabel
self.fillColor=fillColor
self.labelFont= labelFont
self.labelColor=labelColor
self.background=background
self.labelText=labelText
self.labelFormat=labelFormat
self.value=value
self.frame=Frame(master, relief=appearance, bd=bd)
self.canvas=Canvas(self.frame, height=height, width=width, bd=0,
self.labelColor=labelColor
self.background=background
self.labelText=labelText
self.labelFormat=labelFormat
self.value=value
self.frame=Frame(master, relief=appearance, bd=bd)
self.canvas=Canvas(self.frame, height=height, width=width, bd=0,
highlightthickness=0, background=background)
self.scale=self.canvas.create_rectangle(0, 0, width, height,
fill=fillColor)
self.label=self.canvas.create_text(self.canvas.winfo_reqwidth() / 2,
height / 2, text=labelText,
anchor="c", fill=labelColor,
font=self.labelFont)
self.update()
self.canvas.pack(side='top', fill='x', expand='no')
self.scale=self.canvas.create_rectangle(0, 0, width, height,
fill=fillColor)
self.label=self.canvas.create_text(self.canvas.winfo_reqwidth() / 2,
height / 2, text=labelText,
anchor="c", fill=labelColor,
font=self.labelFont)
self.update()
self.canvas.pack(side='top', fill='x', expand='no')
def updateProgress(self, newValue, newMax=None):
if newMax:
@ -45,25 +45,25 @@ class ProgressBar:
self.update()
def update(self):
# Trim the values to be between min and max
value=self.value
if value > self.max:
value = self.max
if value < self.min:
value = self.min
# Adjust the rectangle
if self.orientation == "horizontal":
self.canvas.coords(self.scale, 0, 0,
float(value) / self.max * self.width, self.height)
else:
self.canvas.coords(self.scale, 0,
# Trim the values to be between min and max
value=self.value
if value > self.max:
value = self.max
if value < self.min:
value = self.min
# Adjust the rectangle
if self.orientation == "horizontal":
self.canvas.coords(self.scale, 0, 0,
float(value) / self.max * self.width, self.height)
else:
self.canvas.coords(self.scale, 0,
self.height - (float(value) / self.max*self.height),
self.width, self.height)
# Now update the colors
self.canvas.itemconfig(self.scale, fill=self.fillColor)
self.canvas.itemconfig(self.label, fill=self.labelColor)
# And update the label
if self.doLabel:
self.width, self.height)
# Now update the colors
self.canvas.itemconfig(self.scale, fill=self.fillColor)
self.canvas.itemconfig(self.label, fill=self.labelColor)
# And update the label
if self.doLabel:
if value:
if value >= 0:
pvalue = int((float(value) / float(self.max)) * 100.0)
@ -73,7 +73,7 @@ class ProgressBar:
text=self.labelFormat % value)
else:
self.canvas.itemconfig(self.label, text='')
else:
self.canvas.itemconfig(self.label,
else:
self.canvas.itemconfig(self.label,
text=self.labelFormat % self.labelText)
self.canvas.update_idletasks()
self.canvas.update_idletasks()