Task.py 32 KB

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