formatting

This commit is contained in:
Dave Schuyler 2006-03-17 23:47:12 +00:00
parent 64a75159c6
commit a2aa9486d1
40 changed files with 1211 additions and 1211 deletions

View File

@ -6,7 +6,7 @@
def __repr__(self):
return '%s(\n%s,\n%s,\n%s)' % (
self.__class__.__name__,self.getRow(0).pPrintValues(), self.getRow(1).pPrintValues(), self.getRow(2).pPrintValues())
self.__class__.__name__, self.getRow(0).pPrintValues(), self.getRow(1).pPrintValues(), self.getRow(2).pPrintValues())
def pPrintValues(self):
"""

View File

@ -5,7 +5,7 @@ from libdirect import *
from direct.directnotify.DirectNotifyGlobal import directNotify
notify = directNotify.newCategory("Interval")
Dtool_ObjectToDict(CInterval,"notify", notify)
Dtool_ObjectToDict(CInterval,"notify", notify)
del notify
#####################################################################
def setT(self, t):
@ -16,26 +16,26 @@ def setT(self, t):
self.privPostEvent()
Dtool_ObjectToDict(CInterval, "setT_Old", CInterval.setT)
Dtool_funcToMethod(setT, CInterval)
Dtool_funcToMethod(setT, CInterval)
del setT
#####################################################################
def play(self, t0 = 0.0, duration = None, scale = 1.0):
self.notify.error("using deprecated CInterval.play() interface")
if duration: # None or 0 implies full length
self.start(t0, t0 + duration, scale)
else:
self.start(t0, -1, scale)
Dtool_funcToMethod(play, CInterval)
Dtool_funcToMethod(play, CInterval)
del play
#####################################################################
def stop(self):
self.notify.error("using deprecated CInterval.stop() interface")
self.finish()
Dtool_funcToMethod(stop, CInterval)
Dtool_funcToMethod(stop, CInterval)
del stop
#####################################################################
@ -43,7 +43,7 @@ def setFinalT(self):
self.notify.error("using deprecated CInterval.setFinalT() interface")
self.finish()
Dtool_funcToMethod(setFinalT, CInterval)
Dtool_funcToMethod(setFinalT, CInterval)
del setFinalT
#####################################################################
@ -55,7 +55,7 @@ def privPostEvent(self):
for func in self.setTHooks:
func(t)
Dtool_funcToMethod(privPostEvent, CInterval)
Dtool_funcToMethod(privPostEvent, CInterval)
del privPostEvent
#####################################################################
@ -70,7 +70,7 @@ def popupControls(self, tl = None):
tl = Toplevel()
tl.title('Interval Controls')
outerFrame = Frame(tl)
def entryScaleCommand(t,s=self):
def entryScaleCommand(t, s=self):
s.setT(t)
s.pause()
self.es = es = EntryScale.EntryScale(
@ -91,7 +91,7 @@ def popupControls(self, tl = None):
# Stop/play buttons
def doPlay(s=self, es=es):
s.resume(es.get())
stop = Button(bf, text = 'Stop',
command = lambda s=self: s.pause())
play = Button(
@ -105,7 +105,7 @@ def popupControls(self, tl = None):
bf.pack(expand = 1, fill = X)
outerFrame.pack(expand = 1, fill = X)
# Add function to update slider during setT calls
def update(t,es=es):
def update(t, es=es):
es.set(t, fCommand = 0)
if not hasattr(self, "setTHooks"):
self.setTHooks = []
@ -117,6 +117,6 @@ def popupControls(self, tl = None):
s.setTHooks.remove(u)
tl.bind('<Destroy>', onDestroy)
Dtool_funcToMethod(popupControls, CInterval)
Dtool_funcToMethod(popupControls, CInterval)
del popupControls
#####################################################################

View File

@ -3,7 +3,7 @@ from extension_native_helpers import *
from libpanda import *
####################################################################
#Dtool_funcToMethod(func, class)
#Dtool_funcToMethod(func, class)
#del func
#####################################################################
@ -17,7 +17,7 @@ def id(self):
"""Returns a unique id identifying the NodePath instance"""
return self.getKey()
Dtool_funcToMethod(id, NodePath)
Dtool_funcToMethod(id, NodePath)
del id
#####################################################################
@ -30,7 +30,7 @@ def getChildrenAsList(self):
"""Converts a node path's child NodePathCollection into a list"""
return self.getChildren().asList()
Dtool_funcToMethod(getChildrenAsList, NodePath)
Dtool_funcToMethod(getChildrenAsList, NodePath)
del getChildrenAsList
#####################################################################
@ -38,7 +38,7 @@ def printChildren(self):
"""Prints out the children of the bottom node of a node path"""
for child in self.getChildrenAsList():
print child.getName()
Dtool_funcToMethod(printChildren, NodePath)
Dtool_funcToMethod(printChildren, NodePath)
del printChildren
#####################################################################
@ -46,7 +46,7 @@ def removeChildren(self):
"""Deletes the children of the bottom node of a node path"""
for child in self.getChildrenAsList():
child.removeNode()
Dtool_funcToMethod(removeChildren, NodePath)
Dtool_funcToMethod(removeChildren, NodePath)
del removeChildren
#####################################################################
@ -58,16 +58,16 @@ def toggleVis(self):
else:
self.hide()
return 0
Dtool_funcToMethod(toggleVis, NodePath)
Dtool_funcToMethod(toggleVis, NodePath)
del toggleVis
#####################################################################
def showSiblings(self):
"""Show all the siblings of a node path"""
for sib in self.getParent().getChildrenAsList():
if sib.node() != self.node():
sib.show()
Dtool_funcToMethod(showSiblings, NodePath)
Dtool_funcToMethod(showSiblings, NodePath)
del showSiblings
#####################################################################
@ -76,7 +76,7 @@ def hideSiblings(self):
for sib in self.getParent().getChildrenAsList():
if sib.node() != self.node():
sib.hide()
Dtool_funcToMethod(hideSiblings, NodePath)
Dtool_funcToMethod(hideSiblings, NodePath)
del hideSiblings
#####################################################################
@ -85,7 +85,7 @@ def showAllDescendants(self):
self.show()
for child in self.getChildrenAsList():
child.showAllDescendants()
Dtool_funcToMethod(showAllDescendants, NodePath)
Dtool_funcToMethod(showAllDescendants, NodePath)
del showAllDescendants
#####################################################################
@ -93,7 +93,7 @@ def isolate(self):
"""Show the node path and hide its siblings"""
self.showAllDescendants()
self.hideSiblings()
Dtool_funcToMethod(isolate, NodePath)
Dtool_funcToMethod(isolate, NodePath)
del isolate
#####################################################################
@ -104,7 +104,7 @@ def remove(self):
messenger.send('preRemoveNodePath', [self])
# Remove nodePath
self.removeNode()
Dtool_funcToMethod(remove, NodePath)
Dtool_funcToMethod(remove, NodePath)
del remove
#####################################################################
@ -118,7 +118,7 @@ def lsNames(self):
print type + " " + name
self.lsNamesRecurse()
Dtool_funcToMethod(lsNames, NodePath)
Dtool_funcToMethod(lsNames, NodePath)
del lsNames
#####################################################################
def lsNamesRecurse(self, indentString=' '):
@ -129,7 +129,7 @@ def lsNamesRecurse(self, indentString=' '):
print indentString + type + " " + name
nodePath.lsNamesRecurse(indentString + " ")
Dtool_funcToMethod(lsNamesRecurse, NodePath)
Dtool_funcToMethod(lsNamesRecurse, NodePath)
del lsNamesRecurse
#####################################################################
def reverseLsNames(self):
@ -142,7 +142,7 @@ def reverseLsNames(self):
print indentString + type + " " + name
indentString = indentString + " "
Dtool_funcToMethod(reverseLsNames, NodePath)
Dtool_funcToMethod(reverseLsNames, NodePath)
del reverseLsNames
#####################################################################
def getAncestry(self):
@ -155,16 +155,16 @@ def getAncestry(self):
else:
return [self]
Dtool_funcToMethod(getAncestry, NodePath)
Dtool_funcToMethod(getAncestry, NodePath)
del getAncestry
#####################################################################
def getTightBounds(self):
from pandac.PandaModules import Point3
v1 = Point3.Point3(0)
v2 = Point3.Point3(0)
self.calcTightBounds(v1,v2)
self.calcTightBounds(v1, v2)
return v1, v2
Dtool_funcToMethod(getTightBounds, NodePath)
Dtool_funcToMethod(getTightBounds, NodePath)
del getTightBounds
#####################################################################
@ -191,13 +191,13 @@ def pPrintString(self, other = None):
otherString = '\n'
return (
"%s = {"%(self.getName()) +
otherString +
otherString +
" 'Pos': (%s),\n" % pos.pPrintValues() +
" 'Hpr': (%s),\n" % hpr.pPrintValues() +
" 'Scale': (%s),\n" % scale.pPrintValues() +
" 'Shear': (%s),\n" % shear.pPrintValues() +
"}")
Dtool_funcToMethod(pPrintString, NodePath)
Dtool_funcToMethod(pPrintString, NodePath)
del pPrintString
#####################################################################
@ -210,12 +210,12 @@ def printPos(self, other = None, sd = 2):
else:
pos = self.getPos()
otherString = ''
print (self.getName() + '.setPos(' + otherString +
print (self.getName() + '.setPos(' + otherString +
formatString % pos[0] + ', ' +
formatString % pos[1] + ', ' +
formatString % pos[2] +
')\n')
Dtool_funcToMethod(printPos, NodePath)
Dtool_funcToMethod(printPos, NodePath)
del printPos
#####################################################################
@ -228,12 +228,12 @@ def printHpr(self, other = None, sd = 2):
else:
hpr = self.getHpr()
otherString = ''
print (self.getName() + '.setHpr(' + otherString +
print (self.getName() + '.setHpr(' + otherString +
formatString % hpr[0] + ', ' +
formatString % hpr[1] + ', ' +
formatString % hpr[2] +
')\n')
Dtool_funcToMethod(printHpr, NodePath)
Dtool_funcToMethod(printHpr, NodePath)
del printHpr
#####################################################################
@ -246,13 +246,13 @@ def printScale(self, other = None, sd = 2):
else:
scale = self.getScale()
otherString = ''
print (self.getName() + '.setScale(' + otherString +
print (self.getName() + '.setScale(' + otherString +
formatString % scale[0] + ', ' +
formatString % scale[1] + ', ' +
formatString % scale[2] +
')\n')
Dtool_funcToMethod(printScale, NodePath)
Dtool_funcToMethod(printScale, NodePath)
del printScale
#####################################################################
def printPosHpr(self, other = None, sd = 2):
@ -266,7 +266,7 @@ def printPosHpr(self, other = None, sd = 2):
pos = self.getPos()
hpr = self.getHpr()
otherString = ''
print (self.getName() + '.setPosHpr(' + otherString +
print (self.getName() + '.setPosHpr(' + otherString +
formatString % pos[0] + ', ' +
formatString % pos[1] + ', ' +
formatString % pos[2] + ', ' +
@ -275,7 +275,7 @@ def printPosHpr(self, other = None, sd = 2):
formatString % hpr[2] +
')\n')
Dtool_funcToMethod(printPosHpr, NodePath)
Dtool_funcToMethod(printPosHpr, NodePath)
del printPosHpr
#####################################################################
def printPosHprScale(self, other = None, sd = 2):
@ -291,7 +291,7 @@ def printPosHprScale(self, other = None, sd = 2):
hpr = self.getHpr()
scale = self.getScale()
otherString = ''
print (self.getName() + '.setPosHprScale(' + otherString +
print (self.getName() + '.setPosHprScale(' + otherString +
formatString % pos[0] + ', ' +
formatString % pos[1] + ', ' +
formatString % pos[2] + ', ' +
@ -303,7 +303,7 @@ def printPosHprScale(self, other = None, sd = 2):
formatString % scale[2] +
')\n')
Dtool_funcToMethod(printPosHprScale, NodePath)
Dtool_funcToMethod(printPosHprScale, NodePath)
del printPosHprScale
#####################################################################
@ -314,17 +314,17 @@ def printTransform(self, other = None, sd = 2, fRecursive = 0):
if other == None:
transform = self.getTransform()
else:
transform = self.getTransform(other)
transform = self.getTransform(other)
if transform.hasPos():
pos = transform.getPos()
if not pos.almostEqual(Vec3(0)):
outputString = '%s.setPos(%s, %s, %s)' % (name, fmtStr, fmtStr, fmtStr)
print outputString % (pos[0], pos[1], pos[2])
print outputString % (pos[0], pos[1], pos[2])
if transform.hasHpr():
hpr = transform.getHpr()
if not hpr.almostEqual(Vec3(0)):
outputString = '%s.setHpr(%s, %s, %s)' % (name, fmtStr, fmtStr, fmtStr)
print outputString % (hpr[0], hpr[1], hpr[2])
print outputString % (hpr[0], hpr[1], hpr[2])
if transform.hasScale():
if transform.hasUniformScale():
scale = transform.getUniformScale()
@ -340,63 +340,63 @@ def printTransform(self, other = None, sd = 2, fRecursive = 0):
for child in self.getChildrenAsList():
child.printTransform(other, sd, fRecursive)
Dtool_funcToMethod(printTransform, NodePath)
Dtool_funcToMethod(printTransform, NodePath)
del printTransform
#####################################################################
def iPos(self, other = None):
""" Set node path's pos to 0,0,0 """
""" Set node path's pos to 0, 0, 0 """
if other:
self.setPos(other, 0,0,0)
self.setPos(other, 0, 0, 0)
else:
self.setPos(0,0,0)
Dtool_funcToMethod(iPos, NodePath)
self.setPos(0, 0, 0)
Dtool_funcToMethod(iPos, NodePath)
del iPos
#####################################################################
def iHpr(self, other = None):
""" Set node path's hpr to 0,0,0 """
""" Set node path's hpr to 0, 0, 0 """
if other:
self.setHpr(other, 0,0,0)
self.setHpr(other, 0, 0, 0)
else:
self.setHpr(0,0,0)
self.setHpr(0, 0, 0)
Dtool_funcToMethod(iHpr, NodePath)
Dtool_funcToMethod(iHpr, NodePath)
del iHpr
#####################################################################
def iScale(self, other = None):
""" SEt node path's scale to 1,1,1 """
""" SEt node path's scale to 1, 1, 1 """
if other:
self.setScale(other, 1,1,1)
self.setScale(other, 1, 1, 1)
else:
self.setScale(1,1,1)
self.setScale(1, 1, 1)
Dtool_funcToMethod(iScale, NodePath)
Dtool_funcToMethod(iScale, NodePath)
del iScale
#####################################################################
def iPosHpr(self, other = None):
""" Set node path's pos and hpr to 0,0,0 """
""" Set node path's pos and hpr to 0, 0, 0 """
if other:
self.setPosHpr(other,0,0,0,0,0,0)
self.setPosHpr(other, 0, 0, 0, 0, 0, 0)
else:
self.setPosHpr(0,0,0,0,0,0)
self.setPosHpr(0, 0, 0, 0, 0, 0)
Dtool_funcToMethod(iPosHpr, NodePath)
Dtool_funcToMethod(iPosHpr, NodePath)
del iPosHpr
#####################################################################
def iPosHprScale(self, other = None):
""" Set node path's pos and hpr to 0,0,0 and scale to 1,1,1 """
""" Set node path's pos and hpr to 0, 0, 0 and scale to 1, 1, 1 """
if other:
self.setPosHprScale(other, 0,0,0,0,0,0,1,1,1)
self.setPosHprScale(other, 0, 0, 0, 0, 0, 0, 1, 1, 1)
else:
self.setPosHprScale(0,0,0,0,0,0,1,1,1)
self.setPosHprScale(0, 0, 0, 0, 0, 0, 1, 1, 1)
# private methods
Dtool_funcToMethod(iPosHprScale, NodePath)
Dtool_funcToMethod(iPosHprScale, NodePath)
del iPosHprScale
#####################################################################
def __lerp(self, functorFunc, duration, blendType, taskName=None):
"""
__lerp(self, functorFunc, float, string, string)
@ -409,7 +409,7 @@ def __lerp(self, functorFunc, duration, blendType, taskName=None):
from direct.task import Task
from direct.showbase import LerpBlendHelpers
from direct.task.TaskManagerGlobal import taskMgr
# upon death remove the functorFunc
def lerpUponDeath(task):
# Try to break circular references
@ -421,7 +421,7 @@ def __lerp(self, functorFunc, duration, blendType, taskName=None):
del task.lerp
except:
pass
# make the task function
def lerpTaskFunc(task):
from pandac.PandaModules import Lerp
@ -441,7 +441,7 @@ def __lerp(self, functorFunc, duration, blendType, taskName=None):
return(done)
else:
return(cont)
# make the lerp task
lerpTask = Task.Task(lerpTaskFunc)
lerpTask.init = 1
@ -449,7 +449,7 @@ def __lerp(self, functorFunc, duration, blendType, taskName=None):
lerpTask.duration = duration
lerpTask.blendType = LerpBlendHelpers.getBlend(blendType)
lerpTask.uponDeath = lerpUponDeath
if (taskName == None):
# don't spawn a task, return one instead
return lerpTask
@ -458,7 +458,7 @@ def __lerp(self, functorFunc, duration, blendType, taskName=None):
taskMgr.add(lerpTask, taskName)
return lerpTask
Dtool_funcToMethod(__lerp, NodePath)
Dtool_funcToMethod(__lerp, NodePath)
del __lerp
#####################################################################
def __autoLerp(self, functorFunc, time, blendType, taskName):
@ -475,7 +475,7 @@ def __autoLerp(self, functorFunc, time, blendType, taskName):
lerp.start()
return lerp
Dtool_funcToMethod(__autoLerp, NodePath)
Dtool_funcToMethod(__autoLerp, NodePath)
del __autoLerp
#####################################################################
@ -496,10 +496,10 @@ def lerpColor(self, *posArgs, **keyArgs):
# bad args
raise Exception("Error: NodePath.lerpColor: bad number of args")
Dtool_funcToMethod(lerpColor, NodePath)
Dtool_funcToMethod(lerpColor, NodePath)
del lerpColor
#####################################################################
def lerpColorRGBA(self, r, g, b, a, time,
blendType="noBlend", auto=None, task=None):
"""lerpColorRGBA(self, float, float, float, float, float,
@ -523,7 +523,7 @@ def lerpColorRGBA(self, r, g, b, a, time,
else:
return self.__lerp(functorFunc, time, blendType)
Dtool_funcToMethod(lerpColorRGBA, NodePath)
Dtool_funcToMethod(lerpColorRGBA, NodePath)
del lerpColorRGBA
#####################################################################
def lerpColorRGBARGBA(self, sr, sg, sb, sa, er, eg, eb, ea, time,
@ -546,7 +546,7 @@ def lerpColorRGBARGBA(self, sr, sg, sb, sa, er, eg, eb, ea, time,
else:
return self.__lerp(functorFunc, time, blendType)
Dtool_funcToMethod(lerpColorRGBARGBA, NodePath)
Dtool_funcToMethod(lerpColorRGBARGBA, NodePath)
del lerpColorRGBARGBA
#####################################################################
def lerpColorVBase4(self, endColor, time,
@ -569,7 +569,7 @@ def lerpColorVBase4(self, endColor, time,
else:
return self.__lerp(functorFunc, time, blendType)
Dtool_funcToMethod(lerpColorVBase4, NodePath)
Dtool_funcToMethod(lerpColorVBase4, NodePath)
del lerpColorVBase4
#####################################################################
def lerpColorVBase4VBase4(self, startColor, endColor, time,
@ -594,7 +594,7 @@ def lerpColorVBase4VBase4(self, startColor, endColor, time,
Dtool_funcToMethod(lerpColorVBase4VBase4, NodePath)
Dtool_funcToMethod(lerpColorVBase4VBase4, NodePath)
del lerpColorVBase4VBase4
#####################################################################
# user callable lerp methods
@ -614,8 +614,8 @@ def lerpColorScale(self, *posArgs, **keyArgs):
# bad args
raise Exception("Error: NodePath.lerpColorScale: bad number of args")
Dtool_funcToMethod(lerpColorScale, NodePath)
Dtool_funcToMethod(lerpColorScale, NodePath)
del lerpColorScale
#####################################################################
def lerpColorScaleRGBA(self, r, g, b, a, time,
@ -641,7 +641,7 @@ def lerpColorScaleRGBA(self, r, g, b, a, time,
else:
return self.__lerp(functorFunc, time, blendType)
Dtool_funcToMethod(lerpColorScaleRGBA, NodePath)
Dtool_funcToMethod(lerpColorScaleRGBA, NodePath)
del lerpColorScaleRGBA
#####################################################################
def lerpColorScaleRGBARGBA(self, sr, sg, sb, sa, er, eg, eb, ea, time,
@ -664,7 +664,7 @@ def lerpColorScaleRGBARGBA(self, sr, sg, sb, sa, er, eg, eb, ea, time,
else:
return self.__lerp(functorFunc, time, blendType)
Dtool_funcToMethod(lerpColorScaleRGBARGBA, NodePath)
Dtool_funcToMethod(lerpColorScaleRGBARGBA, NodePath)
del lerpColorScaleRGBARGBA
#####################################################################
def lerpColorScaleVBase4(self, endColor, time,
@ -687,7 +687,7 @@ def lerpColorScaleVBase4(self, endColor, time,
else:
return self.__lerp(functorFunc, time, blendType)
Dtool_funcToMethod(lerpColorScaleVBase4, NodePath)
Dtool_funcToMethod(lerpColorScaleVBase4, NodePath)
del lerpColorScaleVBase4
#####################################################################
def lerpColorScaleVBase4VBase4(self, startColor, endColor, time,
@ -710,9 +710,9 @@ def lerpColorScaleVBase4VBase4(self, startColor, endColor, time,
else:
return self.__lerp(functorFunc, time, blendType)
Dtool_funcToMethod(lerpColorScaleVBase4VBase4, NodePath)
Dtool_funcToMethod(lerpColorScaleVBase4VBase4, NodePath)
del lerpColorScaleVBase4VBase4
#####################################################################
def lerpHpr(self, *posArgs, **keyArgs):
@ -729,8 +729,8 @@ def lerpHpr(self, *posArgs, **keyArgs):
else:
# bad args
raise Exception("Error: NodePath.lerpHpr: bad number of args")
Dtool_funcToMethod(lerpHpr, NodePath)
Dtool_funcToMethod(lerpHpr, NodePath)
del lerpHpr
#####################################################################
def lerpHprHPR(self, h, p, r, time, other=None,
@ -768,8 +768,8 @@ def lerpHprHPR(self, h, p, r, time, other=None,
return self.__lerp(functorFunc, time, blendType, task)
else:
return self.__lerp(functorFunc, time, blendType)
Dtool_funcToMethod(lerpHprHPR, NodePath)
Dtool_funcToMethod(lerpHprHPR, NodePath)
del lerpHprHPR
#####################################################################
def lerpHprVBase3(self, hpr, time, other=None,
@ -801,9 +801,9 @@ def lerpHprVBase3(self, hpr, time, other=None,
return self.__lerp(functorFunc, time, blendType, task)
else:
return self.__lerp(functorFunc, time, blendType)
Dtool_funcToMethod(lerpHprVBase3, NodePath)
Dtool_funcToMethod(lerpHprVBase3, NodePath)
del lerpHprVBase3
#####################################################################
def lerpPos(self, *posArgs, **keyArgs):
@ -821,7 +821,7 @@ def lerpPos(self, *posArgs, **keyArgs):
# bad number off args
raise Exception("Error: NodePath.lerpPos: bad number of args")
Dtool_funcToMethod(lerpPos, NodePath)
Dtool_funcToMethod(lerpPos, NodePath)
del lerpPos
#####################################################################
def lerpPosXYZ(self, x, y, z, time, other=None,
@ -851,7 +851,7 @@ def lerpPosXYZ(self, x, y, z, time, other=None,
else:
return self.__lerp(functorFunc, time, blendType)
Dtool_funcToMethod(lerpPosXYZ, NodePath)
Dtool_funcToMethod(lerpPosXYZ, NodePath)
del lerpPosXYZ
#####################################################################
def lerpPosPoint3(self, pos, time, other=None,
@ -879,7 +879,7 @@ def lerpPosPoint3(self, pos, time, other=None,
return self.__lerp(functorFunc, time, blendType)
Dtool_funcToMethod(lerpPosPoint3, NodePath)
Dtool_funcToMethod(lerpPosPoint3, NodePath)
del lerpPosPoint3
#####################################################################
def lerpPosHpr(self, *posArgs, **keyArgs):
@ -897,7 +897,7 @@ def lerpPosHpr(self, *posArgs, **keyArgs):
# bad number off args
raise Exception("Error: NodePath.lerpPosHpr: bad number of args")
Dtool_funcToMethod(lerpPosHpr, NodePath)
Dtool_funcToMethod(lerpPosHpr, NodePath)
del lerpPosHpr
#####################################################################
def lerpPosHprPoint3VBase3(self, pos, hpr, time, other=None,
@ -934,7 +934,7 @@ def lerpPosHprPoint3VBase3(self, pos, hpr, time, other=None,
else:
return self.__lerp(functorFunc, time, blendType)
Dtool_funcToMethod(lerpPosHprPoint3VBase3, NodePath)
Dtool_funcToMethod(lerpPosHprPoint3VBase3, NodePath)
del lerpPosHprPoint3VBase3
#####################################################################
def lerpPosHprXYZHPR(self, x, y, z, h, p, r, time, other=None,
@ -977,7 +977,7 @@ def lerpPosHprXYZHPR(self, x, y, z, h, p, r, time, other=None,
return self.__lerp(functorFunc, time, blendType)
Dtool_funcToMethod(lerpPosHprXYZHPR, NodePath)
Dtool_funcToMethod(lerpPosHprXYZHPR, NodePath)
del lerpPosHprXYZHPR
#####################################################################
def lerpPosHprScale(self, pos, hpr, scale, time, other=None,
@ -1021,7 +1021,7 @@ def lerpPosHprScale(self, pos, hpr, scale, time, other=None,
return self.__lerp(functorFunc, time, blendType)
Dtool_funcToMethod(lerpPosHprScale, NodePath)
Dtool_funcToMethod(lerpPosHprScale, NodePath)
del lerpPosHprScale
#####################################################################
def lerpScale(self, *posArgs, **keyArgs):
@ -1039,7 +1039,7 @@ def lerpScale(self, *posArgs, **keyArgs):
# bad number off args
raise Exception("Error: NodePath.lerpScale: bad number of args")
Dtool_funcToMethod(lerpScale, NodePath)
Dtool_funcToMethod(lerpScale, NodePath)
del lerpScale
#####################################################################
def lerpScaleVBase3(self, scale, time, other=None,
@ -1067,7 +1067,7 @@ def lerpScaleVBase3(self, scale, time, other=None,
else:
return self.__lerp(functorFunc, time, blendType)
Dtool_funcToMethod(lerpScaleVBase3, NodePath)
Dtool_funcToMethod(lerpScaleVBase3, NodePath)
del lerpScaleVBase3
#####################################################################
def lerpScaleXYZ(self, sx, sy, sz, time, other=None,
@ -1099,8 +1099,8 @@ def lerpScaleXYZ(self, sx, sy, sz, time, other=None,
Dtool_funcToMethod(lerpScaleXYZ, NodePath)
Dtool_funcToMethod(lerpScaleXYZ, NodePath)
del lerpScaleXYZ
#####################################################################
def place(self):
@ -1108,7 +1108,7 @@ def place(self):
from direct.tkpanels import Placer
return Placer.place(self)
Dtool_funcToMethod(place, NodePath)
Dtool_funcToMethod(place, NodePath)
del place
#####################################################################
def explore(self):
@ -1116,7 +1116,7 @@ def explore(self):
from direct.tkwidgets import SceneGraphExplorer
return SceneGraphExplorer.explore(self)
Dtool_funcToMethod(explore, NodePath)
Dtool_funcToMethod(explore, NodePath)
del explore
#####################################################################
def rgbPanel(self, cb = None):
@ -1124,21 +1124,21 @@ def rgbPanel(self, cb = None):
from direct.tkwidgets import Slider
return Slider.rgbPanel(self, cb)
Dtool_funcToMethod(rgbPanel, NodePath)
Dtool_funcToMethod(rgbPanel, NodePath)
del rgbPanel
#####################################################################
def select(self):
base.startDirect(fWantTk = 0)
direct.select(self)
Dtool_funcToMethod(select, NodePath)
Dtool_funcToMethod(select, NodePath)
del select
#####################################################################
def deselect(self):
base.startDirect(fWantTk = 0)
direct.deselect(self)
Dtool_funcToMethod(deselect, NodePath)
Dtool_funcToMethod(deselect, NodePath)
del deselect
#####################################################################
def showCS(self, mask = None):
@ -1154,7 +1154,7 @@ def showCS(self, mask = None):
if (mask == None or (np.node().getIntoCollideMask() & mask).getWord()):
np.show()
Dtool_funcToMethod(showCS, NodePath)
Dtool_funcToMethod(showCS, NodePath)
del showCS
#####################################################################
def hideCS(self, mask = None):
@ -1170,118 +1170,118 @@ def hideCS(self, mask = None):
if (mask == None or (np.node().getIntoCollideMask() & mask).getWord()):
np.hide()
Dtool_funcToMethod(hideCS, NodePath)
Dtool_funcToMethod(hideCS, NodePath)
del hideCS
#####################################################################
def posInterval(self, *args, **kw):
from direct.interval import LerpInterval
return LerpInterval.LerpPosInterval(self, *args, **kw)
Dtool_funcToMethod(posInterval, NodePath)
Dtool_funcToMethod(posInterval, NodePath)
del posInterval
#####################################################################
def hprInterval(self, *args, **kw):
from direct.interval import LerpInterval
return LerpInterval.LerpHprInterval(self, *args, **kw)
Dtool_funcToMethod(hprInterval, NodePath)
Dtool_funcToMethod(hprInterval, NodePath)
del hprInterval
#####################################################################
def quatInterval(self, *args, **kw):
from direct.interval import LerpInterval
return LerpInterval.LerpQuatInterval(self, *args, **kw)
Dtool_funcToMethod(quatInterval, NodePath)
Dtool_funcToMethod(quatInterval, NodePath)
del quatInterval
#####################################################################
def scaleInterval(self, *args, **kw):
from direct.interval import LerpInterval
return LerpInterval.LerpScaleInterval(self, *args, **kw)
Dtool_funcToMethod(scaleInterval, NodePath)
Dtool_funcToMethod(scaleInterval, NodePath)
del scaleInterval
#####################################################################
def shearInterval(self, *args, **kw):
from direct.interval import LerpInterval
return LerpInterval.LerpShearInterval(self, *args, **kw)
Dtool_funcToMethod(shearInterval, NodePath)
Dtool_funcToMethod(shearInterval, NodePath)
del shearInterval
#####################################################################
def posHprInterval(self, *args, **kw):
from direct.interval import LerpInterval
return LerpInterval.LerpPosHprInterval(self, *args, **kw)
Dtool_funcToMethod(posHprInterval, NodePath)
Dtool_funcToMethod(posHprInterval, NodePath)
del posHprInterval
#####################################################################
def posQuatInterval(self, *args, **kw):
from direct.interval import LerpInterval
return LerpInterval.LerpPosQuatInterval(self, *args, **kw)
Dtool_funcToMethod(posQuatInterval, NodePath)
Dtool_funcToMethod(posQuatInterval, NodePath)
del posQuatInterval
#####################################################################
def hprScaleInterval(self, *args, **kw):
from direct.interval import LerpInterval
return LerpInterval.LerpHprScaleInterval(self, *args, **kw)
Dtool_funcToMethod(hprScaleInterval, NodePath)
Dtool_funcToMethod(hprScaleInterval, NodePath)
del hprScaleInterval
#####################################################################
def quatScaleInterval(self, *args, **kw):
from direct.interval import LerpInterval
return LerpInterval.LerpQuatScaleInterval(self, *args, **kw)
Dtool_funcToMethod(quatScaleInterval, NodePath)
Dtool_funcToMethod(quatScaleInterval, NodePath)
del quatScaleInterval
#####################################################################
def posHprScaleInterval(self, *args, **kw):
from direct.interval import LerpInterval
return LerpInterval.LerpPosHprScaleInterval(self, *args, **kw)
Dtool_funcToMethod(posHprScaleInterval, NodePath)
Dtool_funcToMethod(posHprScaleInterval, NodePath)
del posHprScaleInterval
#####################################################################
def posQuatScaleInterval(self, *args, **kw):
from direct.interval import LerpInterval
return LerpInterval.LerpPosQuatScaleInterval(self, *args, **kw)
Dtool_funcToMethod(posQuatScaleInterval, NodePath)
Dtool_funcToMethod(posQuatScaleInterval, NodePath)
del posQuatScaleInterval
#####################################################################
def posHprScaleShearInterval(self, *args, **kw):
from direct.interval import LerpInterval
return LerpInterval.LerpPosHprScaleShearInterval(self, *args, **kw)
Dtool_funcToMethod(posHprScaleShearInterval, NodePath)
Dtool_funcToMethod(posHprScaleShearInterval, NodePath)
del posHprScaleShearInterval
#####################################################################
def posQuatScaleShearInterval(self, *args, **kw):
from direct.interval import LerpInterval
return LerpInterval.LerpPosQuatScaleShearInterval(self, *args, **kw)
Dtool_funcToMethod(posQuatScaleShearInterval, NodePath)
Dtool_funcToMethod(posQuatScaleShearInterval, NodePath)
del posQuatScaleShearInterval
#####################################################################
def colorInterval(self, *args, **kw):
from direct.interval import LerpInterval
return LerpInterval.LerpColorInterval(self, *args, **kw)
Dtool_funcToMethod(colorInterval, NodePath)
Dtool_funcToMethod(colorInterval, NodePath)
del colorInterval
#####################################################################
def colorScaleInterval(self, *args, **kw):
from direct.interval import LerpInterval
return LerpInterval.LerpColorScaleInterval(self, *args, **kw)
Dtool_funcToMethod(colorScaleInterval, NodePath)
Dtool_funcToMethod(colorScaleInterval, NodePath)
del colorScaleInterval
#####################################################################
def attachCollisionSphere(self, name, cx,cy,cz,r, fromCollide, intoCollide):
def attachCollisionSphere(self, name, cx, cy, cz, r, fromCollide, intoCollide):
from pandac.PandaModules import CollisionSphere
from pandac.PandaModules import CollisionNode
coll = CollisionSphere.CollisionSphere(cx,cy,cz,r)
coll = CollisionSphere.CollisionSphere(cx, cy, cz, r)
collNode = CollisionNode.CollisionNode(name)
collNode.addSolid(coll)
collNode.setFromCollideMask(fromCollide)
@ -1289,13 +1289,13 @@ def attachCollisionSphere(self, name, cx,cy,cz,r, fromCollide, intoCollide):
collNodePath = self.attachNewNode(collNode)
return collNodePath
Dtool_funcToMethod(attachCollisionSphere, NodePath)
Dtool_funcToMethod(attachCollisionSphere, NodePath)
del attachCollisionSphere
#####################################################################
def attachCollisionSegment(self, name, ax,ay,az, bx,by,bz, fromCollide, intoCollide):
def attachCollisionSegment(self, name, ax, ay, az, bx, by, bz, fromCollide, intoCollide):
from pandac.PandaModules import CollisionSegment
from pandac.PandaModules import CollisionNode
coll = CollisionSegment.CollisionSegment(ax,ay,az, bx,by,bz)
coll = CollisionSegment.CollisionSegment(ax, ay, az, bx, by, bz)
collNode = CollisionNode.CollisionNode(name)
collNode.addSolid(coll)
collNode.setFromCollideMask(fromCollide)
@ -1303,13 +1303,13 @@ def attachCollisionSegment(self, name, ax,ay,az, bx,by,bz, fromCollide, intoColl
collNodePath = self.attachNewNode(collNode)
return collNodePath
Dtool_funcToMethod(attachCollisionSegment, NodePath)
Dtool_funcToMethod(attachCollisionSegment, NodePath)
del attachCollisionSegment
#####################################################################
def attachCollisionRay(self, name, ox,oy,oz, dx,dy,dz, fromCollide, intoCollide):
def attachCollisionRay(self, name, ox, oy, oz, dx, dy, dz, fromCollide, intoCollide):
from pandac.PandaModules import CollisionRay
from pandac.PandaModules import CollisionNode
coll = CollisionRay.CollisionRay(ox,oy,oz, dx,dy,dz)
coll = CollisionRay.CollisionRay(ox, oy, oz, dx, dy, dz)
collNode = CollisionNode.CollisionNode(name)
collNode.addSolid(coll)
collNode.setFromCollideMask(fromCollide)
@ -1317,7 +1317,7 @@ def attachCollisionRay(self, name, ox,oy,oz, dx,dy,dz, fromCollide, intoCollide)
collNodePath = self.attachNewNode(collNode)
return collNodePath
Dtool_funcToMethod(attachCollisionRay, NodePath)
Dtool_funcToMethod(attachCollisionRay, NodePath)
del attachCollisionRay
#####################################################################
def flattenMultitex(self, stateFrom = None, target = None,
@ -1337,6 +1337,6 @@ def flattenMultitex(self, stateFrom = None, target = None,
else:
mr.scan(self, stateFrom)
mr.flatten(win)
Dtool_funcToMethod(flattenMultitex, NodePath)
Dtool_funcToMethod(flattenMultitex, NodePath)
del flattenMultitex
#####################################################################

View File

@ -10,6 +10,6 @@ def pPrintValues(self):
"""
Pretty print
"""
return "% 10.4f, % 10.4f, % 10.4f" % (self[0],self[1],self[2])
return "% 10.4f, % 10.4f, % 10.4f" % (self[0], self[1], self[2])
Dtool_funcToMethod(pPrintValues, VBase3)
del pPrintValues

View File

@ -10,6 +10,6 @@ def pPrintValues(self):
"""
Pretty print
"""
return "% 10.4f, % 10.4f, % 10.4f, % 10.4f" % (self[0],self[1],self[2],self[3])
return "% 10.4f, % 10.4f, % 10.4f, % 10.4f" % (self[0], self[1], self[2], self[3])
Dtool_funcToMethod(pPrintValues, VBase4)
del pPrintValues

View File

@ -1,18 +1,18 @@
### Tools
### Tools
from libpandaexpress import *
def Dtool_ObjectToDict(clas,name,obj):
clas.DtoolClassDict[name] = obj;
def Dtool_ObjectToDict(clas, name, obj):
clas.DtoolClassDict[name] = obj;
def Dtool_funcToMethod(func,clas,method_name=None):
def Dtool_funcToMethod(func, clas, method_name=None):
"""Adds func to class so it is an accessible method; use method_name to specify the name to be used for calling the method.
The new method is accessible to any instance immediately."""
func.im_class=clas
func.im_func=func
func.im_self=None
if not method_name:
if not method_name:
method_name = func.__name__
clas.DtoolClassDict[method_name] = func;
clas.DtoolClassDict[method_name] = func;

View File

@ -25,7 +25,7 @@ def registerInTypeMap(pythonClass):
WrapperClassMap[typeIndex] = pythonClass
def funcToMethod(func,clas,method_name=None):
def funcToMethod(func, clas, method_name=None):
"""Adds func to class so it is an accessible method; use method_name to specify the name to be used for calling the method.
The new method is accessible to any instance immediately."""
func.im_class=clas
@ -118,7 +118,7 @@ class FFIExternalObject:
# type instead.
if typeHandle.getNumParentClasses() == 0:
# This type has no parents! That shouldn't happen.
FFIConstants.notify.warning("Unknown class type: %s has no parents!" % (typeHandle.getName()))
FFIConstants.notify.warning("Unknown class type: %s has no parents!" % (typeHandle.getName()))
return None
parentType = typeHandle.getParentTowards(rootType, self)
@ -133,7 +133,7 @@ class FFIExternalObject:
WrapperClassMap[typeHandle.getIndex()] = parentWrapperClass
return parentWrapperClass
def setPointer(self):
# See what type it really is and downcast to that type (if necessary)
# Look up the TypeHandle in the dict. get() returns None if it is not there
@ -143,7 +143,7 @@ class FFIExternalObject:
# This is an unknown class type. Perhaps it derives from
# a class type we know.
exactWrapperClass = self.lookUpNewType(self.getType(), self.getClassType())
# We do not need to downcast if we already have the same class
if (exactWrapperClass and (exactWrapperClass != self.__class__)):
# Create a new wrapper class instance
@ -162,7 +162,7 @@ class FFIExternalObject:
return exactObject
else:
return self
def downcast(self, toClass):
fromClass = self.__class__
#FFIConstants.notify.debug('downcast: downcasting from %s to %s' % \
@ -223,7 +223,7 @@ class FFIExternalObject:
def __str__(self):
# This is a more complete version of printing which shows the object type
# and pointer, plus the output from write() or output() whichever is defined
# and pointer, plus the output from write() or output() whichever is defined
# Print this info for all objects
baseRepr = ('[' + self.__class__.__name__ + ' at: ' + `self.this` + ']')
# Lots of Panda classes have an write or output function defined that takes an Ostream
@ -265,4 +265,4 @@ class FFIExternalObject:

View File

@ -1,4 +1,4 @@
from direct.showbase.PythonUtil import *
from direct.showbase.PythonUtil import *
from types import *
import string
import FFIConstants
@ -53,14 +53,14 @@ def getTypeName(classTypeDesc, typeDesc):
# Atomic C++ types are type checked against the builtin
# Python types. This code sorts out the mapping
if typeDesc.isAtomic():
# Ints, bools, and chars are treated as ints.
# Enums are special and are not atomic, see below
if ((typeDesc.atomicType == AT_int) or
(typeDesc.atomicType == AT_bool) or
(typeDesc.atomicType == AT_char)):
return 'IntType'
# Floats and doubles are both floats in Python
elif ((typeDesc.atomicType == AT_float) or
(typeDesc.atomicType == AT_double)):
@ -72,7 +72,7 @@ def getTypeName(classTypeDesc, typeDesc):
# Strings are treated as Python strings
elif ((typeDesc.atomicType == AT_string)):
return 'StringType'
elif (typeDesc.atomicType == AT_void):
# Convert the void type to None type... I guess...
# So far we do not have any code that uses this
@ -80,7 +80,7 @@ def getTypeName(classTypeDesc, typeDesc):
else:
FFIConstants.notify.error("Unknown atomicType: %s" % (typeDesc.atomicType))
# If the type is an enum, we really want to treat it like an int
# To handle this, the type will have __enum__ in the name
# Usually it will start the typeName, but some typeNames have the
@ -91,7 +91,7 @@ def getTypeName(classTypeDesc, typeDesc):
# If it was not atomic or enum, it must be a class which is a
# bit trickier because we output different things depending on the
# scoping of the type.
# scoping of the type.
else:
# classTypeDesc typeDesc fullNestedName Resulting TypeName
@ -103,11 +103,11 @@ def getTypeName(classTypeDesc, typeDesc):
# 6 Inner Inner Outer.Inner Outer.Inner
# 7 None Other Other Other.Other
# CASES 1,4, and 7 are the only ones that are different from the full
# CASES 1, 4, and 7 are the only ones that are different from the full
# nested name, returning Other.Other
returnNestedTypeNames = string.split(typeName, '.')
returnModuleName = returnNestedTypeNames[0]
returnModuleName = returnNestedTypeNames[0]
if classTypeDesc:
classTypeName = classTypeDesc.getFullNestedName()
@ -145,7 +145,7 @@ def getInheritanceLevel(type, checkNested = 1):
# A special case: PyObject * is always the most general
# object. Everything is a PyObject.
return -1
# If this is a nested type, return the inheritance level of the outer type.
if type.isNested:
# Check the level of your outer class
@ -212,7 +212,7 @@ class FFIMethodArgumentTreeCollection:
self.methodSpecList = methodSpecList
self.methodDict = {}
self.treeDict = {}
def outputOverloadedMethodHeader(self, file, nesting):
# If one is static, we assume they all are.
# The current system does not support overloading static and non-static
@ -221,7 +221,7 @@ class FFIMethodArgumentTreeCollection:
# they are not really constructors, they are instance methods that fill
# in the this pointer.
# Global functions do not need static versions
if (self.methodSpecList[0].isStatic() and
if (self.methodSpecList[0].isStatic() and
(not self.methodSpecList[0].isConstructor())):
indent(file, nesting, 'def ' +
self.methodSpecList[0].name + '(*_args):\n')
@ -230,7 +230,7 @@ class FFIMethodArgumentTreeCollection:
self.methodSpecList[0].name + '(self, *_args):\n')
self.methodSpecList[0].outputCFunctionComment(file, nesting+2)
indent(file, nesting+2, 'numArgs = len(_args)\n')
def outputOverloadedMethodFooter(self, file, nesting):
# If this is a static method, we need to output a static version
# If one is static, we assume they all are.
@ -250,7 +250,7 @@ class FFIMethodArgumentTreeCollection:
indent(file, nesting, "FFIExternalObject.funcToMethod("+methodName+','+ self.classTypeDesc.foreignTypeName+ ",'"+methodName+"')\n")
indent(file, nesting, 'del '+methodName+'\n')
indent(file, nesting, ' \n')
indent(file, nesting+1, '\n')
def outputOverloadedStaticFooter(self, file, nesting):
@ -258,7 +258,7 @@ class FFIMethodArgumentTreeCollection:
methodName = self.methodSpecList[0].name
indent(file, nesting, self.classTypeDesc.foreignTypeName + '.' + methodName + ' = staticmethod(' + methodName + ')\n')
indent(file, nesting,'del ' +methodName+' \n\n')
def setup(self):
for method in self.methodSpecList:
numArgs = len(method.typeDescriptor.thislessArgTypes())
@ -298,7 +298,7 @@ class FFIMethodArgumentTreeCollection:
self.outputOverloadedMethodFooter(file, nesting)
class FFIMethodArgumentTree:
"""
@ -319,7 +319,7 @@ class FFIMethodArgumentTree:
for methodSpec in self.methodSpecList:
argTypes = methodSpec.typeDescriptor.thislessArgTypes()
self.fillInArgTypes(argTypes, methodSpec)
def fillInArgTypes(self, argTypes, methodSpec):
# If the method takes no arguments, we will assign a type index of 0
if (len(argTypes) == 0):
@ -327,11 +327,11 @@ class FFIMethodArgumentTree:
FFIMethodArgumentTree(self.classTypeDesc,
self.methodSpecList),
methodSpec]
else:
self.argSpec = argTypes[0]
typeDesc = self.argSpec.typeDescriptor.recursiveTypeDescriptor()
if (len(argTypes) == 1):
# If this is the last parameter, we are a leaf node, so store the
# methodSpec in this dictionary
@ -375,7 +375,7 @@ class FFIMethodArgumentTree:
# Ok, we branch, it was worth a try though
branches = 1
break
prevTree = subTree
# Must only have one subtree, traverse it
subTree = subTree.tree.values()[0][0]
@ -439,9 +439,9 @@ class FFIMethodArgumentTree:
# Legal types for an int parameter include long.
elif (typeName == 'IntType'):
condition += (' or (isinstance(_args[' + `level` + '], LongType))')
indent(file, nesting+2, 'if ' + condition + ':\n')
if (self.tree[typeDesc][0] is not None):
self.tree[typeDesc][0].traverse(file, nesting+1, level+1)
else:

File diff suppressed because it is too large Load Diff

View File

@ -56,27 +56,27 @@ class PieMenu(NodePath, DirectObject):
# Pop up menu
self.reparentTo(render2d)
self.setPos(self.originX,0.0,self.originY)
self.setPos(self.originX, 0.0, self.originY)
# Compensate for window aspect ratio
self.setScale(1.0, 1.0,1.0)
self.setScale(1.0, 1.0, 1.0)
# Start drawing the selection line
self.lines.reset()
self.lines.moveTo(0,0,0)
self.lines.drawTo(0,0,0)
self.lines.moveTo(0, 0, 0)
self.lines.drawTo(0, 0, 0)
self.lines.create()
# Spawn task to update line and select new texture
self.currItem = -1
taskMgr.add(self.pieMenuTask, 'pieMenuTask')
def pieMenuTask(self,state):
def pieMenuTask(self, state):
mouseX = self.dr.mouseX
mouseY = self.dr.mouseY
deltaX = mouseX - self.originX
deltaY = mouseY - self.originY
# Update the line
#self.lines.setVertex(1,(deltaX/self.sfx),0.0,(deltaY/self.sfz))
#self.lines.setVertex(1, (deltaX/self.sfx), 0.0, (deltaY/self.sfz))
# How far from starting point has user moved the cursor?
if ((abs(deltaX) < 0.1) and (abs(deltaY) < 0.1)):
@ -108,16 +108,16 @@ class PieMenu(NodePath, DirectObject):
# Continue task
return Task.cont
def setInitialState(self,state):
def setInitialState(self, state):
self.initialState = state
def getInitialState(self):
return self.initialState
def setItemOffset(self,newOffset):
def setItemOffset(self, newOffset):
self.itemOffset = newOffset
def setUpdateOnlyOnChange(self,flag):
def setUpdateOnlyOnChange(self, flag):
self.fUpdateOnlyOnChange = flag
@ -170,4 +170,4 @@ class TextPieMenu(PieMenu):
self.removeNode()

View File

@ -6,7 +6,7 @@ from direct.directnotify import DirectNotifyGlobal
class ParticleEffect(NodePath):
notify = DirectNotifyGlobal.directNotify.newCategory('ParticleEffect')
pid = 1
pid = 1
def __init__(self, name=None, particles=None):
if name == None:
@ -53,7 +53,7 @@ class ParticleEffect(NodePath):
def enable(self):
# band-aid added for client crash - grw
if hasattr(self, 'forceGroupDict') and hasattr(self, 'particlesDict'):
if hasattr(self, 'forceGroupDict') and hasattr(self, 'particlesDict'):
if (self.renderParent != None):
for p in self.particlesDict.values():
p.setRenderParent(self.renderParent.node())
@ -75,7 +75,7 @@ class ParticleEffect(NodePath):
def isEnabled(self):
"""
Note: this may be misleading if enable(),disable() not used
Note: this may be misleading if enable(), disable() not used
"""
return self.fEnabled
@ -136,7 +136,7 @@ class ParticleEffect(NodePath):
def getParticlesList(self):
return self.particlesDict.values()
def getParticlesNamed(self, name):
return self.particlesDict.get(name, None)
@ -173,7 +173,7 @@ class ParticleEffect(NodePath):
# Save all the particles to file
num = 0
for p in self.particlesDict.values():
target = 'p%d' % num
target = 'p%d' % num
num = num + 1
f.write(target + ' = Particles.Particles(\'%s\')\n' % p.getName())
p.printParams(f, target)

View File

@ -332,11 +332,11 @@ class Particles(ParticleSystem):
if(cbAttrib):
cbMode = cbAttrib.getMode()
if(cbMode > 0):
if(cbMode in (ColorBlendAttrib.MAdd,ColorBlendAttrib.MSubtract,ColorBlendAttrib.MInvSubtract)):
if(cbMode in (ColorBlendAttrib.MAdd, ColorBlendAttrib.MSubtract, ColorBlendAttrib.MInvSubtract)):
cboa = cbAttrib.getOperandA()
cbob = cbAttrib.getOperandB()
file.write(targ+'.renderer.setColorBlendMode(ColorBlendAttrib.%s,ColorBlendAttrib.%s,ColorBlendAttrib.%s)\n' %
(cbmLut[cbMode],cboLut[cboa],cboLut[cbob]))
file.write(targ+'.renderer.setColorBlendMode(ColorBlendAttrib.%s, ColorBlendAttrib.%s, ColorBlendAttrib.%s)\n' %
(cbmLut[cbMode], cboLut[cboa], cboLut[cbob]))
else:
file.write(targ+'.renderer.setColorBlendMode(ColorBlendAttrib.%s)\n' % cbmLut[cbMode])
cim = self.renderer.getColorInterpolationManager()
@ -366,7 +366,7 @@ class Particles(ParticleSystem):
file.write(targ+'.renderer.getColorInterpolationManager().addStepwave('+`t_b`+','+`t_e`+','+ \
'Vec4('+`c_a[0]`+','+`c_a[1]`+','+`c_a[2]`+','+`c_a[3]`+'),' + \
'Vec4('+`c_b[0]`+','+`c_b[1]`+','+`c_b[2]`+','+`c_b[3]`+'),' + \
`w_a`+','+`w_b`+')\n')
`w_a`+','+`w_b`+')\n')
elif typ == 'ColorInterpolationFunctionSinusoid':
c_a = fun.getColorA()
c_b = fun.getColorB()
@ -434,11 +434,11 @@ class Particles(ParticleSystem):
if(cbAttrib):
cbMode = cbAttrib.getMode()
if(cbMode > 0):
if(cbMode in (ColorBlendAttrib.MAdd,ColorBlendAttrib.MSubtract,ColorBlendAttrib.MInvSubtract)):
if(cbMode in (ColorBlendAttrib.MAdd, ColorBlendAttrib.MSubtract, ColorBlendAttrib.MInvSubtract)):
cboa = cbAttrib.getOperandA()
cbob = cbAttrib.getOperandB()
file.write(targ+'.renderer.setColorBlendMode(ColorBlendAttrib.%s,ColorBlendAttrib.%s,ColorBlendAttrib.%s)\n' %
(cbmLut[cbMode],cboLut[cboa],cboLut[cbob]))
file.write(targ+'.renderer.setColorBlendMode(ColorBlendAttrib.%s, ColorBlendAttrib.%s, ColorBlendAttrib.%s)\n' %
(cbmLut[cbMode], cboLut[cboa], cboLut[cbob]))
else:
file.write(targ+'.renderer.setColorBlendMode(ColorBlendAttrib.%s)\n' % cbmLut[cbMode])
cim = self.renderer.getColorInterpolationManager()
@ -468,7 +468,7 @@ class Particles(ParticleSystem):
file.write(targ+'.renderer.getColorInterpolationManager().addStepwave('+`t_b`+','+`t_e`+','+ \
'Vec4('+`c_a[0]`+','+`c_a[1]`+','+`c_a[2]`+','+`c_a[3]`+'),' + \
'Vec4('+`c_b[0]`+','+`c_b[1]`+','+`c_b[2]`+','+`c_b[3]`+'),' + \
`w_a`+','+`w_b`+')\n')
`w_a`+','+`w_b`+')\n')
elif typ == 'ColorInterpolationFunctionSinusoid':
c_a = fun.getColorA()
c_b = fun.getColorB()

View File

@ -33,7 +33,7 @@ class SpriteParticleRendererExt(SpriteParticleRenderer):
t = loader.loadTexture(fileName)
if (t != None):
self.setTexture(t,t.getYSize())
self.setTexture(t, t.getYSize())
self.setSourceTextureName(fileName)
return True
else:
@ -42,14 +42,14 @@ class SpriteParticleRendererExt(SpriteParticleRenderer):
def addTextureFromFile(self, fileName = None):
if(self.getNumAnims() == 0):
return self.setTextureFromFile(fileName)
return self.setTextureFromFile(fileName)
if fileName == None:
fileName = self.getSourceTextureName()
t = loader.loadTexture(fileName)
if (t != None):
self.addTexture(t,t.getYSize())
self.addTexture(t, t.getYSize())
return True
else:
print "Couldn't find rendererSpriteTexture file: %s" % fileName
@ -79,14 +79,14 @@ class SpriteParticleRendererExt(SpriteParticleRenderer):
def setTextureFromNode(self, modelName = None, nodeName = None, sizeFromTexels = False):
if modelName == None:
modelName = self.getSourceFileName()
modelName = self.getSourceFileName()
if nodeName == None:
nodeName = self.getSourceNodeName()
# Load model and get texture
m = loader.loadModelOnce(modelName)
if (m == None):
print "SpriteParticleRendererExt: Couldn't find model: %s!" % modelName
print "SpriteParticleRendererExt: Couldn't find model: %s!" % modelName
return False
np = m.find(nodeName)
@ -100,20 +100,20 @@ class SpriteParticleRendererExt(SpriteParticleRenderer):
self.setSourceNodeName(nodeName)
m.removeNode()
return True
def addTextureFromNode(self, modelName = None, nodeName = None, sizeFromTexels = False):
if(self.getNumAnims() == 0):
return self.setTextureFromNode(modelName,nodeName,sizeFromTexels)
return self.setTextureFromNode(modelName, nodeName, sizeFromTexels)
if modelName == None:
modelName = self.getSourceFileName()
modelName = self.getSourceFileName()
if nodeName == None:
nodeName = self.getSourceNodeName()
# Load model and get texture
m = loader.loadModelOnce(modelName)
if (m == None):
print "SpriteParticleRendererExt: Couldn't find model: %s!" % modelName
print "SpriteParticleRendererExt: Couldn't find model: %s!" % modelName
return False
np = m.find(nodeName)
@ -121,9 +121,9 @@ class SpriteParticleRendererExt(SpriteParticleRenderer):
print "SpriteParticleRendererExt: Couldn't find node: %s!" % nodeName
m.removeNode()
return False
self.addFromNode(np, modelName, nodeName, sizeFromTexels)
m.removeNode()
return True

View File

@ -64,8 +64,8 @@ class Target:
self.toc.addFilter(tocfilter.ExtFilter(self.extypes))
if self.expatterns:
self.toc.addFilter(tocfilter.PatternFilter(self.expatterns))
##------utilities------##
##------utilities------##
def dump(self):
logfile.write("---- %s: %s -----\n" % (self.__class__.__name__, self.name))
pprint.pprint(self.__dict__, logfile)
@ -93,17 +93,17 @@ class Target:
pass
def assemble(self):
pass
class PYZTarget(Target):
def __init__(self, cfg, sectnm, cnvrts):
Target.__init__(self, cfg, sectnm, cnvrts)
# to use a PYZTarget, you'll need imputil and archive
# to use a PYZTarget, you'll need imputil and archive
archivebuilder.GetCompiled([os.path.join(pyinsthome, 'imputil.py')])
print "pyinsthome:", pyinsthome
imputil = resource.makeresource('imputil.py', [pyinsthome])
self._dependencies.append(imputil)
archivebuilder.GetCompiled([os.path.join(pyinsthome, 'archive_rt.py')])
archmodule = resource.makeresource('archive_rt.py', [pyinsthome])
archmodule = resource.makeresource('archive_rt.py', [pyinsthome])
self._dependencies.merge(archmodule.dependencies())
self._dependencies.append(archmodule)
self.toc.addFilter(archmodule)
@ -113,7 +113,7 @@ class PYZTarget(Target):
def edit(self):
if self.extypes:
print "PYZ target %s ignoring extypes = %s" % (self.__name__, self.extypes)
def gather(self):
for script in self.dependencies:
rsrc = resource.makeresource(script, self.pathprefix)
@ -134,17 +134,17 @@ class PYZTarget(Target):
logfile.write("Applying the following filters:\n")
pprint.pprint(self.toc.filters, logfile)
self.toc.filter()
def assemble(self):
contents = self.toc.toList()
if contents:
lib = archive.ZlibArchive()
lib.build(self.name, archivebuilder.GetCompiled(self.toc.toList()))
class CollectTarget(Target):
def __init__(self, cfg, sectnm, cnvrts):
Target.__init__(self, cfg, sectnm, cnvrts)
_rsrcdict = {'COLLECT': resource.dirresource, 'PYZ': resource.zlibresource, 'CARCHIVE': resource.archiveresource}
def gather(self):
@ -205,10 +205,10 @@ class CollectTarget(Target):
self.toc.merge(rsrc.contents())
logfile.write('ltoc after trees:\n')
pprint.pprint(self.toc.toList(), logfile)
self.toc.addFilter(tocfilter.TypeFilter(['d']))
self.toc.addFilter(tocfilter.TypeFilter(['d']))
logfile.write("Applying the following filters:\n")
pprint.pprint(self.toc.filters, logfile)
self.toc.filter()
self.toc.filter()
#don't dupe stuff in a zlib that's part of this target
if self.zlib:
ztoc = ltoc.lTOC()
@ -220,7 +220,7 @@ class CollectTarget(Target):
rsrc = self.toc[i]
if isinstance(rsrc, resource.moduleresource) and rsrc in ztoc:
del self.toc[i]
def assemble(self):
if os.path.exists(self.name):
if os.path.isdir(self.name):
@ -235,16 +235,16 @@ class CollectTarget(Target):
for nm, path, typ in self.toc.toList():
shutil.copy2(path, self.name)
if typ == 'z':
mysite.append('imputil.FuncImporter(archive.ZlibArchive("%s",0).get_code).install()' % nm)
mysite.append('imputil.FuncImporter(archive.ZlibArchive("%s", 0).get_code).install()' % nm)
if mysite:
mysite.insert(0, 'import archive, imputil')
open(os.path.join(self.name, 'site.py'),'w').write(string.join(mysite, '\n'))
class ArchiveTarget(CollectTarget):
usefullname = 1
def __init__(self, cfg, sectnm, cnvrts):
CollectTarget.__init__(self, cfg, sectnm, cnvrts)
CollectTarget.__init__(self, cfg, sectnm, cnvrts)
archivebuilder.GetCompiled([os.path.join(pyinsthome, 'carchive_rt.py')])
carchmodule = resource.makeresource('carchive_rt.py', [pyinsthome])
self._dependencies.merge(carchmodule.dependencies())
@ -253,12 +253,12 @@ class ArchiveTarget(CollectTarget):
def edit(self):
if self.destdir:
print "Warning 'destdir = %s' ignored for %s" % (self.destdir, self.name)
def gather(self):
CollectTarget.gather(self)
_cdict = {'s':2,'m':1,'b':1,'x':1,'a':0,'z':0, 'p':1}
def assemble(self, pkgnm=None):
if pkgnm is None:
pkgnm = self.name
@ -276,7 +276,7 @@ class ArchiveTarget(CollectTarget):
toc = toc + archivebuilder.GetCompiled(pytoc)
arch.build(pkgnm, toc)
return arch
class FullExeTarget(ArchiveTarget):
usefullname = 0
def __init__(self, cfg, sectnm, cnvrts):
@ -289,13 +289,13 @@ class FullExeTarget(ArchiveTarget):
rsrc = resource.scriptresource(rsrc.name, rsrc.path)
#print " resource is", `rsrc`
self.toc.merge(rsrc.binaries)
ArchiveTarget.gather(self)
ArchiveTarget.gather(self)
if not self.zlib:
self.toc.merge(rsrc.modules)
self._dependencies = ltoc.lTOC()
_cdict = {'s':2,'m':0,'b':1,'x':0,'a':0,'z':0}
_edict = { (1,1):'Runw_d.exe', (1,0):'Runw.exe', (0,1):'Run_d.exe', (0,0):'Run.exe'}
_edict = { (1, 1):'Runw_d.exe', (1, 0):'Runw.exe', (0, 1):'Run_d.exe', (0, 0):'Run.exe'}
def assemble(self):
pkgname = tempfile.mktemp()
@ -333,11 +333,11 @@ class FullExeTarget(ArchiveTarget):
else:
copyFile([exe, pkgname], self.name)
#os.remove(pkgname)
class ExeTarget(FullExeTarget):
def __init__(self, cfg, sectnm, cnvrts):
FullExeTarget.__init__(self, cfg, sectnm, cnvrts)
def edit(self):
if not self.script:
raise ValueError, "EXE target %s requires 'script= <script>'" % self.__name__
@ -403,8 +403,8 @@ class InstallTarget(FullExeTarget):
txt = open(s.path, 'r').read()
f.write(txt)
f.close()
dispatch = {
dispatch = {
'PYZ': PYZTarget,
'CARCHIVE': ArchiveTarget,
'COLLECT': CollectTarget,
@ -413,7 +413,7 @@ dispatch = {
'FULLEXE': FullExeTarget,
}
def makeTarget(cfg, section):
return dispatch[cfg.get(section, 'type')](cfg, section, optcnvrts)
@ -430,7 +430,7 @@ optdefaults = { 'type':'PYZ',
'expatterns': '',
'exstdlib': '0',
'extypes': '',
'includes':'', # PYZ
'includes':'', # PYZ
'packages':'', # PYZ
'destdir':'', # COLLECT
'pathprefix': '',
@ -438,13 +438,13 @@ optdefaults = { 'type':'PYZ',
'debug': '0',
'support': '1', # include python20.dll & exceptons.pyc at a minimum
'icon': '',
}
}
optcnvrts = { 'type':'',
'name': 'getstring',
'exstdlib': 'getbool',
'name': 'getstring',
'exstdlib': 'getbool',
'console': 'getbool',
'analyze': 'getbool',
'analyze': 'getbool',
'debug': 'getbool',
'includetk': 'getbool',
'userunw': 'getbool',
@ -492,10 +492,10 @@ def main(opts, args):
names = map(lambda x: getattr(x, 'name'), targets)
raise RuntimeError, "circular dependencies in %s" % `names`
targets = filter(None, targets)
def run(file):
main ([], file)
if __name__ == '__main__':
import getopt
(opts, args) = getopt.getopt(sys.argv[1:], 'dv')

View File

@ -17,7 +17,7 @@ import struct
class Archive:
""" A base class for a repository of python code objects.
The get_code method is used by imputil.FuntionImporter
to get code objects by name.
Archives are flat namespaces, so conflict between module
@ -47,7 +47,7 @@ class Archive:
####### Sub-methods of __init__ - override as needed #############
def checkmagic(self):
"""Verify version and validity of file.
Overridable.
Check to see if the file object self.lib actually has a file
we understand.
@ -61,7 +61,7 @@ class Archive:
def loadtoc(self):
"""Load the table of contents.
Overridable.
Default: After magic comes an int (4 byte native) giving the
position of the TOC within self.lib.
@ -77,7 +77,7 @@ class Archive:
def get_code(self, parent, modname, fqname):
"""The import hook.
Called by imputil.FunctionImporter.
Override extract to tune getting code from the Archive."""
rslt = self.extract(fqname) # None if not found, (ispkg, code) otherwise
@ -91,7 +91,7 @@ class Archive:
####### Core method - Override as needed #########
def extract(self, name):
""" Get the object corresponding to name, or None.
NAME is the name as specified in an 'import name'.
'import a.b' will become:
extract('a') (return None because 'a' is not a code object)
@ -102,7 +102,7 @@ class Archive:
self.toc[name] is pos
self.lib has the code object marshal-ed at pos
"""
ispkg, pos = self.toc.get(name, (0,None))
ispkg, pos = self.toc.get(name, (0, None))
if pos is None:
return None
self.lib.seek(self.start + pos)
@ -113,20 +113,20 @@ class Archive:
def contents(self):
"""Return a list of the contents.
Default implementation assumes self.toc is a dict like object.
"""
return self.toc.keys()
########################################################################
# Building
####### Top level method - shouldn't need overriding #######
def build(self, path, lTOC):
"""Create an archive file of name PATH from LTOC.
lTOC is a 'logical TOC' - a list of (name, path, ...)
where name is the internal (import) name,
where name is the internal (import) name,
and path is a file to get the object from, eg './a.pyc'.
"""
self.path = path
@ -139,18 +139,18 @@ class Archive:
if type(self.TOCTMPLT) == type({}):
self.toc = {}
else: # assume callable
else: # assume callable
self.toc = self.TOCTMPLT()
for tocentry in lTOC:
self.add(tocentry) # the guts of the archive
tocpos = self.lib.tell()
tocpos = self.lib.tell()
self.save_toc(tocpos)
if self.TRLLEN:
self.save_trailer(tocpos)
if self.HDRLEN:
self.update_headers(tocpos)
self.update_headers(tocpos)
self.lib.close()
@ -161,7 +161,7 @@ class Archive:
Override this to influence the mechanics of the Archive.
Assumes entry is a seq beginning with (nm, pth, ...) where
nm is the key by which we'll be asked for the object.
pth is the name of where we find the object.
pth is the name of where we find the object.
"""
if self.os is None:
import os
@ -188,13 +188,13 @@ class Archive:
def update_headers(self, tocpos):
"""Update any header data.
Default header is MAGIC + Python's magic + tocpos"""
self.lib.seek(self.start)
self.lib.write(self.MAGIC)
self.lib.write(self.pymagic)
self.lib.write(struct.pack('=i', tocpos))
##############################################################
#
# ZlibArchive - an archive with compressed entries
@ -215,10 +215,10 @@ class ZlibArchive(Archive):
# dynamic import so not imported if not needed
global zlib
import zlib
def extract(self, name):
"""Get the code object for NAME.
Return None if name is not in the table of contents.
Otherwise, return a tuple (ispkg, code)"""
(ispkg, pos, lngth) = self.toc.get(name, (0, None, 0))
@ -229,7 +229,7 @@ class ZlibArchive(Archive):
def add(self, entry):
"""Add an entry.
ENTRY is a sequence where entry[0] is name and entry[1] is full path name.
zlib compress the code object, and build a toc entry"""
if self.os is None:
@ -243,4 +243,4 @@ class ZlibArchive(Archive):
obj = zlib.compress(f.read(), self.LEVEL)
self.toc[nm] = (ispkg, self.lib.tell(), len(obj))
self.lib.write(obj)

View File

@ -98,7 +98,7 @@ class Archive:
self.toc[name] is pos
self.lib has the code object marshal-ed at pos
"""
ispkg, pos = self.toc.get(name, (0,None))
ispkg, pos = self.toc.get(name, (0, None))
if pos is None:
return None
self.lib.seek(self.start + pos)
@ -116,7 +116,7 @@ class Archive:
########################################################################
# Building
####### Top level method - shouldn't need overriding #######
## def build(self, path, lTOC):
## """Create an archive file of name 'path'.
@ -134,18 +134,18 @@ class Archive:
##
## if type(self.TOCTMPLT) == type({}):
## self.toc = {}
## else: # assume callable
## else: # assume callable
## self.toc = self.TOCTMPLT()
##
## for tocentry in lTOC:
## self.add(tocentry) # the guts of the archive
##
## tocpos = self.lib.tell()
## tocpos = self.lib.tell()
## self.save_toc(tocpos)
## if self.TRLLEN:
## self.save_trailer(tocpos)
## if self.HDRLEN:
## self.update_headers(tocpos)
## self.update_headers(tocpos)
## self.lib.close()
##
##
@ -184,7 +184,7 @@ class Archive:
## self.lib.write(self.MAGIC)
## self.lib.write(self.pymagic)
## self.lib.write(struct.pack('=i', tocpos))
##############################################################
#
# ZlibArchive - an archive with compressed entries
@ -203,7 +203,7 @@ class ZlibArchive(Archive):
# dynamic import so not imported if not needed
global zlib
import zlib
def extract(self, name):
(ispkg, pos, lngth) = self.toc.get(name, (0, None, 0))
if pos is None:
@ -223,4 +223,4 @@ class ZlibArchive(Archive):
## obj = zlib.compress(f.read(), self.LEVEL)
## self.toc[nm] = (ispkg, self.lib.tell(), len(obj))
## self.lib.write(obj)
##
##

View File

@ -21,8 +21,8 @@ import tempfile
import finder
seen = {}
excludes = {'KERNEL32.DLL':1,
'ADVAPI.DLL':1,
excludes = {'KERNEL32.DLL':1,
'ADVAPI.DLL':1,
'MSVCRT.DLL':1,
'ADVAPI32.DLL':1,
'COMCTL32.DLL':1,
@ -43,11 +43,11 @@ excludes = {'KERNEL32.DLL':1,
'COMDLG32.DLL':1,
'ZLIB.DLL':1,
'ODBC32.DLL':1,
'VERSION.DLL':1}
'VERSION.DLL':1}
def getfullnameof(mod, xtrapath = None):
"""Return the full path name of MOD.
MOD is the basename of a dll or pyd.
XTRAPATH is a path or list of paths to search first.
Return the full path name of MOD.
@ -65,10 +65,10 @@ def getfullnameof(mod, xtrapath = None):
if os.path.exists(npth):
return npth
return ''
def getImports1(pth):
"""Find the binary dependencies of PTH.
This implementation (not used right now) uses the MSVC utility dumpbin"""
rslt = []
tmpf = tempfile.mktemp()
@ -83,10 +83,10 @@ def getImports1(pth):
rslt.append(string.strip(tokens[0]))
i = i + 1
return rslt
def getImports2(pth):
"""Find the binary dependencies of PTH.
This implementation walks through the PE header"""
import struct
rslt = []
@ -127,43 +127,43 @@ def getImports2(pth):
except struct.error:
print "bindepend cannot analyze %s - error walking thru pehdr"
return rslt
def Dependencies(lTOC):
"""Expand LTOC to include all the closure of binary dependencies.
LTOC is a logical table of contents, ie, a seq of tuples (name, path).
Return LTOC expanded by all the binary dependencies of the entries
in LTOC, except those listed in the module global EXCLUDES"""
for (nm, pth) in lTOC:
fullnm = string.upper(os.path.basename(pth))
if seen.get(string.upper(nm),0):
if seen.get(string.upper(nm), 0):
continue
print "analyzing", nm
seen[string.upper(nm)] = 1
dlls = getImports(pth)
for lib in dlls:
print " found", lib
if excludes.get(string.upper(lib),0):
if excludes.get(string.upper(lib), 0):
continue
if seen.get(string.upper(lib),0):
if seen.get(string.upper(lib), 0):
continue
npth = getfullnameof(lib)
if npth:
lTOC.append((lib, npth))
else:
print " lib not found:", lib, "dependency of",
print " lib not found:", lib, "dependency of",
return lTOC
##if getfullnameof('dumpbin.exe') == '':
## def getImports(pth):
## return getImports2(pth)
##else:
## def getImports(pth):
## return getImports1(pth)
def getImports(pth):
"""Forwards to either getImports1 or getImports2
"""
return getImports2(pth)

View File

@ -4,11 +4,11 @@ import strop
import zlib
import os
import marshal
class MkImporter:
def __init__(self, db, viewnm='pylib'):
self.db = db
self.view = db.getas(viewnm+'[name:S,ispkg:I,code:M]') # an MkWrap view object
self.view = db.getas(viewnm+'[name:S, ispkg:I, code:M]') # an MkWrap view object
def setImportHooks(self):
imputil.FuncImporter(self.get_code).install()
def get_code(self, parent, modname, fqname):

View File

@ -10,7 +10,7 @@ _cache = {}
def makeresource(name, xtrapath=None):
"""Factory function that returns a resource subclass.
NAME is the logical or physical name of a resource.
XTRAPTH is a path or list of paths to search first.
return one of the resource subclasses.
@ -44,7 +44,7 @@ def makeresource(name, xtrapath=None):
class resource:
""" Base class for all resources.
contents() returns of list of what's contained (eg files in dirs)
dependencies() for Python resources returns a list of moduleresources
and binaryresources """
@ -60,13 +60,13 @@ class resource:
return "(%(name)s, %(path)s, %(typ)s)" % self.__dict__
def contents(self):
"""A list of resources within this resource.
Overridable.
Base implementation returns [self]"""
return [self]
def dependencies(self):
"""A list of resources this resource requires.
Overridable.
Base implementation returns []"""
return []
@ -76,30 +76,30 @@ class resource:
return cmp((self.typ, self.name), (other.typ, other.name))
def asFilter(self):
"""Create a tocfilter based on self.
Pure virtual"""
raise NotImplementedError
def asSource(self):
"""Return self in source form.
Base implementation returns self"""
return self
def asBinary(self):
"""Return self in binary form.
Base implementation returns self"""
return self
class pythonresource(resource):
"""An empty base class.
Used to classify resources."""
pass
class scriptresource(pythonresource):
""" A top-level python resource.
Has (lazily computed) attributes, modules and binaries, which together
are the scripts dependencies() """
def __init__(self, name, fullname):
@ -141,25 +141,25 @@ class scriptresource(pythonresource):
return tocfilter.ModFilter([self.name])
def asSource(self):
"""Return self as a dataresource (ie, a text file wrapper)."""
r = dataresource(self.path)
r = dataresource(self.path)
r.name = apply(os.path.join, string.split(self.name, '.')[:-1]+[r.name])
return r
return r
class moduleresource(scriptresource):
""" A module resource (differs from script in that it will generally
""" A module resource (differs from script in that it will generally
be worked with as a .pyc instead of in source form) """
def __init__(self, name, fullname):
resource.__init__(self, name, fullname, 'm')
def asBinary(self):
"""Return self as a dataresource (ie, a binary file wrapper)."""
r = dataresource(self.path)
r = dataresource(self.path)
r.name = os.path.basename(r.name)
r.typ = 'b'
return r
return r
def asSource(self):
"""Return self as a scriptresource (ie, uncompiled form)."""
return scriptresource(self.name, self.path[:-1]).asSource()
class binaryresource(resource):
"""A .dll or .pyd.
@ -182,7 +182,7 @@ class binaryresource(resource):
def asFilter(self):
"""Create a FileFilter from self."""
return tocfilter.FileFilter([self.name])
class dataresource(resource):
"""A subclass for arbitrary files. """
def __init__(self, name, fullname=None):
@ -190,22 +190,22 @@ class dataresource(resource):
def asFilter(self):
"""Create a FileFilter from self."""
return tocfilter.FileFilter([self.name])
class archiveresource(dataresource):
"""A sublcass for CArchives. """
def __init__(self, name, fullname=None):
resource.__init__(self, name, fullname or name, 'a')
class zlibresource(dataresource):
"""A subclass for ZlibArchives. """
def __init__(self, name, fullname=None):
resource.__init__(self, name, fullname or name, 'z')
class dirresource(resource):
"""A sublcass for a directory.
Generally transformed to a list of files through
contents() and filtered by file extensions or resource type.
Generally transformed to a list of files through
contents() and filtered by file extensions or resource type.
Note that contents() is smart enough to regard a .py and .pyc
as the same resource. """
RECURSIVE = 0
@ -226,7 +226,7 @@ class dirresource(resource):
elif ext == '.pyo' and (bnm + '.pyc' in flist):
pass
else:
rsrc = makeresource(os.path.join(self.path,fnm))
rsrc = makeresource(os.path.join(self.path, fnm))
if isinstance(rsrc, pkgresource):
rsrc = self.__class__(rsrc.path)
if self.RECURSIVE:
@ -241,22 +241,22 @@ class dirresource(resource):
self._contents.append(rsrc)
else:
self._contents.append(rsrc)
except ValueError,e:
except ValueError, e:
raise RuntimeError, "Can't make resource from %s\n ValueError: %s" \
% (os.path.join(self.path, fnm), `e.args`)
return self._contents
def asFilter(self):
return tocfilter.DirFilter([self.path])
class treeresource(dirresource):
"""A subclass for a directory and subdirectories."""
RECURSIVE = 1
def __init__(self, name, fullname=None):
dirresource.__init__(self, name, fullname)
class pkgresource(pythonresource):
"""A Python package.
Note that contents() can be fooled by fancy __path__ statements. """
def __init__(self, nm, fullname):
resource.__init__(self, nm, fullname, 'p')
@ -303,15 +303,15 @@ class pkgresource(pythonresource):
def asFilter(self):
"""Create a PkgFilter from self."""
return tocfilter.PkgFilter([os.path.dirname(self.path)])
if __name__ == '__main__':
s = scriptresource('finder.py', './finder.py')
print "s.modules:", s.modules
print "s.binaries:", s.binaries

View File

@ -8,7 +8,7 @@ or be the same type.
Internally the pool is implemented with 2 lists, free items and used items.
p = Pool([1,2,3,4,5])
p = Pool([1, 2, 3, 4, 5])
x = p.checkout()
p.checkin(x)
@ -20,7 +20,7 @@ from direct.directnotify import DirectNotifyGlobal
class Pool:
notify = DirectNotifyGlobal.directNotify.newCategory("Pool")
def __init__(self, free=None):
if free:
self.__free = free
@ -107,8 +107,8 @@ class Pool:
cleanupFunc(item)
del self.__free
del self.__used
def __repr__(self):
def __repr__(self):
return "free = %s\nused = %s" % (self.__free, self.__used)

View File

@ -18,10 +18,10 @@ class RandomNumGen:
def __init__(self, seed):
"""seed must be an integer or another RandomNumGen"""
if isinstance(seed,RandomNumGen):
if isinstance(seed, RandomNumGen):
# seed this rng with the other rng
rng = seed
seed = rng.randint(0,1L << 16)
seed = rng.randint(0, 1L << 16)
self.notify.debug("seed: " + str(seed))
seed = int(seed)
@ -120,8 +120,8 @@ class RandomNumGen:
raise ValueError, "empty range for randrange()"
return istart + istep*int(self.__rand(n))
def randint(self, a,b):
"""returns integer in [a,b]"""
def randint(self, a, b):
"""returns integer in [a, b]"""
assert a <= b
range = b-a+1
r = self.__rand(range)
@ -131,5 +131,5 @@ class RandomNumGen:
# this function for important decision points where remote
# synchronicity is critical
def random(self):
"""returns random float in [0.0,1.0)"""
"""returns random float in [0.0, 1.0)"""
return float(self.__rng.getUint31()) / float(1L << 31)

View File

@ -9,7 +9,7 @@ This is meant primarily as a demonstration of multipass and
multitexture rendering techniques. It's not a particularly great
way to do shadows.
"""
from pandac.PandaModules import *
from direct.task import Task
@ -18,7 +18,7 @@ sc = None
class ShadowCaster:
texXSize = 128
texYSize = 128
def __init__(self, lightPath, objectPath, filmX, filmY):
self.lightPath = lightPath
self.objectPath = objectPath
@ -75,7 +75,7 @@ class ShadowCaster:
""" Specifies the part of the world that is to be considered
the ground: this is the part onto which the rendered texture
will be applied. """
if self.groundPath:
self.groundPath.clearProjectTexture(self.stage)
@ -128,12 +128,12 @@ def avatarShadow():
return Task.cont
taskMgr.remove('shadowCamera')
taskMgr.add(shadowCameraRotate, 'shadowCamera')
taskMgr.add(shadowCameraRotate, 'shadowCamera')
global sc
if sc != None:
sc.clear()
sc = ShadowCaster(lightPath, objectPath, 4, 6)
# Naively, just apply the shadow to everything in the world. It
@ -147,7 +147,7 @@ def piratesAvatarShadow():
# Force the lod to be 0 at all times
base.localAvatar.getGeomNode().getChild(0).node().forceSwitch(0)
return a
def arbitraryShadow(node):
# Turn off the existing drop shadow, if any
if hasattr(node, "dropShadow"):
@ -174,12 +174,12 @@ def arbitraryShadow(node):
return Task.cont
taskMgr.remove('shadowCamera')
taskMgr.add(shadowCameraRotate, 'shadowCamera')
taskMgr.add(shadowCameraRotate, 'shadowCamera')
global sc
if sc != None:
sc.clear()
sc = ShadowCaster(lightPath, objectPath, 100, 100)
# Naively, just apply the shadow to everything in the world. It
@ -203,16 +203,16 @@ def arbitraryShadow(node):
##aNP = s.attachNewNode(a.upcastToPandaNode())
##b.setLight(aNP)
##d = DirectionalLight("chernabogDirectionalLight")
##d.setDirection(Vec3(0,1,0))
##d.setDirection(Vec3(0, 1, 0))
##d.setColor(Vec4(1))
###d.setColor(Vec4(0.9, 0.7, 0.7, 1.000))
##dNP = s.attachNewNode(d.upcastToPandaNode())
##b.setLight(dNP)
##
##ival = Sequence(LerpPosInterval(bs.lightPath, 0.0, Vec3(-200,0,50)),
## LerpPosInterval(bs.lightPath, 10.0, Vec3(-200,0,200)),
## LerpPosInterval(bs.lightPath, 10.0, Vec3(200,0,200)),
## LerpPosInterval(bs.lightPath, 10.0, Vec3(200,0,50)),
##ival = Sequence(LerpPosInterval(bs.lightPath, 0.0, Vec3(-200, 0, 50)),
## LerpPosInterval(bs.lightPath, 10.0, Vec3(-200, 0, 200)),
## LerpPosInterval(bs.lightPath, 10.0, Vec3(200, 0, 200)),
## LerpPosInterval(bs.lightPath, 10.0, Vec3(200, 0, 50)),
##)
##ival.loop()

View File

@ -14,7 +14,7 @@ class Transitions:
def __init__(self, loader,
model=None,
scale=3.0,
pos=Vec3(0,0,0)):
pos=Vec3(0, 0, 0)):
self.transitionIval = None
self.letterboxIval = None
self.iris = None
@ -24,15 +24,15 @@ class Transitions:
self.imageScale = scale
self.imagePos = pos
if model:
self.alphaOff = Vec4(1,1,1,0)
self.alphaOn = Vec4(1,1,1,1)
self.alphaOff = Vec4(1, 1, 1, 0)
self.alphaOn = Vec4(1, 1, 1, 1)
model.setTransparency(1)
self.lerpFunc = LerpColorScaleInterval
else:
self.alphaOff = Vec4(0,0,0,0)
self.alphaOn = Vec4(0,0,0,1)
self.alphaOff = Vec4(0, 0, 0, 0)
self.alphaOn = Vec4(0, 0, 0, 1)
self.lerpFunc = LerpColorInterval
self.irisTaskName = "irisTask"
self.fadeTaskName = "fadeTask"
self.letterboxTaskName = "letterboxTask"
@ -41,7 +41,7 @@ class Transitions:
if self.fadeModel:
self.fadeModel.removeNode()
self.fadeModel = None
##################################################
# Fade
##################################################
@ -51,18 +51,18 @@ class Transitions:
self.fadeModel = model
# We have to change some default parameters for a custom fadeModel
self.imageScale = scale
self.alphaOn = Vec4(1,1,1,1)
self.alphaOn = Vec4(1, 1, 1, 1)
# Reload fade if its already been created
if self.fade:
del self.fade
self.fade = None
self.loadFade()
def loadFade(self):
if not self.fadeModel:
self.fadeModel = loader.loadModel(self.FadeModelName)
if self.fade == None:
# We create a DirectFrame for the fade polygon, instead of
# simply loading the polygon model and using it directly,
@ -75,14 +75,14 @@ class Transitions:
image = self.fadeModel,
image_scale = self.imageScale,
state = NORMAL,
)
)
def fadeIn(self, t=0.5, finishIval=None):
"""
Play a fade in transition over t seconds.
Places a polygon on the aspect2d plane then lerps the color
from black to transparent. When the color lerp is finished, it
parents the fade polygon to hidden.
parents the fade polygon to hidden.
"""
self.noTransitions()
self.loadFade()
@ -102,7 +102,7 @@ class Transitions:
if finishIval:
self.transitionIval.append(finishIval)
self.transitionIval.start()
def fadeOut(self, t=0.5, finishIval=None):
"""
Play a fade out transition over t seconds.
@ -156,7 +156,7 @@ class Transitions:
self.noTransitions()
self.loadFade()
self.fade.reparentTo(aspect2d, FADE_SORT_INDEX)
self.fade.setColor(color)
self.fade.setColor(color)
def noFade(self):
"""
@ -169,8 +169,8 @@ class Transitions:
self.fade.detachNode()
def setFadeColor(self, r, g, b):
self.alphaOn.set(r,g,b,1)
self.alphaOff.set(r,g,b,0)
self.alphaOn.set(r, g, b, 1)
self.alphaOff.set(r, g, b, 0)
##################################################
@ -180,7 +180,7 @@ class Transitions:
def loadIris(self):
if self.iris == None:
self.iris = loader.loadModel(self.IrisModelName)
self.iris.setPos(0,0,0)
self.iris.setPos(0, 0, 0)
def irisIn(self, t=0.5, finishIval=None):
"""
@ -205,7 +205,7 @@ class Transitions:
if finishIval:
self.transitionIval.append(finishIval)
self.transitionIval.start()
def irisOut(self, t=0.5, finishIval=None):
"""
Play an iris out transition over t seconds.
@ -275,22 +275,22 @@ class Transitions:
guiId = 'letterboxTop',
relief = FLAT,
state = NORMAL,
frameColor = (0,0,0,1),
borderWidth = (0,0),
frameColor = (0, 0, 0, 1),
borderWidth = (0, 0),
frameSize = (-1, 1, 0, 0.2),
pos = (0,0,0.8),
pos = (0, 0, 0.8),
)
self.letterboxBottom = DirectFrame(
parent = self.letterbox,
guiId = 'letterboxBottom',
relief = FLAT,
state = NORMAL,
frameColor = (0,0,0,1),
borderWidth = (0,0),
frameColor = (0, 0, 0, 1),
borderWidth = (0, 0),
frameSize = (-1, 1, 0, 0.2),
pos = (0,0,-1),
pos = (0, 0, -1),
)
def noLetterbox(self):
"""
Removes any current letterbox tasks and parents the letterbox polygon away
@ -309,16 +309,16 @@ class Transitions:
self.loadLetterbox()
if (t == 0):
self.letterbox.reparentTo(render2d, FADE_SORT_INDEX)
self.letterboxBottom.setPos(0,0,-1)
self.letterboxTop.setPos(0,0,0.8)
self.letterboxBottom.setPos(0, 0, -1)
self.letterboxTop.setPos(0, 0, 0.8)
else:
self.letterbox.reparentTo(render2d, FADE_SORT_INDEX)
self.letterboxIval = Sequence(Parallel(LerpPosInterval(self.letterboxBottom, t,
pos = Vec3(0,0,-1),
startPos = Vec3(0,0,-1.2)),
pos = Vec3(0, 0, -1),
startPos = Vec3(0, 0, -1.2)),
LerpPosInterval(self.letterboxTop, t,
pos = Vec3(0,0,0.8),
startPos = Vec3(0,0,1)),
pos = Vec3(0, 0, 0.8),
startPos = Vec3(0, 0, 1)),
LerpColorInterval(self.letterbox, t,
color = self.alphaOn,
startColor = self.alphaOff),
@ -328,7 +328,7 @@ class Transitions:
if finishIval:
self.letterboxIval.append(finishIval)
self.letterboxIval.start()
def letterboxOff(self, t=0.25, finishIval=None):
"""
Move black bars away over t seconds.
@ -340,11 +340,11 @@ class Transitions:
else:
self.letterbox.reparentTo(render2d, FADE_SORT_INDEX)
self.letterboxIval = Sequence(Parallel(LerpPosInterval(self.letterboxBottom, t,
pos = Vec3(0,0,-1.2),
startPos = Vec3(0,0,-1)),
pos = Vec3(0, 0, -1.2),
startPos = Vec3(0, 0, -1)),
LerpPosInterval(self.letterboxTop, t,
pos = Vec3(0,0,1),
startPos = Vec3(0,0,0.8)),
pos = Vec3(0, 0, 1),
startPos = Vec3(0, 0, 0.8)),
LerpColorInterval(self.letterbox, t,
color = self.alphaOff,
startColor = self.alphaOn),

View File

@ -2,11 +2,11 @@
#
# SQUEEZE
#
# squeeze a python program
# squeeze a python program
#
# installation:
# - use this script as is, or squeeze it using the following command:
#
#
# python squeezeTool.py -1su -o squeeze -b squeezeTool squeezeTool.py
#
# notes:
@ -307,11 +307,11 @@ def squeeze(app, start, filelist, outputDir):
fp = open(bootstrap, "w")
fp.write('''\
#%(localMagic)s %(archiveid)s
import ihooks,zlib,base64,marshal
import ihooks, zlib, base64, marshal
s=base64.decodestring("""
%(data)s""")
exec marshal.loads(%(zbegin)ss[:%(loaderlen)d]%(zend)s)
boot("%(app)s",s,%(size)d,%(loaderlen)d)
boot("%(app)s", s, %(size)d, %(loaderlen)d)
exec "import %(start)s"
''' % locals())
bytes = fp.tell()
@ -334,7 +334,7 @@ exec "import %(start)s"
# Note: David Rose adjusted the following to be panda-specific.
fp.write("""\
#%(localMagic)s %(archiveid)s
import ihooks,zlib,marshal,os,sys
import ihooks, zlib, marshal, os, sys
import pandac
@ -356,7 +356,7 @@ if archivePath == None:
f=open(archivePath,"rb")
exec marshal.loads(%(zbegin)sf.read(%(loaderlen)d)%(zend)s)
boot("%(app)s",f,%(size)d)
boot("%(app)s", f, %(size)d)
exec "from %(start)s import *"
#exec "run()"
""" % locals())

View File

@ -14,7 +14,7 @@ if __name__ == "__main__":
print 'Usage: pass in -O for optimized'
print ' pass in -d directory'
sys.exit()
fOptimized = 0
# Store the option values into our variables
for opt in opts:
@ -24,7 +24,7 @@ if __name__ == "__main__":
print 'Squeezing pyo files'
elif (flag == '-d'):
os.chdir(value)
def getSqueezeableFiles():
fileList = os.listdir(".")
newFileList = []
@ -33,21 +33,21 @@ if __name__ == "__main__":
else:
targetFileExtension = ".pyc"
for i in fileList:
base,ext = os.path.splitext(i)
base, ext = os.path.splitext(i)
if (ext == ".py"):
newFileList.append(i)
return newFileList
def squeezePandaFiles():
l = getSqueezeableFiles()
pandaSqueezeTool.squeeze("PandaModules", "PandaModulesUnsqueezed", l)
# Clean up the source files now that they've been squeezed. If
# you don't like this behavior (e.g. if you want to inspect the
# generated files), use genPyCode -n to avoid squeezing
# altogether.
for i in l:
os.unlink(i)
squeezePandaFiles()

View File

@ -65,7 +65,7 @@ def print_exc_plus():
#We have to be careful not to cause a new error in our error
#printer! Calling str() on an unknown object could cause an
#error we don't want.
try:
try:
print value
except:
print "<ERROR WHILE PRINTING VALUE>"
@ -209,8 +209,8 @@ def make_sequence(taskList):
# TaskManager.notify.debug('sequence done: ' + self.name)
frameFinished = 1
taskDoneStatus = done
return taskDoneStatus
return taskDoneStatus
task = Task(func)
task.name = 'sequence'
@ -309,7 +309,7 @@ class TaskManager:
# TODO: there is a bit of a bug when you default this to 0. The first
# task we make, the doLaterProcessor, needs to have this set to 1 or
# else we get an error.
taskTimerVerbose = 1
taskTimerVerbose = 1
extendedExceptions = 0
pStatsTasks = 0
@ -642,7 +642,7 @@ class TaskManager:
task.avgDt = 0
return ret
def __repeatDoMethod(self,task):
def __repeatDoMethod(self, task):
"""
Called when a task execute function returns Task.again because
it wants the task to execute again after the same or a modified
@ -721,7 +721,7 @@ class TaskManager:
# assert TaskManager.notify.debug('step: moving %s from pending to taskList' % (task.name))
self.__addNewTask(task)
self.pendingTaskDict.clear()
def step(self):
# assert TaskManager.notify.debug('step: begin')
self.currentTime, self.currentFrame = self.__getTimeFrame()
@ -766,7 +766,7 @@ class TaskManager:
# Add new pending tasks
self.__addPendingTasksToTaskList()
# Restore default interrupt handler
signal.signal(signal.SIGINT, signal.default_int_handler)
if self.fKeyboardInterrupt:
@ -783,7 +783,7 @@ class TaskManager:
if self.resumeFunc != None:
self.resumeFunc()
if self.stepping:
self.step()
else:
@ -906,7 +906,7 @@ class TaskManager:
# The priority heap is not actually in order - it is a tree
# Make a shallow copy so we can sort it
sortedDoLaterList = self.__doLaterList[:]
sortedDoLaterList.sort(lambda a,b: cmp(a.wakeTime, b.wakeTime))
sortedDoLaterList.sort(lambda a, b: cmp(a.wakeTime, b.wakeTime))
sortedDoLaterList.reverse()
for task in sortedDoLaterList:
remainingTime = ((task.wakeTime) - self.currentTime)
@ -954,7 +954,7 @@ class TaskManager:
def __getTimeFrame(self):
# WARNING: If you are testing tasks without an igLoop,
# you must manually tick the clock
# you must manually tick the clock
# Ask for the time last frame
return globalClock.getFrameTime(), globalClock.getFrameCount()

View File

@ -99,7 +99,7 @@ class AnimPanel(AppShell):
text = 'Toggle Enable',
command = self.toggleAllControls)
b.pack(side = RIGHT, expand = 0)
b = self.createcomponent(
'showSecondsButton', (), None,
Button, (self.menuFrame,),
@ -126,7 +126,7 @@ class AnimPanel(AppShell):
width = 8,
command = self.resetAllToZero)
self.toStartButton.pack(side = LEFT, expand = 1, fill = X)
self.playButton = self.createcomponent(
'playButton', (), None,
Button, (controlFrame,),
@ -148,7 +148,7 @@ class AnimPanel(AppShell):
width = 8,
command = self.resetAllToEnd)
self.toEndButton.pack(side = LEFT, expand = 1, fill = X)
self.loopVar = IntVar()
self.loopVar.set(0)
self.loopButton = self.createcomponent(
@ -264,7 +264,7 @@ class AnimPanel(AppShell):
getModelPath().prependDirectory(fileDirNameFN)
for currActor in self['actorList']:
# replace all currently loaded anims with specified one
# currActor.unloadAnims(None,None,None)
# currActor.unloadAnims(None, None, None)
currActor.loadAnims({fileBaseNameBase:fileBaseNameBase})
self.clearActorControls()
self.createActorControls()
@ -294,7 +294,7 @@ class AnimPanel(AppShell):
def getActorControlAt(self, index):
return self.actorControlList[index]
def enableActorControlAt(self,index):
def enableActorControlAt(self, index):
self.getActorControlAt(index).enableControl()
def toggleAllControls(self):
@ -303,7 +303,7 @@ class AnimPanel(AppShell):
else:
self.enableActorControls()
self.fToggleAll = 1 - self.fToggleAll
def enableActorControls(self):
for actorControl in self.actorControlList:
actorControl.enableControl()
@ -312,7 +312,7 @@ class AnimPanel(AppShell):
for actorControl in self.actorControlList:
actorControl.disableControl()
def disableActorControlAt(self,index):
def disableActorControlAt(self, index):
self.getActorControlAt(index).disableControl()
def displayFrameCounts(self):
@ -371,18 +371,18 @@ class ActorControl(Pmw.MegaWidget):
# Create component widgets
self._label = self.createcomponent(
'label', (), None,
Menubutton, (interior,),
Menubutton, (interior,),
font=('MSSansSerif', 14, 'bold'),
relief = RAISED, bd = 1,
activebackground = '#909090',
text = self['text'])
# Top level menu
labelMenu = Menu(self._label, tearoff = 0)
# Menu to select display mode
self.unitsVar = IntVar()
self.unitsVar.set(FRAMES)
displayMenu = Menu(labelMenu, tearoff = 0)
displayMenu = Menu(labelMenu, tearoff = 0)
displayMenu.add_radiobutton(label = 'Frame count',
value = FRAMES,
variable = self.unitsVar,
@ -500,7 +500,7 @@ class ActorControl(Pmw.MegaWidget):
else:
self.minLabel['text'] = '0.0'
self.maxLabel['text'] = "%.2f" % self.duration
self.frameControl.configure(from_ = 0.0,
self.frameControl.configure(from_ = 0.0,
to = self.duration,
resolution = 0.01)
@ -600,13 +600,13 @@ class ActorControl(Pmw.MegaWidget):
# This flag forces self.currT to be updated to new value
self.fOneShot = 1
self.goToT(0)
def resetToEnd(self):
# This flag forces self.currT to be updated to new value
self.fOneShot = 1
self.goToT(self.duration)
"""
# EXAMPLE CODE
from direct.actor import Actor

View File

@ -37,7 +37,7 @@ class DirectSessionPanel(AppShell):
# Call superclass initialization function
AppShell.__init__(self, parent)
# Active light
if len(direct.lights) > 0:
name = direct.lights.getNameList()[0]
@ -75,7 +75,7 @@ class DirectSessionPanel(AppShell):
('DIRECT_redo', self.redoHook),
('DIRECT_pushRedo', self.pushRedoHook),
('DIRECT_redoListEmpty', self.redoListEmptyHook),
('DIRECT_selectedNodePath',self.selectedNodePathHook),
('DIRECT_selectedNodePath', self.selectedNodePathHook),
('DIRECT_addLight', self.addLight),
]
for event, method in self.actionEvents:
@ -86,7 +86,7 @@ class DirectSessionPanel(AppShell):
interior = self.interior()
# Add placer commands to menubar
self.menuBar.addmenu('DIRECT', 'Direct Session Panel Operations')
self.directEnabled = BooleanVar()
self.directEnabled.set(1)
self.menuBar.addmenuitem('DIRECT', 'checkbutton',
@ -94,7 +94,7 @@ class DirectSessionPanel(AppShell):
label = 'Enable',
variable = self.directEnabled,
command = self.toggleDirect)
self.directGridEnabled = BooleanVar()
self.directGridEnabled.set(direct.grid.isEnabled())
self.menuBar.addmenuitem('DIRECT', 'checkbutton',
@ -113,7 +113,7 @@ class DirectSessionPanel(AppShell):
'Toggle Widget Move/COA Mode',
label = 'Toggle Widget Mode',
command = direct.manipulationControl.toggleObjectHandlesMode)
self.directWidgetOnTop = BooleanVar()
self.directWidgetOnTop.set(0)
self.menuBar.addmenuitem('DIRECT', 'checkbutton',
@ -193,10 +193,10 @@ class DirectSessionPanel(AppShell):
## Environment page ##
# Backgroud color
bkgrdFrame = Frame(envPage, borderwidth = 2, relief = 'sunken')
Label(bkgrdFrame, text = 'Background',
font=('MSSansSerif', 14, 'bold')).pack(expand = 0)
self.backgroundColor = VectorWidgets.ColorEntry(
bkgrdFrame, text = 'Background Color')
self.backgroundColor['command'] = self.setBackgroundColorVec
@ -207,7 +207,7 @@ class DirectSessionPanel(AppShell):
drFrame = Frame(envPage, borderwidth = 2, relief = 'sunken')
Label(drFrame, text = 'Display Region',
font=('MSSansSerif', 14, 'bold')).pack(expand = 0)
nameList = map(lambda x: 'Display Region ' + `x`,
range(len(direct.drList)))
self.drMenu = Pmw.ComboBox(
@ -217,7 +217,7 @@ class DirectSessionPanel(AppShell):
scrolledlist_items = nameList)
self.drMenu.pack(fill = X, expand = 0)
self.bind(self.drMenu, 'Select display region to configure')
self.nearPlane = Floater.Floater(
drFrame,
text = 'Near Plane',
@ -225,7 +225,7 @@ class DirectSessionPanel(AppShell):
self.nearPlane['command'] = self.setNear
self.nearPlane.pack(fill = X, expand = 0)
self.bind(self.nearPlane, 'Set near plane distance')
self.farPlane = Floater.Floater(
drFrame,
text = 'Far Plane',
@ -243,7 +243,7 @@ class DirectSessionPanel(AppShell):
self.hFov['command'] = self.setHFov
self.hFov.pack(fill = X, expand = 0)
self.bind(self.hFov, 'Set horizontal field of view')
self.vFov = Slider.Slider(
fovFloaterFrame,
text = 'Vertical FOV',
@ -270,8 +270,8 @@ class DirectSessionPanel(AppShell):
self.resetFovButton.pack(fill = X, expand = 0)
frame.pack(side = LEFT, fill = X, expand = 0)
fovFrame.pack(fill = X, expand = 1)
drFrame.pack(fill = BOTH, expand = 0)
## Render Style ##
@ -283,7 +283,7 @@ class DirectSessionPanel(AppShell):
text = 'Backface',
command = base.toggleBackface)
self.toggleBackfaceButton.pack(side = LEFT, fill = X, expand = 1)
self.toggleLightsButton = Button(
toggleFrame,
text = 'Lights',
@ -295,7 +295,7 @@ class DirectSessionPanel(AppShell):
text = 'Texture',
command = base.toggleTexture)
self.toggleTextureButton.pack(side = LEFT, fill = X, expand = 1)
self.toggleWireframeButton = Button(
toggleFrame,
text = 'Wireframe',
@ -318,10 +318,10 @@ class DirectSessionPanel(AppShell):
command = self.addPoint)
lightsMenu.add_command(label = 'Add Spotlight',
command = self.addSpot)
self.lightsButton.pack(expand = 0)
self.lightsButton['menu'] = lightsMenu
# Notebook pages for light specific controls
self.lightNotebook = Pmw.NoteBook(lightFrame, tabpos = None,
borderwidth = 0)
@ -344,11 +344,11 @@ class DirectSessionPanel(AppShell):
command = self.toggleLights)
self.enableLightsButton.pack(side = LEFT, fill = X, expand = 0)
mainSwitchFrame.pack(fill = X, expand = 0)
# Widget to select a light to configure
nameList = direct.lights.getNameList()
lightMenuFrame = Frame(lightFrame)
self.lightMenu = Pmw.ComboBox(
lightMenuFrame, labelpos = W, label_text = 'Light:',
entry_width = 20,
@ -356,7 +356,7 @@ class DirectSessionPanel(AppShell):
scrolledlist_items = nameList)
self.lightMenu.pack(side = LEFT, fill = X, expand = 0)
self.bind(self.lightMenu, 'Select light to configure')
self.lightActive = BooleanVar()
self.lightActiveButton = Checkbutton(
lightMenuFrame,
@ -398,7 +398,7 @@ class DirectSessionPanel(AppShell):
self.pConstantAttenuation.pack(fill = X, expand = 0)
self.bind(self.pConstantAttenuation,
'Set point light constant attenuation')
self.pLinearAttenuation = Slider.Slider(
pointPage,
text = 'Linear Attenuation',
@ -407,7 +407,7 @@ class DirectSessionPanel(AppShell):
self.pLinearAttenuation.pack(fill = X, expand = 0)
self.bind(self.pLinearAttenuation,
'Set point light linear attenuation')
self.pQuadraticAttenuation = Slider.Slider(
pointPage,
text = 'Quadratic Attenuation',
@ -416,7 +416,7 @@ class DirectSessionPanel(AppShell):
self.pQuadraticAttenuation.pack(fill = X, expand = 0)
self.bind(self.pQuadraticAttenuation,
'Set point light quadratic attenuation')
# Spot light controls
self.sSpecularColor = VectorWidgets.ColorEntry(
spotPage, text = 'Specular Color')
@ -433,7 +433,7 @@ class DirectSessionPanel(AppShell):
self.sConstantAttenuation.pack(fill = X, expand = 0)
self.bind(self.sConstantAttenuation,
'Set spot light constant attenuation')
self.sLinearAttenuation = Slider.Slider(
spotPage,
text = 'Linear Attenuation',
@ -442,7 +442,7 @@ class DirectSessionPanel(AppShell):
self.sLinearAttenuation.pack(fill = X, expand = 0)
self.bind(self.sLinearAttenuation,
'Set spot light linear attenuation')
self.sQuadraticAttenuation = Slider.Slider(
spotPage,
text = 'Quadratic Attenuation',
@ -451,7 +451,7 @@ class DirectSessionPanel(AppShell):
self.sQuadraticAttenuation.pack(fill = X, expand = 0)
self.bind(self.sQuadraticAttenuation,
'Set spot light quadratic attenuation')
self.sExponent = Slider.Slider(
spotPage,
text = 'Exponent',
@ -462,10 +462,10 @@ class DirectSessionPanel(AppShell):
'Set spot light exponent')
# MRM: Add frustum controls
self.lightNotebook.setnaturalsize()
self.lightNotebook.pack(expand = 1, fill = BOTH)
lightFrame.pack(expand = 1, fill = BOTH)
## GRID PAGE ##
@ -505,7 +505,7 @@ class DirectSessionPanel(AppShell):
value = direct.grid.getGridSpacing())
self.gridSpacing['command'] = direct.grid.setGridSpacing
self.gridSpacing.pack(fill = X, expand = 0)
self.gridSize = Floater.Floater(
gridPage,
text = 'Grid Size',
@ -551,7 +551,7 @@ class DirectSessionPanel(AppShell):
'HPRXYZ Mode'])
self.jbModeMenu.selectitem('Joe Mode')
self.jbModeMenu.pack(fill = X, expand = 1)
self.jbNodePathMenu = Pmw.ComboBox(
joyboxFrame, labelpos = W, label_text = 'Joybox Node Path:',
label_width = 16, entry_width = 20,
@ -648,7 +648,7 @@ class DirectSessionPanel(AppShell):
if (nodePath != None):
# Yes, select it!
direct.select(nodePath)
def addNodePath(self, nodePath):
self.addNodePathToDict(nodePath, self.nodePathNames,
self.nodePathMenu, self.nodePathDict)
@ -670,7 +670,7 @@ class DirectSessionPanel(AppShell):
direct.joybox.demoMode()
elif name == 'HPRXYZ Mode':
direct.joybox.hprXyzMode()
def selectJBNodePathNamed(self, name):
if name == 'selected':
nodePath = direct.selected.last
@ -701,7 +701,7 @@ class DirectSessionPanel(AppShell):
direct.joybox.setNodePath(None)
else:
direct.joybox.setNodePath(nodePath)
def addJBNodePath(self, nodePath):
self.addNodePathToDict(nodePath, self.jbNodePathNames,
self.jbNodePathMenu, self.jbNodePathDict)
@ -726,7 +726,7 @@ class DirectSessionPanel(AppShell):
menu.selectitem(dictName)
## ENVIRONMENT CONTROLS ##
# Background #
# Background #
def setBackgroundColor(self, r, g, b):
self.setBackgroundColorVec((r, g, b))
def setBackgroundColorVec(self, color):
@ -787,7 +787,7 @@ class DirectSessionPanel(AppShell):
dr.setFov(45.0, 33.75)
self.hFov.set(45.0, 0)
self.vFov.set(33.75, 0)
# Lights #
def selectLightNamed(self, name):
# See if light exists
@ -826,7 +826,7 @@ class DirectSessionPanel(AppShell):
def addSpot(self):
return direct.lights.create('spot')
def addLight(self, light):
# Make list reflect current list of lights
listbox = self.lightMenu.component('scrolledlist')
@ -870,7 +870,7 @@ class DirectSessionPanel(AppShell):
def setLinearAttenuation(self, value):
if self.activeLight:
self.activeLight.getLight().setLinearAttenuation(value)
def setQuadraticAttenuation(self, value):
if self.activeLight:
self.activeLight.getLight().setQuadraticAttenuation(value)
@ -907,7 +907,7 @@ class DirectSessionPanel(AppShell):
self.updateLightInfo()
elif page == 'Grid':
self.updateGridInfo()
def updateEnvironmentInfo(self):
bkgrdColor = base.getBackgroundColor() * 255.0
self.backgroundColor.set([bkgrdColor[0],
@ -927,7 +927,7 @@ class DirectSessionPanel(AppShell):
# Set main lighting button
self.enableLights.set(
render.node().hasAttrib(LightAttrib.getClassType()))
# Set light specific info
if self.activeLight:
l = self.activeLight.getLight()
@ -969,7 +969,7 @@ class DirectSessionPanel(AppShell):
self.gridSpacing.set(direct.grid.getGridSpacing(), 0)
self.gridSize.set(direct.grid.getGridSize(), 0)
self.gridSnapAngle.set(direct.grid.getSnapAngle(), 0)
# UNDO/REDO
def pushUndo(self, fResetRedo = 1):
direct.pushUndo([self['nodePath']])
@ -987,7 +987,7 @@ class DirectSessionPanel(AppShell):
def pushRedo(self):
direct.pushRedo([self['nodePath']])
def redoHook(self, nodePathList = []):
pass
@ -998,7 +998,7 @@ class DirectSessionPanel(AppShell):
def redoListEmptyHook(self):
# Make sure button is deactivated
self.redoButton.configure(state = 'disabled')
def onDestroy(self, event):
# Remove hooks
for event, method in self.actionEvents:

View File

@ -61,7 +61,7 @@ class FSMInspector(AppShell):
'Print out ClassicFSM layout',
label = 'Print ClassicFSM layout',
command = self.printLayout)
# States Menu
menuBar.addmenu('States', 'State Inspector Operations')
menuBar.addcascademenu('States', 'Font Size',
@ -107,7 +107,7 @@ class FSMInspector(AppShell):
def canvas(self):
return self._canvas
def setFontSize(self, size):
self._canvas.itemconfigure('labels', font = ('MS Sans Serif', size))
@ -115,7 +115,7 @@ class FSMInspector(AppShell):
for key in self.stateInspectorDict.keys():
self.stateInspectorDict[key].setRadius(size)
self.drawConnections()
def drawConnections(self, event = None):
# Get rid of existing arrows
self._canvas.delete('arrow')
@ -136,25 +136,25 @@ class FSMInspector(AppShell):
fromCenter = fromState.center()
toCenter = toState.center()
angle = self.findAngle(fromCenter, toCenter)
# Compute offset fromState point
newFromPt = map(operator.__add__,
fromCenter,
self.computePoint(fromState.radius,
angle + DELTA))
# Compute offset toState point
newToPt = map(operator.__sub__,
toCenter,
self.computePoint(toState.radius,
angle - DELTA))
return newFromPt + newToPt
def computePoint(self, radius, angle):
x = radius * math.cos(angle)
y = radius * math.sin(angle)
return (x, y)
def findAngle(self, fromPoint, toPoint):
dx = toPoint[0] - fromPoint[0]
dy = toPoint[1] - fromPoint[1]
@ -164,7 +164,7 @@ class FSMInspector(AppShell):
self._width = 1.0 * self._canvas.winfo_width()
self._height = 1.0 * self._canvas.winfo_height()
xview = self._canvas.xview()
yview = self._canvas.yview()
yview = self._canvas.yview()
self._left = xview[0]
self._top = yview[0]
self._dxview = xview[1] - xview[0]
@ -172,7 +172,7 @@ class FSMInspector(AppShell):
self._2lx = event.x
self._2ly = event.y
def mouse2Motion(self,event):
def mouse2Motion(self, event):
newx = self._left - ((event.x - self._2lx)/self._width) * self._dxview
self._canvas.xview_moveto(newx)
newy = self._top - ((event.y - self._2ly)/self._height) * self._dyview
@ -219,19 +219,19 @@ class FSMInspector(AppShell):
return si
def enteredState(self, stateName):
si = self.stateInspectorDict.get(stateName,None)
si = self.stateInspectorDict.get(stateName, None)
if si:
si.enteredState()
def exitedState(self, stateName):
si = self.stateInspectorDict.get(stateName,None)
si = self.stateInspectorDict.get(stateName, None)
if si:
si.exitedState()
def _setGridSize(self):
self._gridSize = self['gridSize']
self.setGridSize(self._gridSize)
def setGridSize(self, size):
for key in self.stateInspectorDict.keys():
self.stateInspectorDict[key].setGridSize(size)
@ -279,14 +279,14 @@ class FSMInspector(AppShell):
self.balloon.configure(state = 'balloon')
else:
self.balloon.configure(state = 'none')
def onDestroy(self, event):
""" Called on ClassicFSM Panel shutdown """
self.fsm.inspecting = 0
for si in self.stateInspectorDict.values():
self.ignore(self.name + '_' + si.getName() + '_entered')
self.ignore(self.name + '_' + si.getName() + '_exited')
class StateInspector(Pmw.MegaArchetype):
def __init__(self, inspector, state, **kw):
@ -297,11 +297,11 @@ class StateInspector(Pmw.MegaArchetype):
# and its corresponding text around together
self.tag = state.getName()
self.fsm = inspector.fsm
# Pointers to the inspector's components
self.scrolledCanvas = inspector.component('scrolledCanvas')
self._canvas = self.scrolledCanvas.component('canvas')
#define the megawidget options
optiondefs = (
('radius', '0.375i', self._setRadius),
@ -343,7 +343,7 @@ class StateInspector(Pmw.MegaArchetype):
self._popupMenu.add_command(label = 'Inspect ' + state.getName() +
' submachine',
command = self.inspectSubMachine)
self.scrolledCanvas.resizescrollregion()
# Add bindings
@ -359,7 +359,7 @@ class StateInspector(Pmw.MegaArchetype):
# Utility methods
def _setRadius(self):
self.setRadius(self['radius'])
def setRadius(self, size):
half = self.radius = self._canvas.winfo_fpixels(size)
c = self.center()
@ -372,7 +372,7 @@ class StateInspector(Pmw.MegaArchetype):
def _setGridSize(self):
self.setGridSize(self['gridSize'])
def setGridSize(self, size):
self.gridSize = self._canvas.winfo_fpixels(size)
if self.gridSize == 0:
@ -382,7 +382,7 @@ class StateInspector(Pmw.MegaArchetype):
def setText(self, text = None):
self._canvas.itemconfigure(self.text, text = text)
def setPos(self, x, y, snapToGrid = 0):
if self.fGridSnap:
self.x = round(x / self.gridSize) * self.gridSize
@ -404,7 +404,7 @@ class StateInspector(Pmw.MegaArchetype):
# Event Handlers
def mouseEnter(self, event):
self._canvas.itemconfig(self.marker, width = 2)
def mouseLeave(self, event):
self._canvas.itemconfig(self.marker, width = 1)
@ -413,14 +413,14 @@ class StateInspector(Pmw.MegaArchetype):
self.startx, self.starty = self.center()
self.lastx = self._canvas.canvasx(event.x)
self.lasty = self._canvas.canvasy(event.y)
def mouseMotion(self, event):
dx = self._canvas.canvasx(event.x) - self.lastx
dy = self._canvas.canvasy(event.y) - self.lasty
newx, newy = map(operator.__add__,(self.startx, self.starty), (dx, dy))
newx, newy = map(operator.__add__, (self.startx, self.starty), (dx, dy))
self.setPos(newx, newy)
def mouseRelease(self,event):
def mouseRelease(self, event):
self.scrolledCanvas.resizescrollregion()
def popupStateMenu(self, event):
@ -531,7 +531,7 @@ from direct.showbase.ShowBaseGlobal import *
# At this point everything will lock up and you won't get your prompt back
# Hit a bunch of Control-C's in rapid succession, in most cases
# this will break you out of whatever badness you were in and
# this will break you out of whatever badness you were in and
# from that point on everything will behave normally

View File

@ -48,7 +48,7 @@ class MopathRecorder(AppShell, DirectObject):
# Call superclass initialization function
AppShell.__init__(self)
self.initialiseoptions(MopathRecorder)
self.selectNodePathNamed('camera')
@ -82,15 +82,15 @@ class MopathRecorder(AppShell, DirectObject):
self.tangentMarker = loader.loadModel('models/misc/sphere')
self.tangentMarker.reparentTo(self.tangentGroup)
self.tangentMarker.setScale(0.5)
self.tangentMarker.setColor(1,0,1,1)
self.tangentMarker.setColor(1, 0, 1, 1)
self.tangentMarker.setName('Tangent Marker')
self.tangentMarkerIds = self.getChildIds(
self.tangentMarker.getChild(0))
self.tangentLines = LineNodePath(self.tangentGroup)
self.tangentLines.setColor(VBase4(1,0,1,1))
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.moveTo(0, 0, 0)
self.tangentLines.drawTo(0, 0, 0)
self.tangentLines.create()
# Active node path dictionary
self.nodePathDict = {}
@ -259,7 +259,7 @@ class MopathRecorder(AppShell, DirectObject):
frame, 'left',
'Recording', 'New Curve',
('Next record session records a new path'),
self.recordingType, 'New Curve',expand = 0)
self.recordingType, 'New Curve', expand = 0)
widget = self.createRadiobutton(
frame, 'left',
'Recording', 'Refine',
@ -284,9 +284,9 @@ class MopathRecorder(AppShell, DirectObject):
self.addKeyframe,
side = LEFT, expand = 1)
frame.pack(fill = X, expand = 1)
mainFrame.pack(expand = 1, fill = X, pady = 3)
# Playback controls
playbackFrame = Frame(interior, relief = SUNKEN,
borderwidth = 2)
@ -348,7 +348,7 @@ class MopathRecorder(AppShell, DirectObject):
string.atof(s.speedVar.get())))
self.speedEntry.pack(side = LEFT, expand = 0)
frame.pack(fill = X, expand = 1)
playbackFrame.pack(fill = X, pady = 2)
# Create notebook pages
@ -365,7 +365,7 @@ class MopathRecorder(AppShell, DirectObject):
label = Label(self.resamplePage, text = 'RESAMPLE CURVE',
font=('MSSansSerif', 12, 'bold'))
label.pack(fill = X)
# Resample
resampleFrame = Frame(
self.resamplePage, relief = SUNKEN, borderwidth = 2)
@ -389,7 +389,7 @@ class MopathRecorder(AppShell, DirectObject):
self.faceForward, side = LEFT, fill = X, expand = 1)
frame.pack(fill = X, expand = 0)
resampleFrame.pack(fill = X, expand = 0, pady = 2)
# Desample
desampleFrame = Frame(
self.resamplePage, relief = SUNKEN, borderwidth = 2)
@ -533,7 +533,7 @@ class MopathRecorder(AppShell, DirectObject):
sfFrame, 'Style', 'Num Segs',
'Set number of segments used to approximate each parametric unit',
min = 1.0, max = 400, resolution = 1.0,
value = 40,
value = 40,
command = self.setNumSegs, side = TOP)
widget.component('hull')['relief'] = RIDGE
widget = self.createSlider(
@ -554,27 +554,27 @@ class MopathRecorder(AppShell, DirectObject):
sfFrame, 'Style', 'Path Color',
'Color of curve',
command = self.setPathColor,
value = [255.0,255.0,255.0,255.0])
value = [255.0, 255.0, 255.0, 255.0])
self.createColorEntry(
sfFrame, 'Style', 'Knot Color',
'Color of knots',
command = self.setKnotColor,
value = [0,0,255.0,255.0])
value = [0, 0, 255.0, 255.0])
self.createColorEntry(
sfFrame, 'Style', 'CV Color',
'Color of CVs',
command = self.setCvColor,
value = [255.0,0,0,255.0])
value = [255.0, 0, 0, 255.0])
self.createColorEntry(
sfFrame, 'Style', 'Tick Color',
'Color of Ticks',
command = self.setTickColor,
value = [255.0,0,0,255.0])
value = [255.0, 0, 0, 255.0])
self.createColorEntry(
sfFrame, 'Style', 'Hull Color',
'Color of Hull',
command = self.setHullColor,
value = [255.0,128.0,128.0,255.0])
value = [255.0, 128.0, 128.0, 255.0])
#drawFrame.pack(fill = X)
@ -622,8 +622,8 @@ class MopathRecorder(AppShell, DirectObject):
# Pack record frame
optionsFrame.pack(fill = X, pady = 2)
self.mainNotebook.setnaturalsize()
self.mainNotebook.setnaturalsize()
def pushUndo(self, fResetRedo = 1):
direct.pushUndo([self.nodePath])
@ -641,7 +641,7 @@ class MopathRecorder(AppShell, DirectObject):
def pushRedo(self):
direct.pushRedo([self.nodePath])
def redoHook(self, nodePathList = []):
# Reflect new changes
pass
@ -653,7 +653,7 @@ class MopathRecorder(AppShell, DirectObject):
def redoListEmptyHook(self):
# Make sure button is deactivated
self.redoButton.configure(state = 'disabled')
def selectedNodePathHook(self, nodePath):
"""
Hook called upon selection of a node path used to select playback
@ -692,7 +692,7 @@ class MopathRecorder(AppShell, DirectObject):
(nodePath.id() == self.tangentMarker.id())):
self.tangentGroup.hide()
def curveEditTask(self,state):
def curveEditTask(self, state):
if self.curveCollection != None:
# Update curve position
if self.manipulandumId == self.playbackMarker.id():
@ -748,11 +748,11 @@ class MopathRecorder(AppShell, DirectObject):
self.manipulandumId = self.playbackMarker.id()
elif direct.selected.last.id() == self.tangentMarker.id():
self.manipulandumId = self.tangentMarker.id()
def manipulateObjectCleanupHook(self, nodePathList = []):
# Clear flag
self.manipulandumId = None
def onDestroy(self, event):
# Remove hooks
for event, method in self.actionEvents:
@ -824,7 +824,7 @@ class MopathRecorder(AppShell, DirectObject):
self.curveNodePath.show()
else:
self.curveNodePath.hide()
def setKnotVis(self):
self.nurbsCurveDrawer.setShowKnots(
self.getVariable('Style', 'Knots').get())
@ -832,11 +832,11 @@ class MopathRecorder(AppShell, DirectObject):
def setCvVis(self):
self.nurbsCurveDrawer.setShowCvs(
self.getVariable('Style', 'CVs').get())
def setHullVis(self):
self.nurbsCurveDrawer.setShowHull(
self.getVariable('Style', 'Hull').get())
def setTraceVis(self):
if self.getVariable('Style', 'Trace').get():
self.trace.show()
@ -852,33 +852,33 @@ class MopathRecorder(AppShell, DirectObject):
def setNumSegs(self, value):
self.numSegs = int(value)
self.nurbsCurveDrawer.setNumSegs(self.numSegs)
def setNumTicks(self, value):
self.nurbsCurveDrawer.setNumTicks(float(value))
def setTickScale(self, value):
self.nurbsCurveDrawer.setTickScale(float(value))
def setPathColor(self, color):
self.nurbsCurveDrawer.setColor(
color[0]/255.0,color[1]/255.0,color[2]/255.0)
color[0]/255.0, color[1]/255.0, color[2]/255.0)
self.nurbsCurveDrawer.draw()
def setKnotColor(self, color):
self.nurbsCurveDrawer.setKnotColor(
color[0]/255.0,color[1]/255.0,color[2]/255.0)
color[0]/255.0, color[1]/255.0, color[2]/255.0)
def setCvColor(self, color):
self.nurbsCurveDrawer.setCvColor(
color[0]/255.0,color[1]/255.0,color[2]/255.0)
color[0]/255.0, color[1]/255.0, color[2]/255.0)
def setTickColor(self, color):
self.nurbsCurveDrawer.setTickColor(
color[0]/255.0,color[1]/255.0,color[2]/255.0)
color[0]/255.0, color[1]/255.0, color[2]/255.0)
def setHullColor(self, color):
self.nurbsCurveDrawer.setHullColor(
color[0]/255.0,color[1]/255.0,color[2]/255.0)
color[0]/255.0, color[1]/255.0, color[2]/255.0)
def setStartStopHook(self, event = None):
# Clear out old hook
@ -904,7 +904,7 @@ class MopathRecorder(AppShell, DirectObject):
self.curveCollection = None
self.curveFitter.reset()
self.nurbsCurveDrawer.hide()
def setSamplingMode(self, mode):
self.samplingMode = mode
@ -921,7 +921,7 @@ class MopathRecorder(AppShell, DirectObject):
def setRefineMode(self):
self.setRecordingType('Refine')
def setExtendMode(self):
self.setRecordingType('Extend')
@ -972,7 +972,7 @@ class MopathRecorder(AppShell, DirectObject):
# Parent record node path to temp
self.nodePath.reparentTo(self.playbackNodePath)
# Align with temp
self.nodePath.setPosHpr(0,0,0,0,0,0)
self.nodePath.setPosHpr(0, 0, 0, 0, 0, 0)
# Set playback start to self.recordStart
self.playbackGoTo(self.recordStart)
# start flying nodePath along path
@ -1009,7 +1009,7 @@ class MopathRecorder(AppShell, DirectObject):
self.setNewCurveMode()
# Compute curve
self.computeCurves()
def recordTask(self, state):
# Record raw data point
time = self.recordStart + (
@ -1201,7 +1201,7 @@ class MopathRecorder(AppShell, DirectObject):
else:
if name == 'widget':
# Record relationship between selected nodes and widget
direct.selected.getWrtAll()
direct.selected.getWrtAll()
if name == 'marker':
self.playbackMarker.show()
# Initialize tangent marker position
@ -1287,7 +1287,7 @@ class MopathRecorder(AppShell, DirectObject):
def setPlaybackSF(self, value):
self.playbackSF = pow(10.0, float(value))
self.speedVar.set('%0.2f' % self.playbackSF)
def playbackTask(self, state):
time = globalClock.getFrameTime()
dTime = self.playbackSF * (time - state.lastTime)
@ -1346,7 +1346,7 @@ class MopathRecorder(AppShell, DirectObject):
def setDesampleFrequency(self, frequency):
self.desampleFrequency = frequency
def desampleCurve(self):
if (self.curveFitter.getNumSamples() == 0):
print 'MopathRecorder.desampleCurve: Must define curve first'
@ -1360,7 +1360,7 @@ class MopathRecorder(AppShell, DirectObject):
def setNumSamples(self, numSamples):
self.numSamples = int(numSamples)
def sampleCurve(self, fCompute = 1):
if self.curveCollection == None:
print 'MopathRecorder.sampleCurve: Must define curve first'
@ -1390,7 +1390,7 @@ class MopathRecorder(AppShell, DirectObject):
def setPathDuration(self, event):
newMaxT = float(self.getWidget('Resample', 'Path Duration').get())
self.setPathDurationTo(newMaxT)
def setPathDurationTo(self, newMaxT):
# Compute scale factor
sf = newMaxT/self.maxT
@ -1415,7 +1415,7 @@ class MopathRecorder(AppShell, DirectObject):
# Compute curve
#self.computeCurves()
def setRecordStart(self,value):
def setRecordStart(self, value):
self.recordStart = value
# Someone else is adjusting values, let them take care of it
if self.fAdjustingValues:
@ -1550,7 +1550,7 @@ class MopathRecorder(AppShell, DirectObject):
# Add it to the curve fitters
self.curveFitter.addXyzHpr(adjustedTime, pos, hpr)
def setCropFrom(self,value):
def setCropFrom(self, value):
self.cropFrom = value
# Someone else is adjusting values, let them take care of it
if self.fAdjustingValues:
@ -1563,7 +1563,7 @@ class MopathRecorder(AppShell, DirectObject):
self.getWidget('Playback', 'Time').set(value)
self.fAdjustingValues = 0
def setCropTo(self,value):
def setCropTo(self, value):
self.cropTo = value
# Someone else is adjusting values, let them take care of it
if self.fAdjustingValues:
@ -1685,7 +1685,7 @@ class MopathRecorder(AppShell, DirectObject):
## WIDGET UTILITY FUNCTIONS ##
def addWidget(self, widget, category, text):
self.widgetDict[category + '-' + text] = widget
def getWidget(self, category, text):
return self.widgetDict[category + '-' + text]
@ -1723,7 +1723,7 @@ class MopathRecorder(AppShell, DirectObject):
self.bind(widget, balloonHelp)
self.widgetDict[category + '-' + text] = widget
return widget
def createCheckbutton(self, parent, category, text,
balloonHelp, command, initialState,
side = 'top', fill = X, expand = 0):
@ -1738,7 +1738,7 @@ class MopathRecorder(AppShell, DirectObject):
self.widgetDict[category + '-' + text] = widget
self.variableDict[category + '-' + text] = bool
return widget
def createRadiobutton(self, parent, side, category, text,
balloonHelp, variable, value,
command = None, fill = X, expand = 0):
@ -1750,7 +1750,7 @@ class MopathRecorder(AppShell, DirectObject):
self.bind(widget, balloonHelp)
self.widgetDict[category + '-' + text] = widget
return widget
def createFloater(self, parent, category, text, balloonHelp,
command = None, min = 0.0, resolution = None,
maxVelocity = 10.0, **kw):
@ -1769,7 +1769,7 @@ class MopathRecorder(AppShell, DirectObject):
def createAngleDial(self, parent, category, text, balloonHelp,
command = None, **kw):
kw['text'] = text
widget = apply(Dial.AngleDial,(parent,), kw)
widget = apply(Dial.AngleDial, (parent,), kw)
# Do this after the widget so command isn't called on creation
widget['command'] = command
widget.pack(fill = X)
@ -1839,7 +1839,7 @@ class MopathRecorder(AppShell, DirectObject):
command = None, **kw):
# Set label's text
kw['text'] = text
widget = apply(VectorWidgets.ColorEntry, (parent,),kw)
widget = apply(VectorWidgets.ColorEntry, (parent,), kw)
# Do this after the widget so command isn't called on creation
widget['command'] = command
widget.pack(fill = X)
@ -1903,12 +1903,12 @@ class MopathRecorder(AppShell, DirectObject):
self.cCamera = render.attachNewNode('cCamera')
self.cCamNode = Camera('cCam')
self.cLens = PerspectiveLens()
self.cLens.setFov(40,40)
self.cLens.setFov(40, 40)
self.cLens.setNear(0.1)
self.cLens.setFar(100.0)
self.cCamNode.setLens(self.cLens)
self.cCamNode.setScene(render)
self.cCam = self.cCamera.attachNewNode(self.cCamNode)
self.cDr.setCamera(self.cCam)

View File

@ -15,7 +15,7 @@ from direct.particles import ForceGroup
from direct.particles import Particles
from direct.particles import ParticleEffect
from pandac.PandaModules import ColorBlendAttrib,getModelPath
from pandac.PandaModules import ColorBlendAttrib, getModelPath
class ParticlePanel(AppShell):
# Override class variables
@ -514,7 +514,7 @@ class ParticlePanel(AppShell):
self.rendererNotebook = Pmw.NoteBook(rendererPage, tabpos = None)
self.rendererNotebook.pack(fill = BOTH, expand = 1)
# Line page #
linePage = self.rendererNotebook.add('LineParticleRenderer')
self.createColorEntry(linePage, 'Line Renderer', 'Head Color',
@ -591,16 +591,16 @@ class ParticlePanel(AppShell):
segmentMenu.add_command(label = 'Add Sinusoid segment',
command = self.addSinusoidInterpolationSegment)
addSegmentButton.pack(expand = 0)
sf = Pmw.ScrolledFrame(p, horizflex = 'elastic')
sf.pack(fill = BOTH, expand = 1)
self.rendererGeomSegmentFrame = sf.interior()
self.rendererGeomSegmentFrame.pack(fill = BOTH, expand = 1)
self.rendererGeomSegmentWidgetList = []
rendererGeomNotebook.setnaturalsize()
# Point #
@ -658,7 +658,7 @@ class ParticlePanel(AppShell):
rendererSpriteNotebook = Pmw.NoteBook(f)
rendererSpriteNotebook.pack(fill = BOTH, expand = 1)
rendererSpriteTexturePage = rendererSpriteNotebook.add('Texture')
rendererSpriteScalePage = rendererSpriteNotebook.add('Scale')
rendererSpriteBlendPage = rendererSpriteNotebook.add('Blend')
@ -680,14 +680,14 @@ class ParticlePanel(AppShell):
self.setRendererSpriteAnimationEnable, 0, side = LEFT)
self.createFloater(bbp, 'Sprite Renderer', 'Frame Rate', 'Animation frame rate',
command = self.setRendererSpriteAnimationFrameRate).pack(side = LEFT)
bbp = Frame(bp)
bbp.pack(pady=3)
Button(bbp, text = 'Add Texture',
command = self.addRendererSpriteAnimationTexture).pack(pady = 3, padx = 15, side = LEFT)
Button(bbp, text = 'Add Animation',
command = self.addRendererSpriteAnimationFromNode).pack(pady = 3, padx = 15, side = LEFT)
pp = Frame(p)
pp.pack(fill = BOTH, expand = 1, pady = 3)
sf = Pmw.ScrolledFrame(pp, horizflex = 'elastic')
@ -801,7 +801,7 @@ class ParticlePanel(AppShell):
pp.pack(fill = BOTH, expand = 1, pady = 3)
sf = Pmw.ScrolledFrame(pp, horizflex = 'elastic')
sf.pack(fill = BOTH, expand = 1)
self.rendererSpriteSegmentFrame = sf.interior()
self.rendererSpriteSegmentFrame.pack(fill = BOTH, expand = 1)
self.rendererSpriteSegmentWidgetList = []
@ -919,7 +919,7 @@ class ParticlePanel(AppShell):
command = None, **kw):
kw['text'] = text
kw['style'] = 'mini'
widget = apply(Dial.AngleDial,(parent,), kw)
widget = apply(Dial.AngleDial, (parent,), kw)
# Do this after the widget so command isn't called on creation
widget['command'] = command
widget.pack(fill = X)
@ -970,7 +970,7 @@ class ParticlePanel(AppShell):
command = None, **kw):
# Set label's text
kw['text'] = text
widget = apply(VectorWidgets.ColorEntry, (parent,),kw)
widget = apply(VectorWidgets.ColorEntry, (parent,), kw)
# Do this after the widget so command isn't called on creation
widget['command'] = command
widget.pack(fill = X)
@ -1186,7 +1186,7 @@ class ParticlePanel(AppShell):
path = '.'
particleFilename = askopenfilename(
defaultextension = '.ptf',
filetypes = (('Particle Files', '*.ptf'),('All files', '*')),
filetypes = (('Particle Files', '*.ptf'), ('All files', '*')),
initialdir = path,
title = 'Load Particle Effect',
parent = self.parent)
@ -1214,7 +1214,7 @@ class ParticlePanel(AppShell):
path = '.'
particleFilename = asksaveasfilename(
defaultextension = '.ptf',
filetypes = (('Particle Files', '*.ptf'),('All files', '*')),
filetypes = (('Particle Files', '*.ptf'), ('All files', '*')),
initialdir = path,
title = 'Save Particle Effect as',
parent = self.parent)
@ -1415,7 +1415,7 @@ class ParticlePanel(AppShell):
radius = emitter.getRadius()
self.getWidget('Ring Emitter', 'Radius').set(radius, 0)
radiusSpread = emitter.getRadiusSpread()
self.getWidget('Ring Emitter', 'Radius Spread').set(radiusSpread,0)
self.getWidget('Ring Emitter', 'Radius Spread').set(radiusSpread, 0)
angle = emitter.getAngle()
self.getWidget('Ring Emitter', 'Angle').set(angle, 0)
elif isinstance(emitter, SphereVolumeEmitter):
@ -1429,7 +1429,7 @@ class ParticlePanel(AppShell):
self.getWidget('Tangent Ring Emitter', 'Radius').set(radius, 0)
radiusSpread = emitter.getRadiusSpread()
self.getWidget('Tangent Ring Emitter', 'Radius Spread').set(
radiusSpread,0)
radiusSpread, 0)
# All #
def setEmissionType(self, newType = None):
if newType:
@ -1633,7 +1633,7 @@ class ParticlePanel(AppShell):
lScale = "SP_SCALE"
self.getVariable('Sparkle Renderer', 'Life Scale').set(lScale)
elif isinstance(renderer, SpriteParticleRenderer):
self.getWidget('Sprite Renderer','Frame Rate').set(renderer.getAnimateFramesRate(),0)
self.getWidget('Sprite Renderer','Frame Rate').set(renderer.getAnimateFramesRate(), 0)
self.getVariable('Sprite Renderer','Enable Animation').set(
renderer.getAnimateFramesEnable())
self.readSpriteRendererAnimations() # Updates widgets with renderer data.
@ -1793,15 +1793,15 @@ class ParticlePanel(AppShell):
parent = self.rendererSpriteSegmentFrame
segName = `len(self.rendererSpriteSegmentWidgetList)`+':Constant'
self.rendererSpriteSegmentWidgetList.append(
self.createConstantInterpolationSegmentWidget(parent,segName,seg))
self.createConstantInterpolationSegmentWidget(parent, segName, seg))
elif(ren.__class__.__name__ == 'GeomParticleRenderer'):
parent = self.rendererGeomSegmentFrame
segName = `len(self.rendererGeomSegmentWidgetList)`+':Constant'
self.rendererGeomSegmentWidgetList.append(
self.createConstantInterpolationSegmentWidget(parent,segName,seg))
self.createConstantInterpolationSegmentWidget(parent, segName, seg))
parent.pack(fill=BOTH, expand=1)
def setRendererSpriteAnimationFrameRate(self,rate):
def setRendererSpriteAnimationFrameRate(self, rate):
self.particles.renderer.setAnimateFramesRate(rate)
def setRendererSpriteAnimationEnable(self):
self.particles.renderer.setAnimateFramesEnable(
@ -1815,17 +1815,17 @@ class ParticlePanel(AppShell):
anim = ren.getAnim(animId)
frameNum = len([x for x in self.rendererSpriteAnimationWidgetList if x])
self.rendererSpriteAnimationWidgetList.append(
self.createSpriteAnimationTextureWidget(parent,anim,`frameNum`))
self.createSpriteAnimationTextureWidget(parent, anim, `frameNum`))
else:
animId = len([x for x in self.rendererSpriteAnimationWidgetList if x and x.valid])
anim = SpriteAnim.STTexture
frameNum = len([x for x in self.rendererSpriteAnimationWidgetList if x])
self.rendererSpriteAnimationWidgetList.append(
self.createSpriteAnimationTextureWidget(parent,anim,`frameNum`))
self.createSpriteAnimationTextureWidget(parent, anim, `frameNum`))
parent.pack(fill=BOTH, expand=1)
def addRendererSpriteAnimationFromNode(self):
ren = self.particles.getRenderer()
@ -1836,19 +1836,19 @@ class ParticlePanel(AppShell):
anim = ren.getAnim(animId)
frameNum = len([x for x in self.rendererSpriteAnimationWidgetList if x])
self.rendererSpriteAnimationWidgetList.append(
self.createSpriteAnimationNodeWidget(parent,anim,`frameNum`))
self.createSpriteAnimationNodeWidget(parent, anim, `frameNum`))
else:
animId = len([x for x in self.rendererSpriteAnimationWidgetList if x and x.valid])
anim = SpriteAnim.STFromNode
frameNum = len([x for x in self.rendererSpriteAnimationWidgetList if x])
self.rendererSpriteAnimationWidgetList.append(
self.createSpriteAnimationNodeWidget(parent,anim,`frameNum`))
self.createSpriteAnimationNodeWidget(parent, anim, `frameNum`))
parent.pack(fill=BOTH, expand=1)
def toggleRendererSpriteXScale(self):
self.particles.renderer.setXScaleFlag(
self.getVariable('Sprite Renderer', 'X Scale').get())
@ -1885,7 +1885,7 @@ class ParticlePanel(AppShell):
def toggleRendererSpriteAlphaDisable(self):
self.particles.renderer.setAlphaDisable(
self.getVariable('Sprite Renderer', 'Alpha Disable').get())
def setRendererColorBlendAttrib(self,rendererName,blendMethodStr,incomingOperandStr,fbufferOperandStr):
def setRendererColorBlendAttrib(self, rendererName, blendMethodStr, incomingOperandStr, fbufferOperandStr):
self.particles.getRenderer().setColorBlendMode(eval('ColorBlendAttrib.'+blendMethodStr),
eval('ColorBlendAttrib.'+incomingOperandStr),
eval('ColorBlendAttrib.'+fbufferOperandStr))
@ -1903,36 +1903,36 @@ class ParticlePanel(AppShell):
incomingOperandStr = self.getVariable('Sprite Renderer','Incoming Op.').get()
fbufferOperandStr = self.getVariable('Sprite Renderer','Fbuffer Op.').get()
self.setRendererColorBlendAttrib('Sprite Renderer',blendMethodStr,incomingOperandStr,fbufferOperandStr)
self.setRendererColorBlendAttrib('Sprite Renderer', blendMethodStr, incomingOperandStr, fbufferOperandStr)
def setRendererSpriteColorBlendIncomingOperand(self, operand):
blendMethodStr = self.getVariable('Sprite Renderer','Color Blend').get()
incomingOperandStr = operand
fbufferOperandStr = self.getVariable('Sprite Renderer','Fbuffer Op.').get()
self.setRendererColorBlendAttrib('Sprite Renderer',blendMethodStr,incomingOperandStr,fbufferOperandStr)
self.setRendererColorBlendAttrib('Sprite Renderer', blendMethodStr, incomingOperandStr, fbufferOperandStr)
def setRendererSpriteColorBlendFbufferOperand(self, operand):
blendMethodStr = self.getVariable('Sprite Renderer','Color Blend').get()
incomingOperandStr = self.getVariable('Sprite Renderer','Incoming Op.').get()
fbufferOperandStr = operand
self.setRendererColorBlendAttrib('Sprite Renderer',blendMethodStr,incomingOperandStr,fbufferOperandStr)
self.setRendererColorBlendAttrib('Sprite Renderer', blendMethodStr, incomingOperandStr, fbufferOperandStr)
def setRendererGeomColorBlendMethod(self, blendMethod):
blendMethodStr = blendMethod
incomingOperandStr = self.getVariable('Geom Renderer','Incoming Op.').get()
fbufferOperandStr = self.getVariable('Geom Renderer','Fbuffer Op.').get()
self.setRendererColorBlendAttrib('Geom Renderer',blendMethodStr,incomingOperandStr,fbufferOperandStr)
self.setRendererColorBlendAttrib('Geom Renderer', blendMethodStr, incomingOperandStr, fbufferOperandStr)
def setRendererGeomColorBlendIncomingOperand(self, operand):
blendMethodStr = self.getVariable('Geom Renderer','Color Blend').get()
incomingOperandStr = operand
fbufferOperandStr = self.getVariable('Geom Renderer','Fbuffer Op.').get()
self.setRendererColorBlendAttrib('Geom Renderer',blendMethodStr,incomingOperandStr,fbufferOperandStr)
self.setRendererColorBlendAttrib('Geom Renderer', blendMethodStr, incomingOperandStr, fbufferOperandStr)
def setRendererGeomColorBlendFbufferOperand(self, operand):
blendMethodStr = self.getVariable('Geom Renderer','Color Blend').get()
incomingOperandStr = self.getVariable('Geom Renderer','Incoming Op.').get()
fbufferOperandStr = operand
self.setRendererColorBlendAttrib('Geom Renderer',blendMethodStr,incomingOperandStr,fbufferOperandStr)
self.setRendererColorBlendAttrib('Geom Renderer', blendMethodStr, incomingOperandStr, fbufferOperandStr)
def addConstantInterpolationSegment(self):
ren = self.particles.getRenderer()
@ -1943,12 +1943,12 @@ class ParticlePanel(AppShell):
parent = self.rendererSpriteSegmentFrame
segName = `len(self.rendererSpriteSegmentWidgetList)`+':Constant'
self.rendererSpriteSegmentWidgetList.append(
self.createConstantInterpolationSegmentWidget(parent,segName,seg))
self.createConstantInterpolationSegmentWidget(parent, segName, seg))
elif(ren.__class__.__name__ == 'GeomParticleRenderer'):
parent = self.rendererGeomSegmentFrame
segName = `len(self.rendererGeomSegmentWidgetList)`+':Constant'
self.rendererGeomSegmentWidgetList.append(
self.createConstantInterpolationSegmentWidget(parent,segName,seg))
self.createConstantInterpolationSegmentWidget(parent, segName, seg))
parent.pack(fill=BOTH, expand=1)
def addLinearInterpolationSegment(self):
@ -1960,12 +1960,12 @@ class ParticlePanel(AppShell):
parent = self.rendererSpriteSegmentFrame
segName = `len(self.rendererSpriteSegmentWidgetList)`+':Linear'
self.rendererSpriteSegmentWidgetList.append(
self.createLinearInterpolationSegmentWidget(parent,segName,seg))
self.createLinearInterpolationSegmentWidget(parent, segName, seg))
elif(ren.__class__.__name__ == 'GeomParticleRenderer'):
parent = self.rendererGeomSegmentFrame
segName = `len(self.rendererGeomSegmentWidgetList)`+':Linear'
self.rendererGeomSegmentWidgetList.append(
self.createLinearInterpolationSegmentWidget(parent,segName,seg))
self.createLinearInterpolationSegmentWidget(parent, segName, seg))
parent.pack(fill=BOTH, expand=1)
def addStepwaveInterpolationSegment(self):
@ -1977,12 +1977,12 @@ class ParticlePanel(AppShell):
parent = self.rendererSpriteSegmentFrame
segName = `len(self.rendererSpriteSegmentWidgetList)`+':Stepwave'
self.rendererSpriteSegmentWidgetList.append(
self.createStepwaveInterpolationSegmentWidget(parent,segName,seg))
self.createStepwaveInterpolationSegmentWidget(parent, segName, seg))
elif(ren.__class__.__name__ == 'GeomParticleRenderer'):
parent = self.rendererGeomSegmentFrame
segName = `len(self.rendererGeomSegmentWidgetList)`+':Stepwave'
self.rendererGeomSegmentWidgetList.append(
self.createStepwaveInterpolationSegmentWidget(parent,segName,seg))
self.createStepwaveInterpolationSegmentWidget(parent, segName, seg))
parent.pack(fill=BOTH, expand=1)
def addSinusoidInterpolationSegment(self):
@ -1994,12 +1994,12 @@ class ParticlePanel(AppShell):
parent = self.rendererSpriteSegmentFrame
segName = `len(self.rendererSpriteSegmentWidgetList)`+':Sinusoid'
self.rendererSpriteSegmentWidgetList.append(
self.createSinusoidInterpolationSegmentWidget(parent,segName,seg))
self.createSinusoidInterpolationSegmentWidget(parent, segName, seg))
elif(ren.__class__.__name__ == 'GeomParticleRenderer'):
parent = self.rendererGeomSegmentFrame
segName = `len(self.rendererGeomSegmentWidgetList)`+':Sinusoid'
self.rendererGeomSegmentWidgetList.append(
self.createSinusoidInterpolationSegmentWidget(parent,segName,seg))
self.createSinusoidInterpolationSegmentWidget(parent, segName, seg))
parent.pack(fill=BOTH, expand=1)
def createInterpolationSegmentFrame(self, parent, segName, seg):
@ -2008,7 +2008,7 @@ class ParticlePanel(AppShell):
def removeInterpolationSegmentFrame(s = self, seg = seg, fr = frame):
s.particles.getRenderer().getColorInterpolationManager().clearSegment(seg.getId())
fr.pack_forget()
def setSegEnabled(s=self,n=segName):
def setSegEnabled(s=self, n=segName):
enabled = s.getVariable('Sprite Renderer', n+' Enabled')
seg.setEnabled(enabled.get())
def setSegBegin(time):
@ -2033,31 +2033,31 @@ class ParticlePanel(AppShell):
f = Frame(frame)
self.createSlider(f,
'Sprite Renderer',segName + ' Begin',
'Sprite Renderer', segName + ' Begin',
'',
command = setSegBegin,
value = seg.getTimeBegin())
self.createSlider(f,'Sprite Renderer',segName + ' End',
self.createSlider(f,'Sprite Renderer', segName + ' End',
'',
command = setSegEnd,
value = seg.getTimeEnd())
f.pack(fill = X, expand = 0)
frame.pack(pady = 3, fill = X, expand = 0)
return frame
def createConstantInterpolationSegmentWidget(self, parent, segName, segment):
fun = segment.getFunction()
def setSegColorA(color):
fun.setColorA(
Vec4(color[0]/255.0,color[1]/255.0,
color[2]/255.0,color[3]/255.0))
Vec4(color[0]/255.0, color[1]/255.0,
color[2]/255.0, color[3]/255.0))
frame = self.createInterpolationSegmentFrame(parent, segName, segment)
f = Frame(frame)
c = fun.getColorA()
c = [c[0]*255.0,c[1]*255.0,c[2]*255.0,c[3]*255.0]
self.createColorEntry(f,'Sprite Renderer',segName + ' Color A',
c = [c[0]*255.0, c[1]*255.0, c[2]*255.0, c[3]*255.0]
self.createColorEntry(f,'Sprite Renderer', segName + ' Color A',
'',
command = setSegColorA,
value = c)
@ -2068,25 +2068,25 @@ class ParticlePanel(AppShell):
fun = segment.getFunction()
def setSegColorA(color):
fun.setColorA(
Vec4(color[0]/255.0,color[1]/255.0,
color[2]/255.0,color[3]/255.0))
Vec4(color[0]/255.0, color[1]/255.0,
color[2]/255.0, color[3]/255.0))
def setSegColorB(color):
fun.setColorB(
Vec4(color[0]/255.0,color[1]/255.0,
color[2]/255.0,color[3]/255.0))
Vec4(color[0]/255.0, color[1]/255.0,
color[2]/255.0, color[3]/255.0))
frame = self.createInterpolationSegmentFrame(parent, segName, segment)
f = Frame(frame)
c = fun.getColorA()
c = [c[0]*255.0,c[1]*255.0,c[2]*255.0,c[3]*255.0]
self.createColorEntry(f,'Sprite Renderer',segName + ' Color A',
c = [c[0]*255.0, c[1]*255.0, c[2]*255.0, c[3]*255.0]
self.createColorEntry(f,'Sprite Renderer', segName + ' Color A',
'',
command = setSegColorA,
value = c)
c = fun.getColorB()
c = [c[0]*255.0,c[1]*255.0,c[2]*255.0,c[3]*255.0]
self.createColorEntry(f,'Sprite Renderer',segName + ' Color B',
c = [c[0]*255.0, c[1]*255.0, c[2]*255.0, c[3]*255.0]
self.createColorEntry(f,'Sprite Renderer', segName + ' Color B',
'',
command = setSegColorB,
value = c)
@ -2094,32 +2094,32 @@ class ParticlePanel(AppShell):
return frame
def createStepwaveInterpolationSegmentWidget(self, parent, segName, segment):
fun = segment.getFunction()
fun = segment.getFunction()
def setColorA(color):
fun.setColorA(
Vec4(color[0]/255.0,color[1]/255.0,
color[2]/255.0,color[3]/255.0))
Vec4(color[0]/255.0, color[1]/255.0,
color[2]/255.0, color[3]/255.0))
def setColorB(color):
fun.setColorB(
Vec4(color[0]/255.0,color[1]/255.0,
color[2]/255.0,color[3]/255.0))
Vec4(color[0]/255.0, color[1]/255.0,
color[2]/255.0, color[3]/255.0))
def setWidthA(width):
fun.setWidthA(width)
def setWidthB(width):
fun.setWidthB(width)
frame = self.createInterpolationSegmentFrame(parent, segName, segment)
f = Frame(frame)
c = fun.getColorA()
c = [c[0]*255.0,c[1]*255.0,c[2]*255.0,c[3]*255.0]
self.createColorEntry(f,'Sprite Renderer',segName + ' Color A',
c = [c[0]*255.0, c[1]*255.0, c[2]*255.0, c[3]*255.0]
self.createColorEntry(f,'Sprite Renderer', segName + ' Color A',
'',
command = setColorA,
value = c)
c = fun.getColorB()
c = [c[0]*255.0,c[1]*255.0,c[2]*255.0,c[3]*255.0]
self.createColorEntry(f,'Sprite Renderer',segName + ' Color B',
c = [c[0]*255.0, c[1]*255.0, c[2]*255.0, c[3]*255.0]
self.createColorEntry(f,'Sprite Renderer', segName + ' Color B',
'',
command = setColorB,
value = c)
@ -2135,32 +2135,32 @@ class ParticlePanel(AppShell):
value = w)
f.pack(fill = X)
return frame
def createSinusoidInterpolationSegmentWidget(self, parent, segName, segment):
fun = segment.getFunction()
fun = segment.getFunction()
def setColorA(color):
fun.setColorA(
Vec4(color[0]/255.0,color[1]/255.0,
color[2]/255.0,color[3]/255.0))
Vec4(color[0]/255.0, color[1]/255.0,
color[2]/255.0, color[3]/255.0))
def setColorB(color):
fun.setColorB(
Vec4(color[0]/255.0,color[1]/255.0,
color[2]/255.0,color[3]/255.0))
Vec4(color[0]/255.0, color[1]/255.0,
color[2]/255.0, color[3]/255.0))
def setPeriod(period):
fun.setPeriod(period)
frame = self.createInterpolationSegmentFrame(parent, segName, segment)
f = Frame(frame)
c = fun.getColorA()
c = [c[0]*255.0,c[1]*255.0,c[2]*255.0,c[3]*255.0]
self.createColorEntry(f,'Sprite Renderer',segName + ' Color A',
c = [c[0]*255.0, c[1]*255.0, c[2]*255.0, c[3]*255.0]
self.createColorEntry(f,'Sprite Renderer', segName + ' Color A',
'',
command = setColorA,
value = c)
c = fun.getColorB()
c = [c[0]*255.0,c[1]*255.0,c[2]*255.0,c[3]*255.0]
self.createColorEntry(f,'Sprite Renderer',segName + ' Color B',
c = [c[0]*255.0, c[1]*255.0, c[2]*255.0, c[3]*255.0]
self.createColorEntry(f,'Sprite Renderer', segName + ' Color B',
'',
command = setColorB,
value = c)
@ -2202,7 +2202,7 @@ class ParticlePanel(AppShell):
type = 'From Node'
else:
frame.valid = True
if(anim.getSourceType()==SpriteAnim.STTexture):
frame.animSourceType = SpriteAnim.STTexture
type = 'Texture'
@ -2216,16 +2216,16 @@ class ParticlePanel(AppShell):
).pack(fill = X, expand = 1)
return frame
def createSpriteAnimationTextureWidget(self, parent, anim, animName):
ren = self.particles.getRenderer()
frame = self.createSpriteAnimationFrame(parent,anim,animName)
frame = self.createSpriteAnimationFrame(parent, anim, animName)
f = Frame(frame)
f.pack(fill=X)
Label(f, text = 'Texture: ', font = ('MSSansSerif',12), width=7).pack(side = LEFT)
Label(f, text = 'Texture: ', font = ('MSSansSerif', 12), width=7).pack(side = LEFT)
strVar = StringVar()
entry = Entry(f,textvariable = strVar).pack(padx=3, pady=3,side=LEFT,fill=X,expand=1)
entry = Entry(f, textvariable = strVar).pack(padx=3, pady=3, side=LEFT, fill=X, expand=1)
if frame.valid:
strVar.set(anim.getTexSource())
else:
@ -2248,40 +2248,40 @@ class ParticlePanel(AppShell):
def createSpriteAnimationNodeWidget(self, parent, anim, animName):
ren = self.particles.getRenderer()
frame = self.createSpriteAnimationFrame(parent,anim, animName)
frame = self.createSpriteAnimationFrame(parent, anim, animName)
f = Frame(frame)
f.pack(fill=X)
lf = Frame(f)
lf.pack(fill=X, expand=1)
Label(lf, text = 'Model: ', font = ('MSSansSerif',12), width=7).pack(side = LEFT)
Label(lf, text = 'Model: ', font = ('MSSansSerif', 12), width=7).pack(side = LEFT)
mStrVar = StringVar()
entry = Entry(lf,textvariable = mStrVar).pack(padx=3, pady=3,side=LEFT,fill=X,expand=1)
entry = Entry(lf, textvariable = mStrVar).pack(padx=3, pady=3, side=LEFT, fill=X, expand=1)
if frame.valid:
mStrVar.set(anim.getModelSource())
else:
mStrVar.set('Base model path: ' + `getModelPath().getValue()`)
mlf = lf
self.variableDict['Sprite Renderer-'+animName+' Anim Model'] = mStrVar
self.widgetDict['Sprite Renderer-'+animName+' Anim Model'] = entry
lf = Frame(f)
lf.pack(fill=X, expand=1)
Label(lf, text = 'Node: ', font = ('MSSansSerif',12), width=7).pack(side = LEFT)
Label(lf, text = 'Node: ', font = ('MSSansSerif', 12), width=7).pack(side = LEFT)
nStrVar = StringVar()
entry = Entry(lf,textvariable = nStrVar).pack(padx=3, pady=3,side=LEFT,fill=X,expand=1)
entry = Entry(lf, textvariable = nStrVar).pack(padx=3, pady=3, side=LEFT, fill=X, expand=1)
if frame.valid:
nStrVar.set(anim.getNodeSource())
else:
nStrVar.set('**/*')
nlf = lf
self.variableDict['Sprite Renderer-'+animName+' Anim Node'] = nStrVar
self.widgetDict['Sprite Renderer-'+animName+' Anim Node'] = entry
def checkForNode(modelStrVar=mStrVar,nodeStrVar=nStrVar):
def checkForNode(modelStrVar=mStrVar, nodeStrVar=nStrVar):
mod = loader.loadModelCopy(modelStrVar.get())
if mod:
node = mod.find(nodeStrVar.get())
@ -2291,7 +2291,7 @@ class ParticlePanel(AppShell):
frame.valid = False
else:
frame.valid = False
self.writeSpriteRendererAnimations()
Button(mlf, text = 'Update',
@ -2314,11 +2314,11 @@ class ParticlePanel(AppShell):
for anim in [ren.getAnim(x) for x in range(ren.getNumAnims())]:
if(anim.getSourceType() == SpriteAnim.STTexture):
w = self.createSpriteAnimationTextureWidget(self.rendererSpriteAnimationFrame,anim,`len(self.rendererSpriteAnimationWidgetList)`)
w = self.createSpriteAnimationTextureWidget(self.rendererSpriteAnimationFrame, anim, `len(self.rendererSpriteAnimationWidgetList)`)
else:
w = self.createSpriteAnimationNodeWidget(self.rendererSpriteAnimationFrame,anim,`len(self.rendererSpriteAnimationWidgetList)`)
w = self.createSpriteAnimationNodeWidget(self.rendererSpriteAnimationFrame, anim, `len(self.rendererSpriteAnimationWidgetList)`)
self.rendererSpriteAnimationWidgetList.append(w)
# set animation info from panel into renderer
def writeSpriteRendererAnimations(self):
ren = self.particles.getRenderer()
@ -2335,8 +2335,8 @@ class ParticlePanel(AppShell):
else:
modelSource = self.getVariable('Sprite Renderer', `x` + ' Anim Model').get()
nodeSource = self.getVariable('Sprite Renderer', `x` + ' Anim Node').get()
ren.addTextureFromNode(modelSource,nodeSource)
ren.addTextureFromNode(modelSource, nodeSource)
## FORCEGROUP COMMANDS ##
def updateForceWidgets(self):
# Select appropriate notebook page
@ -2375,7 +2375,7 @@ class ParticlePanel(AppShell):
if self.forceGroup == None:
self.createNewForceGroup()
self.forceGroup.addForce(f)
self.addForceWidget(self.forceGroup,f)
self.addForceWidget(self.forceGroup, f)
## SYSTEM COMMANDS ##
def createNewEffect(self):

View File

@ -46,7 +46,7 @@ class AppShell(Pmw.MegaWidget, DirectObject):
contactname = 'Mark R. Mine'
contactphone = '(818) 544-2921'
contactemail = 'Mark.Mine@disney.com'
frameWidth = 450
frameHeight = 320
padx = 5
@ -55,7 +55,7 @@ class AppShell(Pmw.MegaWidget, DirectObject):
usestatusarea = 0
balloonState = 'none'
panelCount = 0
def __init__(self, parent = None, **kw):
optiondefs = (
('title', self.appname, None),
@ -96,7 +96,7 @@ class AppShell(Pmw.MegaWidget, DirectObject):
self.initialiseoptions(AppShell)
self.pack(fill = BOTH, expand = 1)
def __createInterface(self):
self.__createBalloon()
self.__createMenuBar()
@ -138,13 +138,13 @@ class AppShell(Pmw.MegaWidget, DirectObject):
spacer.pack(side = LEFT, expand = 0)
self.menuFrame.pack(fill = X)
def __createDataArea(self):
# Create data area where data entry widgets are placed.
self.dataArea = self.createcomponent('dataarea',
(), None,
Frame, (self._hull,),
relief=GROOVE,
Frame, (self._hull,),
relief=GROOVE,
bd=1)
self.dataArea.pack(side=TOP, fill=BOTH, expand=YES,
padx=self['padx'], pady=self['pady'])
@ -162,8 +162,8 @@ class AppShell(Pmw.MegaWidget, DirectObject):
padx=0, pady=0)
self.__buttonBox.pack(side=TOP, expand=NO, fill=X)
if self['usecommandarea']:
self.__commandFrame.pack(side=TOP,
expand=NO,
self.__commandFrame.pack(side=TOP,
expand=NO,
fill=X,
padx=self['padx'],
pady=self['pady'])
@ -172,10 +172,10 @@ class AppShell(Pmw.MegaWidget, DirectObject):
def __createMessageBar(self):
# Create the message bar area for help and status messages.
frame = self.createcomponent('bottomtray', (), None,
Frame,(self._hull,), relief=SUNKEN)
Frame, (self._hull,), relief=SUNKEN)
self.__messageBar = self.createcomponent('messagebar',
(), None,
Pmw.MessageBar,
Pmw.MessageBar,
(frame,),
#entry_width = 40,
entry_relief=SUNKEN,
@ -193,7 +193,7 @@ class AppShell(Pmw.MegaWidget, DirectObject):
self.updateProgress(0)
if self['usestatusarea']:
frame.pack(side=BOTTOM, expand=NO, fill=X)
self.__balloon.configure(statuscommand = \
self.__messageBar.helpmessage)
@ -202,12 +202,12 @@ class AppShell(Pmw.MegaWidget, DirectObject):
Pmw.aboutcopyright(self.copyright)
Pmw.aboutcontact(
'For more information, contact:\n %s\n Phone: %s\n Email: %s' %\
(self.contactname, self.contactphone,
(self.contactname, self.contactphone,
self.contactemail))
self.about = Pmw.AboutDialog(self._hull,
self.about = Pmw.AboutDialog(self._hull,
applicationname=self.appname)
self.about.withdraw()
def toggleBalloon(self):
if self.toggleBalloonVar.get():
self.__balloon.configure(state = 'both')
@ -218,7 +218,7 @@ class AppShell(Pmw.MegaWidget, DirectObject):
# Create the dialog to display about and contact information.
self.about.show()
self.about.focus_set()
def quit(self):
self.parent.destroy()
@ -227,7 +227,7 @@ class AppShell(Pmw.MegaWidget, DirectObject):
def appInit(self):
# Called before interface is created (should be overridden).
pass
def createInterface(self):
# Override this method to create the interface for the app.
pass
@ -240,7 +240,7 @@ class AppShell(Pmw.MegaWidget, DirectObject):
# Creates default menus. Can be overridden or simply augmented
# Using button Add below
self.menuBar.addmenuitem('Help', 'command',
'Get information on application',
'Get information on application',
label='About...', command=self.showAbout)
self.toggleBalloonVar = IntVar()
if self.balloonState == 'none':
@ -256,7 +256,7 @@ class AppShell(Pmw.MegaWidget, DirectObject):
self.menuBar.addmenuitem('File', 'command', 'Quit this application',
label='Quit',
command=self.quit)
# Getters
def interior(self):
# Retrieve the interior site where widgets should go.
@ -299,13 +299,13 @@ class AppShell(Pmw.MegaWidget, DirectObject):
## WIDGET UTILITY FUNCTIONS ##
def addWidget(self, category, text, widget):
self.widgetDict[category + '-' + text] = widget
def getWidget(self, category, text):
return self.widgetDict.get(category + '-' + text, None)
def addVariable(self, category, text, variable):
self.variableDict[category + '-' + text] = variable
def getVariable(self, category, text):
return self.variableDict.get(category + '-' + text, None)
@ -325,7 +325,7 @@ class AppShell(Pmw.MegaWidget, DirectObject):
self.addWidget(category, text, widget)
return widget
def newCreateLabeledEntry(self, parent, category, text, help = '',
def newCreateLabeledEntry(self, parent, category, text, help = '',
command = None, value = '',
width = 12, relief = SUNKEN,
side = LEFT, fill = X, expand = 0):
@ -359,7 +359,7 @@ class AppShell(Pmw.MegaWidget, DirectObject):
widget = self.createWidget(parent, category, text, Button,
help, command, side, fill, expand, kw)
return widget
def newCreateCheckbutton(self, parent, category, text,
help = '', command = None,
initialState = 0, anchor = W,
@ -375,9 +375,9 @@ class AppShell(Pmw.MegaWidget, DirectObject):
self.addVariable(category, text, variable)
widget['variable'] = variable
return widget
def newCreateRadiobutton(self, parent, category, text, variable, value,
command = None, help = '', anchor = W,
def newCreateRadiobutton(self, parent, category, text, variable, value,
command = None, help = '', anchor = W,
side = LEFT, fill = X, expand = 0, **kw):
"""
createRadiobutton(parent, category, text, variable, value, [options])
@ -390,9 +390,9 @@ class AppShell(Pmw.MegaWidget, DirectObject):
widget['value'] = value
widget['variable'] = variable
return widget
def newCreateFloater(self, parent, category, text,
help = '', command = None,
def newCreateFloater(self, parent, category, text,
help = '', command = None,
side = LEFT, fill = X, expand = 0, **kw):
# Create the widget
widget = self.createWidget(parent, category, text,
@ -428,7 +428,7 @@ class AppShell(Pmw.MegaWidget, DirectObject):
return widget
def newCreateVector2Entry(self, parent, category, text,
help = '', command = None,
help = '', command = None,
side = LEFT, fill = X, expand = 0, **kw):
# Create the widget
widget = self.createWidget(parent, category, text,
@ -436,7 +436,7 @@ class AppShell(Pmw.MegaWidget, DirectObject):
help, command, side, fill, expand, kw)
def newCreateVector3Entry(self, parent, category, text,
help = '', command = None,
help = '', command = None,
side = LEFT, fill = X, expand = 0, **kw):
# Create the widget
widget = self.createWidget(parent, category, text,
@ -445,7 +445,7 @@ class AppShell(Pmw.MegaWidget, DirectObject):
return widget
def newCreateColorEntry(self, parent, category, text,
help = '', command = None,
help = '', command = None,
side = LEFT, fill = X, expand = 0, **kw):
# Create the widget
widget = self.createWidget(parent, category, text,
@ -486,7 +486,7 @@ class AppShell(Pmw.MegaWidget, DirectObject):
def newCreateComboBox(self, parent, category, text,
help = '', command = None,
items = [], state = DISABLED, history = 0,
labelpos = W, label_anchor = W,
labelpos = W, label_anchor = W,
label_width = 16, entry_width = 16,
side = LEFT, fill = X, expand = 0, **kw):
# Update kw to reflect user inputs
@ -532,13 +532,13 @@ class TestAppShell(AppShell):
# Call superclass initialization function
AppShell.__init__(self)
self.initialiseoptions(TestAppShell)
def createButtons(self):
self.buttonAdd('Ok',
helpMessage='Exit',
statusMessage='Exit',
command=self.quit)
def createMain(self):
self.label = self.createcomponent('label', (), None,
Label,
@ -546,11 +546,11 @@ class TestAppShell(AppShell):
text='Data Area')
self.label.pack()
self.bind(self.label, 'Space taker')
def createInterface(self):
self.createButtons()
self.createMain()
if __name__ == '__main__':
test = TestAppShell(balloon_state='none')

View File

@ -58,9 +58,9 @@ class Dial(Valuator):
self.interior().columnconfigure(2, weight = 1)
else:
if self._label:
self._label.grid(row=0,column=0, sticky = EW)
self._entry.grid(row=0,column=1, sticky = EW)
self._valuator.grid(row=0,column=2, padx = 2, pady = 2)
self._label.grid(row=0, column=0, sticky = EW)
self._entry.grid(row=0, column=1, sticky = EW)
self._valuator.grid(row=0, column=2, padx = 2, pady = 2)
self.interior().columnconfigure(0, weight = 1)
def addValuatorPropertiesToDialog(self):
@ -79,7 +79,7 @@ class Dial(Valuator):
{ 'widget': self._valuator,
'type': 'integer',
'help': 'Number of segments to divide dial into.'})
def addValuatorMenuEntries(self):
# The popup menu
self._fSnap = IntVar()
@ -93,15 +93,15 @@ class Dial(Valuator):
self._popupMenu.add_checkbutton(label = 'Rollover',
variable = self._fRollover,
command = self._setRollover)
def setBase(self):
""" Set Dial base value: value = base + delta * numRevs """
self._valuator['base'] = self['base']
def setDelta(self):
""" Set Dial delta value: value = base + delta * numRevs """
self._valuator['delta'] = self['delta']
def _setSnap(self):
""" Menu command to turn Dial angle snap on/off """
self._valuator['fSnap'] = self._fSnap.get()
@ -177,11 +177,11 @@ class DialWidget(Pmw.MegaWidget):
('callbackData', [], None),
)
self.defineoptions(kw, optiondefs)
# Initialize the superclass
Pmw.MegaWidget.__init__(self, parent)
# Set up some local and instance variables
# Set up some local and instance variables
# Create the components
interior = self.interior()
@ -191,7 +191,7 @@ class DialWidget(Pmw.MegaWidget):
# Running total which increments/decrements every time around dial
self.rollCount = 0
# Base dial size on style, if size not specified,
# Base dial size on style, if size not specified,
if not self['size']:
if self['style'] == VALUATOR_FULL:
size = DIAL_FULL_SIZE
@ -199,19 +199,19 @@ class DialWidget(Pmw.MegaWidget):
size = DIAL_MINI_SIZE
else:
size = self['size']
# Radius of the dial
radius = self.radius = int(size/2.0)
# Radius of the inner knob
inner_radius = max(3,radius * INNER_SF)
inner_radius = max(3, radius * INNER_SF)
# The canvas
# The canvas
self._widget = self.createcomponent('canvas', (), None,
Canvas, (interior,),
width = size, height = size,
background = self['background'],
highlightthickness = 0,
scrollregion = (-radius,-radius,
scrollregion = (-radius, -radius,
radius, radius))
self._widget.pack(expand = 1, fill = BOTH)
@ -242,7 +242,7 @@ class DialWidget(Pmw.MegaWidget):
self._widget.tag_bind('knob', '<Enter>', self.highlightKnob)
self._widget.tag_bind('knob', '<Leave>', self.restoreKnob)
# Make sure input variables processed
# Make sure input variables processed
self.initialiseoptions(DialWidget)
def set(self, value, fCommand = 1):
@ -260,7 +260,7 @@ class DialWidget(Pmw.MegaWidget):
apply(self['command'], [value] + self['commandData'])
# Record value
self.value = value
def get(self):
"""
self.get()
@ -270,25 +270,25 @@ class DialWidget(Pmw.MegaWidget):
## Canvas callback functions
# Dial
def mouseDown(self,event):
def mouseDown(self, event):
self._onButtonPress()
self.lastAngle = dialAngle = self.computeDialAngle(event)
self.computeValueFromAngle(dialAngle)
def mouseUp(self,event):
def mouseUp(self, event):
self._onButtonRelease()
def shiftMouseMotion(self,event):
def shiftMouseMotion(self, event):
self.mouseMotion(event, 1)
def mouseMotion(self, event, fShift = 0):
dialAngle = self.computeDialAngle(event, fShift)
self.computeValueFromAngle(dialAngle)
def computeDialAngle(self,event, fShift = 0):
def computeDialAngle(self, event, fShift = 0):
x = self._widget.canvasx(event.x)
y = self._widget.canvasy(event.y)
rawAngle = math.atan2(y,x)
rawAngle = math.atan2(y, x)
# Snap to grid
# Convert to dial coords to do snapping
dialAngle = rawAngle + POINTFIVE_PI
@ -318,8 +318,8 @@ class DialWidget(Pmw.MegaWidget):
def updateIndicatorDegrees(self, degAngle):
self.updateIndicatorRadians(degAngle * (math.pi/180.0))
def updateIndicatorRadians(self,dialAngle):
def updateIndicatorRadians(self, dialAngle):
rawAngle = dialAngle - POINTFIVE_PI
# Compute end points
endx = math.cos(rawAngle) * self.radius
@ -329,7 +329,7 @@ class DialWidget(Pmw.MegaWidget):
endx, endy)
# Knob velocity controller
def knobMouseDown(self,event):
def knobMouseDown(self, event):
self._onButtonPress()
self.knobSF = 0.0
self.updateTask = taskMgr.add(self.updateDialTask, 'updateDial')
@ -364,9 +364,9 @@ class DialWidget(Pmw.MegaWidget):
def setNumDigits(self):
# Set minimum exponent to use in velocity task
self.minExp = math.floor(-self['numDigits']/
math.log10(Valuator.sfBase))
math.log10(Valuator.sfBase))
# Methods to modify dial characteristics
# Methods to modify dial characteristics
def setRelief(self):
self.interior()['relief'] = self['relief']
@ -417,7 +417,7 @@ class DialWidget(Pmw.MegaWidget):
if self['postCallback']:
apply(self['postCallback'], self['callbackData'])
if __name__ == '__main__':
tl = Toplevel()
d = Dial(tl)

View File

@ -13,7 +13,7 @@ Change Min/Max buttons to labels, add highlight binding
class EntryScale(Pmw.MegaWidget):
"Scale with linked and validated entry"
def __init__(self, parent = None, **kw):
# Define the megawidget options.
@ -31,7 +31,7 @@ class EntryScale(Pmw.MegaWidget):
('numDigits', 2, self._setSigDigits),
)
self.defineoptions(kw, optiondefs)
# Initialise superclass
Pmw.MegaWidget.__init__(self, parent)
@ -66,8 +66,8 @@ class EntryScale(Pmw.MegaWidget):
entry_justify = 'right',
entry_textvar = self.entryValue,
command = self._entryCommand)
self.entry.pack(side='left',padx = 4)
self.entry.pack(side='left', padx = 4)
# Create the EntryScale's label
self.label = self.createcomponent('label', (), None,
Label, self.labelFrame,
@ -122,7 +122,7 @@ class EntryScale(Pmw.MegaWidget):
self.maxLabel.bind('<Button-3>', self.askForMax)
self.maxLabel.pack(side='left', fill = 'x')
self.minMaxFrame.pack(expand = 1, fill = 'both')
# Check keywords and initialise options based on input values.
self.initialiseoptions(EntryScale)
@ -140,7 +140,7 @@ class EntryScale(Pmw.MegaWidget):
parent = self.interior())
if newLabel:
self['text'] = newLabel
def askForMin(self, event = None):
newMin = askfloat(title = self['text'],
prompt = 'New min val:',
@ -148,13 +148,13 @@ class EntryScale(Pmw.MegaWidget):
parent = self.interior())
if newMin:
self.setMin(newMin)
def setMin(self, newMin):
self['min'] = newMin
self.scale['from_'] = newMin
self.minLabel['text'] = newMin
self.entry.checkentry()
def askForMax(self, event = None):
newMax = askfloat(title = self['text'],
parent = self.interior(),
@ -168,7 +168,7 @@ class EntryScale(Pmw.MegaWidget):
self.scale['to'] = newMax
self.maxLabel['text'] = newMax
self.entry.checkentry()
def askForResolution(self, event = None):
newResolution = askfloat(title = self['text'],
parent = self.interior(),
@ -181,7 +181,7 @@ class EntryScale(Pmw.MegaWidget):
self['resolution'] = newResolution
self.scale['resolution'] = newResolution
self.entry.checkentry()
def _updateLabelText(self):
self.label['text'] = self['text']
@ -213,9 +213,9 @@ class EntryScale(Pmw.MegaWidget):
def _entryCommand(self, event = None):
try:
val = string.atof(self.entryValue.get())
apply(self.onReturn,self['callbackData'])
apply(self.onReturn, self['callbackData'])
self.set(val)
apply(self.onReturnRelease,self['callbackData'])
apply(self.onReturnRelease, self['callbackData'])
except ValueError:
pass
@ -227,7 +227,7 @@ class EntryScale(Pmw.MegaWidget):
def get(self):
return self.value
def set(self, newVal, fCommand = 1):
# Clamp value
if self['min'] is not None:
@ -247,7 +247,7 @@ class EntryScale(Pmw.MegaWidget):
# Update entry to reflect formatted value
self.entryValue.set(self.entryFormat % self.value)
self.entry.checkentry()
# execute command
if fCommand and (self['command'] is not None):
self['command'](newVal)
@ -313,7 +313,7 @@ class EntryScaleGroup(Pmw.MegaToplevel):
# Initialize the toplevel widget
Pmw.MegaToplevel.__init__(self, parent)
# Create the components
interior = self.interior()
# Get a copy of the initial value (making sure its a list)
@ -321,11 +321,11 @@ class EntryScaleGroup(Pmw.MegaToplevel):
# The Menu Bar
self.balloon = Pmw.Balloon()
menubar = self.createcomponent('menubar',(), None,
menubar = self.createcomponent('menubar', (), None,
Pmw.MenuBar, (interior,),
balloon = self.balloon)
menubar.pack(fill=X)
# EntryScaleGroup Menu
menubar.addmenu('EntryScale Group', 'EntryScale Group Operations')
menubar.addmenuitem(
@ -339,7 +339,7 @@ class EntryScaleGroup(Pmw.MegaToplevel):
menubar.addmenuitem(
'EntryScale Group', 'command', 'Dismiss EntryScale Group panel',
label = 'Dismiss', command = dismissCommand)
menubar.addmenu('Help', 'EntryScale Group Help Operations')
self.toggleBalloonVar = IntVar()
self.toggleBalloonVar.set(0)
@ -370,8 +370,8 @@ class EntryScaleGroup(Pmw.MegaToplevel):
# Make sure entryScales are initialized
self.set(self['value'])
# Make sure input variables processed
# Make sure input variables processed
self.initialiseoptions(EntryScaleGroup)
def _updateLabels(self):
@ -388,7 +388,7 @@ class EntryScaleGroup(Pmw.MegaToplevel):
def get(self):
return self._value
def getAt(self,index):
def getAt(self, index):
return self._value[index]
# This is the command is used to set the groups value
@ -503,10 +503,10 @@ def rgbPanel(nodePath, callback = None):
print "Vec4(%.3f, %.3f, %.3f, %.3f)"%(c[0], c[1], c[2], c[3])
menu.insert_command(index = 5, label = 'Print to log',
command = printToLog)
# Set callback
def onRelease(r,g,b,a, nodePath = nodePath):
messenger.send('RGBPanel_setColor', [nodePath, r,g,b,a])
def onRelease(r, g, b, a, nodePath = nodePath):
messenger.send('RGBPanel_setColor', [nodePath, r, g, b, a])
esg['postCallback'] = onRelease
return esg
@ -519,14 +519,14 @@ if __name__ == '__main__':
# Dummy command
def printVal(val):
print val
# Create and pack a EntryScale megawidget.
mega1 = EntryScale(root, command = printVal)
mega1.pack(side = 'left', expand = 1, fill = 'x')
"""
# These are things you can set/configure
# Starting value for entryScale
# Starting value for entryScale
mega1['value'] = 123.456
mega1['text'] = 'Drive delta X'
mega1['min'] = 0.0
@ -549,6 +549,6 @@ if __name__ == '__main__':
Valuator_max = 255.0,
Valuator_resolution = 1.0,
command = printVal)
# Uncomment this if you aren't running in IDLE
#root.mainloop()

View File

@ -5,7 +5,7 @@ Floater Class: Velocity style controller for floating point values with
from direct.showbase.TkGlobal import *
from Valuator import *
from direct.task import Task
import math,sys,string
import math, sys, string
FLOATER_WIDTH = 22
FLOATER_HEIGHT = 18
@ -20,7 +20,7 @@ class Floater(Valuator):
# Initialize the superclass
Valuator.__init__(self, parent)
self.initialiseoptions(Floater)
def createValuator(self):
self._valuator = self.createcomponent('valuator',
(('floater', 'valuator'),),
@ -34,9 +34,9 @@ class Floater(Valuator):
def packValuator(self):
# Position components
if self._label:
self._label.grid(row=0,column=0, sticky = EW)
self._entry.grid(row=0,column=1, sticky = EW)
self._valuator.grid(row=0,column=2, padx = 2, pady = 2)
self._label.grid(row=0, column=0, sticky = EW)
self._entry.grid(row=0, column=1, sticky = EW)
self._valuator.grid(row=0, column=2, padx = 2, pady = 2)
self.interior().columnconfigure(0, weight = 1)
@ -70,7 +70,7 @@ class FloaterWidget(Pmw.MegaWidget):
# Initialize the superclass
Pmw.MegaWidget.__init__(self, parent)
# Set up some local and instance variables
# Set up some local and instance variables
# Create the components
interior = self.interior()
@ -109,7 +109,7 @@ class FloaterWidget(Pmw.MegaWidget):
self._widget.bind('<Enter>', self.highlightWidget)
self._widget.bind('<Leave>', self.restoreWidget)
# Make sure input variables processed
# Make sure input variables processed
self.initialiseoptions(FloaterWidget)
def set(self, value, fCommand = 1):
@ -126,7 +126,7 @@ class FloaterWidget(Pmw.MegaWidget):
def updateIndicator(self, value):
# Nothing visible to update on this type of widget
pass
def get(self):
"""
self.get()
@ -136,7 +136,7 @@ class FloaterWidget(Pmw.MegaWidget):
## Canvas callback functions
# Floater velocity controller
def mouseDown(self,event):
def mouseDown(self, event):
""" Begin mouse interaction """
# Exectute user redefinable callback function (if any)
self['relief'] = SUNKEN
@ -188,9 +188,9 @@ class FloaterWidget(Pmw.MegaWidget):
upon the number of digits to be displayed in the result
"""
self.minExp = math.floor(-self['numDigits']/
math.log10(Valuator.sfBase))
math.log10(Valuator.sfBase))
# Methods to modify floater characteristics
# Methods to modify floater characteristics
def setRelief(self):
self.interior()['relief'] = self['relief']
@ -234,7 +234,7 @@ class FloaterGroup(Pmw.MegaToplevel):
# Initialize the toplevel widget
Pmw.MegaToplevel.__init__(self, parent)
# Create the components
interior = self.interior()
# Get a copy of the initial value (making sure its a list)
@ -242,11 +242,11 @@ class FloaterGroup(Pmw.MegaToplevel):
# The Menu Bar
self.balloon = Pmw.Balloon()
menubar = self.createcomponent('menubar',(), None,
menubar = self.createcomponent('menubar', (), None,
Pmw.MenuBar, (interior,),
balloon = self.balloon)
menubar.pack(fill=X)
# FloaterGroup Menu
menubar.addmenu('Floater Group', 'Floater Group Operations')
menubar.addmenuitem(
@ -256,7 +256,7 @@ class FloaterGroup(Pmw.MegaToplevel):
menubar.addmenuitem(
'Floater Group', 'command', 'Dismiss Floater Group panel',
label = 'Dismiss', command = self.withdraw)
menubar.addmenu('Help', 'Floater Group Help Operations')
self.toggleBalloonVar = IntVar()
self.toggleBalloonVar.set(0)
@ -281,8 +281,8 @@ class FloaterGroup(Pmw.MegaToplevel):
# Make sure floaters are initialized
self.set(self['value'])
# Make sure input variables processed
# Make sure input variables processed
self.initialiseoptions(FloaterGroup)
def _updateLabels(self):
@ -299,7 +299,7 @@ class FloaterGroup(Pmw.MegaToplevel):
def get(self):
return self._value
def getAt(self,index):
def getAt(self, index):
return self._value[index]
# This is the command is used to set the groups value
@ -324,7 +324,7 @@ class FloaterGroup(Pmw.MegaToplevel):
def reset(self):
self.set(self['value'])
## SAMPLE CODE
if __name__ == '__main__':
# Initialise Tkinter and Pmw.
@ -334,14 +334,14 @@ if __name__ == '__main__':
# Dummy command
def printVal(val):
print val
# Create and pack a Floater megawidget.
mega1 = Floater(root, command = printVal)
mega1.pack(side = 'left', expand = 1, fill = 'x')
"""
# These are things you can set/configure
# Starting value for floater
# Starting value for floater
mega1['value'] = 123.456
mega1['text'] = 'Drive delta X'
# To change the color of the label:
@ -361,6 +361,6 @@ if __name__ == '__main__':
Valuator_max = 255.0,
Valuator_resolution = 1.0,
command = printVal)
# Uncomment this if you aren't running in IDLE
#root.mainloop()

View File

@ -6,7 +6,7 @@ from Tree import *
DEFAULT_MENU_ITEMS = [
'Update Explorer',
'Separator',
'Select', 'Deselect',
'Select', 'Deselect',
'Separator',
'Delete',
'Separator',
@ -25,19 +25,19 @@ class SceneGraphExplorer(Pmw.MegaWidget, DirectObject):
('menuItems', [], Pmw.INITOPT),
)
self.defineoptions(kw, optiondefs)
# Initialise superclass
Pmw.MegaWidget.__init__(self, parent)
# Initialize some class variables
self.nodePath = nodePath
# Create the components.
# Setup up container
interior = self.interior()
interior.configure(relief = GROOVE, borderwidth = 2)
# Create a label and an entry
self._scrolledCanvas = self.createcomponent(
'scrolledCanvas',
@ -49,14 +49,14 @@ class SceneGraphExplorer(Pmw.MegaWidget, DirectObject):
self._canvas['scrollregion'] = ('0i', '0i', '2i', '4i')
self._scrolledCanvas.resizescrollregion()
self._scrolledCanvas.pack(padx = 3, pady = 3, expand=1, fill = BOTH)
self._canvas.bind('<ButtonPress-2>', self.mouse2Down)
self._canvas.bind('<B2-Motion>', self.mouse2Motion)
self._canvas.bind('<Configure>',
lambda e, sc = self._scrolledCanvas:
sc.resizescrollregion())
self.interior().bind('<Destroy>', self.onDestroy)
# Create the contents
self._treeItem = SceneGraphExplorerItem(self.nodePath)
@ -93,7 +93,7 @@ class SceneGraphExplorer(Pmw.MegaWidget, DirectObject):
self._width = 1.0 * self._canvas.winfo_width()
self._height = 1.0 * self._canvas.winfo_height()
xview = self._canvas.xview()
yview = self._canvas.yview()
yview = self._canvas.yview()
self._left = xview[0]
self._top = yview[0]
self._dxview = xview[1] - xview[0]
@ -101,7 +101,7 @@ class SceneGraphExplorer(Pmw.MegaWidget, DirectObject):
self._2lx = event.x
self._2ly = event.y
def mouse2Motion(self,event):
def mouse2Motion(self, event):
newx = self._left - ((event.x - self._2lx)/self._width) * self._dxview
self._canvas.xview_moveto(newx)
newy = self._top - ((event.y - self._2ly)/self._height) * self._dyview

View File

@ -5,7 +5,7 @@ Slider Class: Velocity style controller for floating point values with
from direct.showbase.TkGlobal import *
from Valuator import *
from direct.task import Task
import math,sys,string
import math, sys, string
import operator
from pandac.PandaModules import ClockObject
@ -63,9 +63,9 @@ class Slider(Valuator):
self.interior().columnconfigure(0, weight = 1)
else:
if self._label:
self._label.grid(row=0,column=0, sticky = EW)
self._entry.grid(row=0,column=1, sticky = EW)
self._valuator.grid(row=0,column=2, padx = 2, pady = 2)
self._label.grid(row=0, column=0, sticky = EW)
self._entry.grid(row=0, column=1, sticky = EW)
self._valuator.grid(row=0, column=2, padx = 2, pady = 2)
self.interior().columnconfigure(0, weight = 1)
def setMin(self):
@ -207,7 +207,7 @@ class SliderWidget(Pmw.MegaWidget):
(), None,
Canvas, (interior,), borderwidth = 0,
relief = FLAT, width = 14, height = 14,
scrollregion = (-7,-7,7,7))
scrollregion = (-7, -7, 7, 7))
self._arrowBtn.pack(expand = 1, fill = BOTH)
self._arrowBtn.create_polygon(-5, -5, 5, -5, 0, 5,
fill = 'grey50',
@ -231,17 +231,17 @@ class SliderWidget(Pmw.MegaWidget):
self._arrowBtn.bind('<1>', self._postSlider)
self._arrowBtn.bind('<Enter>', self.highlightWidget)
self._arrowBtn.bind('<Leave>', self.restoreWidget)
# Need to unpost the popup if the arrow Button is unmapped (eg:
# Need to unpost the popup if the arrow Button is unmapped (eg:
# its toplevel window is withdrawn) while the popup slider is
# displayed.
self._arrowBtn.bind('<Unmap>', self._unpostSlider)
# Bind events to the dropdown window.
self._popup.bind('<Escape>', self._unpostSlider)
self._popup.bind('<ButtonRelease-1>', self._widgetBtnRelease)
self._popup.bind('<ButtonPress-1>', self._widgetBtnPress)
self._popup.bind('<Motion>', self._widgetMove)
self._widget.bind('<Left>', self._decrementValue)
self._widget.bind('<Right>', self._incrementValue)
self._widget.bind('<Shift-Left>', self._bigDecrementValue)
@ -253,7 +253,7 @@ class SliderWidget(Pmw.MegaWidget):
self._widget['command'] = self._firstScaleCommand
self._widget.bind('<ButtonRelease-1>', self._scaleBtnRelease)
self._widget.bind('<ButtonPress-1>', self._scaleBtnPress)
# Check keywords and initialise options.
self.initialiseoptions(SliderWidget)
@ -303,7 +303,7 @@ class SliderWidget(Pmw.MegaWidget):
# Update scale's variable, which update scale without
# Calling scale's command
self._widgetVar.set(value)
#======================================================================
# Private methods for slider.
@ -324,7 +324,7 @@ class SliderWidget(Pmw.MegaWidget):
y = self._arrowBtn.winfo_rooty() + self._arrowBtn.winfo_height()
# Popup border width
bd = self._popup['bd']
# bd = string.atoi(self._popup['bd'])
# bd = string.atoi(self._popup['bd'])
# Get width of label
minW = self._minLabel.winfo_width()
# Width of canvas to adjust for
@ -352,7 +352,7 @@ class SliderWidget(Pmw.MegaWidget):
self._firstPress = 1
self._fPressInsde = 0
def _updateValue(self,event):
def _updateValue(self, event):
mouseX = self._widget.canvasx(
event.x_root - self._widget.winfo_rootx())
if mouseX < self.left:
@ -381,7 +381,7 @@ class SliderWidget(Pmw.MegaWidget):
else:
self._fPressInside = 0
self._fUpdate = 0
def _widgetMove(self, event):
if self._firstPress and not self._fUpdate:
canvasY = self._widget.canvasy(
@ -397,7 +397,7 @@ class SliderWidget(Pmw.MegaWidget):
def _scaleBtnPress(self, event):
if self['preCallback']:
apply(self['preCallback'], self['callbackData'])
def _scaleBtnRelease(self, event):
# Do post callback if any
if self['postCallback']:
@ -460,7 +460,7 @@ class SliderWidget(Pmw.MegaWidget):
def _scaleCommand(self, val):
self.set(string.atof(val))
# Methods to modify floater characteristics
# Methods to modify floater characteristics
def setMin(self):
self._minLabel['text'] = self.formatString % self['min']
if self['style'] == VALUATOR_FULL:

View File

@ -43,7 +43,7 @@ class Valuator(Pmw.MegaWidget):
('callbackData', [], None),
)
self.defineoptions(kw, optiondefs)
# Initialize the superclass
Pmw.MegaWidget.__init__(self, parent)
@ -53,7 +53,7 @@ class Valuator(Pmw.MegaWidget):
# Create the components
interior = self.interior()
interior.configure(relief = self['relief'], bd = self['borderwidth'])
# The Valuator
self.createValuator()
# Set valuator callbacks for mouse start/stop
@ -65,7 +65,7 @@ class Valuator(Pmw.MegaWidget):
self._label = self.createcomponent('label', (), None,
Label, (interior,),
text = self['text'],
font = ('MS Sans Serif',12),
font = ('MS Sans Serif', 12),
anchor = CENTER)
else:
self._label = None
@ -114,13 +114,13 @@ class Valuator(Pmw.MegaWidget):
'type': 'string',
'help': 'Enter state: normal or disabled.'
},
'text':
{'widget': self,
'type': 'string',
'help': 'Enter label text.'
},
'min':
{ 'widget': self,
'type': 'real',
@ -136,14 +136,14 @@ class Valuator(Pmw.MegaWidget):
'type': 'integer',
'help': 'Number of digits after decimal point.'
},
'resolution':
{'widget': self,
'type': 'real',
'fNone': 1,
'help':'Widget resolution. Enter None for no resolution .'
},
'resetValue':
{ 'widget': self,
'type': 'real',
@ -155,7 +155,7 @@ class Valuator(Pmw.MegaWidget):
'resolution', 'resetValue']
# Add any valuator specific properties
self.addValuatorPropertiesToDialog()
# Make sure input variables processed
self.fInit = self['fCommandOnInit']
self.initialiseoptions(Valuator)
@ -173,7 +173,7 @@ class Valuator(Pmw.MegaWidget):
# will result in command being executed, otherwise a set with
# commandData == 0 will stick and commands will not be executed
self._valuator['commandData'] = [1]
def get(self):
""" Return current widget value """
return self.adjustedValue
@ -242,7 +242,7 @@ class Valuator(Pmw.MegaWidget):
""" Function to execute at start of mouse interaction """
# Execute pre interaction callback
self._preCallback()
def _mouseUp(self):
""" Function to execute at end of mouse interaction """
# Execute post interaction callback
@ -291,16 +291,16 @@ class Valuator(Pmw.MegaWidget):
"""
self.set(self['resetValue'])
def mouseReset(self,event):
def mouseReset(self, event):
"""
Reset valuator to resetValue
"""
# If not over any canvas item
#if not self._widget.find_withtag(CURRENT):
self.reset()
# Popup dialog to adjust widget properties
def _popupValuatorMenu(self,event):
def _popupValuatorMenu(self, event):
self._popupMenu.post(event.widget.winfo_pointerx(),
event.widget.winfo_pointery())
@ -315,7 +315,7 @@ class Valuator(Pmw.MegaWidget):
def addPropertyToDialog(self, property, pDict):
self.propertyDict[property] = pDict
self.propertyList.append(property)
# Virtual functions to be redefined by subclass
def createValuator(self):
""" Function used by subclass to create valuator geometry """
@ -375,7 +375,7 @@ class ValuatorGroup(Pmw.MegaWidget):
# Initialize the toplevel widget
Pmw.MegaWidget.__init__(self, parent)
# Create the components
interior = self.interior()
# Get a copy of the initial value (making sure its a list)
@ -414,8 +414,8 @@ class ValuatorGroup(Pmw.MegaWidget):
# Make sure valuators are initialized
self.set(self['value'], fCommand = 0)
# Make sure input variables processed
# Make sure input variables processed
self.initialiseoptions(ValuatorGroup)
# This is the command is used to set the groups value
@ -440,7 +440,7 @@ class ValuatorGroup(Pmw.MegaWidget):
def get(self):
return self._value
def getAt(self,index):
def getAt(self, index):
return self._value[index]
def _setNumDigits(self):
@ -456,7 +456,7 @@ class ValuatorGroup(Pmw.MegaWidget):
# Execute pre callback
if self['preCallback']:
apply(self['preCallback'], valGroup.get())
def _postCallback(self, valGroup):
# Execute post callback
if self['postCallback']:
@ -464,14 +464,14 @@ class ValuatorGroup(Pmw.MegaWidget):
def __len__(self):
return self['dim']
def __repr__(self):
str = '[' + self.formatString % self._value[0]
for val in self._value[1:]:
str += ', ' + self.formatString % val
str += ']'
return str
class ValuatorGroupPanel(Pmw.MegaToplevel):
@ -513,17 +513,17 @@ class ValuatorGroupPanel(Pmw.MegaToplevel):
# Initialize the toplevel widget
Pmw.MegaToplevel.__init__(self, parent)
# Create the components
interior = self.interior()
# The Menu Bar
self.balloon = Pmw.Balloon()
menubar = self.createcomponent('menubar',(), None,
menubar = self.createcomponent('menubar', (), None,
Pmw.MenuBar, (interior,),
balloon = self.balloon)
menubar.pack(fill=X)
# ValuatorGroup Menu
menubar.addmenu('Valuator Group', 'Valuator Group Operations')
menubar.addmenuitem(
@ -539,7 +539,7 @@ class ValuatorGroupPanel(Pmw.MegaToplevel):
menubar.addmenuitem(
'Valuator Group', 'command', 'Dismiss Valuator Group panel',
label = 'Dismiss', command = dismissCommand)
menubar.addmenu('Help', 'Valuator Group Help Operations')
self.toggleBalloonVar = IntVar()
self.toggleBalloonVar.set(0)
@ -564,8 +564,8 @@ class ValuatorGroupPanel(Pmw.MegaToplevel):
labels = self['labels'],
command = self['command'])
self.valuatorGroup.pack(expand = 1, fill = X)
# Make sure input variables processed
# Make sure input variables processed
self.initialiseoptions(ValuatorGroupPanel)
def toggleBalloon(self):
@ -579,7 +579,7 @@ class ValuatorGroupPanel(Pmw.MegaToplevel):
def _setNumDigits(self):
self.valuatorGroup['numDigits'] = self['numDigits']
def _setCommand(self):
self.valuatorGroup['command'] = self['command']
@ -599,8 +599,8 @@ Pmw.forwardmethods(ValuatorGroupPanel, ValuatorGroup, 'valuatorGroup')
def rgbPanel(nodePath, callback = None, style = 'mini'):
def onRelease(r,g,b,a, nodePath = nodePath):
messenger.send('RGBPanel_setColor', [nodePath, r,g,b,a])
def onRelease(r, g, b, a, nodePath = nodePath):
messenger.send('RGBPanel_setColor', [nodePath, r, g, b, a])
def popupColorPicker():
# Can pass in current color with: color = (255, 0, 0)
@ -641,13 +641,13 @@ def rgbPanel(nodePath, callback = None, style = 'mini'):
# Set callback
vgp['postCallback'] = onRelease
# Add a print button which will also serve as a color tile
pButton = Button(vgp.interior(), text = 'Print to Log',
bg = getTkColorString(initColor),
command = printToLog)
pButton.pack(expand = 1, fill = BOTH)
# Update menu
menu = vgp.component('menubar').component('Valuator Group-menu')
# Some helper functions
@ -678,7 +678,7 @@ def rgbPanel(nodePath, callback = None, style = 'mini'):
if callback:
callback(color)
vgp['command'] = setNodePathColor
return vgp
@ -696,7 +696,7 @@ def lightRGBPanel(light, style = 'mini'):
n = light.getName()
c=light.getColor()
print n + (".setColor(Vec4(%.3f, %.3f, %.3f, %.3f))" %
(c[0],c[1],c[2],c[3]))
(c[0], c[1], c[2], c[3]))
# Check init color
initColor = light.getColor() * 255.0
# Create entry scale group

View File

@ -47,7 +47,7 @@ class VectorEntry(Pmw.MegaWidget):
self._floaters = None
self.entryFormat = '%.2f'
# Get a handle on the parent container
# Get a handle on the parent container
interior = self.interior()
# This does double duty as a menu button
@ -103,15 +103,15 @@ class VectorEntry(Pmw.MegaWidget):
# if the user kills the floaterGroup and then tries to pop it open again
self._floaters.userdeletefunc(self._floaters.withdraw)
self._floaters.withdraw()
# Make sure entries are updated
self.set(self['value'])
# Record entry color
self.entryBackground = self.cget('Entry_entry_background')
# Make sure input variables processed
# Make sure input variables processed
self.initialiseoptions(VectorEntry)
def menu(self):
@ -131,7 +131,7 @@ class VectorEntry(Pmw.MegaWidget):
def _clearFloaters(self):
self._floaters.withdraw()
def _updateText(self):
self._label['text'] = self['text']
@ -139,7 +139,7 @@ class VectorEntry(Pmw.MegaWidget):
self.interior()['relief'] = self['relief']
def _updateBorderWidth(self):
self.interior()['bd'] = self['bd']
self.interior()['bd'] = self['bd']
def _updateEntryWidth(self):
self['Entry_entry_width'] = self['entryWidth']
@ -162,14 +162,14 @@ class VectorEntry(Pmw.MegaWidget):
'maxstrict': 0})
# Reflect changes in floaters
self.configure(valuator_min = self['min'],
valuator_max = self['max'])
valuator_max = self['max'])
def get(self):
return self._value
def getAt(self,index):
def getAt(self, index):
return self._value[index]
def set(self, value, fCommand = 1):
if type(value) in (types.FloatType, types.IntType, types.LongType):
value = [value] * self['dim']
@ -182,15 +182,15 @@ class VectorEntry(Pmw.MegaWidget):
self.variableList[index].set(self.entryFormat % value)
self._value[index] = value
self.action(fCommand)
def _entryUpdateAt(self, index):
entryVar = self.variableList[index]
# Did we get a valid float?
try:
try:
newVal = string.atof(entryVar.get())
except ValueError:
return
# Clamp value
if self['min'] is not None:
if newVal < self['min']:
@ -208,19 +208,19 @@ class VectorEntry(Pmw.MegaWidget):
# Update the floaters and call the command
self.action()
def _refreshEntry(self,index):
def _refreshEntry(self, index):
self.variableList[index].set(self.entryFormat % self._value[index])
self.entryList[index].checkentry()
def _refreshFloaters(self):
if self._floaters:
self._floaters.set(self._value, 0)
def action(self, fCommand = 1):
self._refreshFloaters()
if fCommand and (self['command'] != None):
self['command'](self._value)
self['command'](self._value)
def reset(self):
self.set(self['resetValue'])

View File

@ -53,7 +53,7 @@ class WidgetPropertiesDialog(Toplevel):
parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def destroy(self):
"""Destroy the window"""
self.propertyDict = {}
@ -62,12 +62,12 @@ class WidgetPropertiesDialog(Toplevel):
for balloon in self.balloonList:
balloon.withdraw()
Toplevel.destroy(self)
#
# construction hooks
def body(self, master):
"""create dialog body.
return entry that should have initial focus.
return entry that should have initial focus.
This method should be overridden, and is called
by the __init__ method.
"""
@ -132,8 +132,8 @@ class WidgetPropertiesDialog(Toplevel):
balloon.bind(entry, helpString)
# Create callback to execute whenever a value is changed
modifiedCallback = (lambda f=self.modified, w=widget, e=entry,
p=property, t=entryType,fn=fAllowNone:
f(w,e,p,t, fn))
p=property, t=entryType, fn=fAllowNone:
f(w, e, p, t, fn))
entry['modifiedcommand'] = modifiedCallback
# Keep track of the entrys
entryList.append(entry)
@ -149,10 +149,10 @@ class WidgetPropertiesDialog(Toplevel):
return self
def modified(self, widget, entry, property, type, fNone):
self.modifiedDict[property] = (widget,entry,type,fNone)
self.modifiedDict[property] = (widget, entry, type, fNone)
def buttonbox(self):
"""add standard button box buttons.
"""add standard button box buttons.
"""
box = Frame(self)
# Create buttons
@ -193,7 +193,7 @@ class WidgetPropertiesDialog(Toplevel):
self.validateChanges()
self.apply()
self.cancel()
def cancel(self, event=None):
# put focus back to the parent window
self.parent.focus_set()