Task.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  1. """ This module defines a Python-level wrapper around the C++
  2. :class:`~panda3d.core.AsyncTaskManager` interface. It replaces the old
  3. full-Python implementation of the Task system.
  4. For more information about the task system, consult the
  5. :ref:`tasks-and-event-handling` page in the programming manual.
  6. """
  7. __all__ = ['Task', 'TaskManager',
  8. 'cont', 'done', 'again', 'pickup', 'exit',
  9. 'sequence', 'loop', 'pause']
  10. from direct.directnotify.DirectNotifyGlobal import directNotify
  11. from direct.showbase.PythonUtil import Functor, ScratchPad
  12. from direct.showbase.MessengerGlobal import messenger
  13. import types
  14. import random
  15. import importlib
  16. import sys
  17. # On Android, there's no use handling SIGINT, and in fact we can't, since we
  18. # run the application in a separate thread from the main thread.
  19. if hasattr(sys, 'getandroidapilevel'):
  20. signal = None
  21. else:
  22. try:
  23. import _signal as signal
  24. except ImportError:
  25. signal = None
  26. from panda3d.core import (
  27. AsyncTask,
  28. AsyncTaskPause,
  29. AsyncTaskManager,
  30. AsyncTaskSequence,
  31. ClockObject,
  32. ConfigVariableBool,
  33. GlobPattern,
  34. PythonTask,
  35. Thread,
  36. )
  37. from direct.extensions_native import HTTPChannel_extensions # pylint: disable=unused-import
  38. def print_exc_plus():
  39. """
  40. Print the usual traceback information, followed by a listing of all the
  41. local variables in each frame.
  42. """
  43. import traceback
  44. tb = sys.exc_info()[2]
  45. while 1:
  46. if not tb.tb_next:
  47. break
  48. tb = tb.tb_next
  49. stack = []
  50. f = tb.tb_frame
  51. while f:
  52. stack.append(f)
  53. f = f.f_back
  54. stack.reverse()
  55. traceback.print_exc()
  56. print("Locals by frame, innermost last")
  57. for frame in stack:
  58. print("")
  59. print("Frame %s in %s at line %s" % (frame.f_code.co_name,
  60. frame.f_code.co_filename,
  61. frame.f_lineno))
  62. for key, value in list(frame.f_locals.items()):
  63. #We have to be careful not to cause a new error in our error
  64. #printer! Calling str() on an unknown object could cause an
  65. #error we don't want.
  66. try:
  67. valueStr = str(value)
  68. except Exception:
  69. valueStr = "<ERROR WHILE PRINTING VALUE>"
  70. print("\t%20s = %s" % (key, valueStr))
  71. # For historical purposes, we remap the C++-defined enumeration to
  72. # these Python names, and define them both at the module level, here,
  73. # and at the class level (below). The preferred access is via the
  74. # class level.
  75. done = AsyncTask.DSDone
  76. cont = AsyncTask.DSCont
  77. again = AsyncTask.DSAgain
  78. pickup = AsyncTask.DSPickup
  79. exit = AsyncTask.DSExit
  80. #: Task aliases to :class:`panda3d.core.PythonTask` for historical purposes.
  81. Task = PythonTask
  82. # Copy the module-level enums above into the class level. This funny
  83. # syntax is necessary because it's a C++-wrapped extension type, not a
  84. # true Python class.
  85. # We can't override 'done', which is already a known method. We have a
  86. # special check in PythonTask for when the method is being returned.
  87. #Task.DtoolClassDict['done'] = done
  88. Task.DtoolClassDict['cont'] = cont
  89. Task.DtoolClassDict['again'] = again
  90. Task.DtoolClassDict['pickup'] = pickup
  91. Task.DtoolClassDict['exit'] = exit
  92. # Alias the AsyncTaskPause constructor as Task.pause().
  93. pause = AsyncTaskPause
  94. Task.DtoolClassDict['pause'] = staticmethod(pause)
  95. gather = Task.gather
  96. shield = Task.shield
  97. def sequence(*taskList):
  98. seq = AsyncTaskSequence('sequence')
  99. for task in taskList:
  100. seq.addTask(task)
  101. return seq
  102. Task.DtoolClassDict['sequence'] = staticmethod(sequence)
  103. def loop(*taskList):
  104. seq = AsyncTaskSequence('loop')
  105. for task in taskList:
  106. seq.addTask(task)
  107. seq.setRepeatCount(-1)
  108. return seq
  109. Task.DtoolClassDict['loop'] = staticmethod(loop)
  110. class TaskManager:
  111. notify = directNotify.newCategory("TaskManager")
  112. taskTimerVerbose = ConfigVariableBool('task-timer-verbose', False)
  113. extendedExceptions = ConfigVariableBool('extended-exceptions', False)
  114. pStatsTasks = ConfigVariableBool('pstats-tasks', False)
  115. MaxEpochSpeed = 1.0/30.0
  116. def __init__(self):
  117. self.mgr = AsyncTaskManager.getGlobalPtr()
  118. self.resumeFunc = None
  119. self.globalClock = self.mgr.getClock()
  120. self.stepping = False
  121. self.running = False
  122. self.destroyed = False
  123. self.fKeyboardInterrupt = False
  124. self.interruptCount = 0
  125. if signal:
  126. self.__prevHandler = signal.default_int_handler
  127. self._frameProfileQueue = []
  128. # this will be set when it's safe to import StateVar
  129. self._profileFrames = None
  130. self._frameProfiler = None
  131. self._profileTasks = None
  132. self._taskProfiler = None
  133. self._taskProfileInfo = ScratchPad(
  134. taskId = None,
  135. profiled = False,
  136. session = None,
  137. )
  138. def finalInit(self):
  139. # This function should be called once during startup, after
  140. # most things are imported.
  141. from direct.fsm.StatePush import StateVar
  142. self._profileTasks = StateVar(False)
  143. self.setProfileTasks(ConfigVariableBool('profile-task-spikes', 0).getValue())
  144. self._profileFrames = StateVar(False)
  145. self.setProfileFrames(ConfigVariableBool('profile-frames', 0).getValue())
  146. def destroy(self):
  147. # This should be safe to call multiple times.
  148. self.running = False
  149. self.notify.info("TaskManager.destroy()")
  150. self.destroyed = True
  151. self._frameProfileQueue.clear()
  152. self.mgr.cleanup()
  153. def setClock(self, clockObject):
  154. self.mgr.setClock(clockObject)
  155. self.globalClock = clockObject
  156. clock = property(lambda self: self.mgr.getClock(), setClock)
  157. def invokeDefaultHandler(self, signalNumber, stackFrame):
  158. print('*** allowing mid-frame keyboard interrupt.')
  159. # Restore default interrupt handler
  160. if signal:
  161. signal.signal(signal.SIGINT, self.__prevHandler)
  162. # and invoke it
  163. raise KeyboardInterrupt
  164. def keyboardInterruptHandler(self, signalNumber, stackFrame):
  165. self.fKeyboardInterrupt = 1
  166. self.interruptCount += 1
  167. if self.interruptCount == 1:
  168. print('* interrupt by keyboard')
  169. elif self.interruptCount == 2:
  170. print('** waiting for end of frame before interrupting...')
  171. # The user must really want to interrupt this process
  172. # Next time around invoke the default handler
  173. signal.signal(signal.SIGINT, self.invokeDefaultHandler)
  174. def getCurrentTask(self):
  175. """ Returns the task currently executing on this thread, or
  176. None if this is being called outside of the task manager. """
  177. return Thread.getCurrentThread().getCurrentTask()
  178. def hasTaskChain(self, chainName):
  179. """ Returns true if a task chain with the indicated name has
  180. already been defined, or false otherwise. Note that
  181. setupTaskChain() will implicitly define a task chain if it has
  182. not already been defined, or modify an existing one if it has,
  183. so in most cases there is no need to check this method
  184. first. """
  185. return self.mgr.findTaskChain(chainName) is not None
  186. def setupTaskChain(self, chainName, numThreads = None, tickClock = None,
  187. threadPriority = None, frameBudget = None,
  188. frameSync = None, timeslicePriority = None):
  189. """Defines a new task chain. Each task chain executes tasks
  190. potentially in parallel with all of the other task chains (if
  191. numThreads is more than zero). When a new task is created, it
  192. may be associated with any of the task chains, by name (or you
  193. can move a task to another task chain with
  194. task.setTaskChain()). You can have any number of task chains,
  195. but each must have a unique name.
  196. numThreads is the number of threads to allocate for this task
  197. chain. If it is 1 or more, then the tasks on this task chain
  198. will execute in parallel with the tasks on other task chains.
  199. If it is greater than 1, then the tasks on this task chain may
  200. execute in parallel with themselves (within tasks of the same
  201. sort value).
  202. If tickClock is True, then this task chain will be responsible
  203. for ticking the global clock each frame (and thereby
  204. incrementing the frame counter). There should be just one
  205. task chain responsible for ticking the clock, and usually it
  206. is the default, unnamed task chain.
  207. threadPriority specifies the priority level to assign to
  208. threads on this task chain. It may be one of TPLow, TPNormal,
  209. TPHigh, or TPUrgent. This is passed to the underlying
  210. threading system to control the way the threads are scheduled.
  211. frameBudget is the maximum amount of time (in seconds) to
  212. allow this task chain to run per frame. Set it to -1 to mean
  213. no limit (the default). It's not directly related to
  214. threadPriority.
  215. frameSync is true to force the task chain to sync to the
  216. clock. When this flag is false, the default, the task chain
  217. will finish all of its tasks and then immediately start from
  218. the first task again, regardless of the clock frame. When it
  219. is true, the task chain will finish all of its tasks and then
  220. wait for the clock to tick to the next frame before resuming
  221. the first task. This only makes sense for threaded tasks
  222. chains; non-threaded task chains are automatically
  223. synchronous.
  224. timeslicePriority is False in the default mode, in which each
  225. task runs exactly once each frame, round-robin style,
  226. regardless of the task's priority value; or True to change the
  227. meaning of priority so that certain tasks are run less often,
  228. in proportion to their time used and to their priority value.
  229. See AsyncTaskManager.setTimeslicePriority() for more.
  230. """
  231. chain = self.mgr.makeTaskChain(chainName)
  232. if numThreads is not None:
  233. chain.setNumThreads(numThreads)
  234. if tickClock is not None:
  235. chain.setTickClock(tickClock)
  236. if threadPriority is not None:
  237. chain.setThreadPriority(threadPriority)
  238. if frameBudget is not None:
  239. chain.setFrameBudget(frameBudget)
  240. if frameSync is not None:
  241. chain.setFrameSync(frameSync)
  242. if timeslicePriority is not None:
  243. chain.setTimeslicePriority(timeslicePriority)
  244. def hasTaskNamed(self, taskName):
  245. """Returns true if there is at least one task, active or
  246. sleeping, with the indicated name. """
  247. return bool(self.mgr.findTask(taskName))
  248. def getTasksNamed(self, taskName):
  249. """Returns a list of all tasks, active or sleeping, with the
  250. indicated name. """
  251. return list(self.mgr.findTasks(taskName))
  252. def getTasksMatching(self, taskPattern):
  253. """Returns a list of all tasks, active or sleeping, with a
  254. name that matches the pattern, which can include standard
  255. shell globbing characters like \\*, ?, and []. """
  256. return list(self.mgr.findTasksMatching(GlobPattern(taskPattern)))
  257. def getAllTasks(self):
  258. """Returns list of all tasks, active and sleeping, in
  259. arbitrary order. """
  260. return list(self.mgr.getTasks())
  261. def getTasks(self):
  262. """Returns list of all active tasks in arbitrary order. """
  263. return list(self.mgr.getActiveTasks())
  264. def getDoLaters(self):
  265. """Returns list of all sleeping tasks in arbitrary order. """
  266. return list(self.mgr.getSleepingTasks())
  267. def doMethodLater(self, delayTime, funcOrTask, name, extraArgs = None,
  268. sort = None, priority = None, taskChain = None,
  269. uponDeath = None, appendTask = False, owner = None):
  270. """Adds a task to be performed at some time in the future.
  271. This is identical to `add()`, except that the specified
  272. delayTime is applied to the Task object first, which means
  273. that the task will not begin executing until at least the
  274. indicated delayTime (in seconds) has elapsed.
  275. After delayTime has elapsed, the task will become active, and
  276. will run in the soonest possible frame thereafter. If you
  277. wish to specify a task that will run in the next frame, use a
  278. delayTime of 0.
  279. """
  280. if delayTime < 0:
  281. assert self.notify.warning('doMethodLater: added task: %s with negative delay: %s' % (name, delayTime))
  282. task = self.__setupTask(funcOrTask, name, priority, sort, extraArgs, taskChain, appendTask, owner, uponDeath)
  283. task.setDelay(delayTime)
  284. self.mgr.add(task)
  285. return task
  286. do_method_later = doMethodLater
  287. def add(self, funcOrTask, name = None, sort = None, extraArgs = None,
  288. priority = None, uponDeath = None, appendTask = False,
  289. taskChain = None, owner = None, delay = None):
  290. """
  291. Add a new task to the taskMgr. The task will begin executing
  292. immediately, or next frame if its sort value has already
  293. passed this frame.
  294. Parameters:
  295. funcOrTask: either an existing Task object (not already
  296. added to the task manager), or a callable function
  297. object. If this is a function, a new Task object will be
  298. created and returned. You may also pass in a coroutine
  299. object.
  300. name (str): the name to assign to the Task. Required,
  301. unless you are passing in a Task object that already has
  302. a name.
  303. extraArgs (list): the list of arguments to pass to the task
  304. function. If this is omitted, the list is just the task
  305. object itself.
  306. appendTask (bool): If this is true, then the task object
  307. itself will be appended to the end of the extraArgs list
  308. before calling the function.
  309. sort (int): the sort value to assign the task. The default
  310. sort is 0. Within a particular task chain, it is
  311. guaranteed that the tasks with a lower sort value will
  312. all run before tasks with a higher sort value run.
  313. priority (int): the priority at which to run the task. The
  314. default priority is 0. Higher priority tasks are run
  315. sooner, and/or more often. For historical purposes, if
  316. you specify a priority without also specifying a sort,
  317. the priority value is understood to actually be a sort
  318. value. (Previously, there was no priority value, only a
  319. sort value, and it was called "priority".)
  320. uponDeath (bool): a function to call when the task
  321. terminates, either because it has run to completion, or
  322. because it has been explicitly removed.
  323. taskChain (str): the name of the task chain to assign the
  324. task to.
  325. owner: an optional Python object that is declared as the
  326. "owner" of this task for maintenance purposes. The
  327. owner must have two methods:
  328. ``owner._addTask(self, task)``, which is called when the
  329. task begins, and ``owner._clearTask(self, task)``, which
  330. is called when the task terminates. This is all the
  331. ownermeans.
  332. delay: an optional amount of seconds to wait before starting
  333. the task (equivalent to doMethodLater).
  334. Returns:
  335. The new Task object that has been added, or the original
  336. Task object that was passed in.
  337. """
  338. task = self.__setupTask(funcOrTask, name, priority, sort, extraArgs, taskChain, appendTask, owner, uponDeath)
  339. if delay is not None:
  340. task.setDelay(delay)
  341. self.mgr.add(task)
  342. return task
  343. def __setupTask(self, funcOrTask, name, priority, sort, extraArgs, taskChain, appendTask, owner, uponDeath):
  344. wasTask = False
  345. if isinstance(funcOrTask, AsyncTask):
  346. task = funcOrTask
  347. wasTask = True
  348. elif hasattr(funcOrTask, '__call__') or \
  349. hasattr(funcOrTask, 'cr_await') or \
  350. isinstance(funcOrTask, types.GeneratorType):
  351. # It's a function, coroutine, or something emulating a coroutine.
  352. task = PythonTask(funcOrTask)
  353. if name is None:
  354. name = getattr(funcOrTask, '__qualname__', None) or \
  355. getattr(funcOrTask, '__name__', None)
  356. else:
  357. self.notify.error(
  358. 'add: Tried to add a task that was not a Task or a func')
  359. if hasattr(task, 'setArgs'):
  360. # It will only accept arguments if it's a PythonTask.
  361. if extraArgs is None:
  362. if wasTask:
  363. extraArgs = task.getArgs()
  364. #do not append the task to an existing task. It was already there
  365. #from the last time it was addeed
  366. appendTask = False
  367. else:
  368. extraArgs = []
  369. appendTask = True
  370. task.setArgs(extraArgs, appendTask)
  371. elif extraArgs is not None:
  372. self.notify.error(
  373. 'Task %s does not accept arguments.' % (repr(task)))
  374. if name is not None:
  375. task.setName(name)
  376. assert task.hasName()
  377. # For historical reasons, if priority is specified but not
  378. # sort, it really means sort.
  379. if priority is not None and sort is None:
  380. task.setSort(priority)
  381. else:
  382. if priority is not None:
  383. task.setPriority(priority)
  384. if sort is not None:
  385. task.setSort(sort)
  386. if taskChain is not None:
  387. task.setTaskChain(taskChain)
  388. if owner is not None:
  389. task.setOwner(owner)
  390. if uponDeath is not None:
  391. task.setUponDeath(uponDeath)
  392. return task
  393. def remove(self, taskOrName):
  394. """Removes a task from the task manager. The task is stopped,
  395. almost as if it had returned task.done. (But if the task is
  396. currently executing, it will finish out its current frame
  397. before being removed.) You may specify either an explicit
  398. Task object, or the name of a task. If you specify a name,
  399. all tasks with the indicated name are removed. Returns the
  400. number of tasks removed. """
  401. if isinstance(taskOrName, AsyncTask):
  402. return self.mgr.remove(taskOrName)
  403. elif isinstance(taskOrName, list):
  404. for task in taskOrName:
  405. self.remove(task)
  406. else:
  407. tasks = self.mgr.findTasks(taskOrName)
  408. return self.mgr.remove(tasks)
  409. def removeTasksMatching(self, taskPattern):
  410. """Removes all tasks whose names match the pattern, which can
  411. include standard shell globbing characters like \\*, ?, and [].
  412. See also :meth:`remove()`.
  413. Returns the number of tasks removed.
  414. """
  415. tasks = self.mgr.findTasksMatching(GlobPattern(taskPattern))
  416. return self.mgr.remove(tasks)
  417. def step(self):
  418. """Invokes the task manager for one frame, and then returns.
  419. Normally, this executes each task exactly once, though task
  420. chains that are in sub-threads or that have frame budgets
  421. might execute their tasks differently. """
  422. startFrameTime = self.globalClock.getRealTime()
  423. # Replace keyboard interrupt handler during task list processing
  424. # so we catch the keyboard interrupt but don't handle it until
  425. # after task list processing is complete.
  426. self.fKeyboardInterrupt = 0
  427. self.interruptCount = 0
  428. if signal:
  429. self.__prevHandler = signal.signal(signal.SIGINT, self.keyboardInterruptHandler)
  430. try:
  431. self.mgr.poll()
  432. # This is the spot for an internal yield function
  433. nextTaskTime = self.mgr.getNextWakeTime()
  434. self.doYield(startFrameTime, nextTaskTime)
  435. finally:
  436. # Restore previous interrupt handler
  437. if signal:
  438. signal.signal(signal.SIGINT, self.__prevHandler)
  439. self.__prevHandler = signal.default_int_handler
  440. if self.fKeyboardInterrupt:
  441. raise KeyboardInterrupt
  442. def run(self):
  443. """Starts the task manager running. Does not return until an
  444. exception is encountered (including KeyboardInterrupt). """
  445. if sys.platform == 'emscripten':
  446. return
  447. # Set the clock to have last frame's time in case we were
  448. # Paused at the prompt for a long time
  449. t = self.globalClock.getFrameTime()
  450. timeDelta = t - self.globalClock.getRealTime()
  451. self.globalClock.setRealTime(t)
  452. messenger.send("resetClock", [timeDelta])
  453. if self.resumeFunc is not None:
  454. self.resumeFunc()
  455. if self.stepping:
  456. self.step()
  457. else:
  458. self.running = True
  459. while self.running:
  460. try:
  461. if len(self._frameProfileQueue) > 0:
  462. numFrames, session, callback = self._frameProfileQueue.pop(0)
  463. def _profileFunc(numFrames=numFrames):
  464. self._doProfiledFrames(numFrames)
  465. session.setFunc(_profileFunc)
  466. session.run()
  467. _profileFunc = None
  468. if callback:
  469. callback()
  470. session.release()
  471. else:
  472. self.step()
  473. except KeyboardInterrupt:
  474. self.stop()
  475. except SystemExit:
  476. self.stop()
  477. raise
  478. except IOError as ioError:
  479. code, message = self._unpackIOError(ioError)
  480. # Since upgrading to Python 2.4.1, pausing the execution
  481. # often gives this IOError during the sleep function:
  482. # IOError: [Errno 4] Interrupted function call
  483. # So, let's just handle that specific exception and stop.
  484. # All other IOErrors should still get raised.
  485. # Only problem: legit IOError 4s will be obfuscated.
  486. if code == 4:
  487. self.stop()
  488. else:
  489. raise
  490. except Exception as e:
  491. if self.extendedExceptions:
  492. self.stop()
  493. print_exc_plus()
  494. else:
  495. from direct.showbase import ExceptionVarDump
  496. if ExceptionVarDump.wantStackDumpLog and \
  497. ExceptionVarDump.dumpOnExceptionInit:
  498. ExceptionVarDump._varDump__print(e)
  499. raise
  500. except:
  501. if self.extendedExceptions:
  502. self.stop()
  503. print_exc_plus()
  504. else:
  505. raise
  506. self.mgr.stopThreads()
  507. def _unpackIOError(self, ioError):
  508. # IOError unpack from http://www.python.org/doc/essays/stdexceptions/
  509. # this needs to be in its own method, exceptions that occur inside
  510. # a nested try block are not caught by the inner try block's except
  511. try:
  512. (code, message) = ioError
  513. except Exception:
  514. code = 0
  515. message = ioError
  516. return code, message
  517. def stop(self):
  518. # Set a flag so we will stop before beginning next frame
  519. self.running = False
  520. def __tryReplaceTaskMethod(self, task, oldMethod, newFunction):
  521. if not isinstance(task, PythonTask):
  522. return 0
  523. method = task.getFunction()
  524. if isinstance(method, types.MethodType):
  525. function = method.__func__
  526. else:
  527. function = method
  528. if function == oldMethod:
  529. newMethod = types.MethodType(newFunction, method.__self__)
  530. task.setFunction(newMethod)
  531. # Found a match
  532. return 1
  533. return 0
  534. def replaceMethod(self, oldMethod, newFunction):
  535. numFound = 0
  536. for task in self.getAllTasks():
  537. numFound += self.__tryReplaceTaskMethod(task, oldMethod, newFunction)
  538. return numFound
  539. def popupControls(self):
  540. # Don't use a regular import, to prevent ModuleFinder from picking
  541. # it up as a dependency when building a .p3d package.
  542. TaskManagerPanel = importlib.import_module('direct.tkpanels.TaskManagerPanel')
  543. return TaskManagerPanel.TaskManagerPanel(self)
  544. def getProfileSession(self, name=None):
  545. # call to get a profile session that you can modify before passing to profileFrames()
  546. if name is None:
  547. name = 'taskMgrFrameProfile'
  548. # Defer this import until we need it: some Python
  549. # distributions don't provide the profile and pstats modules.
  550. PS = importlib.import_module('direct.showbase.ProfileSession')
  551. return PS.ProfileSession(name)
  552. def profileFrames(self, num=None, session=None, callback=None):
  553. if num is None:
  554. num = 1
  555. if session is None:
  556. session = self.getProfileSession()
  557. # make sure the profile session doesn't get destroyed before we're done with it
  558. session.acquire()
  559. self._frameProfileQueue.append((num, session, callback))
  560. def _doProfiledFrames(self, numFrames):
  561. for i in range(numFrames):
  562. self.step()
  563. def getProfileFrames(self):
  564. return self._profileFrames.get()
  565. def getProfileFramesSV(self):
  566. return self._profileFrames
  567. def setProfileFrames(self, profileFrames):
  568. self._profileFrames.set(profileFrames)
  569. if (not self._frameProfiler) and profileFrames:
  570. # import here due to import dependencies
  571. FP = importlib.import_module('direct.task.FrameProfiler')
  572. self._frameProfiler = FP.FrameProfiler()
  573. def getProfileTasks(self):
  574. return self._profileTasks.get()
  575. def getProfileTasksSV(self):
  576. return self._profileTasks
  577. def setProfileTasks(self, profileTasks):
  578. self._profileTasks.set(profileTasks)
  579. if (not self._taskProfiler) and profileTasks:
  580. # import here due to import dependencies
  581. TP = importlib.import_module('direct.task.TaskProfiler')
  582. self._taskProfiler = TP.TaskProfiler()
  583. def logTaskProfiles(self, name=None):
  584. if self._taskProfiler:
  585. self._taskProfiler.logProfiles(name)
  586. def flushTaskProfiles(self, name=None):
  587. if self._taskProfiler:
  588. self._taskProfiler.flush(name)
  589. def _setProfileTask(self, task):
  590. if self._taskProfileInfo.session:
  591. self._taskProfileInfo.session.release()
  592. self._taskProfileInfo.session = None
  593. self._taskProfileInfo = ScratchPad(
  594. taskFunc = task.getFunction(),
  595. taskArgs = task.getArgs(),
  596. task = task,
  597. profiled = False,
  598. session = None,
  599. )
  600. # Temporarily replace the task's own function with our
  601. # _profileTask method.
  602. task.setFunction(self._profileTask)
  603. task.setArgs([self._taskProfileInfo], True)
  604. def _profileTask(self, profileInfo, task):
  605. # This is called instead of the task function when we have
  606. # decided to profile a task.
  607. assert profileInfo.task == task
  608. # don't profile the same task twice in a row
  609. assert not profileInfo.profiled
  610. # Restore the task's proper function for next time.
  611. appendTask = False
  612. taskArgs = profileInfo.taskArgs
  613. if taskArgs and taskArgs[-1] == task:
  614. appendTask = True
  615. taskArgs = taskArgs[:-1]
  616. task.setArgs(taskArgs, appendTask)
  617. task.setFunction(profileInfo.taskFunc)
  618. # Defer this import until we need it: some Python
  619. # distributions don't provide the profile and pstats modules.
  620. PS = importlib.import_module('direct.showbase.ProfileSession')
  621. profileSession = PS.ProfileSession('profiled-task-%s' % task.getName(),
  622. Functor(profileInfo.taskFunc, *profileInfo.taskArgs))
  623. ret = profileSession.run()
  624. # set these values *after* profiling in case we're profiling the TaskProfiler
  625. profileInfo.session = profileSession
  626. profileInfo.profiled = True
  627. return ret
  628. def _hasProfiledDesignatedTask(self):
  629. # have we run a profile of the designated task yet?
  630. return self._taskProfileInfo.profiled
  631. def _getLastTaskProfileSession(self):
  632. return self._taskProfileInfo.session
  633. def _getRandomTask(self):
  634. # Figure out when the next frame is likely to expire, so we
  635. # won't grab any tasks that are sleeping for a long time.
  636. now = self.globalClock.getFrameTime()
  637. avgFrameRate = self.globalClock.getAverageFrameRate()
  638. if avgFrameRate < .00001:
  639. avgFrameDur = 0.
  640. else:
  641. avgFrameDur = (1. / self.globalClock.getAverageFrameRate())
  642. next = now + avgFrameDur
  643. # Now grab a task at random, until we find one that we like.
  644. tasks = self.mgr.getTasks()
  645. i = random.randrange(tasks.getNumTasks())
  646. task = tasks.getTask(i)
  647. while not isinstance(task, PythonTask) or \
  648. task.getWakeTime() > next:
  649. tasks.removeTask(i)
  650. i = random.randrange(tasks.getNumTasks())
  651. task = tasks.getTask(i)
  652. return task
  653. def __repr__(self):
  654. return str(self.mgr)
  655. # In the event we want to do frame time managment, this is the
  656. # function to replace or overload.
  657. def doYield(self, frameStartTime, nextScheduledTaskTime):
  658. pass
  659. #def doYieldExample(self, frameStartTime, nextScheduledTaskTime):
  660. # minFinTime = frameStartTime + self.MaxEpochSpeed
  661. # if nextScheduledTaskTime > 0 and nextScheduledTaskTime < minFinTime:
  662. # print(' Adjusting Time')
  663. # minFinTime = nextScheduledTaskTime
  664. # delta = minFinTime - self.globalClock.getRealTime()
  665. # while delta > 0.002:
  666. # print ' sleep %s'% (delta)
  667. # time.sleep(delta)
  668. # delta = minFinTime - self.globalClock.getRealTime()
  669. if __debug__:
  670. def checkLeak():
  671. import gc
  672. gc.enable()
  673. from direct.showbase.DirectObject import DirectObject
  674. from direct.task.TaskManagerGlobal import taskMgr
  675. class TestClass(DirectObject):
  676. def doTask(self, task):
  677. return task.done
  678. obj = TestClass()
  679. startRefCount = sys.getrefcount(obj)
  680. print('sys.getrefcount(obj): %s' % sys.getrefcount(obj))
  681. print('** addTask')
  682. t = obj.addTask(obj.doTask, 'test')
  683. print('sys.getrefcount(obj): %s' % sys.getrefcount(obj))
  684. print('task.getRefCount(): %s' % t.getRefCount())
  685. print('** removeTask')
  686. obj.removeTask('test')
  687. print('sys.getrefcount(obj): %s' % sys.getrefcount(obj))
  688. print('task.getRefCount(): %s' % t.getRefCount())
  689. print('** step')
  690. taskMgr.step()
  691. taskMgr.step()
  692. taskMgr.step()
  693. print('sys.getrefcount(obj): %s' % sys.getrefcount(obj))
  694. print('task.getRefCount(): %s' % t.getRefCount())
  695. print('** task release')
  696. t = None
  697. print('sys.getrefcount(obj): %s' % sys.getrefcount(obj))
  698. assert sys.getrefcount(obj) == startRefCount