Browse Source

direct: Add `base.clock`, deprecate `globalClock`

rdb 4 years ago
parent
commit
eefcae7b05

+ 4 - 3
direct/src/cluster/ClusterClient.py

@@ -122,9 +122,10 @@ class ClusterClient(DirectObject.DirectObject):
         taskMgr.add(self.synchronizeTimeTask, "synchronizeTimeTask", -40)
         taskMgr.add(self.synchronizeTimeTask, "synchronizeTimeTask", -40)
 
 
     def synchronizeTimeTask(self, task):
     def synchronizeTimeTask(self, task):
-        frameCount = globalClock.getFrameCount()
-        frameTime = globalClock.getFrameTime()
-        dt = globalClock.getDt()
+        clock = ClockObject.getGlobalClock()
+        frameCount = clock.getFrameCount()
+        frameTime = clock.getFrameTime()
+        dt = clock.dt
         for server in self.serverList:
         for server in self.serverList:
             server.sendTimeData(frameCount, frameTime, dt)
             server.sendTimeData(frameCount, frameTime, dt)
         return Task.cont
         return Task.cont

+ 5 - 4
direct/src/cluster/ClusterServer.py

@@ -52,7 +52,7 @@ class ClusterServer(DirectObject.DirectObject):
             self.startSwapCoordinator()
             self.startSwapCoordinator()
             base.graphicsEngine.setAutoFlip(0)
             base.graphicsEngine.setAutoFlip(0)
         # Set global clock mode to slave mode
         # Set global clock mode to slave mode
-        globalClock.setMode(ClockObject.MSlave)
+        ClockObject.getGlobalClock().setMode(ClockObject.MSlave)
         # Send verification of startup to client
         # Send verification of startup to client
         self.daemon = DirectD()
         self.daemon = DirectD()
 
 
@@ -335,9 +335,10 @@ class ClusterServer(DirectObject.DirectObject):
         """ Update cameraJig position to reflect latest position """
         """ 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
         # Use frame time from client for both real and frame time
-        globalClock.setFrameCount(frameCount)
-        globalClock.setFrameTime(frameTime)
-        globalClock.setDt(dt)
+        clock = ClockObject.getGlobalClock()
+        clock.setFrameCount(frameCount)
+        clock.setFrameTime(frameTime)
+        clock.dt = dt
 
 
     def handleCommandString(self, dgi):
     def handleCommandString(self, dgi):
         """ Handle arbitrary command string from client """
         """ Handle arbitrary command string from client """

+ 1 - 1
direct/src/directbase/TestStart.py

@@ -13,7 +13,7 @@ base.camera.setPosHpr(0, -10.0, 0, 0, 0, 0)
 base.camLens.setFov(52.0)
 base.camLens.setFov(52.0)
 base.camLens.setNearFar(1.0, 10000.0)
 base.camLens.setNearFar(1.0, 10000.0)
 
 
-globalClock.setMaxDt(0.2)
+base.clock.setMaxDt(0.2)
 base.enableParticles()
 base.enableParticles()
 
 
 # Force the screen to update:
 # Force the screen to update:

+ 1 - 1
direct/src/directbase/ThreeUpStart.py

@@ -15,7 +15,7 @@ base.camera.setPosHpr(0, -10.0, 0, 0, 0, 0)
 base.camLens.setFov(52.0)
 base.camLens.setFov(52.0)
 base.camLens.setNearFar(1.0, 10000.0)
 base.camLens.setNearFar(1.0, 10000.0)
 
 
-globalClock.setMaxDt(0.2)
+base.clock.setMaxDt(0.2)
 base.enableParticles()
 base.enableParticles()
 base.addAngularIntegrator()
 base.addAngularIntegrator()
 
 

+ 5 - 3
direct/src/directdevices/DirectJoybox.py

@@ -5,6 +5,8 @@ from direct.directtools.DirectUtil import *
 from direct.gui import OnscreenText
 from direct.gui import OnscreenText
 from direct.task import Task
 from direct.task import Task
 from direct.task.TaskManagerGlobal import taskMgr
 from direct.task.TaskManagerGlobal import taskMgr
+from panda3d.core import ClockObject
+
 import math
 import math
 
 
 #TODO: Handle interaction between widget, followSelectedTask and updateTask
 #TODO: Handle interaction between widget, followSelectedTask and updateTask
@@ -58,7 +60,7 @@ class DirectJoybox(DirectObject):
                         R_TWIST, L_TWIST, NULL_AXIS]
                         R_TWIST, L_TWIST, NULL_AXIS]
         self.modifier = [1, 1, 1, -1, -1, 0]
         self.modifier = [1, 1, 1, -1, -1, 0]
         # Initialize time
         # Initialize time
-        self.lastTime = globalClock.getFrameTime()
+        self.lastTime = ClockObject.getGlobalClock().getFrameTime()
         # Record node path
         # Record node path
         self.nodePath = nodePath
         self.nodePath = nodePath
         self.headingNP = headingNP
         self.headingNP = headingNP
@@ -148,7 +150,7 @@ class DirectJoybox(DirectObject):
 
 
     def updateVals(self):
     def updateVals(self):
         # Update delta time
         # Update delta time
-        cTime = globalClock.getFrameTime()
+        cTime = ClockObject.getGlobalClock().getFrameTime()
         self.deltaTime = cTime - self.lastTime
         self.deltaTime = cTime - self.lastTime
         self.lastTime = cTime
         self.lastTime = cTime
         # Update analogs
         # Update analogs
@@ -164,7 +166,7 @@ class DirectJoybox(DirectObject):
 
 
     def updateValsUnrolled(self):
     def updateValsUnrolled(self):
         # Update delta time
         # Update delta time
-        cTime = globalClock.getFrameTime()
+        cTime = ClockObject.getGlobalClock().getFrameTime()
         self.deltaTime = cTime - self.lastTime
         self.deltaTime = cTime - self.lastTime
         self.lastTime = cTime
         self.lastTime = cTime
         # Update analogs
         # Update analogs

+ 8 - 8
direct/src/directtools/DirectCameraControl.py

@@ -129,8 +129,8 @@ class DirectCameraControl(DirectObject):
             # Hide the marker for this kind of motion
             # Hide the marker for this kind of motion
             self.coaMarker.hide()
             self.coaMarker.hide()
             # Record time of start of mouse interaction
             # Record time of start of mouse interaction
-            self.startT= globalClock.getFrameTime()
-            self.startF = globalClock.getFrameCount()
+            self.startT = base.clock.getFrameTime()
+            self.startF = base.clock.getFrameCount()
             # If the cam is orthogonal, spawn differentTask
             # If the cam is orthogonal, spawn differentTask
             if hasattr(base.direct, "manipulationControl") and base.direct.manipulationControl.fMultiView and\
             if hasattr(base.direct, "manipulationControl") and base.direct.manipulationControl.fMultiView and\
                base.direct.camera.getName() != 'persp':
                base.direct.camera.getName() != 'persp':
@@ -169,8 +169,8 @@ class DirectCameraControl(DirectObject):
             # Hide the marker for this kind of motion
             # Hide the marker for this kind of motion
             self.coaMarker.hide()
             self.coaMarker.hide()
             # Record time of start of mouse interaction
             # Record time of start of mouse interaction
-            self.startT= globalClock.getFrameTime()
-            self.startF = globalClock.getFrameCount()
+            self.startT = base.clock.getFrameTime()
+            self.startF = base.clock.getFrameCount()
             # Start manipulation
             # Start manipulation
             # If the cam is orthogonal, spawn differentTask
             # If the cam is orthogonal, spawn differentTask
             if hasattr(base.direct, "manipulationControl") and base.direct.manipulationControl.fMultiView and\
             if hasattr(base.direct, "manipulationControl") and base.direct.manipulationControl.fMultiView and\
@@ -186,8 +186,8 @@ class DirectCameraControl(DirectObject):
                 # Hide the marker for this kind of motion
                 # Hide the marker for this kind of motion
                 self.coaMarker.hide()
                 self.coaMarker.hide()
                 # Record time of start of mouse interaction
                 # Record time of start of mouse interaction
-                self.startT= globalClock.getFrameTime()
-                self.startF = globalClock.getFrameCount()
+                self.startT = base.clock.getFrameTime()
+                self.startF = base.clock.getFrameCount()
                 # Start manipulation
                 # Start manipulation
                 self.spawnXZTranslateOrHPanYZoom()
                 self.spawnXZTranslateOrHPanYZoom()
                 # END MOUSE IN CENTRAL REGION
                 # END MOUSE IN CENTRAL REGION
@@ -204,9 +204,9 @@ class DirectCameraControl(DirectObject):
 
 
     def mouseFlyStop(self):
     def mouseFlyStop(self):
         self.__stopManipulateCamera()
         self.__stopManipulateCamera()
-        stopT = globalClock.getFrameTime()
+        stopT = base.clock.getFrameTime()
         deltaT = stopT - self.startT
         deltaT = stopT - self.startT
-        stopF = globalClock.getFrameCount()
+        stopF = base.clock.getFrameCount()
         deltaF = stopF - self.startF
         deltaF = stopF - self.startF
         ## No reason this shouldn't work with Maya cam on
         ## No reason this shouldn't work with Maya cam on
         # if not self.useMayaCamControls and (deltaT <= 0.25) or (deltaF <= 1):
         # if not self.useMayaCamControls and (deltaT <= 0.25) or (deltaF <= 1):

+ 1 - 1
direct/src/directtools/DirectUtil.py

@@ -36,7 +36,7 @@ def lerpBackgroundColor(r, g, b, duration):
     Function to lerp background color to a new value
     Function to lerp background color to a new value
     """
     """
     def lerpColor(state):
     def lerpColor(state):
-        dt = globalClock.getDt()
+        dt = base.clock.getDt()
         state.time += dt
         state.time += dt
         sf = state.time / state.duration
         sf = state.time / state.duration
         if sf >= 1.0:
         if sf >= 1.0:

+ 4 - 3
direct/src/directutil/Mopath.py

@@ -2,7 +2,8 @@ from direct.showbase.DirectObject import DirectObject
 from direct.showbase.MessengerGlobal import messenger
 from direct.showbase.MessengerGlobal import messenger
 from direct.directtools.DirectGeometry import *
 from direct.directtools.DirectGeometry import *
 
 
-from panda3d.core import NodePath, LineSegs
+from panda3d.core import NodePath, LineSegs, ClockObject
+
 
 
 class Mopath(DirectObject):
 class Mopath(DirectObject):
 
 
@@ -152,13 +153,13 @@ class Mopath(DirectObject):
         self.stop()
         self.stop()
         t = taskMgr.add(self.__playTask, self.name + '-play')
         t = taskMgr.add(self.__playTask, self.name + '-play')
         t.currentTime = time
         t.currentTime = time
-        t.lastTime = globalClock.getFrameTime()
+        t.lastTime = ClockObject.getGlobalClock().getFrameTime()
 
 
     def stop(self):
     def stop(self):
         taskMgr.remove(self.name + '-play')
         taskMgr.remove(self.name + '-play')
 
 
     def __playTask(self, task):
     def __playTask(self, task):
-        time = globalClock.getFrameTime()
+        time = ClockObject.getGlobalClock().getFrameTime()
         dTime = time - task.lastTime
         dTime = time - task.lastTime
         task.lastTime = time
         task.lastTime = time
         if self.loop:
         if self.loop:

+ 2 - 2
direct/src/distributed/ClientRepository.py

@@ -6,7 +6,7 @@ from direct.showbase.MessengerGlobal import messenger
 from .MsgTypesCMU import *
 from .MsgTypesCMU import *
 from .PyDatagram import PyDatagram
 from .PyDatagram import PyDatagram
 from .PyDatagramIterator import PyDatagramIterator
 from .PyDatagramIterator import PyDatagramIterator
-from panda3d.core import UniqueIdAllocator, Notify
+from panda3d.core import UniqueIdAllocator, Notify, ClockObject
 
 
 
 
 class ClientRepository(ClientRepositoryBase):
 class ClientRepository(ClientRepositoryBase):
@@ -281,7 +281,7 @@ class ClientRepository(ClientRepositoryBase):
         datagram.addUint16(CLIENT_HEARTBEAT_CMU)
         datagram.addUint16(CLIENT_HEARTBEAT_CMU)
         # Send it!
         # Send it!
         self.send(datagram)
         self.send(datagram)
-        self.lastHeartbeat = globalClock.getRealTime()
+        self.lastHeartbeat = ClockObject.getGlobalClock().getRealTime()
         # This is important enough to consider flushing immediately
         # This is important enough to consider flushing immediately
         # (particularly if we haven't run readerPollTask recently).
         # (particularly if we haven't run readerPollTask recently).
         self.considerFlush()
         self.considerFlush()

+ 3 - 3
direct/src/distributed/ClientRepositoryBase.py

@@ -186,7 +186,7 @@ class ClientRepositoryBase(ConnectionRepository):
                 self.doGenerate(*args)
                 self.doGenerate(*args)
 
 
                 if deferrable:
                 if deferrable:
-                    self.lastGenerate = globalClock.getFrameTime()
+                    self.lastGenerate = ClockObject.getGlobalClock().getFrameTime()
 
 
                 for dg, di in updates:
                 for dg, di in updates:
                     # non-DC updates that need to be played back in-order are
                     # non-DC updates that need to be played back in-order are
@@ -207,7 +207,7 @@ class ClientRepositoryBase(ConnectionRepository):
         """ This is the task that generates an object on the deferred
         """ This is the task that generates an object on the deferred
         queue. """
         queue. """
 
 
-        now = globalClock.getFrameTime()
+        now = ClockObject.getGlobalClock().getFrameTime()
         while self.deferredGenerates:
         while self.deferredGenerates:
             if now - self.lastGenerate < self.deferInterval:
             if now - self.lastGenerate < self.deferInterval:
                 # Come back later.
                 # Come back later.
@@ -539,7 +539,7 @@ class ClientRepositoryBase(ConnectionRepository):
             self.notify.debug("Heartbeats not started; not sending.")
             self.notify.debug("Heartbeats not started; not sending.")
             return
             return
 
 
-        elapsed = globalClock.getRealTime() - self.lastHeartbeat
+        elapsed = ClockObject.getGlobalClock().getRealTime() - self.lastHeartbeat
         if elapsed < 0 or elapsed > self.heartbeatInterval:
         if elapsed < 0 or elapsed > self.heartbeatInterval:
             # It's time to send the heartbeat again (or maybe someone
             # It's time to send the heartbeat again (or maybe someone
             # reset the clock back).
             # reset the clock back).

+ 2 - 1
direct/src/distributed/DistributedSmoothNode.py

@@ -187,7 +187,7 @@ class DistributedSmoothNode(DistributedNode.DistributedNode,
         reflect the node's current position
         reflect the node's current position
         """
         """
         if self.stopped:
         if self.stopped:
-            currTime = globalClock.getFrameTime()
+            currTime = ClockObject.getGlobalClock().getFrameTime()
             now = currTime - self.smoother.getExpectedBroadcastPeriod()
             now = currTime - self.smoother.getExpectedBroadcastPeriod()
             last = self.smoother.getMostRecentTimestamp()
             last = self.smoother.getMostRecentTimestamp()
             if now > last:
             if now > last:
@@ -348,6 +348,7 @@ class DistributedSmoothNode(DistributedNode.DistributedNode,
                 self.smoother.setPhonyTimestamp()
                 self.smoother.setPhonyTimestamp()
             self.smoother.markPosition()
             self.smoother.markPosition()
         else:
         else:
+            globalClock = ClockObject.getGlobalClock()
             now = globalClock.getFrameTime()
             now = globalClock.getFrameTime()
             local = globalClockDelta.networkToLocalTime(timestamp, now)
             local = globalClockDelta.networkToLocalTime(timestamp, now)
             realTime = globalClock.getRealTime()
             realTime = globalClock.getRealTime()

+ 3 - 3
direct/src/distributed/DoInterestManager.py

@@ -157,7 +157,7 @@ class DoInterestManager(DirectObject.DirectObject):
         """
         """
         assert DoInterestManager.notify.debugCall()
         assert DoInterestManager.notify.debugCall()
         handle = self._getNextHandle()
         handle = self._getNextHandle()
-        # print 'base.cr.addInterest(',description,',',handle,'):',globalClock.getFrameCount()
+        # print 'base.cr.addInterest(',description,',',handle,'):',base.clock.getFrameCount()
         if self._noNewInterests:
         if self._noNewInterests:
             DoInterestManager.notify.warning(
             DoInterestManager.notify.warning(
                 "addInterest: addingInterests on delete: %s" % (handle))
                 "addInterest: addingInterests on delete: %s" % (handle))
@@ -229,7 +229,7 @@ class DoInterestManager(DirectObject.DirectObject):
         """
         """
         Stop looking in a (set of) zone(s)
         Stop looking in a (set of) zone(s)
         """
         """
-        # print 'base.cr.removeInterest(',handle,'):',globalClock.getFrameCount()
+        # print 'base.cr.removeInterest(',handle,'):',base.clock.getFrameCount()
 
 
         assert DoInterestManager.notify.debugCall()
         assert DoInterestManager.notify.debugCall()
         assert isinstance(handle, InterestHandle)
         assert isinstance(handle, InterestHandle)
@@ -567,7 +567,7 @@ class DoInterestManager(DirectObject.DirectObject):
         def checkMoreInterests():
         def checkMoreInterests():
             # if there are new interests, cancel this delayed callback, another
             # if there are new interests, cancel this delayed callback, another
             # will automatically be scheduled when all interests complete
             # will automatically be scheduled when all interests complete
-            # print 'checkMoreInterests(',self._completeEventCount.num,'):',globalClock.getFrameCount()
+            # print 'checkMoreInterests(',self._completeEventCount.num,'):',base.clock.getFrameCount()
             return self._completeEventCount.num > 0
             return self._completeEventCount.num > 0
         def sendEvent():
         def sendEvent():
             messenger.send(self.getAllInterestsCompleteEvent())
             messenger.send(self.getAllInterestsCompleteEvent())

+ 5 - 3
direct/src/distributed/TimeManager.py

@@ -6,6 +6,7 @@ from direct.distributed import DistributedObject
 from direct.directnotify import DirectNotifyGlobal
 from direct.directnotify import DirectNotifyGlobal
 from direct.distributed.ClockDelta import globalClockDelta
 from direct.distributed.ClockDelta import globalClockDelta
 
 
+
 class TimeManager(DistributedObject.DistributedObject):
 class TimeManager(DistributedObject.DistributedObject):
     """
     """
     This DistributedObject lives on the AI and on the client side, and
     This DistributedObject lives on the AI and on the client side, and
@@ -128,7 +129,7 @@ class TimeManager(DistributedObject.DistributedObject):
         The return value is true if the attempt is made, or false if
         The return value is true if the attempt is made, or false if
         it is too soon since the last attempt.
         it is too soon since the last attempt.
         """
         """
-        now = globalClock.getRealTime()
+        now = ClockObject.getGlobalClock().getRealTime()
 
 
         if now - self.lastAttempt < self.minWait:
         if now - self.lastAttempt < self.minWait:
             self.notify.debug("Not resyncing (too soon): %s" % (description))
             self.notify.debug("Not resyncing (too soon): %s" % (description))
@@ -157,7 +158,8 @@ class TimeManager(DistributedObject.DistributedObject):
         determine the clock delta between the AI and the client
         determine the clock delta between the AI and the client
         machines.
         machines.
         """
         """
-        end = globalClock.getRealTime()
+        clock = ClockObject.getGlobalClock()
+        end = clock.getRealTime()
 
 
         if context != self.thisContext:
         if context != self.thisContext:
             self.notify.info("Ignoring TimeManager response for old context %d" % (context))
             self.notify.info("Ignoring TimeManager response for old context %d" % (context))
@@ -177,7 +179,7 @@ class TimeManager(DistributedObject.DistributedObject):
         if globalClockDelta.getUncertainty() > self.maxUncertainty:
         if globalClockDelta.getUncertainty() > self.maxUncertainty:
             if self.attemptCount < self.maxAttempts:
             if self.attemptCount < self.maxAttempts:
                 self.notify.info("Uncertainty is too high, trying again.")
                 self.notify.info("Uncertainty is too high, trying again.")
-                self.start = globalClock.getRealTime()
+                self.start = clock.getRealTime()
                 self.sendUpdate("requestServerTime", [self.thisContext])
                 self.sendUpdate("requestServerTime", [self.thisContext])
                 return
                 return
             self.notify.info("Giving up on uncertainty requirement.")
             self.notify.info("Giving up on uncertainty requirement.")

+ 4 - 4
direct/src/interval/IntervalTest.py

@@ -137,22 +137,22 @@ if __name__ == "__main__":
     startTime = 0.0
     startTime = 0.0
     def printStart():
     def printStart():
         global startTime
         global startTime
-        startTime = globalClock.getFrameTime()
+        startTime = base.clock.getFrameTime()
         print('Start')
         print('Start')
 
 
     def printPreviousStart():
     def printPreviousStart():
         global startTime
         global startTime
-        currTime = globalClock.getFrameTime()
+        currTime = base.clock.getFrameTime()
         print('PREVIOUS_END %0.2f' % (currTime - startTime))
         print('PREVIOUS_END %0.2f' % (currTime - startTime))
 
 
     def printPreviousEnd():
     def printPreviousEnd():
         global startTime
         global startTime
-        currTime = globalClock.getFrameTime()
+        currTime = base.clock.getFrameTime()
         print('PREVIOUS_END %0.2f' % (currTime - startTime))
         print('PREVIOUS_END %0.2f' % (currTime - startTime))
 
 
     def printTrackStart():
     def printTrackStart():
         global startTime
         global startTime
-        currTime = globalClock.getFrameTime()
+        currTime = base.clock.getFrameTime()
         print('TRACK_START %0.2f' % (currTime - startTime))
         print('TRACK_START %0.2f' % (currTime - startTime))
 
 
     def printArguments(a, b, c):
     def printArguments(a, b, c):

+ 3 - 2
direct/src/leveleditor/LevelEditorBase.py

@@ -8,6 +8,7 @@ Refer LevelEditor.py for example.
 from direct.showbase.DirectObject import *
 from direct.showbase.DirectObject import *
 from direct.directtools.DirectUtil import *
 from direct.directtools.DirectUtil import *
 from direct.gui.DirectGui import *
 from direct.gui.DirectGui import *
+from panda3d.core import ClockObject
 
 
 from .CurveEditor import *
 from .CurveEditor import *
 from .FileMgr import *
 from .FileMgr import *
@@ -385,7 +386,7 @@ class LevelEditorBase(DirectObject):
                     alreadyExists = True
                     alreadyExists = True
                     break
                     break
             if not alreadyExists:
             if not alreadyExists:
-                time = globalClock.getRealTime() + 15
+                time = ClockObject.getGlobalClock().getRealTime() + 15
                 self.statusLines.append([time,status,color])
                 self.statusLines.append([time,status,color])
 
 
         # update display of new status lines
         # update display of new status lines
@@ -407,7 +408,7 @@ class LevelEditorBase(DirectObject):
     def updateStatusReadoutTimeouts(self,task=None):
     def updateStatusReadoutTimeouts(self,task=None):
         removalList = []
         removalList = []
         for currLine in self.statusLines:
         for currLine in self.statusLines:
-            if globalClock.getRealTime() >= currLine[0]:
+            if ClockObject.getGlobalClock().getRealTime() >= currLine[0]:
                 removalList.append(currLine)
                 removalList.append(currLine)
         for currRemoval in removalList:
         for currRemoval in removalList:
             self.statusLines.remove(currRemoval)
             self.statusLines.remove(currRemoval)

+ 6 - 5
direct/src/showbase/JobManager.py

@@ -150,9 +150,10 @@ class JobManager:
             self._useOverflowTime = ConfigVariableBool('job-use-overflow-time', 1).value
             self._useOverflowTime = ConfigVariableBool('job-use-overflow-time', 1).value
 
 
         if len(self._pri2jobId2job) > 0:
         if len(self._pri2jobId2job) > 0:
+            clock = ClockObject.getGlobalClock()
             #assert self.notify.debugCall()
             #assert self.notify.debugCall()
             # figure out how long we can run
             # figure out how long we can run
-            endT = globalClock.getRealTime() + (self.getTimeslice() * .9)
+            endT = clock.getRealTime() + (self.getTimeslice() * .9)
             while True:
             while True:
                 if self._jobIdGenerator is None:
                 if self._jobIdGenerator is None:
                     # round-robin the jobs, giving high-priority jobs more timeslices
                     # round-robin the jobs, giving high-priority jobs more timeslices
@@ -173,7 +174,7 @@ class JobManager:
                 # check if there's overflow time that we need to make up for
                 # check if there's overflow time that we need to make up for
                 if self._useOverflowTime:
                 if self._useOverflowTime:
                     overflowTime = self._jobId2overflowTime[jobId]
                     overflowTime = self._jobId2overflowTime[jobId]
-                    timeLeft = endT - globalClock.getRealTime()
+                    timeLeft = endT - clock.getRealTime()
                     if overflowTime >= timeLeft:
                     if overflowTime >= timeLeft:
                         self._jobId2overflowTime[jobId] = max(0., overflowTime-timeLeft)
                         self._jobId2overflowTime[jobId] = max(0., overflowTime-timeLeft)
                         # don't run any more jobs this frame, this makes up
                         # don't run any more jobs this frame, this makes up
@@ -184,7 +185,7 @@ class JobManager:
                 if __debug__:
                 if __debug__:
                     job._pstats.start()
                     job._pstats.start()
                 job.resume()
                 job.resume()
-                while globalClock.getRealTime() < endT:
+                while clock.getRealTime() < endT:
                     try:
                     try:
                         result = next(gen)
                         result = next(gen)
                     except StopIteration:
                     except StopIteration:
@@ -210,9 +211,9 @@ class JobManager:
                         break
                         break
                 else:
                 else:
                     # we've run out of time
                     # we've run out of time
-                    #assert self.notify.debug('timeslice end: %s, %s' % (endT, globalClock.getRealTime()))
+                    #assert self.notify.debug('timeslice end: %s, %s' % (endT, clock.getRealTime()))
                     job.suspend()
                     job.suspend()
-                    overflowTime = globalClock.getRealTime() - endT
+                    overflowTime = clock.getRealTime() - endT
                     if overflowTime > self.getTimeslice():
                     if overflowTime > self.getTimeslice():
                         self._jobId2overflowTime[jobId] += overflowTime
                         self._jobId2overflowTime[jobId] += overflowTime
                     if __debug__:
                     if __debug__:

+ 6 - 4
direct/src/showbase/PythonUtil.py

@@ -43,7 +43,7 @@ import functools
 
 
 __report_indent = 3
 __report_indent = 3
 
 
-from panda3d.core import ConfigVariableBool
+from panda3d.core import ConfigVariableBool, ClockObject
 
 
 
 
 ## with one integer positional arg, this uses about 4/5 of the memory of the Functor class below
 ## with one integer positional arg, this uses about 4/5 of the memory of the Functor class below
@@ -2053,6 +2053,7 @@ def report(types = [], prefix = '', xform = None, notifyFunc = None, dConfigPara
             if prefixes:
             if prefixes:
                 outStr = '%%s %s' % (outStr,)
                 outStr = '%%s %s' % (outStr,)
 
 
+            globalClock = ClockObject.getGlobalClock()
 
 
             if 'module' in types:
             if 'module' in types:
                 outStr = '%s {M:%s}' % (outStr, f.__module__.split('.')[-1])
                 outStr = '%s {M:%s}' % (outStr, f.__module__.split('.')[-1])
@@ -2264,9 +2265,10 @@ if __debug__:
                 # at the time that PythonUtil is loaded
                 # at the time that PythonUtil is loaded
                 if not ConfigVariableBool("profile-debug", False):
                 if not ConfigVariableBool("profile-debug", False):
                     #dumb timings
                     #dumb timings
-                    st=globalClock.getRealTime()
-                    f(*args,**kArgs)
-                    s=globalClock.getRealTime()-st
+                    clock = ClockObject.getGlobalClock()
+                    st = clock.getRealTime()
+                    f(*args, **kArgs)
+                    s = clock.getRealTime() - st
                     print("Function %s.%s took %s seconds"%(f.__module__, f.__name__,s))
                     print("Function %s.%s took %s seconds"%(f.__module__, f.__name__,s))
                 else:
                 else:
                     import profile as prof, pstats
                     import profile as prof, pstats

+ 12 - 10
direct/src/showbase/ShowBase.py

@@ -384,18 +384,19 @@ class ShowBase(DirectObject.DirectObject):
 
 
         # Get a pointer to Panda's global ClockObject, used for
         # Get a pointer to Panda's global ClockObject, used for
         # synchronizing events between Python and C.
         # synchronizing events between Python and C.
-        globalClock = ClockObject.getGlobalClock()
+        clock = ClockObject.getGlobalClock()
+        self.clock = clock
 
 
         # Since we have already started up a TaskManager, and probably
         # Since we have already started up a TaskManager, and probably
         # a number of tasks; and since the TaskManager had to use the
         # a number of tasks; and since the TaskManager had to use the
         # TrueClock to tell time until this moment, make sure the
         # TrueClock to tell time until this moment, make sure the
         # globalClock object is exactly in sync with the TrueClock.
         # globalClock object is exactly in sync with the TrueClock.
         trueClock = TrueClock.getGlobalPtr()
         trueClock = TrueClock.getGlobalPtr()
-        globalClock.setRealTime(trueClock.getShortTime())
-        globalClock.tick()
+        clock.setRealTime(trueClock.getShortTime())
+        clock.tick()
 
 
-        # Now we can make the TaskManager start using the new globalClock.
-        taskMgr.globalClock = globalClock
+        # Now we can make the TaskManager start using the new clock.
+        taskMgr.globalClock = clock
 
 
         # client CPU affinity is determined by, in order:
         # client CPU affinity is determined by, in order:
         # - client-cpu-affinity-mask config
         # - client-cpu-affinity-mask config
@@ -444,7 +445,7 @@ class ShowBase(DirectObject.DirectObject):
         builtins.ostream = Notify.out()
         builtins.ostream = Notify.out()
         builtins.directNotify = directNotify
         builtins.directNotify = directNotify
         builtins.giveNotify = giveNotify
         builtins.giveNotify = giveNotify
-        builtins.globalClock = globalClock
+        builtins.globalClock = clock
         builtins.vfs = vfs
         builtins.vfs = vfs
         builtins.cpMgr = ConfigPageManager.getGlobalPtr()
         builtins.cpMgr = ConfigPageManager.getGlobalPtr()
         builtins.cvMgr = ConfigVariableManager.getGlobalPtr()
         builtins.cvMgr = ConfigVariableManager.getGlobalPtr()
@@ -1899,7 +1900,7 @@ class ShowBase(DirectObject.DirectObject):
         return self.physicsMgrEnabled
         return self.physicsMgrEnabled
 
 
     def updateManagers(self, state):
     def updateManagers(self, state):
-        dt = globalClock.getDt()
+        dt = self.clock.dt
         if self.particleMgrEnabled:
         if self.particleMgrEnabled:
             self.particleMgr.doParticles(dt)
             self.particleMgr.doParticles(dt)
         if self.physicsMgrEnabled:
         if self.physicsMgrEnabled:
@@ -2927,14 +2928,15 @@ class ShowBase(DirectObject.DirectObject):
         Returns:
         Returns:
             A `~direct.task.Task` that can be awaited.
             A `~direct.task.Task` that can be awaited.
         """
         """
-        globalClock.setMode(ClockObject.MNonRealTime)
-        globalClock.setDt(1.0/float(fps))
+        clock = self.clock
+        clock.mode = ClockObject.MNonRealTime
+        clock.dt = 1.0 / fps
         t = self.taskMgr.add(self._movieTask, namePrefix + '_task')
         t = self.taskMgr.add(self._movieTask, namePrefix + '_task')
         t.frameIndex = 0  # Frame 0 is not captured.
         t.frameIndex = 0  # Frame 0 is not captured.
         t.numFrames = int(duration * fps)
         t.numFrames = int(duration * fps)
         t.source = source
         t.source = source
         t.outputString = namePrefix + '_%0' + repr(sd) + 'd.' + format
         t.outputString = namePrefix + '_%0' + repr(sd) + 'd.' + format
-        t.setUponDeath(lambda state: globalClock.setMode(ClockObject.MNormal))
+        t.setUponDeath(lambda state: clock.setMode(ClockObject.MNormal))
         return t
         return t
 
 
     def _movieTask(self, state):
     def _movieTask(self, state):

+ 1 - 0
direct/src/showbase/ShowBaseGlobal.py

@@ -33,6 +33,7 @@ ostream = Notify.out()
 
 
 #: The clock object used by default for rendering and animation, obtained using
 #: The clock object used by default for rendering and animation, obtained using
 #: :meth:`panda3d.core.ClockObject.getGlobalClock()`.
 #: :meth:`panda3d.core.ClockObject.getGlobalClock()`.
+#: @deprecated Use `base.clock` instead.
 globalClock = ClockObject.getGlobalClock()
 globalClock = ClockObject.getGlobalClock()
 
 
 #: See :meth:`panda3d.core.ConfigPageManager.getGlobalPtr()`.
 #: See :meth:`panda3d.core.ConfigPageManager.getGlobalPtr()`.

+ 4 - 3
direct/src/showbase/TaskThreaded.py

@@ -5,6 +5,7 @@ __all__ = ['TaskThreaded', 'TaskThread']
 from direct.directnotify.DirectNotifyGlobal import directNotify
 from direct.directnotify.DirectNotifyGlobal import directNotify
 from direct.task import Task
 from direct.task import Task
 from direct.task.TaskManagerGlobal import taskMgr
 from direct.task.TaskManagerGlobal import taskMgr
+from panda3d.core import ClockObject
 
 
 from .PythonUtil import SerialNumGen, Functor
 from .PythonUtil import SerialNumGen, Functor
 
 
@@ -89,14 +90,14 @@ class TaskThreaded:
     def _doCallback(self, callback, taskName, task):
     def _doCallback(self, callback, taskName, task):
         assert self.notify.debugCall()
         assert self.notify.debugCall()
         self.__taskNames.remove(taskName)
         self.__taskNames.remove(taskName)
-        self._taskStartTime = globalClock.getRealTime()
+        self._taskStartTime = ClockObject.getGlobalClock().getRealTime()
         callback()
         callback()
         self._taskStartTime = None
         self._taskStartTime = None
         return Task.done
         return Task.done
 
 
     def _doThreadCallback(self, thread, taskName, task):
     def _doThreadCallback(self, thread, taskName, task):
         assert self.notify.debugCall()
         assert self.notify.debugCall()
-        self._taskStartTime = globalClock.getRealTime()
+        self._taskStartTime = ClockObject.getGlobalClock().getRealTime()
         thread.run()
         thread.run()
         self._taskStartTime = None
         self._taskStartTime = None
         if thread.isFinished():
         if thread.isFinished():
@@ -114,7 +115,7 @@ class TaskThreaded:
             # we must not be in a task callback, we must be running in non-threaded
             # we must not be in a task callback, we must be running in non-threaded
             # mode
             # mode
             return True
             return True
-        return (globalClock.getRealTime() - self._taskStartTime) < self.__timeslice
+        return (ClockObject.getGlobalClock().getRealTime() - self._taskStartTime) < self.__timeslice
 
 
 class TaskThread:
 class TaskThread:
     # derive and override these four funcs
     # derive and override these four funcs

+ 3 - 3
direct/src/task/FrameProfiler.py

@@ -1,4 +1,4 @@
-from panda3d.core import ConfigVariableBool
+from panda3d.core import ConfigVariableBool, ClockObject
 from direct.directnotify.DirectNotifyGlobal import directNotify
 from direct.directnotify.DirectNotifyGlobal import directNotify
 from direct.fsm.StatePush import FunctionCall
 from direct.fsm.StatePush import FunctionCall
 from direct.showbase.PythonUtil import formatTimeExact, normalDistrib, serialNum
 from direct.showbase.PythonUtil import formatTimeExact, normalDistrib, serialNum
@@ -59,7 +59,7 @@ class FrameProfiler:
     def _setEnabled(self, enabled):
     def _setEnabled(self, enabled):
         if enabled:
         if enabled:
             self.notify.info('frame profiler started')
             self.notify.info('frame profiler started')
-            self._startTime = globalClock.getFrameTime()
+            self._startTime = ClockObject.getGlobalClock().getFrameTime()
             self._profileCounter = 0
             self._profileCounter = 0
             self._jitter = None
             self._jitter = None
             self._period2aggregateProfile = {}
             self._period2aggregateProfile = {}
@@ -110,7 +110,7 @@ class FrameProfiler:
             self._analyzeResults, sessionId))
             self._analyzeResults, sessionId))
 
 
         # schedule the next profile
         # schedule the next profile
-        delay = max(time - globalClock.getFrameTime(), 0.)
+        delay = max(time - ClockObject.getGlobalClock().getFrameTime(), 0.)
         self._task = taskMgr.doMethodLater(delay, self._scheduleNextProfileDoLater,
         self._task = taskMgr.doMethodLater(delay, self._scheduleNextProfileDoLater,
                                            'FrameProfiler-%s' % serialNum())
                                            'FrameProfiler-%s' % serialNum())
 
 

+ 5 - 3
direct/src/task/Timer.py

@@ -2,6 +2,8 @@
 
 
 __all__ = ['Timer']
 __all__ = ['Timer']
 
 
+from panda3d.core import ClockObject
+
 from . import Task
 from . import Task
 from .TaskManagerGlobal import taskMgr
 from .TaskManagerGlobal import taskMgr
 
 
@@ -25,7 +27,7 @@ class Timer:
         self.callback = None
         self.callback = None
         self.finalT = t
         self.finalT = t
         self.name = name
         self.name = name
-        self.startT = globalClock.getFrameTime()
+        self.startT = ClockObject.getGlobalClock().getFrameTime()
         self.currT = 0.0
         self.currT = 0.0
         taskMgr.add(self.__timerTask, self.name + '-run')
         taskMgr.add(self.__timerTask, self.name + '-run')
         self.started = 1
         self.started = 1
@@ -35,7 +37,7 @@ class Timer:
             self.stop()
             self.stop()
         self.callback = callback
         self.callback = callback
         self.finalT = t
         self.finalT = t
-        self.startT = globalClock.getFrameTime()
+        self.startT = ClockObject.getGlobalClock().getFrameTime()
         self.currT = 0.0
         self.currT = 0.0
         taskMgr.add(self.__timerTask, self.name + '-run')
         taskMgr.add(self.__timerTask, self.name + '-run')
         self.started = 1
         self.started = 1
@@ -71,7 +73,7 @@ class Timer:
         return self.finalT - self.currT
         return self.finalT - self.currT
 
 
     def __timerTask(self, task):
     def __timerTask(self, task):
-        t = globalClock.getFrameTime()
+        t = ClockObject.getGlobalClock().getFrameTime()
         te = t - self.startT
         te = t - self.startT
         self.currT = te
         self.currT = te
         if te >= self.finalT:
         if te >= self.finalT:

+ 3 - 3
direct/src/tkpanels/AnimPanel.py

@@ -5,7 +5,7 @@ __all__ = ['AnimPanel', 'ActorControl']
 ### SEE END OF FILE FOR EXAMPLE USEAGE ###
 ### SEE END OF FILE FOR EXAMPLE USEAGE ###
 
 
 # Import Tkinter, Pmw, and the floater code from this directory tree.
 # Import Tkinter, Pmw, and the floater code from this directory tree.
-from panda3d.core import Filename, getModelPath
+from panda3d.core import Filename, getModelPath, ClockObject
 from direct.tkwidgets.AppShell import *
 from direct.tkwidgets.AppShell import *
 from direct.showbase.TkGlobal import *
 from direct.showbase.TkGlobal import *
 from direct.task import Task
 from direct.task import Task
@@ -294,7 +294,7 @@ class AnimPanel(AppShell):
 
 
     def playActorControls(self):
     def playActorControls(self):
         self.stopActorControls()
         self.stopActorControls()
-        self.lastT = globalClock.getFrameTime()
+        self.lastT = ClockObject.getGlobalClock().getFrameTime()
         self.playList = self.actorControlList[:]
         self.playList = self.actorControlList[:]
         taskMgr.add(self.play, self.id + '_UpdateTask')
         taskMgr.add(self.play, self.id + '_UpdateTask')
 
 
@@ -302,7 +302,7 @@ class AnimPanel(AppShell):
         if not self.playList:
         if not self.playList:
             return Task.done
             return Task.done
         fLoop = self.loopVar.get()
         fLoop = self.loopVar.get()
-        currT = globalClock.getFrameTime()
+        currT = ClockObject.getGlobalClock().getFrameTime()
         deltaT = currT - self.lastT
         deltaT = currT - self.lastT
         self.lastT = currT
         self.lastT = currT
         for actorControl in self.playList:
         for actorControl in self.playList:

+ 4 - 4
direct/src/tkpanels/MopathRecorder.py

@@ -983,7 +983,7 @@ class MopathRecorder(AppShell, DirectObject):
                 # Start new task
                 # Start new task
                 t = taskMgr.add(
                 t = taskMgr.add(
                     self.recordTask, self.name + '-recordTask')
                     self.recordTask, self.name + '-recordTask')
-                t.startTime = globalClock.getFrameTime()
+                t.startTime = ClockObject.getGlobalClock().getFrameTime()
         else:
         else:
             if self.samplingMode == 'Continuous':
             if self.samplingMode == 'Continuous':
                 # Kill old task
                 # Kill old task
@@ -1016,7 +1016,7 @@ class MopathRecorder(AppShell, DirectObject):
     def recordTask(self, state):
     def recordTask(self, state):
         # Record raw data point
         # Record raw data point
         time = self.recordStart + (
         time = self.recordStart + (
-            globalClock.getFrameTime() - state.startTime)
+            ClockObject.getGlobalClock().getFrameTime() - state.startTime)
         self.recordPoint(time)
         self.recordPoint(time)
         return Task.cont
         return Task.cont
 
 
@@ -1281,7 +1281,7 @@ class MopathRecorder(AppShell, DirectObject):
         t = taskMgr.add(
         t = taskMgr.add(
             self.playbackTask, self.name + '-playbackTask')
             self.playbackTask, self.name + '-playbackTask')
         t.currentTime = self.playbackTime
         t.currentTime = self.playbackTime
-        t.lastTime = globalClock.getFrameTime()
+        t.lastTime = ClockObject.getGlobalClock().getFrameTime()
 
 
     def setSpeedScale(self, value):
     def setSpeedScale(self, value):
         self.speedScale.set(math.log10(value))
         self.speedScale.set(math.log10(value))
@@ -1291,7 +1291,7 @@ class MopathRecorder(AppShell, DirectObject):
         self.speedVar.set('%0.2f' % self.playbackSF)
         self.speedVar.set('%0.2f' % self.playbackSF)
 
 
     def playbackTask(self, state):
     def playbackTask(self, state):
-        time = globalClock.getFrameTime()
+        time = ClockObject.getGlobalClock().getFrameTime()
         dTime = self.playbackSF * (time - state.lastTime)
         dTime = self.playbackSF * (time - state.lastTime)
         state.lastTime = time
         state.lastTime = time
         if self.loopPlayback:
         if self.loopPlayback:

+ 3 - 2
direct/src/tkwidgets/Dial.py

@@ -8,6 +8,7 @@ __all__ = ['Dial', 'AngleDial', 'DialWidget']
 from direct.showbase.TkGlobal import *
 from direct.showbase.TkGlobal import *
 from .Valuator import Valuator, VALUATOR_MINI, VALUATOR_FULL
 from .Valuator import Valuator, VALUATOR_MINI, VALUATOR_FULL
 from direct.task import Task
 from direct.task import Task
+from panda3d.core import ClockObject
 import math
 import math
 import operator
 import operator
 import Pmw
 import Pmw
@@ -335,11 +336,11 @@ class DialWidget(Pmw.MegaWidget):
         self._onButtonPress()
         self._onButtonPress()
         self.knobSF = 0.0
         self.knobSF = 0.0
         self.updateTask = taskMgr.add(self.updateDialTask, 'updateDial')
         self.updateTask = taskMgr.add(self.updateDialTask, 'updateDial')
-        self.updateTask.lastTime = globalClock.getFrameTime()
+        self.updateTask.lastTime = ClockObject.getGlobalClock().getFrameTime()
 
 
     def updateDialTask(self, state):
     def updateDialTask(self, state):
         # Update value
         # Update value
-        currT = globalClock.getFrameTime()
+        currT = ClockObject.getGlobalClock().getFrameTime()
         dt = currT - state.lastTime
         dt = currT - state.lastTime
         self.set(self.value + self.knobSF * dt)
         self.set(self.value + self.knobSF * dt)
         state.lastTime = currT
         state.lastTime = currT

+ 3 - 2
direct/src/tkwidgets/Floater.py

@@ -8,6 +8,7 @@ __all__ = ['Floater', 'FloaterWidget', 'FloaterGroup']
 from direct.showbase.TkGlobal import *
 from direct.showbase.TkGlobal import *
 from .Valuator import Valuator, VALUATOR_MINI, VALUATOR_FULL
 from .Valuator import Valuator, VALUATOR_MINI, VALUATOR_FULL
 from direct.task import Task
 from direct.task import Task
+from panda3d.core import ClockObject
 import math
 import math
 import Pmw
 import Pmw
 
 
@@ -149,14 +150,14 @@ class FloaterWidget(Pmw.MegaWidget):
         self.velocitySF = 0.0
         self.velocitySF = 0.0
         self.updateTask = taskMgr.add(self.updateFloaterTask,
         self.updateTask = taskMgr.add(self.updateFloaterTask,
                                         'updateFloater')
                                         'updateFloater')
-        self.updateTask.lastTime = globalClock.getFrameTime()
+        self.updateTask.lastTime = ClockObject.getGlobalClock().getFrameTime()
 
 
     def updateFloaterTask(self, state):
     def updateFloaterTask(self, state):
         """
         """
         Update floaterWidget value based on current scaleFactor
         Update floaterWidget value based on current scaleFactor
         Adjust for time to compensate for fluctuating frame rates
         Adjust for time to compensate for fluctuating frame rates
         """
         """
-        currT = globalClock.getFrameTime()
+        currT = ClockObject.getGlobalClock().getFrameTime()
         dt = currT - state.lastTime
         dt = currT - state.lastTime
         self.set(self.value + self.velocitySF * dt)
         self.set(self.value + self.velocitySF * dt)
         state.lastTime = currT
         state.lastTime = currT