formatting

This commit is contained in:
Dave Schuyler 2006-03-17 21:41:36 +00:00
parent 21c8a3685c
commit 26ea29157c
31 changed files with 391 additions and 391 deletions

View File

@ -395,14 +395,14 @@ class Actor(DirectObject, NodePath):
# and sort them every time somebody asks for the list
self.__sortedLODNames = self.__partBundleDict.keys()
# Reverse sort the doing a string->int
def sortFunc(x,y):
def sortFunc(x, y):
if not str(x).isdigit():
smap = {'h':2,
'm':1,
'l':0}
return cmp(smap[y[0]],smap[x[0]])
return cmp(smap[y[0]], smap[x[0]])
else:
return cmp (int(y),int(x))
return cmp (int(y), int(x))
self.__sortedLODNames.sort(sortFunc)

View File

@ -31,5 +31,5 @@ class DistributedActor(DistributedNode.DistributedNode, Actor.Actor):
Actor.Actor.delete(self)
def loop(self, animName, restart=1, partName=None,fromFrame=None, toFrame=None):
return Actor.Actor.loop(self,animName,restart,partName,fromFrame,toFrame)
def loop(self, animName, restart=1, partName=None, fromFrame=None, toFrame=None):
return Actor.Actor.loop(self, animName, restart, partName, fromFrame, toFrame)

View File

@ -52,8 +52,8 @@ class ClusterClient(DirectObject.DirectObject):
self.serverList = []
self.msgHandler = ClusterMsgHandler(ClusterClient.MGR_NUM, self.notify)
for serverConfig in configList:
server = DisplayConnection(self.qcm,serverConfig.serverName,
serverConfig.serverPort,self.msgHandler)
server = DisplayConnection(self.qcm, serverConfig.serverName,
serverConfig.serverPort, self.msgHandler)
if server == None:
self.notify.error('Could not open %s on %s port %d' %
(serverConfig.serverConfigName,
@ -63,7 +63,7 @@ class ClusterClient(DirectObject.DirectObject):
self.notify.debug('send cam pos')
#server.sendMoveCam(Point3(0), Vec3(0))
self.notify.debug('send cam offset')
server.sendCamOffset(serverConfig.xyz,serverConfig.hpr)
server.sendCamOffset(serverConfig.xyz, serverConfig.hpr)
if serverConfig.fFrustum:
self.notify.debug('send cam frustum')
server.sendCamFrustum(serverConfig.focalLength,
@ -81,7 +81,7 @@ class ClusterClient(DirectObject.DirectObject):
self.notify.debug('broadcasting frame time')
taskMgr.add(self.synchronizeTimeTask, "synchronizeTimeTask", -40)
def synchronizeTimeTask(self,task):
def synchronizeTimeTask(self, task):
frameCount = globalClock.getFrameCount()
frameTime = globalClock.getFrameTime()
dt = globalClock.getDt()
@ -93,7 +93,7 @@ class ClusterClient(DirectObject.DirectObject):
self.notify.debug('adding move cam')
taskMgr.add(self.moveCameraTask, "moveCamTask", 49)
def moveCameraTask(self,task):
def moveCameraTask(self, task):
self.moveCamera(
base.camera.getPos(render),
base.camera.getHpr(render))
@ -102,7 +102,7 @@ class ClusterClient(DirectObject.DirectObject):
def moveCamera(self, xyz, hpr):
self.notify.debug('moving unsynced camera')
for server in self.serverList:
server.sendMoveCam(xyz,hpr)
server.sendMoveCam(xyz, hpr)
def startMoveSelectedTask(self):
taskMgr.add(self.moveSelectedTask, "moveSelectedTask", 48)
@ -116,7 +116,7 @@ class ClusterClient(DirectObject.DirectObject):
scale = VBase3(1)
decomposeMatrix(last.getMat(), scale, hpr, xyz)
for server in self.serverList:
server.sendMoveSelected(xyz,hpr,scale)
server.sendMoveSelected(xyz, hpr, scale)
return Task.cont
def getNodePathFindCmd(self, nodePath):
@ -182,7 +182,7 @@ class ClusterClientSync(ClusterClient):
def startSwapCoordinatorTask(self):
taskMgr.add(self.swapCoordinator, "clientSwapCoordinator", 51)
def swapCoordinator(self,task):
def swapCoordinator(self, task):
self.ready = 1
if self.waitForSwap:
self.waitForSwap=0
@ -201,15 +201,15 @@ class ClusterClientSync(ClusterClient):
"------------------------------------------END swap")
return Task.cont
def moveCamera(self,xyz,hpr):
def moveCamera(self, xyz, hpr):
if self.ready:
self.notify.debug('moving synced camera')
ClusterClient.moveCamera(self,xyz,hpr)
ClusterClient.moveCamera(self, xyz, hpr)
self.waitForSwap=1
class DisplayConnection:
def __init__(self,qcm,serverName,port,msgHandler):
def __init__(self, qcm, serverName, port, msgHandler):
self.msgHandler = msgHandler
gameServerTimeoutMs = base.config.GetInt(
"cluster-server-timeout-ms", 300000)
@ -225,15 +225,15 @@ class DisplayConnection:
self.qcr.addConnection(self.tcpConn)
self.cw=ConnectionWriter(qcm, 0)
def sendCamOffset(self,xyz,hpr):
def sendCamOffset(self, xyz, hpr):
ClusterClient.notify.debug("send cam offset...")
ClusterClient.notify.debug(("packet %d xyz,hpr=%f %f %f %f %f %f" %
(self.msgHandler.packetNumber,xyz[0],xyz[1],xyz[2],
hpr[0],hpr[1],hpr[2])))
ClusterClient.notify.debug(("packet %d xyz, hpr=%f %f %f %f %f %f" %
(self.msgHandler.packetNumber, xyz[0], xyz[1], xyz[2],
hpr[0], hpr[1], hpr[2])))
datagram = self.msgHandler.makeCamOffsetDatagram(xyz, hpr)
self.cw.send(datagram, self.tcpConn)
def sendCamFrustum(self,focalLength, filmSize, filmOffset):
def sendCamFrustum(self, focalLength, filmSize, filmOffset):
ClusterClient.notify.info("send cam frustum...")
ClusterClient.notify.info(
(("packet %d" % self.msgHandler.packetNumber) +
@ -245,23 +245,23 @@ class DisplayConnection:
focalLength, filmSize, filmOffset)
self.cw.send(datagram, self.tcpConn)
def sendMoveCam(self,xyz,hpr):
def sendMoveCam(self, xyz, hpr):
ClusterClient.notify.debug("send cam move...")
ClusterClient.notify.debug(("packet %d xyz,hpr=%f %f %f %f %f %f" %
(self.msgHandler.packetNumber,xyz[0],xyz[1],xyz[2],
hpr[0],hpr[1],hpr[2])))
ClusterClient.notify.debug(("packet %d xyz, hpr=%f %f %f %f %f %f" %
(self.msgHandler.packetNumber, xyz[0], xyz[1], xyz[2],
hpr[0], hpr[1], hpr[2])))
datagram = self.msgHandler.makeCamMovementDatagram(xyz, hpr)
self.cw.send(datagram, self.tcpConn)
def sendMoveSelected(self,xyz,hpr,scale):
def sendMoveSelected(self, xyz, hpr, scale):
ClusterClient.notify.debug("send move selected...")
ClusterClient.notify.debug(
"packet %d xyz,hpr=%f %f %f %f %f %f %f %f %f" %
"packet %d xyz, hpr=%f %f %f %f %f %f %f %f %f" %
(self.msgHandler.packetNumber,
xyz[0],xyz[1],xyz[2],
hpr[0],hpr[1],hpr[2],
scale[0],scale[1],scale[2]))
datagram = self.msgHandler.makeSelectedMovementDatagram(xyz, hpr,scale)
xyz[0], xyz[1], xyz[2],
hpr[0], hpr[1], hpr[2],
scale[0], scale[1], scale[2]))
datagram = self.msgHandler.makeSelectedMovementDatagram(xyz, hpr, scale)
self.cw.send(datagram, self.tcpConn)
# the following should only be called by a synchronized cluster manger
@ -293,7 +293,7 @@ class DisplayConnection:
datagram = self.msgHandler.makeExitDatagram()
self.cw.send(datagram, self.tcpConn)
def sendTimeData(self,frameCount, frameTime, dt):
def sendTimeData(self, frameCount, frameTime, dt):
ClusterClient.notify.debug("send time data...")
datagram = self.msgHandler.makeTimeDataDatagram(
frameCount, frameTime, dt)
@ -362,7 +362,7 @@ def createClusterClient():
if serverName == '':
base.notify.warning(
'%s undefined in Configrc: expected by %s display client.'%
(serverConfigName,clusterConfig))
(serverConfigName, clusterConfig))
base.notify.warning('%s will not be used.' % serverConfigName)
else:
# Server port

View File

@ -28,12 +28,12 @@ ClientConfigs = {
'two-server': [{'display name': 'master',
'display mode': 'client',
'pos': Vec3(0),
#'hpr': Vec3(30,0,0)},
'hpr': Vec3(0,0,0)},
#'hpr': Vec3(30, 0, 0)},
'hpr': Vec3(0, 0, 0)},
{'display name': 'la',
'pos': Vec3(0),
#'hpr': Vec3(-30,0,0)
'hpr': Vec3(0,0,0)
#'hpr': Vec3(-30, 0, 0)
'hpr': Vec3(0, 0, 0)
}
],
'mono-cave': [{'display name': 'la',
@ -418,11 +418,11 @@ ClientConfigs = {
'hpr': Vec3(0),
},
{'display name': 'left',
'pos': Vec3(-.105,0,0),
'hpr': Vec3(0,0,0)},
'pos': Vec3(-.105, 0, 0),
'hpr': Vec3(0, 0, 0)},
{'display name': 'right',
'pos': Vec3(.105,0,0),
'hpr': Vec3(0,0,0)}
'pos': Vec3(.105, 0, 0),
'hpr': Vec3(0, 0, 0)}
],
'ursula': [{'display name': 'master',
'display mode': 'client',
@ -430,16 +430,16 @@ ClientConfigs = {
'hpr': Vec3(0),
},
{'display name': 'l',
'pos': Vec3(-.105,0,0),
'hpr': Vec3(0,0,0),
'pos': Vec3(-.105, 0, 0),
'hpr': Vec3(0, 0, 0),
'focal length': 15,
'film size': (13.33, 10),
#'film offset': (0.105, -2),
'film offset': (0.105, -1),
},
{'display name': 'r',
'pos': Vec3(.105,0,0),
'hpr': Vec3(0,0,0),
'pos': Vec3(.105, 0, 0),
'hpr': Vec3(0, 0, 0),
'focal length': 15,
'film size': (13.33, 10),
#'film offset': (-0.105, -2),

View File

@ -41,13 +41,13 @@ SERVER_STARTUP_STRING = (
class ClusterMsgHandler:
"""ClusterMsgHandler: wrapper for PC clusters/multi-piping networking"""
def __init__(self,packetStart, notify):
def __init__(self, packetStart, notify):
# packetStart can be used to distinguish which ClusterMsgHandler
# sends a given packet.
self.packetNumber = packetStart
self.notify = notify
def nonBlockingRead(self,qcr):
def nonBlockingRead(self, qcr):
"""
Return a datagram iterator and type if data is available on the
queued connection reader
@ -65,9 +65,9 @@ class ClusterMsgHandler:
dgi = None
type = CLUSTER_NONE
# Note, return datagram to keep a handle on the data
return (datagram, dgi,type)
return (datagram, dgi, type)
def blockingRead(self,qcr):
def blockingRead(self, qcr):
"""
Block until data is available on the queued connection reader.
Returns a datagram iterator and type
@ -88,14 +88,14 @@ class ClusterMsgHandler:
# Note, return datagram to keep a handle on the data
return (datagram, dgi, type)
def readHeader(self,datagram):
def readHeader(self, datagram):
dgi = PyDatagramIterator(datagram)
number = dgi.getUint32()
type = dgi.getUint8()
self.notify.debug("Packet %d type %d received" % (number,type))
return (dgi,type)
self.notify.debug("Packet %d type %d received" % (number, type))
return (dgi, type)
def makeCamOffsetDatagram(self,xyz,hpr):
def makeCamOffsetDatagram(self, xyz, hpr):
datagram = PyDatagram()
datagram.addUint32(self.packetNumber)
self.packetNumber = self.packetNumber + 1
@ -115,10 +115,10 @@ class ClusterMsgHandler:
h=dgi.getFloat32()
p=dgi.getFloat32()
r=dgi.getFloat32()
self.notify.debug('new offset=%f %f %f %f %f %f' % (x,y,z,h,p,r))
return (x,y,z,h,p,r)
self.notify.debug('new offset=%f %f %f %f %f %f' % (x, y, z, h, p, r))
return (x, y, z, h, p, r)
def makeCamFrustumDatagram(self,focalLength, filmSize, filmOffset):
def makeCamFrustumDatagram(self, focalLength, filmSize, filmOffset):
datagram = PyDatagram()
datagram.addUint32(self.packetNumber)
self.packetNumber = self.packetNumber + 1
@ -133,13 +133,13 @@ class ClusterMsgHandler:
def parseCamFrustumDatagram(self, dgi):
focalLength = dgi.getFloat32()
filmSize = (dgi.getFloat32(), dgi.getFloat32())
filmOffset = (dgi.getFloat32(),dgi.getFloat32())
filmOffset = (dgi.getFloat32(), dgi.getFloat32())
self.notify.debug('fl, fs, fo=%f, (%f, %f), (%f, %f)' %
(focalLength, filmSize[0], filmSize[1],
filmOffset[0], filmOffset[1]))
return (focalLength, filmSize, filmOffset)
def makeCamMovementDatagram(self,xyz,hpr):
def makeCamMovementDatagram(self, xyz, hpr):
datagram = PyDatagram()
datagram.addUint32(self.packetNumber)
self.packetNumber = self.packetNumber + 1
@ -160,10 +160,10 @@ class ClusterMsgHandler:
p=dgi.getFloat32()
r=dgi.getFloat32()
self.notify.debug((' new position=%f %f %f %f %f %f' %
(x,y,z,h,p,r)))
return (x,y,z,h,p,r)
(x, y, z, h, p, r)))
return (x, y, z, h, p, r)
def makeSelectedMovementDatagram(self,xyz,hpr,scale):
def makeSelectedMovementDatagram(self, xyz, hpr, scale):
datagram = PyDatagram()
datagram.addUint32(self.packetNumber)
self.packetNumber = self.packetNumber + 1
@ -190,8 +190,8 @@ class ClusterMsgHandler:
sy=dgi.getFloat32()
sz=dgi.getFloat32()
self.notify.debug(' new position=%f %f %f %f %f %f %f %f %f' %
(x,y,z,h,p,r,sx,sy,sz))
return (x,y,z,h,p,r,sx,sy,sz)
(x, y, z, h, p, r, sx, sy, sz))
return (x, y, z, h, p, r, sx, sy, sz)
def makeCommandStringDatagram(self, commandString):
datagram = PyDatagram()
@ -226,7 +226,7 @@ class ClusterMsgHandler:
datagram.addUint8(CLUSTER_EXIT)
return datagram
def makeTimeDataDatagram(self,frameCount, frameTime, dt):
def makeTimeDataDatagram(self, frameCount, frameTime, dt):
datagram = PyDatagram()
datagram.addUint32(self.packetNumber)
self.packetNumber = self.packetNumber + 1

View File

@ -18,7 +18,7 @@ class ClusterServer(DirectObject.DirectObject):
notify = DirectNotifyGlobal.directNotify.newCategory("ClusterServer")
MSG_NUM = 2000000
def __init__(self,cameraJig,camera):
def __init__(self, cameraJig, camera):
global clusterServerPort, clusterSyncFlag
global clusterDaemonClient, clusterDaemonPort
# Store information about the cluster's camera
@ -31,7 +31,7 @@ class ClusterServer(DirectObject.DirectObject):
self.qcm = QueuedConnectionManager()
self.qcl = QueuedConnectionListener(self.qcm, 0)
self.qcr = QueuedConnectionReader(self.qcm, 0)
self.cw = ConnectionWriter(self.qcm,0)
self.cw = ConnectionWriter(self.qcm, 0)
try:
port = clusterServerPort
except NameError:
@ -68,7 +68,7 @@ class ClusterServer(DirectObject.DirectObject):
def startListenerPollTask(self):
# Run this task near the start of frame, sometime after the dataLoop
taskMgr.add(self.listenerPollTask, "serverListenerPollTask",-40)
taskMgr.add(self.listenerPollTask, "serverListenerPollTask", -40)
def listenerPollTask(self, task):
""" Task to listen for a new connection from the client """
@ -78,7 +78,7 @@ class ClusterServer(DirectObject.DirectObject):
rendezvous = PointerToConnection()
netAddress = NetAddress()
newConnection = PointerToConnection()
if self.qcl.getNewConnection(rendezvous,netAddress,newConnection):
if self.qcl.getNewConnection(rendezvous, netAddress, newConnection):
# Crazy dereferencing
newConnection=newConnection.p()
self.qcr.addConnection(newConnection)
@ -101,7 +101,7 @@ class ClusterServer(DirectObject.DirectObject):
def _readerPollTask(self, state):
""" Non blocking task to read all available datagrams """
while 1:
(datagram, dgi,type) = self.msgHandler.nonBlockingRead(self.qcr)
(datagram, dgi, type) = self.msgHandler.nonBlockingRead(self.qcr)
# Queue is empty, done for now
if type is CLUSTER_NONE:
break
@ -118,9 +118,9 @@ class ClusterServer(DirectObject.DirectObject):
type = CLUSTER_NONE
while type != CLUSTER_CAM_MOVEMENT:
# Block until you get a new datagram
(datagram,dgi,type) = self.msgHandler.blockingRead(self.qcr)
(datagram, dgi, type) = self.msgHandler.blockingRead(self.qcr)
# Process datagram
self.handleDatagram(dgi,type)
self.handleDatagram(dgi, type)
return Task.cont
def startSwapCoordinator(self):
@ -133,8 +133,8 @@ class ClusterServer(DirectObject.DirectObject):
self.sendSwapReady()
# Wait for swap command (processing any intermediate datagrams)
while 1:
(datagram,dgi,type) = self.msgHandler.blockingRead(self.qcr)
self.handleDatagram(dgi,type)
(datagram, dgi, type) = self.msgHandler.blockingRead(self.qcr)
self.handleDatagram(dgi, type)
if type == CLUSTER_SWAP_NOW:
break
return Task.cont
@ -176,35 +176,35 @@ class ClusterServer(DirectObject.DirectObject):
return type
# Server specific tasks
def handleCamOffset(self,dgi):
def handleCamOffset(self, dgi):
""" Set offset of camera from cameraJig """
(x,y,z,h,p,r) = self.msgHandler.parseCamOffsetDatagram(dgi)
(x, y, z, h, p, r) = self.msgHandler.parseCamOffsetDatagram(dgi)
self.lens.setIodOffset(x)
self.lens.setViewHpr(h,p,r)
self.lens.setViewHpr(h, p, r)
def handleCamFrustum(self,dgi):
def handleCamFrustum(self, dgi):
""" Adjust camera frustum based on parameters sent by client """
(fl,fs,fo) = self.msgHandler.parseCamFrustumDatagram(dgi)
(fl, fs, fo) = self.msgHandler.parseCamFrustumDatagram(dgi)
self.lens.setFocalLength(fl)
self.lens.setFilmSize(fs[0], fs[1])
self.lens.setFilmOffset(fo[0], fo[1])
def handleCamMovement(self,dgi):
def handleCamMovement(self, dgi):
""" Update cameraJig position to reflect latest position """
(x,y,z,h,p,r) = self.msgHandler.parseCamMovementDatagram(dgi)
self.cameraJig.setPosHpr(render,x,y,z,h,p,r)
(x, y, z, h, p, r) = self.msgHandler.parseCamMovementDatagram(dgi)
self.cameraJig.setPosHpr(render, x, y, z, h, p, r)
self.fPosReceived = 1
def handleSelectedMovement(self,dgi):
def handleSelectedMovement(self, dgi):
""" Update cameraJig position to reflect latest position """
(x,y,z,h,p,r,sx,sy,sz) = self.msgHandler.parseSelectedMovementDatagram(
(x, y, z, h, p, r, sx, sy, sz) = self.msgHandler.parseSelectedMovementDatagram(
dgi)
if last:
last.setPosHprScale(x,y,z,h,p,r,sx,sy,sz)
last.setPosHprScale(x, y, z, h, p, r, sx, sy, sz)
def handleTimeData(self,dgi):
def handleTimeData(self, dgi):
""" Update cameraJig position to reflect latest position """
(frameCount,frameTime,dt) = self.msgHandler.parseTimeDataDatagram(dgi)
(frameCount, frameTime, dt) = self.msgHandler.parseTimeDataDatagram(dgi)
# Use frame time from client for both real and frame time
globalClock.setFrameCount(frameCount)
globalClock.setFrameTime(frameTime)

View File

@ -11,13 +11,13 @@ def ToggleStrafe():
def SetStrafe(status):
global BattleStrafe
BattleStrafe = status
class BattleWalker(GravityWalker.GravityWalker):
def __init__(self):
GravityWalker.GravityWalker.__init__(self)
self.slideSpeed = 0
self.advanceSpeed = 0
def getSpeeds(self):
return (self.speed, self.rotationSpeed, self.slideSpeed, self.advanceSpeed)
@ -37,7 +37,7 @@ class BattleWalker(GravityWalker.GravityWalker):
# Determine what the speeds are based on the buttons:
self.speed=(forward and self.avatarControlForwardSpeed or
reverse and -self.avatarControlReverseSpeed)
# Slide speed is a scaled down version of forward speed
# Slide speed is a scaled down version of forward speed
self.slideSpeed=(slideLeft and -self.avatarControlForwardSpeed or
slideRight and self.avatarControlForwardSpeed) * 0.5
self.rotationSpeed=not (slideLeft or slideRight) and (
@ -108,7 +108,7 @@ class BattleWalker(GravityWalker.GravityWalker):
# Consider commenting out this normalize. If you do so
# then going up and down slops is a touch slower and
# steeper terrain can cut the movement in half. Without
# the normalize the movement is slowed by the cosine of
# the normalize the movement is slowed by the cosine of
# the slope (i.e. it is multiplied by the sign as a
# side effect of the cross product above).
forward.normalize()
@ -151,12 +151,12 @@ class BattleWalker(GravityWalker.GravityWalker):
slide = inputState.isSet("slide")
jump = inputState.isSet("jump")
# Determine what the speeds are based on the buttons:
self.advanceSpeed=(forward and self.avatarControlForwardSpeed or
self.advanceSpeed=(forward and self.avatarControlForwardSpeed or
reverse and -self.avatarControlReverseSpeed)
if run and self.advanceSpeed>0.0:
self.advanceSpeed*=2.0 #*#
# Should fSlide be renamed slideButton?
self.slideSpeed=.15*(turnLeft and -self.avatarControlForwardSpeed or
self.slideSpeed=.15*(turnLeft and -self.avatarControlForwardSpeed or
turnRight and self.avatarControlForwardSpeed)
print 'slideSpeed: ', self.slideSpeed
self.rotationSpeed=0
@ -261,7 +261,7 @@ class BattleWalker(GravityWalker.GravityWalker):
distance = 0
# Take a step in the direction of our previous heading.
self.vel=Vec3(Vec3.forward() * distance +
self.vel=Vec3(Vec3.forward() * distance +
Vec3.right() * slideDistance)
if self.vel != Vec3.zero() or self.priorParent != Vec3.zero():
# rotMat is the rotation matrix corresponding to

View File

@ -29,10 +29,10 @@ class ControlManager:
self.isEnabled = 1
#self.monitorTask = taskMgr.add(self.monitor, "ControlManager-%s"%(id(self)), priority=-1)
inputState.watch("run", "running-on", "running-off")
inputState.watchWithModifiers("forward", "arrow_up")
inputState.watch("forward", "force-forward", "force-forward-stop")
inputState.watchWithModifiers("reverse", "arrow_down")
inputState.watchWithModifiers("reverse", "mouse4")
@ -65,9 +65,9 @@ class ControlManager:
controls is an avatar control system.
name is any key that you want to use to refer to the
the controls later (e.g. using the use(<name>) call).
Add a control instance to the list of available control systems.
See also: use().
"""
assert self.notify.debugCall(id(self))
@ -85,11 +85,11 @@ class ControlManager:
def remove(self, name):
"""
name is any key that was used to refer to the
the controls when they were added (e.g.
the controls when they were added (e.g.
using the add(<controls>, <name>) call).
Remove a control instance from the list of available control systems.
See also: add().
"""
assert self.notify.debugCall(id(self))
@ -108,13 +108,13 @@ class ControlManager:
def unlockControls(self):
if hasattr(self, "ignoreUse"):
del self.ignoreUse
def use(self, name, avatar):
"""
name is a key (string) that was previously passed to add().
Use a previously added control system.
See also: add().
"""
assert self.notify.debugCall(id(self))
@ -162,9 +162,9 @@ class ControlManager:
if self.wantWASD:
inputState.ignore("slideLeft")
inputState.ignore("slideRight")
#self.monitorTask.remove()
def getSpeeds(self):
return self.currentControls.getSpeeds()
@ -194,7 +194,7 @@ class ControlManager:
assert self.notify.debugCall(id(self))
self.isEnabled = 1
self.currentControls.enableAvatarControls()
def disable(self):
assert self.notify.debugCall(id(self))
self.isEnabled = 0
@ -219,7 +219,7 @@ class ControlManager:
self.enableJumpCounter-=1
if self.enableJumpCounter <= 0:
inputState.force("jump", 0)
def monitor(self, foo):
#assert(self.debugPrint("monitor()"))
#if 1:

View File

@ -56,11 +56,11 @@ class DevWalker(DirectObject.DirectObject):
def setWallBitMask(self, bitMask):
pass
def setFloorBitMask(self, bitMask):
pass
def initializeCollisions(self, collisionTraverser, avatarNodePath,
def initializeCollisions(self, collisionTraverser, avatarNodePath,
wallCollideMask, floorCollideMask,
avatarRadius = 1.4, floorOffset = 1.0, reach = 1.0):
assert not avatarNodePath.isEmpty()
@ -79,7 +79,7 @@ class DevWalker(DirectObject.DirectObject):
def setCollisionsActive(self, active = 1):
pass
def placeOnFloor(self):
pass
@ -111,21 +111,21 @@ class DevWalker(DirectObject.DirectObject):
run = inputState.isSet("run") and self.runMultiplier or 1.0
# Determine what the speeds are based on the buttons:
self.speed=(
(forward and self.avatarControlForwardSpeed or
(forward and self.avatarControlForwardSpeed or
reverse and -self.avatarControlReverseSpeed))
self.liftSpeed=(
(levitateUp and self.avatarControlForwardSpeed or
(levitateUp and self.avatarControlForwardSpeed or
levitateDown and -self.avatarControlReverseSpeed))
self.slideSpeed=(
(slideLeft and -self.avatarControlForwardSpeed) or
(slideLeft and -self.avatarControlForwardSpeed) or
(slideRight and self.avatarControlForwardSpeed))
self.rotationSpeed=(
(turnLeft and self.avatarControlRotateSpeed) or
(turnRight and -self.avatarControlRotateSpeed))
if self.wantDebugIndicator:
self.displayDebugInfo()
# Check to see if we're moving at all:
if self.speed or self.liftSpeed or self.slideSpeed or self.rotationSpeed:
# How far did we move based on the amount of time elapsed?
@ -136,8 +136,8 @@ class DevWalker(DirectObject.DirectObject):
rotation = dt * self.rotationSpeed
# Take a step in the direction of our previous heading.
self.vel=Vec3(Vec3.forward() * distance +
Vec3.up() * lift +
self.vel=Vec3(Vec3.forward() * distance +
Vec3.up() * lift +
Vec3.right() * slideDistance)
if self.vel != Vec3.zero():
# rotMat is the rotation matrix corresponding to
@ -172,7 +172,7 @@ class DevWalker(DirectObject.DirectObject):
if self.task:
self.task.remove()
self.task = None
if __debug__:
def debugPrint(self, message):
"""for debugging"""

View File

@ -526,7 +526,7 @@ class GravityWalker(DirectObject.DirectObject):
# Consider commenting out this normalize. If you do so
# then going up and down slops is a touch slower and
# steeper terrain can cut the movement in half. Without
# the normalize the movement is slowed by the cosine of
# the normalize the movement is slowed by the cosine of
# the slope (i.e. it is multiplied by the sign as a
# side effect of the cross product above).
forward.normalize()

View File

@ -13,7 +13,7 @@ class InputState(DirectObject.DirectObject):
to use it:) If in doubt, don't use this class and listen for
events instead.
"""
notify = DirectNotifyGlobal.directNotify.newCategory("InputState")
def __init__(self):
@ -21,10 +21,10 @@ class InputState(DirectObject.DirectObject):
assert self.debugPrint("InputState()")
self.watching = {}
self.forcing = {}
def delete(self):
self.ignoreAll()
def watch(self, name, eventOn, eventOff, default = 0):
"""
name is any string (or actually any valid dictionary key).
@ -57,21 +57,21 @@ class InputState(DirectObject.DirectObject):
'control-alt-%s', 'shift-%s',)
for pattern in patterns:
self.watch(name, pattern % event, '%s-up' % event, default)
def force(self, name, value):
"""
Force isSet(name) to return value.
See Also: unforce()
"""
self.forcing[name] = value
def unforce(self, name):
"""
Stop forcing a value.
See Also: force()
"""
del self.forcing[name]
def ignore(self, name):
"""
The opposite of watch(name, ...)
@ -83,7 +83,7 @@ class InputState(DirectObject.DirectObject):
DirectObject.DirectObject.ignore(self, eventOff)
del self.watching[name]
del self.state[name]
def set(self, name, isSet):
assert self.debugPrint("set(name=%s, isSet=%s)"%(name, isSet))
self.state[name] = isSet
@ -91,7 +91,7 @@ class InputState(DirectObject.DirectObject):
# be the same name that messenger used to call InputState.set()
# this avoids running in circles:
messenger.send("InputState-%s"%(name,), [isSet])
def isSet(self, name):
"""
returns 0, 1
@ -101,7 +101,7 @@ class InputState(DirectObject.DirectObject):
if r is not None:
return r
return self.state.get(name, 0)
def debugPrint(self, message):
"""for debugging"""
return self.notify.debug(

View File

@ -112,7 +112,7 @@ class NonPhysicsWalker(DirectObject.DirectObject):
# and float above them as we go down. I increased this
# from 8.0 to 16.0 to prevent this
self.lifter.setMaxVelocity(16.0)
self.pusher.addCollider(self.cSphereNodePath, avatarNodePath)
self.lifter.addCollider(self.cRayNodePath, avatarNodePath)
@ -150,11 +150,11 @@ class NonPhysicsWalker(DirectObject.DirectObject):
# Now that we have disabled collisions, make one more pass
# right now to ensure we aren't standing in a wall.
self.oneTimeCollide()
def placeOnFloor(self):
"""
Make a reasonable effor to place the avatar on the ground.
For example, this is useful when switching away from the
For example, this is useful when switching away from the
current walker.
"""
# With these on, getAirborneHeight is not returning the correct value so
@ -193,11 +193,11 @@ class NonPhysicsWalker(DirectObject.DirectObject):
slide = inputState.isSet(self.slideName) or 0
#jump = inputState.isSet("jump")
# Determine what the speeds are based on the buttons:
self.speed=(forward and self.avatarControlForwardSpeed or
self.speed=(forward and self.avatarControlForwardSpeed or
reverse and -self.avatarControlReverseSpeed)
# Should fSlide be renamed slideButton?
self.slideSpeed=slide and (
(turnLeft and -self.avatarControlForwardSpeed) or
(turnLeft and -self.avatarControlForwardSpeed) or
(turnRight and self.avatarControlForwardSpeed))
self.rotationSpeed=not slide and (
(turnLeft and self.avatarControlRotateSpeed) or
@ -212,7 +212,7 @@ class NonPhysicsWalker(DirectObject.DirectObject):
messenger.send("walkerIsOutOfWorld", [self.avatarNodePath])
self._calcSpeeds()
if __debug__:
debugRunning = inputState.isSet("debugRunning")
if debugRunning:
@ -237,7 +237,7 @@ class NonPhysicsWalker(DirectObject.DirectObject):
rotation = dt * self.rotationSpeed
# Take a step in the direction of our previous heading.
self.vel=Vec3(Vec3.forward() * distance +
self.vel=Vec3(Vec3.forward() * distance +
Vec3.right() * slideDistance)
if self.vel != Vec3.zero():
# rotMat is the rotation matrix corresponding to
@ -249,16 +249,16 @@ class NonPhysicsWalker(DirectObject.DirectObject):
messenger.send("avatarMoving")
else:
self.vel.set(0.0, 0.0, 0.0)
self.__oldPosDelta = self.avatarNodePath.getPosDelta(render)
self.__oldDt = dt
self.worldVelocity = self.__oldPosDelta*(1/self.__oldDt)
return Task.cont
def doDeltaPos(self):
assert self.debugPrint("doDeltaPos()")
def reset(self):
assert self.debugPrint("reset()")
@ -285,7 +285,7 @@ class NonPhysicsWalker(DirectObject.DirectObject):
assert self.debugPrint("disableAvatarControls")
taskName = "AvatarControls-%s"%(id(self),)
taskMgr.remove(taskName)
if __debug__:
def debugPrint(self, message):
"""for debugging"""

View File

@ -52,16 +52,16 @@ class ObserverWalker(NonPhysicsWalker.NonPhysicsWalker):
self.pusher = CollisionHandlerPusher()
self.pusher.setInPattern("enter%in")
self.pusher.setOutPattern("exit%in")
self.pusher.addCollider(self.cSphereNodePath, avatarNodePath)
# activate the collider with the traverser and pusher
self.setCollisionsActive(1)
class Foo:
def hasContact(self):
return 1
self.lifter = Foo()
def deleteCollisions(self):

View File

@ -28,10 +28,10 @@ class PhysicsWalker(DirectObject.DirectObject):
notify = DirectNotifyGlobal.directNotify.newCategory("PhysicsWalker")
wantDebugIndicator = base.config.GetBool('want-avatar-physics-indicator', 0)
wantAvatarPhysicsIndicator = base.config.GetBool('want-avatar-physics-indicator', 0)
useLifter = 0
useHeightRay = 0
# special methods
def __init__(self, gravity = -32.1740, standableGround=0.707,
hardLandingForce=16.0):
@ -41,7 +41,7 @@ class PhysicsWalker(DirectObject.DirectObject):
self.__gravity=gravity
self.__standableGround=standableGround
self.__hardLandingForce=hardLandingForce
self.needToDeltaPos = 0
self.physVelocityIndicator=None
self.avatarControlForwardSpeed=0
@ -58,7 +58,7 @@ class PhysicsWalker(DirectObject.DirectObject):
self.__slideSpeed=0.0
self.__vel=Vec3(0.0)
self.collisionsActive = 0
self.isAirborne = 0
self.highMark = 0
@ -70,14 +70,14 @@ class PhysicsWalker(DirectObject.DirectObject):
from pandac.PandaModules import *
from direct.interval.IntervalGlobal import *
from toontown.coghq import MovingPlatform
if hasattr(self, "platform"):
# Remove the prior instantiation:
self.moveIval.pause()
del self.moveIval
self.platform.destroy()
del self.platform
model = loader.loadModelCopy('phase_9/models/cogHQ/platform1')
fakeId = id(self)
self.platform = MovingPlatform.MovingPlatform()
@ -263,16 +263,16 @@ class PhysicsWalker(DirectObject.DirectObject):
#fnp.remove()
return avatarNodePath
def initializeCollisions(self, collisionTraverser, avatarNodePath,
wallBitmask, floorBitmask,
def initializeCollisions(self, collisionTraverser, avatarNodePath,
wallBitmask, floorBitmask,
avatarRadius = 1.4, floorOffset = 1.0, reach = 1.0):
"""
Set up the avatar collisions
"""
assert self.debugPrint("initializeCollisions()")
assert not avatarNodePath.isEmpty()
self.cTrav = collisionTraverser
self.floorOffset = floorOffset = 7.0
@ -356,7 +356,7 @@ class PhysicsWalker(DirectObject.DirectObject):
del self.cSphereNodePath
del self.pusher
del self.getAirborneHeight
def setCollisionsActive(self, active = 1):
@ -382,11 +382,11 @@ class PhysicsWalker(DirectObject.DirectObject):
assert(self.debugPrint("getCollisionsActive() returning=%s"%(
self.collisionsActive,)))
return self.collisionsActive
def placeOnFloor(self):
"""
Make a reasonable effort to place the avatar on the ground.
For example, this is useful when switching away from the
For example, this is useful when switching away from the
current walker.
"""
self.oneTimeCollide()
@ -415,7 +415,7 @@ class PhysicsWalker(DirectObject.DirectObject):
For debug use.
"""
onScreenDebug.add("w controls", "PhysicsWalker")
if self.useLifter:
onScreenDebug.add("w airborneHeight", self.lifter.getAirborneHeight())
onScreenDebug.add("w isOnGround", self.lifter.isOnGround())
@ -443,14 +443,14 @@ class PhysicsWalker(DirectObject.DirectObject):
#rotAvatarToPhys=Mat3.rotateMatNormaxis(-self.avatarNodePath.getH(), Vec3.up())
#rotPhysToAvatar=Mat3.rotateMatNormaxis(self.avatarNodePath.getH(), Vec3.up())
contact=self.actorNode.getContactVector()
# hack fix for falling through the floor:
if contact==Vec3.zero() and self.avatarNodePath.getZ()<-50.0:
# DCR: don't reset X and Y; allow player to move
self.reset()
self.avatarNodePath.setZ(50.0)
messenger.send("walkerIsOutOfWorld", [self.avatarNodePath])
if self.wantDebugIndicator:
self.displayDebugInfo()
@ -464,14 +464,14 @@ class PhysicsWalker(DirectObject.DirectObject):
slideRight = 0#inputState.isSet("slideRight")
jump = inputState.isSet("jump")
# Determine what the speeds are based on the buttons:
self.__speed=(forward and self.avatarControlForwardSpeed or
self.__speed=(forward and self.avatarControlForwardSpeed or
reverse and -self.avatarControlReverseSpeed)
avatarSlideSpeed=self.avatarControlForwardSpeed*0.5
#self.__slideSpeed=slide and (
# (turnLeft and -avatarSlideSpeed) or
# (turnLeft and -avatarSlideSpeed) or
# (turnRight and avatarSlideSpeed))
self.__slideSpeed=(
(slideLeft and -avatarSlideSpeed) or
(slideLeft and -avatarSlideSpeed) or
(slideRight and avatarSlideSpeed))
self.__rotationSpeed=not slide and (
(turnLeft and self.avatarControlRotateSpeed) or
@ -502,13 +502,13 @@ class PhysicsWalker(DirectObject.DirectObject):
if self.wantDebugIndicator:
onScreenDebug.add("posDelta1",
self.avatarNodePath.getPosDelta(render).pPrintValues())
if 0:
onScreenDebug.add("posDelta3",
render.getRelativeVector(
self.avatarNodePath,
self.avatarNodePath.getPosDelta(render)).pPrintValues())
if 0:
onScreenDebug.add("gravity",
self.gravity.getLocalVector().pPrintValues())
@ -516,7 +516,7 @@ class PhysicsWalker(DirectObject.DirectObject):
self.priorParent.getLocalVector().pPrintValues())
onScreenDebug.add("avatarViscosity",
"% 10.4f"%(self.avatarViscosity.getCoef(),))
onScreenDebug.add("physObject pos",
physObject.getPosition().pPrintValues())
onScreenDebug.add("physObject hpr",
@ -531,7 +531,7 @@ class PhysicsWalker(DirectObject.DirectObject):
"% 10.4f"%physObject.getVelocity().length())
if 0:
onScreenDebug.add("posDelta4",
onScreenDebug.add("posDelta4",
self.priorParentNp.getRelativeVector(
render,
self.avatarNodePath.getPosDelta(render)).pPrintValues())
@ -636,7 +636,7 @@ class PhysicsWalker(DirectObject.DirectObject):
self.__oldAirborneHeight=airborneHeight
moveToGround = Vec3.zero()
if not self.useHeightRay or self.isAirborne:
if not self.useHeightRay or self.isAirborne:
# ...the airborne check is a hack to stop sliding.
self.phys.doPhysics(dt)
if __debug__:
@ -662,9 +662,9 @@ class PhysicsWalker(DirectObject.DirectObject):
# update pos:
# Take a step in the direction of our previous heading.
self.__vel=Vec3(
Vec3.forward() * distance +
Vec3.forward() * distance +
Vec3.right() * slideDistance)
# rotMat is the rotation matrix corresponding to
# our previous heading.
rotMat=Mat3.rotateMatNormaxis(self.avatarNodePath.getH(), Vec3.up())
@ -690,20 +690,20 @@ class PhysicsWalker(DirectObject.DirectObject):
# Clear the contact vector so we can tell if we contact something next frame:
self.actorNode.setContactVector(Vec3.zero())
return Task.cont
def doDeltaPos(self):
assert self.debugPrint("doDeltaPos()")
self.needToDeltaPos = 1
def setPriorParentVector(self):
assert self.debugPrint("doDeltaPos()")
print "self.__oldDt", self.__oldDt, "self.__oldPosDelta", self.__oldPosDelta
if __debug__:
onScreenDebug.add("__oldDt", "% 10.4f"%self.__oldDt)
onScreenDebug.add("self.__oldPosDelta",
self.__oldPosDelta.pPrintValues())
velocity = self.__oldPosDelta*(1/self.__oldDt)*4.0 # *4.0 is a hack
assert self.debugPrint(" __oldPosDelta=%s"%(self.__oldPosDelta,))
assert self.debugPrint(" velocity=%s"%(velocity,))
@ -711,7 +711,7 @@ class PhysicsWalker(DirectObject.DirectObject):
if __debug__:
if self.wantDebugIndicator:
onScreenDebug.add("velocity", velocity.pPrintValues())
def reset(self):
assert self.debugPrint("reset()")
self.actorNode.getPhysicsObject().resetPosition(self.avatarNodePath.getPos())
@ -763,7 +763,7 @@ class PhysicsWalker(DirectObject.DirectObject):
self.ignore("control-f3") #*#
self.ignore("f3")
if __debug__:
def setupAvatarPhysicsIndicator(self):
if self.wantDebugIndicator:

View File

@ -28,11 +28,11 @@ class ShipPilot(PhysicsWalker):
notify = directNotify.newCategory("PhysicsWalker")
wantDebugIndicator = base.config.GetBool(
'want-avatar-physics-indicator', 0)
useBowSternSpheres = 1
useLifter = 0
useHeightRay = 0
# special methods
def __init__(self, gravity = -32.1740, standableGround=0.707,
hardLandingForce=16.0):
@ -44,7 +44,7 @@ class ShipPilot(PhysicsWalker):
self.__gravity=gravity
self.__standableGround=standableGround
self.__hardLandingForce=hardLandingForce
self.needToDeltaPos = 0
self.physVelocityIndicator=None
self.avatarControlForwardSpeed=0
@ -61,7 +61,7 @@ class ShipPilot(PhysicsWalker):
self.__slideSpeed=0.0
self.__vel=Vec3(0.0)
self.collisionsActive = 0
self.isAirborne = 0
self.highMark = 0
self.ship = None
@ -85,7 +85,7 @@ class ShipPilot(PhysicsWalker):
#self.setupShip()
self.setupPhysics(ship)
self.ship = ship
#*# Debug:
if not hasattr(ship, "acceleration"):
self.ship.acceleration = 60
@ -211,7 +211,7 @@ class ShipPilot(PhysicsWalker):
self.pusher.addCollider(
self.cBowSphereNodePath, self.avatarNodePath)
# Back sphere:
self.cSternSphere = CollisionSphere(
0.0, self.backSphereOffset, -5.0, avatarRadius)
@ -232,7 +232,7 @@ class ShipPilot(PhysicsWalker):
shipCollWall = self.avatarNodePath.hull.find("**/collision_hull")
if not shipCollWall.isEmpty():
shipCollWall.stash()
def takedownPhysics(self):
assert self.debugPrint("takedownPhysics()")
if hasattr(self, "phys"):
@ -241,7 +241,7 @@ class ShipPilot(PhysicsWalker):
del self.phys
if self.ship != None:
self.ship.worldVelocity = Vec3.zero()
def setupPhysics(self, avatarNodePath):
assert self.debugPrint("setupPhysics()")
if avatarNodePath is None:
@ -269,7 +269,7 @@ class ShipPilot(PhysicsWalker):
self.actorNode = physicsActor.node()
self.actorNode.getPhysicsObject().setOriented(1)
self.actorNode.getPhysical(0).setViscosity(0.1)
fn=ForceNode("ship gravity")
fnp=NodePath(fn)
#fnp.reparentTo(physicsActor)
@ -290,7 +290,7 @@ class ShipPilot(PhysicsWalker):
fn.addForce(buoyancy)
self.phys.addLinearForce(buoyancy)
self.buoyancy = buoyancy
fn=ForceNode("ship keel")
fnp=NodePath(fn)
#fnp.reparentTo(physicsActor)
@ -299,7 +299,7 @@ class ShipPilot(PhysicsWalker):
self.keel=AngularVectorForce(0.0, 0.0, 0.0)
fn.addForce(self.keel)
self.phys.addAngularForce(self.keel)
fn=ForceNode("ship priorParent")
fnp=NodePath(fn)
fnp.reparentTo(render)
@ -309,7 +309,7 @@ class ShipPilot(PhysicsWalker):
self.phys.addLinearForce(priorParent)
self.priorParentNp = fnp
self.priorParent = priorParent
if 1:
fn=ForceNode("ship viscosity")
fnp=NodePath(fn)
@ -334,7 +334,7 @@ class ShipPilot(PhysicsWalker):
self.nodes.append(fnp)
fn.addForce(self.momentumForce)
self.phys.addLinearForce(self.momentumForce)
self.acForce=LinearVectorForce(0.0, 0.0, 0.0)
self.acForce.setAmplitude(5)
fn=ForceNode("ship avatarControls")
@ -345,11 +345,11 @@ class ShipPilot(PhysicsWalker):
self.phys.addLinearForce(self.acForce)
#self.phys.removeLinearForce(self.acForce)
#fnp.remove()
if 0 or self.useHeightRay:
#self.setupRay(self.floorBitmask, self.avatarRadius)
self.setupRay(self.floorBitmask, 0.0)
#avatarNodePath.reparentTo(render)
self.avatarNodePath = avatarNodePath
@ -398,7 +398,7 @@ class ShipPilot(PhysicsWalker):
del self.cSphereNodePath
del self.pusher
self.getAirborneHeight = None
def setTag(self, key, value):
@ -493,11 +493,11 @@ class ShipPilot(PhysicsWalker):
assert self.debugPrint(
"getCollisionsActive() returning=%s"%(self.collisionsActive,))
return self.collisionsActive
def placeOnFloor(self):
"""
Make a reasonable effort to place the avatar on the ground.
For example, this is useful when switching away from the
For example, this is useful when switching away from the
current walker.
"""
self.oneTimeCollide()
@ -585,7 +585,7 @@ class ShipPilot(PhysicsWalker):
## onScreenDebug.add("w keel vec",
## keel.pPrintValues())
if 0:
onScreenDebug.add("posDelta4",
onScreenDebug.add("posDelta4",
self.priorParentNp.getRelativeVector(
render,
self.avatarNodePath.getPosDelta(render)).pPrintValues())
@ -621,7 +621,7 @@ class ShipPilot(PhysicsWalker):
#rotPhysToAvatar=Mat3.rotateMatNormaxis(
# self.avatarNodePath.getH(), Vec3.up())
contact=self.actorNode.getContactVector()
depth=physObject.getPosition().getZ()
if depth < 0.0:
# self.buoyancy.setVector(Vec3.zero())
@ -664,14 +664,14 @@ class ShipPilot(PhysicsWalker):
self.sailsDeployed = -1.0
self.__speed = self.ship.acceleration * self.sailsDeployed
else:
self.__speed=(forward and self.ship.acceleration or
self.__speed=(forward and self.ship.acceleration or
reverse and -self.ship.reverseAcceleration)
avatarSlideSpeed=self.ship.acceleration*0.5
#self.__slideSpeed=slide and (
# (turnLeft and -avatarSlideSpeed) or
# (turnLeft and -avatarSlideSpeed) or
# (turnRight and avatarSlideSpeed))
self.__slideSpeed=(forward or reverse) and (
(slideLeft and -avatarSlideSpeed) or
(slideLeft and -avatarSlideSpeed) or
(slideRight and avatarSlideSpeed))
self.__rotationSpeed=not slide and (
(turnLeft and self.ship.turnRate) or
@ -803,7 +803,7 @@ class ShipPilot(PhysicsWalker):
assert self.avatarNodePath.getPos().almostEqual(physObject.getPosition(), 0.0001)
moveToGround = Vec3.zero()
if not self.useHeightRay or self.isAirborne:
if not self.useHeightRay or self.isAirborne:
# ...the airborne check is a hack to stop sliding.
self.phys.doPhysics(dt)
if __debug__:
@ -814,7 +814,7 @@ class ShipPilot(PhysicsWalker):
# moveToGround = Vec3(0.0, 0.0, -airborneHeight)
#moveToGround = Vec3(0.0, 0.0, -airborneHeight)
moveToGround = Vec3(0.0, 0.0, -self.determineHeight())
if __debug__:
if __debug__:
onScreenDebug.add("phys", "off")
#debugTempH=self.avatarNodePath.getH()
@ -830,9 +830,9 @@ class ShipPilot(PhysicsWalker):
physVel = physObject.getVelocity()
physVelLen = physVel.length()
if (physVelLen!=0.
or self.__speed
or self.__slideSpeed
or self.__rotationSpeed
or self.__speed
or self.__slideSpeed
or self.__rotationSpeed
or moveToGround!=Vec3.zero()):
distance = dt * self.__speed
goForward = True
@ -841,11 +841,11 @@ class ShipPilot(PhysicsWalker):
distance /= 5
slideDistance = dt * self.__slideSpeed
rotation = dt * self.__rotationSpeed
# update pos:
# Take a step in the direction of our previous heading.
self.__vel=Vec3(
Vec3.forward() * distance +
Vec3.forward() * distance +
Vec3.right() * slideDistance)
# rotMat is the rotation matrix corresponding to
@ -875,13 +875,13 @@ class ShipPilot(PhysicsWalker):
onScreenDebug.add("newVector length",
newVector.length())
self.acForce.setVector(Vec3(newVector))
#momentum = self.momentumForce.getLocalVector()
#momentum *= 0.9
#self.momentumForce.setVector(momentum)
#physObject.setPosition(Point3(
# physObject.getPosition()+step+moveToGround))
@ -901,7 +901,7 @@ class ShipPilot(PhysicsWalker):
self.__vel.set(0.0, 0.0, 0.0)
goForward = True
#*#
speed = physVel
if (goForward):
@ -955,28 +955,28 @@ class ShipPilot(PhysicsWalker):
self.ship.worldVelocity.pPrintValues())
onScreenDebug.add("w worldVelocity len",
"% 10.4f"%self.ship.worldVelocity.length())
# if hasattr(self.ship, 'sailBillow'):
# self.ship.sailBillow = self.sailsDeployed
if hasattr(self.ship, 'currentTurning'):
self.ship.currentTurning = self.currentTurning
return Task.cont
def doDeltaPos(self):
assert self.debugPrint("doDeltaPos()")
self.needToDeltaPos = 1
def setPriorParentVector(self):
assert self.debugPrint("doDeltaPos()")
#print "self.__oldDt", self.__oldDt, "self.__oldPosDelta", self.__oldPosDelta
if __debug__:
onScreenDebug.add("__oldDt", "% 10.4f"%self.__oldDt)
onScreenDebug.add("self.__oldPosDelta",
self.__oldPosDelta.pPrintValues())
velocity = self.__oldPosDelta*(1/self.__oldDt)*4.0 # *4.0 is a hack
assert self.debugPrint(" __oldPosDelta=%s"%(self.__oldPosDelta,))
assert self.debugPrint(" velocity=%s"%(velocity,))
@ -984,7 +984,7 @@ class ShipPilot(PhysicsWalker):
if __debug__:
if self.wantDebugIndicator:
onScreenDebug.add("velocity", velocity.pPrintValues())
def reset(self):
assert self.debugPrint("reset()")
self.actorNode.getPhysicsObject().resetPosition(

View File

@ -59,7 +59,7 @@ class DirectFastrak(DirectObject):
return Task.cont
def fastrakUpdate(self):
# Get tracker position in feet. Flip x,z axes.
# Get tracker position in feet. Flip x, z axes.
pos = direct.fastrak[self.deviceNo].tracker.getPos()
self.trackerPos = Vec3(3.280839895013123 * pos[2],
3.280839895013123 * pos[1],

View File

@ -47,13 +47,13 @@ class DirectJoybox(DirectObject):
self.device = device
self.analogs = direct.deviceManager.createAnalogs(self.device)
self.buttons = direct.deviceManager.createButtons(self.device)
self.aList = [0,0,0,0,0,0,0,0]
self.bList = [0,0,0,0,0,0,0,0,0,0,0,0]
self.aList = [0, 0, 0, 0, 0, 0, 0, 0]
self.bList = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
# For joybox fly mode
# Default is joe mode
self.mapping = [R_LEFT_RIGHT, R_FWD_BACK, L_FWD_BACK,
R_TWIST, L_TWIST, NULL_AXIS]
self.modifier = [1,1,1,-1,-1,0]
self.modifier = [1, 1, 1, -1, -1, 0]
# Initialize time
self.lastTime = globalClock.getFrameTime()
# Record node path
@ -232,67 +232,67 @@ class DirectJoybox(DirectObject):
x = getAxisVal(0) * self.modifier[0]
y = getAxisVal(1) * self.modifier[1]
z = getAxisVal(2) * self.modifier[2]
pos = Vec3(x,y,z) * (posScale * self.deltaTime)
pos = Vec3(x, y, z) * (posScale * self.deltaTime)
h = getAxisVal(3) * self.modifier[3]
p = getAxisVal(4) * self.modifier[4]
r = getAxisVal(5) * self.modifier[5]
hpr = Vec3(h,p,r) * (hprScale * self.deltaTime)
hpr = Vec3(h, p, r) * (hprScale * self.deltaTime)
# Move node path
self.nodePath.setPosHpr(self.nodePath, pos, hpr)
def joeMode(self):
self.mapping = [R_LEFT_RIGHT, R_FWD_BACK, L_FWD_BACK,
R_TWIST, L_TWIST, NULL_AXIS]
self.modifier = [1,1,1,-1,-1,0]
self.modifier = [1, 1, 1, -1, -1, 0]
self.setMode(self.joyboxFly, 'Joe Mode')
def lucMode(self):
self.mapping = [R_LEFT_RIGHT, R_FWD_BACK, L_FWD_BACK,
R_TWIST, L_TWIST, L_LEFT_RIGHT]
self.modifier = [1,1,1,-1,-1,0]
self.modifier = [1, 1, 1, -1, -1, 0]
self.setMode(self.joyboxFly, 'Luc Mode')
def driveMode(self):
self.mapping = [L_LEFT_RIGHT, R_FWD_BACK, R_TWIST,
R_LEFT_RIGHT, L_FWD_BACK, NULL_AXIS]
self.modifier = [1,1,-1,-1,-1,0]
self.modifier = [1, 1, -1, -1, -1, 0]
self.setMode(self.joyboxFly, 'Drive Mode')
def lookAtMode(self):
self.mapping = [R_LEFT_RIGHT, R_TWIST, R_FWD_BACK,
L_LEFT_RIGHT, L_FWD_BACK, NULL_AXIS]
self.modifier = [1,1,1,-1,1,0]
self.modifier = [1, 1, 1, -1, 1, 0]
self.setMode(self.joyboxFly, 'Look At Mode')
def lookAroundMode(self):
self.mapping = [NULL_AXIS, NULL_AXIS, NULL_AXIS,
R_LEFT_RIGHT, R_FWD_BACK, NULL_AXIS]
self.modifier = [0,0,0,-1,-1,0]
self.modifier = [0, 0, 0, -1, -1, 0]
self.setMode(self.joyboxFly, 'Lookaround Mode')
def demoMode(self):
self.mapping = [R_LEFT_RIGHT, R_FWD_BACK, L_FWD_BACK,
R_TWIST, NULL_AXIS, NULL_AXIS]
self.modifier = [1,1,1,-1,0,0]
self.modifier = [1, 1, 1, -1, 0, 0]
self.setMode(self.joyboxFly, 'Demo Mode')
def hprXyzMode(self):
self.mapping = [R_LEFT_RIGHT, R_FWD_BACK, R_TWIST,
L_TWIST, L_FWD_BACK, L_LEFT_RIGHT]
self.modifier = [1,1,-1,-1,-1,1]
self.modifier = [1, 1, -1, -1, -1, 1]
self.setMode(self.joyboxFly, 'HprXyz Mode')
def mopathMode(self):
self.mapping = [R_LEFT_RIGHT, R_FWD_BACK, R_TWIST,
L_LEFT_RIGHT, L_FWD_BACK, L_LEFT_RIGHT]
self.modifier = [1,1,-1,-1,1,0]
self.modifier = [1, 1, -1, -1, 1, 0]
self.setMode(self.joyboxFly, 'Mopath Mode')
def walkthruMode(self):
self.mapping = [R_LEFT_RIGHT, R_FWD_BACK, L_TWIST,
R_TWIST, L_FWD_BACK, L_LEFT_RIGHT]
self.modifier = [1,1,-1,-1,-1, 1]
self.modifier = [1, 1, -1, -1, -1, 1]
self.setMode(self.joyboxFly, 'Walkthru Mode')
def spaceMode(self):
@ -330,7 +330,7 @@ class DirectJoybox(DirectObject):
dh = -1 * hprScale * self.aList[R_LEFT_RIGHT] * self.deltaTime
self.nodePath.setHpr(self.nodePath, dh, dp, dr)
dy = posScale * self.aList[L_FWD_BACK] * self.deltaTime
dPos = VBase3(0,dy,0)
dPos = VBase3(0, dy, 0)
for planet, radius in self.auxData:
# Are we within min radius?
# How far above planet are we?
@ -389,7 +389,7 @@ class DirectJoybox(DirectObject):
self.orbitNode(rx, ry, 0)
pos = self.nodePath.getPos(self.refCS)
if Vec3(pos).length() < 0.005:
pos.set(0,-0.01, 0)
pos.set(0, -0.01, 0)
# Now move on out
pos.assign(pos * (1 + r))
self.nodePath.setPos(self.refCS, pos)

View File

@ -32,7 +32,7 @@ class DirectRadamec(DirectObject):
self.device = device
self.analogs = direct.deviceManager.createAnalogs(self.device)
self.numAnalogs = len(self.analogs)
self.aList = [0,0,0,0,0,0,0,0]
self.aList = [0, 0, 0, 0, 0, 0, 0, 0]
# Radamec device max/mins
# Note: These values change quite often, i.e. everytime
# you unplug the radamec cords, or jostle them too
@ -61,8 +61,8 @@ class DirectRadamec(DirectObject):
return Task.cont
def radamecDebug(self):
panVal = self.normalizeChannel(RAD_PAN,-180,180)
tiltVal = self.normalizeChannel(RAD_TILT,-90,90)
panVal = self.normalizeChannel(RAD_PAN, -180, 180)
tiltVal = self.normalizeChannel(RAD_TILT, -90, 90)
self.notify.debug("PAN = %s" % self.aList[RAD_PAN])
self.notify.debug("TILT = %s" % self.aList[RAD_TILT])
@ -70,7 +70,7 @@ class DirectRadamec(DirectObject):
self.notify.debug("FOCUS = %s" % self.aList[RAD_FOCUS])
self.notify.debug("Normalized: panVal: %s tiltVal: %s" % (panVal, tiltVal))
# Normalize to the range [-minVal,maxVal] based on some hard-coded
# Normalize to the range [-minVal, maxVal] based on some hard-coded
# max/min numbers of the Radamec device
def normalizeChannel(self, chan, minVal = -1, maxVal = 1):
try:

View File

@ -10,7 +10,7 @@ class DirectNotify:
DirectNotify class: this class contains methods for creating
mulitple notify categories via a dictionary of Notifiers.
"""
def __init__(self):
"""
DirectNotify class keeps a dictionary of Notfiers
@ -70,7 +70,7 @@ class DirectNotify:
config
except:
return 0
dconfigParam = ("notify-level-" + categoryName)
level = config.GetString(dconfigParam, "")
@ -103,7 +103,7 @@ class DirectNotify:
else:
print ("DirectNotify: unknown notify level: " + str(level)
+ " for category: " + str(categoryName))
def setDconfigLevels(self):
for categoryName in self.getCategories():
self.setDconfigLevel(categoryName)

View File

@ -9,12 +9,12 @@ class Logger:
def __init__(self, fileName="log"):
"""
Logger constructor
"""
"""
self.__timeStamp = 1
self.__startTime = 0.0
self.__logFile = None
self.__logFileName = fileName
def setTimeStamp(self, bool):
"""
Toggle time stamp printing with log entries on and off
@ -29,7 +29,7 @@ class Logger:
# logging control
def resetStartTime(self):
"""
Reset the start time of the log file for time stamps
@ -45,9 +45,9 @@ class Logger:
self.__logFile.write(self.__getTimeStamp())
self.__logFile.write(entryString + '\n')
# logging functions
def __openLogFile(self):
"""
Open a file for logging error/warning messages

View File

@ -54,7 +54,7 @@ class Notifier:
# from Python-level notify messages.
from pandac.PandaModules import NotifyCategory
NotifyCategory.setServerDelta(self.serverDelta)
self.info("Notify clock adjusted by %s (and timezone adjusted by %s hours) to synchronize with server." % (PythonUtil.formatElapsedSeconds(delta), (time.timezone - timezone) / 3600))
def getTime(self):
@ -216,11 +216,11 @@ class Notifier:
self.streamWriter.appendData(string + '\n')
else:
print string
def debugStateCall(self, obj=None, fsmMemberName='fsm',
secondaryFsm='secondaryFSM'):
"""
If this notify is in debug mode, print the time of the
If this notify is in debug mode, print the time of the
call followed by the [fsm state] notifier category and
the function call (with parameters).
"""
@ -229,14 +229,14 @@ class Notifier:
state = ''
doId = ''
if obj is not None:
fsm=obj.__dict__.get(fsmMemberName)
if fsm is not None:
stateObj = fsm.getCurrentState()
if stateObj is not None:
#state = "%s=%s"%(fsmMemberName, stateObj.getName())
state = stateObj.getName()
fsm=obj.__dict__.get(secondaryFsm)
if fsm is not None:
stateObj = fsm.getCurrentState()
@ -261,7 +261,7 @@ class Notifier:
def debugCall(self, debugString=''):
"""
If this notify is in debug mode, print the time of the
If this notify is in debug mode, print the time of the
call followed by the notifier category and
the function call (with parameters).
"""

View File

@ -8,7 +8,7 @@ class RotatingLog:
A file() (or open()) replacement that will automatically open and write
to a new file if the prior file is too large or after a time interval.
"""
def __init__(self, path="./log_file", hourInterval=24, megabyteLimit=1024):
"""
path is a full or partial path with file name.
@ -73,12 +73,12 @@ class RotatingLog:
file=open(path, "a")
if file:
self.close()
# This should be redundant with "a" open() mode,
# but on some platforms tell() will return 0
# This should be redundant with "a" open() mode,
# but on some platforms tell() will return 0
# until the first write:
file.seek(0, 2)
self.file=file
# Some of these data members may be expected by some of our clients:
self.closed = self.file.closed
self.mode = self.file.mode
@ -86,13 +86,13 @@ class RotatingLog:
self.softspace = self.file.softspace
#self.encoding = self.file.encoding # Python 2.3
#self.newlines = self.file.newlines # Python 2.3, maybe
if self.timeLimit is not None and time.time() > self.timeLimit:
self.timeLimit=time.time()+self.timeInterval
else:
# We'll keep writing to the old file, if available.
print "RotatingLog error: Unable to open new log file \"%s\"."%(path,)
def write(self, data):
"""
Write the data to either the current log or a new one,
@ -109,7 +109,7 @@ class RotatingLog:
def flush(self):
return self.file.flush()
def fileno(self):
def fileno(self):
return self.file.fileno()
def isatty(self):
@ -118,7 +118,7 @@ class RotatingLog:
def next(self):
return self.file.next()
def read(self, size):
def read(self, size):
return self.file.read(size)
def readline(self, size):

View File

@ -48,7 +48,7 @@
#
########################################################################
import os,sys,parser,symbol,token,types,re
import os, sys, parser, symbol, token, types, re
########################################################################
#
@ -68,7 +68,7 @@ def readFile(fn):
except:
sys.exit("Cannot read "+fn)
def writeFile(wfile,data):
def writeFile(wfile, data):
try:
dsthandle = open(wfile, "wb")
dsthandle.write(data)
@ -89,7 +89,7 @@ def findFiles(dirlist, ext, ign, list):
elif (os.path.isdir(full)):
findFiles(full, ext, ign, list)
def textToHTML(comment,sep,delsection=None):
def textToHTML(comment, sep, delsection=None):
sections = [""]
included = {}
for line in comment.split("\n"):
@ -143,7 +143,7 @@ class InterrogateTokenizer:
used by interrogate databases.
"""
def __init__(self,fn):
def __init__(self, fn):
self.fn = fn
self.pos = 0
self.data = readFile(fn)
@ -299,9 +299,9 @@ class InterrogateDatabase:
#
########################################################################
def printTree(tree,indent):
def printTree(tree, indent):
spacing = " "[:indent]
if isinstance(tree,types.TupleType) and isinstance(tree[0], types.IntType):
if isinstance(tree, types.TupleType) and isinstance(tree[0], types.IntType):
if symbol.sym_name.has_key(tree[0]):
for i in range(len(tree)):
if (i==0):
@ -446,7 +446,7 @@ class ParseTreeInfo:
elif cstmt[0] == symbol.classdef:
name = cstmt[2][1]
self.class_info[name] = ParseTreeInfo(cstmt and cstmt[-1] or None, name)
self.extract_derivs(self.class_info[name],cstmt)
self.extract_derivs(self.class_info[name], cstmt)
def extract_derivs(self, classinfo, tree):
if (len(tree)==8):
@ -667,9 +667,9 @@ def generateLinkTable(link, text, cols, urlprefix, urlsuffix):
if (slot < len(link)): linkval = link[slot]
if (slot < len(text)): textval = text[slot]
if (i==0):
line = line + '<td width="' + str(percent) + '%">' + linkTo(urlprefix+linkval+urlsuffix,textval) + "</td>"
line = line + '<td width="' + str(percent) + '%">' + linkTo(urlprefix+linkval+urlsuffix, textval) + "</td>"
else:
line = line + '<td>' + linkTo(urlprefix+linkval+urlsuffix,textval) + "</td>"
line = line + '<td>' + linkTo(urlprefix+linkval+urlsuffix, textval) + "</td>"
result = result + "<tr>" + line + "</tr>\n"
result = result + "</table>\n"
return result
@ -702,9 +702,9 @@ def generate(pversion, indirlist, directdirlist, docdir, header, footer, urlpref
inheritance = code.getInheritance(type)
body = body + "<h2>Inheritance:</h2>\n<ul>\n"
for inh in inheritance:
line = " " + linkTo(urlprefix+inh+urlsuffix,inh) + ": "
line = " " + linkTo(urlprefix+inh+urlsuffix, inh) + ": "
for parent in code.getClassParents(inh):
line = line + linkTo(urlprefix+parent+urlsuffix,parent) + " "
line = line + linkTo(urlprefix+parent+urlsuffix, parent) + " "
body = body + line + "<br>\n"
body = body + "</ul>\n"
for sclass in inheritance:
@ -731,7 +731,7 @@ def generate(pversion, indirlist, directdirlist, docdir, header, footer, urlpref
xclasses.sort()
index = "<h1>List of Classes - Panda " + pversion + "</h1>\n"
index = index + generateLinkTable(xclasses,xclasses,3,urlprefix,urlsuffix)
index = index + generateLinkTable(xclasses, xclasses, 3, urlprefix, urlsuffix)
fnlist = code.getGlobalFunctionList()[:]
fnlist.sort()
fnnames = []
@ -741,7 +741,7 @@ def generate(pversion, indirlist, directdirlist, docdir, header, footer, urlpref
writeFile(docdir + "/classes.html", index)
index = "<h1>List of Global Functions - Panda " + pversion + "</h1>\n"
index = index + generateLinkTable(fnnames,fnnames,3,"#","")
index = index + generateLinkTable(fnnames, fnnames, 3,"#","")
for func in fnlist:
index = index + generateFunctionDocs(code, func)
index = header + index + footer

View File

@ -9,7 +9,7 @@ Options:
Specifies the CVSROOT string to use to tag and export the
tree. The default is $SFROOT if it is defined, or $CVSROOT
otherwise.
-r tag
Specifies the tag to export from. If this parameter is
specified, the tree is not tagged again; otherwise, the
@ -17,7 +17,7 @@ Options:
name.
-m module
Specifies the module to check out and build. The default is
Specifies the module to check out and build. The default is
panda3d.
"""

View File

@ -12,7 +12,7 @@
#
##############################################################################
import sys,os,getopt,string,shutil,py_compile
import sys, os, getopt, string, shutil, py_compile
OPTIONLIST = [
("game", 1, "Name of directory containing game"),
@ -30,9 +30,9 @@ def ParseFailure():
print ""
for (opt, hasval, explanation) in OPTIONLIST:
if (hasval):
print " --%-10s %s"%(opt+" x",explanation)
print " --%-10s %s"%(opt+" x", explanation)
else:
print " --%-10s %s"%(opt+" ",explanation)
print " --%-10s %s"%(opt+" ", explanation)
sys.exit(1)
def ParseOptions(args):
@ -50,7 +50,7 @@ def ParseOptions(args):
longopts.append(opt)
options[opt] = 0
opts, extras = getopt.getopt(args, "", longopts)
for option,value in opts:
for option, value in opts:
for (opt, hasval, explanation) in OPTIONLIST:
if (option == "--"+opt):
if (hasval==2): options[opt].append(value)
@ -97,8 +97,8 @@ GAME=os.path.abspath(GAME)
NAME=os.path.basename(GAME)
SMDIRECTORY=os.path.basename(GAME)
if (VER!=""): SMDIRECTORY=SMDIRECTORY+" "+VER
ICON=os.path.join(GAME,NAME+".ico")
BITMAP=os.path.join(GAME,NAME+".bmp")
ICON=os.path.join(GAME, NAME+".ico")
BITMAP=os.path.join(GAME, NAME+".bmp")
LICENSE=os.path.join(GAME,"LICENSE.TXT")
OUTFILE=os.path.basename(GAME)
if (VER!=""): OUTFILE=OUTFILE+"-"+VER
@ -112,24 +112,24 @@ else: MAIN=NAME+".py"
def PrintFileStatus(label, file):
if (os.path.exists(file)):
print "%-15s: %s"%(label,file)
print "%-15s: %s"%(label, file)
else:
print "%-15s: %s (MISSING)"%(label,file)
print "%-15s: %s (MISSING)"%(label, file)
PrintFileStatus("Game",GAME)
print "%-15s: %s"%("Name",NAME)
print "%-15s: %s"%("Start Menu",SMDIRECTORY)
PrintFileStatus("Main",os.path.join(GAME,MAIN))
PrintFileStatus("Icon",ICON)
PrintFileStatus("Bitmap",BITMAP)
PrintFileStatus("License",LICENSE)
print "%-15s: %s"%("Output",OUTFILE)
print "%-15s: %s"%("Install Dir",INSTALLDIR)
PrintFileStatus("Game", GAME)
print "%-15s: %s"%("Name", NAME)
print "%-15s: %s"%("Start Menu", SMDIRECTORY)
PrintFileStatus("Main", os.path.join(GAME, MAIN))
PrintFileStatus("Icon", ICON)
PrintFileStatus("Bitmap", BITMAP)
PrintFileStatus("License", LICENSE)
print "%-15s: %s"%("Output", OUTFILE)
print "%-15s: %s"%("Install Dir", INSTALLDIR)
if (os.path.isdir(GAME)==0):
sys.exit("Difficulty reading "+GAME+". Cannot continue.")
if (os.path.isfile(os.path.join(GAME,NAME+".py"))==0):
if (os.path.isfile(os.path.join(GAME, NAME+".py"))==0):
sys.exit("Difficulty reading "+NAME+".py. Cannot continue.")
if (os.path.isfile(LICENSE)==0):
@ -198,7 +198,7 @@ def CompileFiles(file):
else: pass
elif (os.path.isdir(file)):
for x in os.listdir(file):
CompileFiles(os.path.join(file,x))
CompileFiles(os.path.join(file, x))
def DeleteFiles(file):
base = string.lower(os.path.basename(file))
@ -209,7 +209,7 @@ def DeleteFiles(file):
shutil.rmtree(file)
return
for x in os.listdir(file):
DeleteFiles(os.path.join(file,x))
DeleteFiles(os.path.join(file, x))
else:
for ext in OPTIONS["rmext"]:
if (base[-(len(ext)+1):] == string.lower("."+ext)):

View File

@ -7,7 +7,7 @@ from direct.task import Task
CAM_MOVE_DURATION = 1.2
COA_MARKER_SF = 0.0075
Y_AXIS = Vec3(0,1,0)
Y_AXIS = Vec3(0, 1, 0)
class DirectCameraControl(DirectObject):
def __init__(self):
@ -16,12 +16,12 @@ class DirectCameraControl(DirectObject):
self.startF = 0
self.orthoViewRoll = 0.0
self.lastView = 0
self.coa = Point3(0,100,0)
self.coa = Point3(0, 100, 0)
self.coaMarker = loader.loadModel('models/misc/sphere')
self.coaMarker.setName('DirectCameraCOAMarker')
self.coaMarker.setTransparency(1)
self.coaMarker.setColor(1,0,0,0)
self.coaMarker.setPos(0,100,0)
self.coaMarker.setColor(1, 0, 0, 0)
self.coaMarker.setPos(0, 100, 0)
useDirectRenderStyle(self.coaMarker)
self.coaMarkerPos = Point3(0)
self.coaMarkerColorIval = None
@ -208,7 +208,7 @@ class DirectCameraControl(DirectObject):
# Translation action
return self.XZTranslateTask(state)
def XZTranslateTask(self,state):
def XZTranslateTask(self, state):
coaDist = Vec3(self.coaMarker.getPos(direct.camera)).length()
xlateSF = (coaDist / direct.dr.near)
direct.camera.setPos(direct.camera,
@ -221,7 +221,7 @@ class DirectCameraControl(DirectObject):
xlateSF))
return Task.cont
def HPanYZoomTask(self,state):
def HPanYZoomTask(self, state):
# If the cam is orthogonal, don't rotate or zoom.
if (hasattr(direct.camera.node(), "getLens") and
direct.camera.node().getLens().__class__.__name__ == "OrthographicLens"):
@ -400,11 +400,11 @@ class DirectCameraControl(DirectObject):
# At least display it
dist = pow(10.0, self.nullHitPointCount)
direct.message('COA Distance: ' + `dist`)
coa.set(0,dist,0)
coa.set(0, dist, 0)
# Compute COA Dist
coaDist = Vec3(coa - ZERO_POINT).length()
if coaDist < (1.1 * dr.near):
coa.set(0,100,0)
coa.set(0, 100, 0)
coaDist = 100
# Update coa and marker
self.updateCoa(coa, coaDist = coaDist)
@ -444,8 +444,8 @@ class DirectCameraControl(DirectObject):
self.coaMarkerColorIval.finish()
self.coaMarkerColorIval = Sequence(
Func(self.coaMarker.unstash),
self.coaMarker.colorInterval(1.5, Vec4(1,0,0,0),
startColor = Vec4(1,0,0,1),
self.coaMarker.colorInterval(1.5, Vec4(1, 0, 0, 0),
startColor = Vec4(1, 0, 0, 1),
blendType = 'easeInOut'),
Func(self.coaMarker.stash)
)
@ -481,7 +481,7 @@ class DirectCameraControl(DirectObject):
zAxis = Vec3(mCam2Render.xformVec(Z_AXIS))
zAxis.normalize()
# Compute rotation angle needed to upright cam
orbitAngle = rad2Deg(math.acos(CLAMP(zAxis.dot(Z_AXIS),-1,1)))
orbitAngle = rad2Deg(math.acos(CLAMP(zAxis.dot(Z_AXIS), -1, 1)))
# Check angle
if orbitAngle < 0.1:
# Already upright
@ -490,7 +490,7 @@ class DirectCameraControl(DirectObject):
rotAxis = Vec3(zAxis.cross(Z_AXIS))
rotAxis.normalize()
# Find angle between rot Axis and render X_AXIS
rotAngle = rad2Deg(math.acos(CLAMP(rotAxis.dot(X_AXIS),-1,1)))
rotAngle = rad2Deg(math.acos(CLAMP(rotAxis.dot(X_AXIS), -1, 1)))
# Determine sign or rotation angle
if rotAxis[1] < 0:
rotAngle *= -1
@ -593,7 +593,7 @@ class DirectCameraControl(DirectObject):
# Record view for next time around
self.lastView = view
t = direct.camera.lerpPosHpr(ZERO_POINT,
VBase3(0,0,self.orthoViewRoll),
VBase3(0, 0, self.orthoViewRoll),
CAM_MOVE_DURATION,
other = self.camManipRef,
blendType = 'easeInOut',
@ -616,7 +616,7 @@ class DirectCameraControl(DirectObject):
parent = direct.camera.getParent()
direct.camera.wrtReparentTo(self.camManipRef)
manipTask = self.camManipRef.lerpHpr(VBase3(degrees,0,0),
manipTask = self.camManipRef.lerpHpr(VBase3(degrees, 0, 0),
CAM_MOVE_DURATION,
blendType = 'easeInOut',
task = 'manipulateCamera')
@ -634,7 +634,7 @@ class DirectCameraControl(DirectObject):
taskMgr.remove('manipulateCamera')
# How big is the node?
nodeScale = direct.widget.scalingNode.getScale(render)
maxScale = max(nodeScale[0],nodeScale[1],nodeScale[2])
maxScale = max(nodeScale[0], nodeScale[1], nodeScale[2])
maxDim = min(direct.dr.nearWidth, direct.dr.nearHeight)
# At what distance does the object fill 30% of the screen?
@ -655,7 +655,7 @@ class DirectCameraControl(DirectObject):
parent = direct.camera.getParent()
direct.camera.wrtReparentTo(self.camManipRef)
fitTask = direct.camera.lerpPos(Point3(0,0,0),
fitTask = direct.camera.lerpPos(Point3(0, 0, 0),
CAM_MOVE_DURATION,
blendType = 'easeInOut',
task = 'manipulateCamera')

View File

@ -154,7 +154,7 @@ def getScreenXY(nodePath):
percentX = (nearX - direct.dr.left)/direct.dr.nearWidth
percentY = (nearY - direct.dr.bottom)/direct.dr.nearHeight
# Map this percentage to the same -1 to 1 space as the mouse
screenXY = Vec3((2 * percentX) - 1.0,nearVec[1],(2 * percentY) - 1.0)
screenXY = Vec3((2 * percentX) - 1.0, nearVec[1], (2 * percentY) - 1.0)
# Return the resulting value
return screenXY
@ -163,7 +163,7 @@ def getCrankAngle(center):
# origin) in screen space
x = direct.dr.mouseX - center[0]
y = direct.dr.mouseY - center[2]
return (180 + rad2Deg(math.atan2(y,x)))
return (180 + rad2Deg(math.atan2(y, x)))
def relHpr(nodePath, base, h, p, r):
# Compute nodePath2newNodePath relative to base coordinate system
@ -171,7 +171,7 @@ def relHpr(nodePath, base, h, p, r):
mNodePath2Base = nodePath.getMat(base)
# delta scale, orientation, and position matrix
mBase2NewBase = Mat4()
composeMatrix(mBase2NewBase, UNIT_VEC, VBase3(h,p,r), ZERO_VEC,
composeMatrix(mBase2NewBase, UNIT_VEC, VBase3(h, p, r), ZERO_VEC,
CSDefault)
# base2nodePath
mBase2NodePath = base.getMat(nodePath)

View File

@ -4,12 +4,12 @@ UNPICKABLE = ['x-disc-visible', 'y-disc-visible', 'z-disc-visible',
'GridBack', 'unpickable']
# For linmath operations
X_AXIS = Vec3(1,0,0)
Y_AXIS = Vec3(0,1,0)
Z_AXIS = Vec3(0,0,1)
NEG_X_AXIS = Vec3(-1,0,0)
NEG_Y_AXIS = Vec3(0,-1,0)
NEG_Z_AXIS = Vec3(0,0,-1)
X_AXIS = Vec3(1, 0, 0)
Y_AXIS = Vec3(0, 1, 0)
Z_AXIS = Vec3(0, 0, 1)
NEG_X_AXIS = Vec3(-1, 0, 0)
NEG_Y_AXIS = Vec3(0, -1, 0)
NEG_Z_AXIS = Vec3(0, 0, -1)
ZERO_VEC = ORIGIN = Vec3(0)
UNIT_VEC = Vec3(1)
ZERO_POINT = Point3(0)

View File

@ -16,30 +16,30 @@ class DirectGrid(NodePath, DirectObject):
# Polygon used to mark grid plane
self.gridBack = loader.loadModel('models/misc/gridBack')
self.gridBack.reparentTo(self)
self.gridBack.setColor(0.5,0.5,0.5,0.5)
self.gridBack.setColor(0.5, 0.5, 0.5, 0.5)
# Grid Lines
self.lines = self.attachNewNode('gridLines')
self.minorLines = LineNodePath(self.lines)
self.minorLines.lineNode.setName('minorLines')
self.minorLines.setColor(VBase4(0.3,0.55,1,1))
self.minorLines.setColor(VBase4(0.3, 0.55, 1, 1))
self.minorLines.setThickness(1)
self.majorLines = LineNodePath(self.lines)
self.majorLines.lineNode.setName('majorLines')
self.majorLines.setColor(VBase4(0.3,0.55,1,1))
self.majorLines.setColor(VBase4(0.3, 0.55, 1, 1))
self.majorLines.setThickness(5)
self.centerLines = LineNodePath(self.lines)
self.centerLines.lineNode.setName('centerLines')
self.centerLines.setColor(VBase4(1,0,0,0))
self.centerLines.setColor(VBase4(1, 0, 0, 0))
self.centerLines.setThickness(3)
# Small marker to hilight snap-to-grid point
self.snapMarker = loader.loadModel('models/misc/sphere')
self.snapMarker.node().setName('gridSnapMarker')
self.snapMarker.reparentTo(self)
self.snapMarker.setColor(1,0,0,1)
self.snapMarker.setColor(1, 0, 0, 1)
self.snapMarker.setScale(0.3)
self.snapPos = Point3(0)
@ -79,11 +79,11 @@ class DirectGrid(NodePath, DirectObject):
# Now redraw lines
numLines = int(math.ceil(self.gridSize/self.gridSpacing))
scaledSize = numLines * self.gridSpacing
center = self.centerLines
minor = self.minorLines
major = self.majorLines
for i in range(-numLines,numLines + 1):
for i in range(-numLines, numLines + 1):
if i == 0:
center.moveTo(i * self.gridSpacing, -scaledSize, 0)
center.drawTo(i * self.gridSpacing, scaledSize, 0)
@ -105,7 +105,7 @@ class DirectGrid(NodePath, DirectObject):
minor.create()
major.create()
self.gridBack.setScale(scaledSize)
def setXyzSnap(self, fSnap):
self.fXyzSnap = fSnap
@ -127,7 +127,7 @@ class DirectGrid(NodePath, DirectObject):
ROUND_TO(self.snapPos[0], self.gridSpacing),
ROUND_TO(self.snapPos[1], self.gridSpacing),
ROUND_TO(self.snapPos[2], self.gridSpacing))
# Move snap marker to this point
self.snapMarker.setPos(self.snapPos)
@ -146,7 +146,7 @@ class DirectGrid(NodePath, DirectObject):
def setGridSpacing(self, spacing):
self.gridSpacing = spacing
self.updateGrid()
def getGridSpacing(self):
return self.gridSpacing

View File

@ -20,7 +20,7 @@ class DirectLight(NodePath):
def getName(self):
return self.light.getName()
def getLight(self):
return self.light
@ -61,13 +61,13 @@ class DirectLights(NodePath):
nameList = map(lambda x: x.getName(), self.lightDict.values())
nameList.sort()
return nameList
def create(self, type):
type = type.lower()
if type == 'ambient':
self.ambientCount += 1
light = AmbientLight('ambient-' + `self.ambientCount`)
light.setColor(VBase4(.3,.3,.3,1))
light.setColor(VBase4(.3, .3, .3, 1))
elif type == 'directional':
self.directionalCount += 1
light = DirectionalLight('directional-' + `self.directionalCount`)
@ -85,7 +85,7 @@ class DirectLights(NodePath):
print 'Invalid light type'
return None
# Add the new light
directLight = DirectLight(light,self)
directLight = DirectLight(light, self)
self.lightDict[directLight.getName()] = directLight
# Turn it on as a default
self.setOn(directLight)
@ -128,7 +128,7 @@ class DirectLights(NodePath):
Turn on the given directLight
"""
render.setLight(directLight)
def setOff(self, directLight):
"""
Turn off the given directLight

View File

@ -39,7 +39,7 @@ class DirectManipulationControl(DirectObject):
self.defaultSkipFlags = SKIP_HIDDEN | SKIP_BACKFACE
self.optionalSkipFlags = 0
self.unmovableTagList = []
def manipulationStart(self, modifiers):
# Start out in select mode
self.mode = 'select'
@ -55,7 +55,7 @@ class DirectManipulationControl(DirectObject):
else:
# Nope, off the widget, no constraint
self.constraint = None
if not direct.gotAlt(modifiers):
# Check to see if we are moving the object
# We are moving the object if we either wait long enough
@ -183,7 +183,7 @@ class DirectManipulationControl(DirectObject):
# Changes: none
# Returns: list of edit types
#--------------------------------------------------------------------------
def getEditTypes(self,objects):
def getEditTypes(self, objects):
# See if any of the selected in the don't manipulate tag list
editTypes = 0
for tag in self.unmovableTagList:
@ -218,7 +218,7 @@ class DirectManipulationControl(DirectObject):
self.objectHandles.hideAllHandles()
self.objectHandles.showHandle(self.constraint)
if direct.clusterMode == 'client':
oh = 'direct.manipulationControl.objectHandles'
oh = 'direct.manipulationControl.objectHandles'
cluster(oh + '.showGuides()', 0)
cluster(oh + '.hideAllHandles()', 0)
cluster(oh + ('.showHandle("%s")'% self.constraint), 0)
@ -229,7 +229,7 @@ class DirectManipulationControl(DirectObject):
# Send event to signal start of manipulation
messenger.send('DIRECT_manipulateObjectStart')
# Manipulate the real object with the constraint
# The constraint is passed as the name of the node
# The constraint is passed as the name of the node
self.spawnManipulateObjectTask()
def spawnManipulateObjectTask(self):
@ -338,7 +338,7 @@ class DirectManipulationControl(DirectObject):
direct.widget.setPos(direct.widget, offset)
def rotate1D(self, state):
# Constrained 1D rotation about the widget's main axis (X,Y, or Z)
# Constrained 1D rotation about the widget's main axis (X, Y, or Z)
# Rotation depends upon circular motion of the mouse about the
# projection of the widget's origin on the image plane
# A complete circle about the widget results in a change in
@ -351,7 +351,7 @@ class DirectManipulationControl(DirectObject):
self.fWidgetTop = self.widgetCheck('top?')
self.rotationCenter = getScreenXY(direct.widget)
self.lastCrankAngle = getCrankAngle(self.rotationCenter)
# Rotate widget based on how far cursor has swung around origin
newAngle = getCrankAngle(self.rotationCenter)
deltaAngle = self.lastCrankAngle - newAngle
@ -366,7 +366,7 @@ class DirectManipulationControl(DirectObject):
# Record crank angle for next time around
self.lastCrankAngle = newAngle
def widgetCheck(self,type):
def widgetCheck(self, type):
# Utility to see if we are looking at the top or bottom of
# a 2D planar widget or if we are looking at a 2D planar widget
# edge on
@ -530,7 +530,7 @@ class DirectManipulationControl(DirectObject):
direct.selected.getWrtAll()
# Move selected
direct.widget.setPos(
direct.camera,entry.getSurfacePoint(entry.getFromNodePath()))
direct.camera, entry.getSurfacePoint(entry.getFromNodePath()))
# Move all the selected objects with widget
# Move the objects with the widget
direct.selected.moveWrtWidgetAll()
@ -538,7 +538,7 @@ class DirectManipulationControl(DirectObject):
messenger.send('DIRECT_manipulateObjectCleanup',
[direct.selected.getSelectedAsList()])
class ObjectHandles(NodePath,DirectObject):
class ObjectHandles(NodePath, DirectObject):
def __init__(self):
# Initialize the superclass
NodePath.__init__(self)
@ -560,7 +560,7 @@ class ObjectHandles(NodePath,DirectObject):
self.xDiscGroup = self.xHandles.find('**/x-disc-group')
self.xDisc = self.xHandles.find('**/x-disc-visible')
self.xDiscCollision = self.xHandles.find('**/x-disc')
self.yHandles = self.find('**/Y')
self.yPostGroup = self.yHandles.find('**/y-post-group')
self.yPostCollision = self.yHandles.find('**/y-post')
@ -569,7 +569,7 @@ class ObjectHandles(NodePath,DirectObject):
self.yDiscGroup = self.yHandles.find('**/y-disc-group')
self.yDisc = self.yHandles.find('**/y-disc-visible')
self.yDiscCollision = self.yHandles.find('**/y-disc')
self.zHandles = self.find('**/Z')
self.zPostGroup = self.zHandles.find('**/z-post-group')
self.zPostCollision = self.zHandles.find('**/z-post')
@ -582,13 +582,13 @@ class ObjectHandles(NodePath,DirectObject):
# Adjust visiblity, colors, and transparency
self.xPostCollision.hide()
self.xRingCollision.hide()
self.xDisc.setColor(1,0,0,.2)
self.xDisc.setColor(1, 0, 0, .2)
self.yPostCollision.hide()
self.yRingCollision.hide()
self.yDisc.setColor(0,1,0,.2)
self.yDisc.setColor(0, 1, 0, .2)
self.zPostCollision.hide()
self.zRingCollision.hide()
self.zDisc.setColor(0,0,1,.2)
self.zDisc.setColor(0, 0, 1, .2)
# Augment geometry with lines
self.createObjectHandleLines()
# Create long markers to help line up in world
@ -603,7 +603,7 @@ class ObjectHandles(NodePath,DirectObject):
useDirectRenderStyle(self)
def coaModeColor(self):
self.setColor(.5,.5,.5,1)
self.setColor(.5, .5, .5, 1)
def manipModeColor(self):
self.clearColor()
@ -783,7 +783,7 @@ class ObjectHandles(NodePath,DirectObject):
def multiplyScalingFactorBy(self, factor):
taskMgr.remove('resizeObjectHandles')
sf = self.ohScalingFactor = self.ohScalingFactor * factor
self.scalingNode.lerpScale(sf,sf,sf, 0.5,
self.scalingNode.lerpScale(sf, sf, sf, 0.5,
blendType = 'easeInOut',
task = 'resizeObjectHandles')
@ -794,7 +794,7 @@ class ObjectHandles(NodePath,DirectObject):
minDim = min(direct.dr.nearWidth, direct.dr.nearHeight)
sf = 0.15 * minDim * (pos[1]/direct.dr.near)
self.ohScalingFactor = sf
self.scalingNode.lerpScale(sf,sf,sf, 0.5,
self.scalingNode.lerpScale(sf, sf, sf, 0.5,
blendType = 'easeInOut',
task = 'resizeObjectHandles')
@ -802,51 +802,51 @@ class ObjectHandles(NodePath,DirectObject):
# X post
self.xPost = self.xPostGroup.attachNewNode('x-post-visible')
lines = LineNodePath(self.xPost)
lines.setColor(VBase4(1,0,0,1))
lines.setColor(VBase4(1, 0, 0, 1))
lines.setThickness(5)
lines.moveTo(0,0,0)
lines.drawTo(1.5,0,0)
lines.moveTo(0, 0, 0)
lines.drawTo(1.5, 0, 0)
lines.create()
lines = LineNodePath(self.xPost)
lines.setColor(VBase4(1,0,0,1))
lines.setColor(VBase4(1, 0, 0, 1))
lines.setThickness(1.5)
lines.moveTo(0,0,0)
lines.drawTo(-1.5,0,0)
lines.moveTo(0, 0, 0)
lines.drawTo(-1.5, 0, 0)
lines.create()
# X ring
self.xRing = self.xRingGroup.attachNewNode('x-ring-visible')
lines = LineNodePath(self.xRing)
lines.setColor(VBase4(1,0,0,1))
lines.setColor(VBase4(1, 0, 0, 1))
lines.setThickness(3)
lines.moveTo(0,1,0)
lines.moveTo(0, 1, 0)
for ang in range(15, 370, 15):
lines.drawTo(0,
math.cos(deg2Rad(ang)),
math.sin(deg2Rad(ang)))
lines.create()
# Y post
self.yPost = self.yPostGroup.attachNewNode('y-post-visible')
lines = LineNodePath(self.yPost)
lines.setColor(VBase4(0,1,0,1))
lines.setColor(VBase4(0, 1, 0, 1))
lines.setThickness(5)
lines.moveTo(0,0,0)
lines.drawTo(0,1.5,0)
lines.moveTo(0, 0, 0)
lines.drawTo(0, 1.5, 0)
lines.create()
lines = LineNodePath(self.yPost)
lines.setColor(VBase4(0,1,0,1))
lines.setColor(VBase4(0, 1, 0, 1))
lines.setThickness(1.5)
lines.moveTo(0,0,0)
lines.drawTo(0,-1.5,0)
lines.moveTo(0, 0, 0)
lines.drawTo(0, -1.5, 0)
lines.create()
# Y ring
self.yRing = self.yRingGroup.attachNewNode('y-ring-visible')
lines = LineNodePath(self.yRing)
lines.setColor(VBase4(0,1,0,1))
lines.setColor(VBase4(0, 1, 0, 1))
lines.setThickness(3)
lines.moveTo(1,0,0)
lines.moveTo(1, 0, 0)
for ang in range(15, 370, 15):
lines.drawTo(math.cos(deg2Rad(ang)),
0,
@ -856,24 +856,24 @@ class ObjectHandles(NodePath,DirectObject):
# Z post
self.zPost = self.zPostGroup.attachNewNode('z-post-visible')
lines = LineNodePath(self.zPost)
lines.setColor(VBase4(0,0,1,1))
lines.setColor(VBase4(0, 0, 1, 1))
lines.setThickness(5)
lines.moveTo(0,0,0)
lines.drawTo(0,0,1.5)
lines.moveTo(0, 0, 0)
lines.drawTo(0, 0, 1.5)
lines.create()
lines = LineNodePath(self.zPost)
lines.setColor(VBase4(0,0,1,1))
lines.setColor(VBase4(0, 0, 1, 1))
lines.setThickness(1.5)
lines.moveTo(0,0,0)
lines.drawTo(0,0,-1.5)
lines.moveTo(0, 0, 0)
lines.drawTo(0, 0, -1.5)
lines.create()
# Z ring
self.zRing = self.zRingGroup.attachNewNode('z-ring-visible')
lines = LineNodePath(self.zRing)
lines.setColor(VBase4(0,0,1,1))
lines.setColor(VBase4(0, 0, 1, 1))
lines.setThickness(3)
lines.moveTo(1,0,0)
lines.moveTo(1, 0, 0)
for ang in range(15, 370, 15):
lines.drawTo(math.cos(deg2Rad(ang)),
math.sin(deg2Rad(ang)),
@ -884,28 +884,28 @@ class ObjectHandles(NodePath,DirectObject):
self.guideLines = self.attachNewNode('guideLines')
# X guide lines
lines = LineNodePath(self.guideLines)
lines.setColor(VBase4(1,0,0,1))
lines.setColor(VBase4(1, 0, 0, 1))
lines.setThickness(0.5)
lines.moveTo(-500,0,0)
lines.drawTo(500,0,0)
lines.moveTo(-500, 0, 0)
lines.drawTo(500, 0, 0)
lines.create()
lines.setName('x-guide')
# Y guide lines
lines = LineNodePath(self.guideLines)
lines.setColor(VBase4(0,1,0,1))
lines.setColor(VBase4(0, 1, 0, 1))
lines.setThickness(0.5)
lines.moveTo(0,-500,0)
lines.drawTo(0,500,0)
lines.moveTo(0, -500, 0)
lines.drawTo(0, 500, 0)
lines.create()
lines.setName('y-guide')
# Z guide lines
lines = LineNodePath(self.guideLines)
lines.setColor(VBase4(0,0,1,1))
lines.setColor(VBase4(0, 0, 1, 1))
lines.setThickness(0.5)
lines.moveTo(0,0,-500)
lines.drawTo(0,0,500)
lines.moveTo(0, 0, -500)
lines.drawTo(0, 0, 500)
lines.create()
lines.setName('z-guide')
@ -960,12 +960,12 @@ class ObjectHandles(NodePath,DirectObject):
# Calc the xfrom from camera to the nodePath
mCam2NodePath = direct.camera.getMat(nodePath)
# And determine where the viewpoint is relative to widget
lineOrigin = VBase3(0)
decomposeMatrix(mCam2NodePath, VBase3(0), VBase3(0), lineOrigin,
CSDefault)
# Next we find the vector from viewpoint to the widget through
# the mouse's position on near plane.
# This defines the intersection ray