Task.py 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302
  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 *
  11. from direct.showbase import ExceptionVarDump
  12. from direct.showbase.PythonUtil import *
  13. from direct.showbase.MessengerGlobal import messenger
  14. import types
  15. import random
  16. import importlib
  17. try:
  18. import signal
  19. except ImportError:
  20. signal = None
  21. from panda3d.core import *
  22. from direct.extensions_native import HTTPChannel_extensions
  23. def print_exc_plus():
  24. """
  25. Print the usual traceback information, followed by a listing of all the
  26. local variables in each frame.
  27. """
  28. import sys
  29. import traceback
  30. tb = sys.exc_info()[2]
  31. while 1:
  32. if not tb.tb_next:
  33. break
  34. tb = tb.tb_next
  35. stack = []
  36. f = tb.tb_frame
  37. while f:
  38. stack.append(f)
  39. f = f.f_back
  40. stack.reverse()
  41. traceback.print_exc()
  42. print("Locals by frame, innermost last")
  43. for frame in stack:
  44. print("")
  45. print("Frame %s in %s at line %s" % (frame.f_code.co_name,
  46. frame.f_code.co_filename,
  47. frame.f_lineno))
  48. for key, value in list(frame.f_locals.items()):
  49. #We have to be careful not to cause a new error in our error
  50. #printer! Calling str() on an unknown object could cause an
  51. #error we don't want.
  52. try:
  53. valueStr = str(value)
  54. except:
  55. valueStr = "<ERROR WHILE PRINTING VALUE>"
  56. print("\t%20s = %s" % (key, valueStr))
  57. # For historical purposes, we remap the C++-defined enumeration to
  58. # these Python names, and define them both at the module level, here,
  59. # and at the class level (below). The preferred access is via the
  60. # class level.
  61. done = AsyncTask.DSDone
  62. cont = AsyncTask.DSCont
  63. again = AsyncTask.DSAgain
  64. pickup = AsyncTask.DSPickup
  65. exit = AsyncTask.DSExit
  66. #: Task aliases to :class:`panda3d.core.PythonTask` for historical purposes.
  67. Task = PythonTask
  68. # Copy the module-level enums above into the class level. This funny
  69. # syntax is necessary because it's a C++-wrapped extension type, not a
  70. # true Python class.
  71. # We can't override 'done', which is already a known method. We have a
  72. # special check in PythonTask for when the method is being returned.
  73. #Task.DtoolClassDict['done'] = done
  74. Task.DtoolClassDict['cont'] = cont
  75. Task.DtoolClassDict['again'] = again
  76. Task.DtoolClassDict['pickup'] = pickup
  77. Task.DtoolClassDict['exit'] = exit
  78. # Alias the AsyncTaskPause constructor as Task.pause().
  79. pause = AsyncTaskPause
  80. Task.DtoolClassDict['pause'] = staticmethod(pause)
  81. gather = Task.gather
  82. def sequence(*taskList):
  83. seq = AsyncTaskSequence('sequence')
  84. for task in taskList:
  85. seq.addTask(task)
  86. return seq
  87. Task.DtoolClassDict['sequence'] = staticmethod(sequence)
  88. def loop(*taskList):
  89. seq = AsyncTaskSequence('loop')
  90. for task in taskList:
  91. seq.addTask(task)
  92. seq.setRepeatCount(-1)
  93. return seq
  94. Task.DtoolClassDict['loop'] = staticmethod(loop)
  95. class TaskManager:
  96. notify = directNotify.newCategory("TaskManager")
  97. taskTimerVerbose = ConfigVariableBool('task-timer-verbose', False)
  98. extendedExceptions = ConfigVariableBool('extended-exceptions', False)
  99. pStatsTasks = ConfigVariableBool('pstats-tasks', False)
  100. MaxEpochSpeed = 1.0/30.0
  101. def __init__(self):
  102. self.mgr = AsyncTaskManager.getGlobalPtr()
  103. self.resumeFunc = None
  104. self.globalClock = self.mgr.getClock()
  105. self.stepping = False
  106. self.running = False
  107. self.destroyed = False
  108. self.fKeyboardInterrupt = False
  109. self.interruptCount = 0
  110. self._frameProfileQueue = []
  111. # this will be set when it's safe to import StateVar
  112. self._profileFrames = None
  113. self._frameProfiler = None
  114. self._profileTasks = None
  115. self._taskProfiler = None
  116. self._taskProfileInfo = ScratchPad(
  117. taskId = None,
  118. profiled = False,
  119. session = None,
  120. )
  121. def finalInit(self):
  122. # This function should be called once during startup, after
  123. # most things are imported.
  124. from direct.fsm.StatePush import StateVar
  125. self._profileTasks = StateVar(False)
  126. self.setProfileTasks(ConfigVariableBool('profile-task-spikes', 0).getValue())
  127. self._profileFrames = StateVar(False)
  128. self.setProfileFrames(ConfigVariableBool('profile-frames', 0).getValue())
  129. def destroy(self):
  130. # This should be safe to call multiple times.
  131. self.running = False
  132. self.notify.info("TaskManager.destroy()")
  133. self.destroyed = True
  134. self._frameProfileQueue.clear()
  135. self.mgr.cleanup()
  136. def setClock(self, clockObject):
  137. self.mgr.setClock(clockObject)
  138. self.globalClock = clockObject
  139. clock = property(lambda self: self.mgr.getClock(), setClock)
  140. def invokeDefaultHandler(self, signalNumber, stackFrame):
  141. print('*** allowing mid-frame keyboard interrupt.')
  142. # Restore default interrupt handler
  143. if signal:
  144. signal.signal(signal.SIGINT, signal.default_int_handler)
  145. # and invoke it
  146. raise KeyboardInterrupt
  147. def keyboardInterruptHandler(self, signalNumber, stackFrame):
  148. self.fKeyboardInterrupt = 1
  149. self.interruptCount += 1
  150. if self.interruptCount == 1:
  151. print('* interrupt by keyboard')
  152. elif self.interruptCount == 2:
  153. print('** waiting for end of frame before interrupting...')
  154. # The user must really want to interrupt this process
  155. # Next time around invoke the default handler
  156. signal.signal(signal.SIGINT, self.invokeDefaultHandler)
  157. def getCurrentTask(self):
  158. """ Returns the task currently executing on this thread, or
  159. None if this is being called outside of the task manager. """
  160. return Thread.getCurrentThread().getCurrentTask()
  161. def hasTaskChain(self, chainName):
  162. """ Returns true if a task chain with the indicated name has
  163. already been defined, or false otherwise. Note that
  164. setupTaskChain() will implicitly define a task chain if it has
  165. not already been defined, or modify an existing one if it has,
  166. so in most cases there is no need to check this method
  167. first. """
  168. return (self.mgr.findTaskChain(chainName) != None)
  169. def setupTaskChain(self, chainName, numThreads = None, tickClock = None,
  170. threadPriority = None, frameBudget = None,
  171. frameSync = None, timeslicePriority = None):
  172. """Defines a new task chain. Each task chain executes tasks
  173. potentially in parallel with all of the other task chains (if
  174. numThreads is more than zero). When a new task is created, it
  175. may be associated with any of the task chains, by name (or you
  176. can move a task to another task chain with
  177. task.setTaskChain()). You can have any number of task chains,
  178. but each must have a unique name.
  179. numThreads is the number of threads to allocate for this task
  180. chain. If it is 1 or more, then the tasks on this task chain
  181. will execute in parallel with the tasks on other task chains.
  182. If it is greater than 1, then the tasks on this task chain may
  183. execute in parallel with themselves (within tasks of the same
  184. sort value).
  185. If tickClock is True, then this task chain will be responsible
  186. for ticking the global clock each frame (and thereby
  187. incrementing the frame counter). There should be just one
  188. task chain responsible for ticking the clock, and usually it
  189. is the default, unnamed task chain.
  190. threadPriority specifies the priority level to assign to
  191. threads on this task chain. It may be one of TPLow, TPNormal,
  192. TPHigh, or TPUrgent. This is passed to the underlying
  193. threading system to control the way the threads are scheduled.
  194. frameBudget is the maximum amount of time (in seconds) to
  195. allow this task chain to run per frame. Set it to -1 to mean
  196. no limit (the default). It's not directly related to
  197. threadPriority.
  198. frameSync is true to force the task chain to sync to the
  199. clock. When this flag is false, the default, the task chain
  200. will finish all of its tasks and then immediately start from
  201. the first task again, regardless of the clock frame. When it
  202. is true, the task chain will finish all of its tasks and then
  203. wait for the clock to tick to the next frame before resuming
  204. the first task. This only makes sense for threaded tasks
  205. chains; non-threaded task chains are automatically
  206. synchronous.
  207. timeslicePriority is False in the default mode, in which each
  208. task runs exactly once each frame, round-robin style,
  209. regardless of the task's priority value; or True to change the
  210. meaning of priority so that certain tasks are run less often,
  211. in proportion to their time used and to their priority value.
  212. See AsyncTaskManager.setTimeslicePriority() for more.
  213. """
  214. chain = self.mgr.makeTaskChain(chainName)
  215. if numThreads is not None:
  216. chain.setNumThreads(numThreads)
  217. if tickClock is not None:
  218. chain.setTickClock(tickClock)
  219. if threadPriority is not None:
  220. chain.setThreadPriority(threadPriority)
  221. if frameBudget is not None:
  222. chain.setFrameBudget(frameBudget)
  223. if frameSync is not None:
  224. chain.setFrameSync(frameSync)
  225. if timeslicePriority is not None:
  226. chain.setTimeslicePriority(timeslicePriority)
  227. def hasTaskNamed(self, taskName):
  228. """Returns true if there is at least one task, active or
  229. sleeping, with the indicated name. """
  230. return bool(self.mgr.findTask(taskName))
  231. def getTasksNamed(self, taskName):
  232. """Returns a list of all tasks, active or sleeping, with the
  233. indicated name. """
  234. return self.__makeTaskList(self.mgr.findTasks(taskName))
  235. def getTasksMatching(self, taskPattern):
  236. """Returns a list of all tasks, active or sleeping, with a
  237. name that matches the pattern, which can include standard
  238. shell globbing characters like \\*, ?, and []. """
  239. return self.__makeTaskList(self.mgr.findTasksMatching(GlobPattern(taskPattern)))
  240. def getAllTasks(self):
  241. """Returns list of all tasks, active and sleeping, in
  242. arbitrary order. """
  243. return self.__makeTaskList(self.mgr.getTasks())
  244. def getTasks(self):
  245. """Returns list of all active tasks in arbitrary order. """
  246. return self.__makeTaskList(self.mgr.getActiveTasks())
  247. def getDoLaters(self):
  248. """Returns list of all sleeping tasks in arbitrary order. """
  249. return self.__makeTaskList(self.mgr.getSleepingTasks())
  250. def __makeTaskList(self, taskCollection):
  251. l = []
  252. for i in range(taskCollection.getNumTasks()):
  253. l.append(taskCollection.getTask(i))
  254. return l
  255. def doMethodLater(self, delayTime, funcOrTask, name, extraArgs = None,
  256. sort = None, priority = None, taskChain = None,
  257. uponDeath = None, appendTask = False, owner = None):
  258. """Adds a task to be performed at some time in the future.
  259. This is identical to `add()`, except that the specified
  260. delayTime is applied to the Task object first, which means
  261. that the task will not begin executing until at least the
  262. indicated delayTime (in seconds) has elapsed.
  263. After delayTime has elapsed, the task will become active, and
  264. will run in the soonest possible frame thereafter. If you
  265. wish to specify a task that will run in the next frame, use a
  266. delayTime of 0.
  267. """
  268. if delayTime < 0:
  269. assert self.notify.warning('doMethodLater: added task: %s with negative delay: %s' % (name, delayTime))
  270. task = self.__setupTask(funcOrTask, name, priority, sort, extraArgs, taskChain, appendTask, owner, uponDeath)
  271. task.setDelay(delayTime)
  272. self.mgr.add(task)
  273. return task
  274. do_method_later = doMethodLater
  275. def add(self, funcOrTask, name = None, sort = None, extraArgs = None,
  276. priority = None, uponDeath = None, appendTask = False,
  277. taskChain = None, owner = None):
  278. """
  279. Add a new task to the taskMgr. The task will begin executing
  280. immediately, or next frame if its sort value has already
  281. passed this frame.
  282. Parameters:
  283. funcOrTask: either an existing Task object (not already
  284. added to the task manager), or a callable function
  285. object. If this is a function, a new Task object will be
  286. created and returned. You may also pass in a coroutine
  287. object.
  288. name (str): the name to assign to the Task. Required,
  289. unless you are passing in a Task object that already has
  290. a name.
  291. extraArgs (list): the list of arguments to pass to the task
  292. function. If this is omitted, the list is just the task
  293. object itself.
  294. appendTask (bool): If this is true, then the task object
  295. itself will be appended to the end of the extraArgs list
  296. before calling the function.
  297. sort (int): the sort value to assign the task. The default
  298. sort is 0. Within a particular task chain, it is
  299. guaranteed that the tasks with a lower sort value will
  300. all run before tasks with a higher sort value run.
  301. priority (int): the priority at which to run the task. The
  302. default priority is 0. Higher priority tasks are run
  303. sooner, and/or more often. For historical purposes, if
  304. you specify a priority without also specifying a sort,
  305. the priority value is understood to actually be a sort
  306. value. (Previously, there was no priority value, only a
  307. sort value, and it was called "priority".)
  308. uponDeath (bool): a function to call when the task
  309. terminates, either because it has run to completion, or
  310. because it has been explicitly removed.
  311. taskChain (str): the name of the task chain to assign the
  312. task to.
  313. owner: an optional Python object that is declared as the
  314. "owner" of this task for maintenance purposes. The
  315. owner must have two methods:
  316. ``owner._addTask(self, task)``, which is called when the
  317. task begins, and ``owner._clearTask(self, task)``, which
  318. is called when the task terminates. This is all the
  319. ownermeans.
  320. Returns:
  321. The new Task object that has been added, or the original
  322. Task object that was passed in.
  323. """
  324. task = self.__setupTask(funcOrTask, name, priority, sort, extraArgs, taskChain, appendTask, owner, uponDeath)
  325. self.mgr.add(task)
  326. return task
  327. def __setupTask(self, funcOrTask, name, priority, sort, extraArgs, taskChain, appendTask, owner, uponDeath):
  328. if isinstance(funcOrTask, AsyncTask):
  329. task = funcOrTask
  330. elif hasattr(funcOrTask, '__call__'):
  331. task = PythonTask(funcOrTask)
  332. if name is None:
  333. name = getattr(funcOrTask, '__qualname__', None) or \
  334. getattr(funcOrTask, '__name__', None)
  335. elif hasattr(funcOrTask, 'cr_await') or type(funcOrTask) == types.GeneratorType:
  336. # It's a coroutine, or something emulating one.
  337. task = PythonTask(funcOrTask)
  338. if name is None:
  339. name = getattr(funcOrTask, '__qualname__', None) or \
  340. getattr(funcOrTask, '__name__', None)
  341. else:
  342. self.notify.error(
  343. 'add: Tried to add a task that was not a Task or a func')
  344. if hasattr(task, 'setArgs'):
  345. # It will only accept arguments if it's a PythonTask.
  346. if extraArgs is None:
  347. extraArgs = []
  348. appendTask = True
  349. task.setArgs(extraArgs, appendTask)
  350. elif extraArgs is not None:
  351. self.notify.error(
  352. 'Task %s does not accept arguments.' % (repr(task)))
  353. if name is not None:
  354. task.setName(name)
  355. assert task.hasName()
  356. # For historical reasons, if priority is specified but not
  357. # sort, it really means sort.
  358. if priority is not None and sort is None:
  359. task.setSort(priority)
  360. else:
  361. if priority is not None:
  362. task.setPriority(priority)
  363. if sort is not None:
  364. task.setSort(sort)
  365. if taskChain is not None:
  366. task.setTaskChain(taskChain)
  367. if owner is not None:
  368. task.setOwner(owner)
  369. if uponDeath is not None:
  370. task.setUponDeath(uponDeath)
  371. return task
  372. def remove(self, taskOrName):
  373. """Removes a task from the task manager. The task is stopped,
  374. almost as if it had returned task.done. (But if the task is
  375. currently executing, it will finish out its current frame
  376. before being removed.) You may specify either an explicit
  377. Task object, or the name of a task. If you specify a name,
  378. all tasks with the indicated name are removed. Returns the
  379. number of tasks removed. """
  380. if isinstance(taskOrName, AsyncTask):
  381. return self.mgr.remove(taskOrName)
  382. elif isinstance(taskOrName, list):
  383. for task in taskOrName:
  384. self.remove(task)
  385. else:
  386. tasks = self.mgr.findTasks(taskOrName)
  387. return self.mgr.remove(tasks)
  388. def removeTasksMatching(self, taskPattern):
  389. """Removes all tasks whose names match the pattern, which can
  390. include standard shell globbing characters like \\*, ?, and [].
  391. See also :meth:`remove()`.
  392. Returns the number of tasks removed.
  393. """
  394. tasks = self.mgr.findTasksMatching(GlobPattern(taskPattern))
  395. return self.mgr.remove(tasks)
  396. def step(self):
  397. """Invokes the task manager for one frame, and then returns.
  398. Normally, this executes each task exactly once, though task
  399. chains that are in sub-threads or that have frame budgets
  400. might execute their tasks differently. """
  401. # Replace keyboard interrupt handler during task list processing
  402. # so we catch the keyboard interrupt but don't handle it until
  403. # after task list processing is complete.
  404. self.fKeyboardInterrupt = 0
  405. self.interruptCount = 0
  406. if signal:
  407. signal.signal(signal.SIGINT, self.keyboardInterruptHandler)
  408. startFrameTime = self.globalClock.getRealTime()
  409. self.mgr.poll()
  410. # This is the spot for an internal yield function
  411. nextTaskTime = self.mgr.getNextWakeTime()
  412. self.doYield(startFrameTime, nextTaskTime)
  413. # Restore default interrupt handler
  414. if signal:
  415. signal.signal(signal.SIGINT, signal.default_int_handler)
  416. if self.fKeyboardInterrupt:
  417. raise KeyboardInterrupt
  418. def run(self):
  419. """Starts the task manager running. Does not return until an
  420. exception is encountered (including KeyboardInterrupt). """
  421. if PandaSystem.getPlatform() == 'emscripten':
  422. return
  423. # Set the clock to have last frame's time in case we were
  424. # Paused at the prompt for a long time
  425. t = self.globalClock.getFrameTime()
  426. timeDelta = t - self.globalClock.getRealTime()
  427. self.globalClock.setRealTime(t)
  428. messenger.send("resetClock", [timeDelta])
  429. if self.resumeFunc != None:
  430. self.resumeFunc()
  431. if self.stepping:
  432. self.step()
  433. else:
  434. self.running = True
  435. while self.running:
  436. try:
  437. if len(self._frameProfileQueue):
  438. numFrames, session, callback = self._frameProfileQueue.pop(0)
  439. def _profileFunc(numFrames=numFrames):
  440. self._doProfiledFrames(numFrames)
  441. session.setFunc(_profileFunc)
  442. session.run()
  443. _profileFunc = None
  444. if callback:
  445. callback()
  446. session.release()
  447. else:
  448. self.step()
  449. except KeyboardInterrupt:
  450. self.stop()
  451. except SystemExit:
  452. self.stop()
  453. raise
  454. except IOError as ioError:
  455. code, message = self._unpackIOError(ioError)
  456. # Since upgrading to Python 2.4.1, pausing the execution
  457. # often gives this IOError during the sleep function:
  458. # IOError: [Errno 4] Interrupted function call
  459. # So, let's just handle that specific exception and stop.
  460. # All other IOErrors should still get raised.
  461. # Only problem: legit IOError 4s will be obfuscated.
  462. if code == 4:
  463. self.stop()
  464. else:
  465. raise
  466. except Exception as e:
  467. if self.extendedExceptions:
  468. self.stop()
  469. print_exc_plus()
  470. else:
  471. if (ExceptionVarDump.wantStackDumpLog and
  472. ExceptionVarDump.dumpOnExceptionInit):
  473. ExceptionVarDump._varDump__print(e)
  474. raise
  475. except:
  476. if self.extendedExceptions:
  477. self.stop()
  478. print_exc_plus()
  479. else:
  480. raise
  481. self.mgr.stopThreads()
  482. def _unpackIOError(self, ioError):
  483. # IOError unpack from http://www.python.org/doc/essays/stdexceptions/
  484. # this needs to be in its own method, exceptions that occur inside
  485. # a nested try block are not caught by the inner try block's except
  486. try:
  487. (code, message) = ioError
  488. except:
  489. code = 0
  490. message = ioError
  491. return code, message
  492. def stop(self):
  493. # Set a flag so we will stop before beginning next frame
  494. self.running = False
  495. def __tryReplaceTaskMethod(self, task, oldMethod, newFunction):
  496. if not isinstance(task, PythonTask):
  497. return 0
  498. method = task.getFunction()
  499. if (type(method) == types.MethodType):
  500. function = method.__func__
  501. else:
  502. function = method
  503. if (function == oldMethod):
  504. newMethod = types.MethodType(newFunction,
  505. method.__self__,
  506. method.__self__.__class__)
  507. task.setFunction(newMethod)
  508. # Found a match
  509. return 1
  510. return 0
  511. def replaceMethod(self, oldMethod, newFunction):
  512. numFound = 0
  513. for task in self.getAllTasks():
  514. numFound += self.__tryReplaceTaskMethod(task, oldMethod, newFunction)
  515. return numFound
  516. def popupControls(self):
  517. # Don't use a regular import, to prevent ModuleFinder from picking
  518. # it up as a dependency when building a .p3d package.
  519. TaskManagerPanel = importlib.import_module('direct.tkpanels.TaskManagerPanel')
  520. return TaskManagerPanel.TaskManagerPanel(self)
  521. def getProfileSession(self, name=None):
  522. # call to get a profile session that you can modify before passing to profileFrames()
  523. if name is None:
  524. name = 'taskMgrFrameProfile'
  525. # Defer this import until we need it: some Python
  526. # distributions don't provide the profile and pstats modules.
  527. PS = importlib.import_module('direct.showbase.ProfileSession')
  528. return PS.ProfileSession(name)
  529. def profileFrames(self, num=None, session=None, callback=None):
  530. if num is None:
  531. num = 1
  532. if session is None:
  533. session = self.getProfileSession()
  534. # make sure the profile session doesn't get destroyed before we're done with it
  535. session.acquire()
  536. self._frameProfileQueue.append((num, session, callback))
  537. def _doProfiledFrames(self, numFrames):
  538. for i in range(numFrames):
  539. result = self.step()
  540. return result
  541. def getProfileFrames(self):
  542. return self._profileFrames.get()
  543. def getProfileFramesSV(self):
  544. return self._profileFrames
  545. def setProfileFrames(self, profileFrames):
  546. self._profileFrames.set(profileFrames)
  547. if (not self._frameProfiler) and profileFrames:
  548. # import here due to import dependencies
  549. FP = importlib.import_module('direct.task.FrameProfiler')
  550. self._frameProfiler = FP.FrameProfiler()
  551. def getProfileTasks(self):
  552. return self._profileTasks.get()
  553. def getProfileTasksSV(self):
  554. return self._profileTasks
  555. def setProfileTasks(self, profileTasks):
  556. self._profileTasks.set(profileTasks)
  557. if (not self._taskProfiler) and profileTasks:
  558. # import here due to import dependencies
  559. TP = importlib.import_module('direct.task.TaskProfiler')
  560. self._taskProfiler = TP.TaskProfiler()
  561. def logTaskProfiles(self, name=None):
  562. if self._taskProfiler:
  563. self._taskProfiler.logProfiles(name)
  564. def flushTaskProfiles(self, name=None):
  565. if self._taskProfiler:
  566. self._taskProfiler.flush(name)
  567. def _setProfileTask(self, task):
  568. if self._taskProfileInfo.session:
  569. self._taskProfileInfo.session.release()
  570. self._taskProfileInfo.session = None
  571. self._taskProfileInfo = ScratchPad(
  572. taskFunc = task.getFunction(),
  573. taskArgs = task.getArgs(),
  574. task = task,
  575. profiled = False,
  576. session = None,
  577. )
  578. # Temporarily replace the task's own function with our
  579. # _profileTask method.
  580. task.setFunction(self._profileTask)
  581. task.setArgs([self._taskProfileInfo], True)
  582. def _profileTask(self, profileInfo, task):
  583. # This is called instead of the task function when we have
  584. # decided to profile a task.
  585. assert profileInfo.task == task
  586. # don't profile the same task twice in a row
  587. assert not profileInfo.profiled
  588. # Restore the task's proper function for next time.
  589. appendTask = False
  590. taskArgs = profileInfo.taskArgs
  591. if taskArgs and taskArgs[-1] == task:
  592. appendTask = True
  593. taskArgs = taskArgs[:-1]
  594. task.setArgs(taskArgs, appendTask)
  595. task.setFunction(profileInfo.taskFunc)
  596. # Defer this import until we need it: some Python
  597. # distributions don't provide the profile and pstats modules.
  598. PS = importlib.import_module('direct.showbase.ProfileSession')
  599. profileSession = PS.ProfileSession('profiled-task-%s' % task.getName(),
  600. Functor(profileInfo.taskFunc, *profileInfo.taskArgs))
  601. ret = profileSession.run()
  602. # set these values *after* profiling in case we're profiling the TaskProfiler
  603. profileInfo.session = profileSession
  604. profileInfo.profiled = True
  605. return ret
  606. def _hasProfiledDesignatedTask(self):
  607. # have we run a profile of the designated task yet?
  608. return self._taskProfileInfo.profiled
  609. def _getLastTaskProfileSession(self):
  610. return self._taskProfileInfo.session
  611. def _getRandomTask(self):
  612. # Figure out when the next frame is likely to expire, so we
  613. # won't grab any tasks that are sleeping for a long time.
  614. now = self.globalClock.getFrameTime()
  615. avgFrameRate = self.globalClock.getAverageFrameRate()
  616. if avgFrameRate < .00001:
  617. avgFrameDur = 0.
  618. else:
  619. avgFrameDur = (1. / self.globalClock.getAverageFrameRate())
  620. next = now + avgFrameDur
  621. # Now grab a task at random, until we find one that we like.
  622. tasks = self.mgr.getTasks()
  623. i = random.randrange(tasks.getNumTasks())
  624. task = tasks.getTask(i)
  625. while not isinstance(task, PythonTask) or \
  626. task.getWakeTime() > next:
  627. tasks.removeTask(i)
  628. i = random.randrange(tasks.getNumTasks())
  629. task = tasks.getTask(i)
  630. return task
  631. def __repr__(self):
  632. return str(self.mgr)
  633. # In the event we want to do frame time managment, this is the
  634. # function to replace or overload.
  635. def doYield(self, frameStartTime, nextScheduledTaskTime):
  636. pass
  637. """
  638. def doYieldExample(self, frameStartTime, nextScheduledTaskTime):
  639. minFinTime = frameStartTime + self.MaxEpochSpeed
  640. if nextScheduledTaskTime > 0 and nextScheduledTaskTime < minFinTime:
  641. print ' Adjusting Time'
  642. minFinTime = nextScheduledTaskTime
  643. delta = minFinTime - self.globalClock.getRealTime()
  644. while(delta > 0.002):
  645. print ' sleep %s'% (delta)
  646. time.sleep(delta)
  647. delta = minFinTime - self.globalClock.getRealTime()
  648. """
  649. if __debug__:
  650. # to catch memory leaks during the tests at the bottom of the file
  651. def _startTrackingMemLeaks(self):
  652. pass
  653. def _stopTrackingMemLeaks(self):
  654. pass
  655. def _checkMemLeaks(self):
  656. pass
  657. def _runTests(self):
  658. if __debug__:
  659. tm = TaskManager()
  660. tm.setClock(ClockObject())
  661. tm.setupTaskChain("default", tickClock = True)
  662. # check for memory leaks after every test
  663. tm._startTrackingMemLeaks()
  664. tm._checkMemLeaks()
  665. # run-once task
  666. l = []
  667. def _testDone(task, l=l):
  668. l.append(None)
  669. return task.done
  670. tm.add(_testDone, 'testDone')
  671. tm.step()
  672. assert len(l) == 1
  673. tm.step()
  674. assert len(l) == 1
  675. _testDone = None
  676. tm._checkMemLeaks()
  677. # remove by name
  678. def _testRemoveByName(task):
  679. return task.done
  680. tm.add(_testRemoveByName, 'testRemoveByName')
  681. assert tm.remove('testRemoveByName') == 1
  682. assert tm.remove('testRemoveByName') == 0
  683. _testRemoveByName = None
  684. tm._checkMemLeaks()
  685. # duplicate named tasks
  686. def _testDupNamedTasks(task):
  687. return task.done
  688. tm.add(_testDupNamedTasks, 'testDupNamedTasks')
  689. tm.add(_testDupNamedTasks, 'testDupNamedTasks')
  690. assert tm.remove('testRemoveByName') == 0
  691. _testDupNamedTasks = None
  692. tm._checkMemLeaks()
  693. # continued task
  694. l = []
  695. def _testCont(task, l = l):
  696. l.append(None)
  697. return task.cont
  698. tm.add(_testCont, 'testCont')
  699. tm.step()
  700. assert len(l) == 1
  701. tm.step()
  702. assert len(l) == 2
  703. tm.remove('testCont')
  704. _testCont = None
  705. tm._checkMemLeaks()
  706. # continue until done task
  707. l = []
  708. def _testContDone(task, l = l):
  709. l.append(None)
  710. if len(l) >= 2:
  711. return task.done
  712. else:
  713. return task.cont
  714. tm.add(_testContDone, 'testContDone')
  715. tm.step()
  716. assert len(l) == 1
  717. tm.step()
  718. assert len(l) == 2
  719. tm.step()
  720. assert len(l) == 2
  721. assert not tm.hasTaskNamed('testContDone')
  722. _testContDone = None
  723. tm._checkMemLeaks()
  724. # hasTaskNamed
  725. def _testHasTaskNamed(task):
  726. return task.done
  727. tm.add(_testHasTaskNamed, 'testHasTaskNamed')
  728. assert tm.hasTaskNamed('testHasTaskNamed')
  729. tm.step()
  730. assert not tm.hasTaskNamed('testHasTaskNamed')
  731. _testHasTaskNamed = None
  732. tm._checkMemLeaks()
  733. # task sort
  734. l = []
  735. def _testPri1(task, l = l):
  736. l.append(1)
  737. return task.cont
  738. def _testPri2(task, l = l):
  739. l.append(2)
  740. return task.cont
  741. tm.add(_testPri1, 'testPri1', sort = 1)
  742. tm.add(_testPri2, 'testPri2', sort = 2)
  743. tm.step()
  744. assert len(l) == 2
  745. assert l == [1, 2,]
  746. tm.step()
  747. assert len(l) == 4
  748. assert l == [1, 2, 1, 2,]
  749. tm.remove('testPri1')
  750. tm.remove('testPri2')
  751. _testPri1 = None
  752. _testPri2 = None
  753. tm._checkMemLeaks()
  754. # task extraArgs
  755. l = []
  756. def _testExtraArgs(arg1, arg2, l=l):
  757. l.extend([arg1, arg2,])
  758. return done
  759. tm.add(_testExtraArgs, 'testExtraArgs', extraArgs=[4,5])
  760. tm.step()
  761. assert len(l) == 2
  762. assert l == [4, 5,]
  763. _testExtraArgs = None
  764. tm._checkMemLeaks()
  765. # task appendTask
  766. l = []
  767. def _testAppendTask(arg1, arg2, task, l=l):
  768. l.extend([arg1, arg2,])
  769. return task.done
  770. tm.add(_testAppendTask, '_testAppendTask', extraArgs=[4,5], appendTask=True)
  771. tm.step()
  772. assert len(l) == 2
  773. assert l == [4, 5,]
  774. _testAppendTask = None
  775. tm._checkMemLeaks()
  776. # task uponDeath
  777. l = []
  778. def _uponDeathFunc(task, l=l):
  779. l.append(task.name)
  780. def _testUponDeath(task):
  781. return done
  782. tm.add(_testUponDeath, 'testUponDeath', uponDeath=_uponDeathFunc)
  783. tm.step()
  784. assert len(l) == 1
  785. assert l == ['testUponDeath']
  786. _testUponDeath = None
  787. _uponDeathFunc = None
  788. tm._checkMemLeaks()
  789. # task owner
  790. class _TaskOwner:
  791. def _addTask(self, task):
  792. self.addedTaskName = task.name
  793. def _clearTask(self, task):
  794. self.clearedTaskName = task.name
  795. to = _TaskOwner()
  796. l = []
  797. def _testOwner(task):
  798. return done
  799. tm.add(_testOwner, 'testOwner', owner=to)
  800. tm.step()
  801. assert getattr(to, 'addedTaskName', None) == 'testOwner'
  802. assert getattr(to, 'clearedTaskName', None) == 'testOwner'
  803. _testOwner = None
  804. del to
  805. _TaskOwner = None
  806. tm._checkMemLeaks()
  807. doLaterTests = [0,]
  808. # doLater
  809. l = []
  810. def _testDoLater1(task, l=l):
  811. l.append(1)
  812. def _testDoLater2(task, l=l):
  813. l.append(2)
  814. def _monitorDoLater(task, tm=tm, l=l, doLaterTests=doLaterTests):
  815. if task.time > .03:
  816. assert l == [1, 2,]
  817. doLaterTests[0] -= 1
  818. return task.done
  819. return task.cont
  820. tm.doMethodLater(.01, _testDoLater1, 'testDoLater1')
  821. tm.doMethodLater(.02, _testDoLater2, 'testDoLater2')
  822. doLaterTests[0] += 1
  823. # make sure we run this task after the doLaters if they all occur on the same frame
  824. tm.add(_monitorDoLater, 'monitorDoLater', sort=10)
  825. _testDoLater1 = None
  826. _testDoLater2 = None
  827. _monitorDoLater = None
  828. # don't check until all the doLaters are finished
  829. #tm._checkMemLeaks()
  830. # doLater sort
  831. l = []
  832. def _testDoLaterPri1(task, l=l):
  833. l.append(1)
  834. def _testDoLaterPri2(task, l=l):
  835. l.append(2)
  836. def _monitorDoLaterPri(task, tm=tm, l=l, doLaterTests=doLaterTests):
  837. if task.time > .02:
  838. assert l == [1, 2,]
  839. doLaterTests[0] -= 1
  840. return task.done
  841. return task.cont
  842. tm.doMethodLater(.01, _testDoLaterPri1, 'testDoLaterPri1', sort=1)
  843. tm.doMethodLater(.01, _testDoLaterPri2, 'testDoLaterPri2', sort=2)
  844. doLaterTests[0] += 1
  845. # make sure we run this task after the doLaters if they all occur on the same frame
  846. tm.add(_monitorDoLaterPri, 'monitorDoLaterPri', sort=10)
  847. _testDoLaterPri1 = None
  848. _testDoLaterPri2 = None
  849. _monitorDoLaterPri = None
  850. # don't check until all the doLaters are finished
  851. #tm._checkMemLeaks()
  852. # doLater extraArgs
  853. l = []
  854. def _testDoLaterExtraArgs(arg1, l=l):
  855. l.append(arg1)
  856. def _monitorDoLaterExtraArgs(task, tm=tm, l=l, doLaterTests=doLaterTests):
  857. if task.time > .02:
  858. assert l == [3,]
  859. doLaterTests[0] -= 1
  860. return task.done
  861. return task.cont
  862. tm.doMethodLater(.01, _testDoLaterExtraArgs, 'testDoLaterExtraArgs', extraArgs=[3,])
  863. doLaterTests[0] += 1
  864. # make sure we run this task after the doLaters if they all occur on the same frame
  865. tm.add(_monitorDoLaterExtraArgs, 'monitorDoLaterExtraArgs', sort=10)
  866. _testDoLaterExtraArgs = None
  867. _monitorDoLaterExtraArgs = None
  868. # don't check until all the doLaters are finished
  869. #tm._checkMemLeaks()
  870. # doLater appendTask
  871. l = []
  872. def _testDoLaterAppendTask(arg1, task, l=l):
  873. assert task.name == 'testDoLaterAppendTask'
  874. l.append(arg1)
  875. def _monitorDoLaterAppendTask(task, tm=tm, l=l, doLaterTests=doLaterTests):
  876. if task.time > .02:
  877. assert l == [4,]
  878. doLaterTests[0] -= 1
  879. return task.done
  880. return task.cont
  881. tm.doMethodLater(.01, _testDoLaterAppendTask, 'testDoLaterAppendTask',
  882. extraArgs=[4,], appendTask=True)
  883. doLaterTests[0] += 1
  884. # make sure we run this task after the doLaters if they all occur on the same frame
  885. tm.add(_monitorDoLaterAppendTask, 'monitorDoLaterAppendTask', sort=10)
  886. _testDoLaterAppendTask = None
  887. _monitorDoLaterAppendTask = None
  888. # don't check until all the doLaters are finished
  889. #tm._checkMemLeaks()
  890. # doLater uponDeath
  891. l = []
  892. def _testUponDeathFunc(task, l=l):
  893. assert task.name == 'testDoLaterUponDeath'
  894. l.append(10)
  895. def _testDoLaterUponDeath(arg1, l=l):
  896. return done
  897. def _monitorDoLaterUponDeath(task, tm=tm, l=l, doLaterTests=doLaterTests):
  898. if task.time > .02:
  899. assert l == [10,]
  900. doLaterTests[0] -= 1
  901. return task.done
  902. return task.cont
  903. tm.doMethodLater(.01, _testDoLaterUponDeath, 'testDoLaterUponDeath',
  904. uponDeath=_testUponDeathFunc)
  905. doLaterTests[0] += 1
  906. # make sure we run this task after the doLaters if they all occur on the same frame
  907. tm.add(_monitorDoLaterUponDeath, 'monitorDoLaterUponDeath', sort=10)
  908. _testUponDeathFunc = None
  909. _testDoLaterUponDeath = None
  910. _monitorDoLaterUponDeath = None
  911. # don't check until all the doLaters are finished
  912. #tm._checkMemLeaks()
  913. # doLater owner
  914. class _DoLaterOwner:
  915. def _addTask(self, task):
  916. self.addedTaskName = task.name
  917. def _clearTask(self, task):
  918. self.clearedTaskName = task.name
  919. doLaterOwner = _DoLaterOwner()
  920. l = []
  921. def _testDoLaterOwner(l=l):
  922. pass
  923. def _monitorDoLaterOwner(task, tm=tm, l=l, doLaterOwner=doLaterOwner,
  924. doLaterTests=doLaterTests):
  925. if task.time > .02:
  926. assert getattr(doLaterOwner, 'addedTaskName', None) == 'testDoLaterOwner'
  927. assert getattr(doLaterOwner, 'clearedTaskName', None) == 'testDoLaterOwner'
  928. doLaterTests[0] -= 1
  929. return task.done
  930. return task.cont
  931. tm.doMethodLater(.01, _testDoLaterOwner, 'testDoLaterOwner',
  932. owner=doLaterOwner)
  933. doLaterTests[0] += 1
  934. # make sure we run this task after the doLaters if they all occur on the same frame
  935. tm.add(_monitorDoLaterOwner, 'monitorDoLaterOwner', sort=10)
  936. _testDoLaterOwner = None
  937. _monitorDoLaterOwner = None
  938. del doLaterOwner
  939. _DoLaterOwner = None
  940. # don't check until all the doLaters are finished
  941. #tm._checkMemLeaks()
  942. # run the doLater tests
  943. while doLaterTests[0] > 0:
  944. tm.step()
  945. del doLaterTests
  946. tm._checkMemLeaks()
  947. # getTasks
  948. def _testGetTasks(task):
  949. return task.cont
  950. # No doLaterProcessor in the new world.
  951. assert len(tm.getTasks()) == 0
  952. tm.add(_testGetTasks, 'testGetTasks1')
  953. assert len(tm.getTasks()) == 1
  954. assert (tm.getTasks()[0].name == 'testGetTasks1' or
  955. tm.getTasks()[1].name == 'testGetTasks1')
  956. tm.add(_testGetTasks, 'testGetTasks2')
  957. tm.add(_testGetTasks, 'testGetTasks3')
  958. assert len(tm.getTasks()) == 3
  959. tm.remove('testGetTasks2')
  960. assert len(tm.getTasks()) == 2
  961. tm.remove('testGetTasks1')
  962. tm.remove('testGetTasks3')
  963. assert len(tm.getTasks()) == 0
  964. _testGetTasks = None
  965. tm._checkMemLeaks()
  966. # getDoLaters
  967. def _testGetDoLaters():
  968. pass
  969. assert len(tm.getDoLaters()) == 0
  970. tm.doMethodLater(.1, _testGetDoLaters, 'testDoLater1')
  971. assert len(tm.getDoLaters()) == 1
  972. assert tm.getDoLaters()[0].name == 'testDoLater1'
  973. tm.doMethodLater(.1, _testGetDoLaters, 'testDoLater2')
  974. tm.doMethodLater(.1, _testGetDoLaters, 'testDoLater3')
  975. assert len(tm.getDoLaters()) == 3
  976. tm.remove('testDoLater2')
  977. assert len(tm.getDoLaters()) == 2
  978. tm.remove('testDoLater1')
  979. tm.remove('testDoLater3')
  980. assert len(tm.getDoLaters()) == 0
  981. _testGetDoLaters = None
  982. tm._checkMemLeaks()
  983. # duplicate named doLaters removed via taskMgr.remove
  984. def _testDupNameDoLaters():
  985. pass
  986. # the doLaterProcessor is always running
  987. tm.doMethodLater(.1, _testDupNameDoLaters, 'testDupNameDoLater')
  988. tm.doMethodLater(.1, _testDupNameDoLaters, 'testDupNameDoLater')
  989. assert len(tm.getDoLaters()) == 2
  990. tm.remove('testDupNameDoLater')
  991. assert len(tm.getDoLaters()) == 0
  992. _testDupNameDoLaters = None
  993. tm._checkMemLeaks()
  994. # duplicate named doLaters removed via remove()
  995. def _testDupNameDoLatersRemove():
  996. pass
  997. # the doLaterProcessor is always running
  998. dl1 = tm.doMethodLater(.1, _testDupNameDoLatersRemove, 'testDupNameDoLaterRemove')
  999. dl2 = tm.doMethodLater(.1, _testDupNameDoLatersRemove, 'testDupNameDoLaterRemove')
  1000. assert len(tm.getDoLaters()) == 2
  1001. dl2.remove()
  1002. assert len(tm.getDoLaters()) == 1
  1003. dl1.remove()
  1004. assert len(tm.getDoLaters()) == 0
  1005. _testDupNameDoLatersRemove = None
  1006. # nameDict etc. isn't cleared out right away with task.remove()
  1007. tm._checkMemLeaks()
  1008. # getTasksNamed
  1009. def _testGetTasksNamed(task):
  1010. return task.cont
  1011. assert len(tm.getTasksNamed('testGetTasksNamed')) == 0
  1012. tm.add(_testGetTasksNamed, 'testGetTasksNamed')
  1013. assert len(tm.getTasksNamed('testGetTasksNamed')) == 1
  1014. assert tm.getTasksNamed('testGetTasksNamed')[0].name == 'testGetTasksNamed'
  1015. tm.add(_testGetTasksNamed, 'testGetTasksNamed')
  1016. tm.add(_testGetTasksNamed, 'testGetTasksNamed')
  1017. assert len(tm.getTasksNamed('testGetTasksNamed')) == 3
  1018. tm.remove('testGetTasksNamed')
  1019. assert len(tm.getTasksNamed('testGetTasksNamed')) == 0
  1020. _testGetTasksNamed = None
  1021. tm._checkMemLeaks()
  1022. # removeTasksMatching
  1023. def _testRemoveTasksMatching(task):
  1024. return task.cont
  1025. tm.add(_testRemoveTasksMatching, 'testRemoveTasksMatching')
  1026. assert len(tm.getTasksNamed('testRemoveTasksMatching')) == 1
  1027. tm.removeTasksMatching('testRemoveTasksMatching')
  1028. assert len(tm.getTasksNamed('testRemoveTasksMatching')) == 0
  1029. tm.add(_testRemoveTasksMatching, 'testRemoveTasksMatching1')
  1030. tm.add(_testRemoveTasksMatching, 'testRemoveTasksMatching2')
  1031. assert len(tm.getTasksNamed('testRemoveTasksMatching1')) == 1
  1032. assert len(tm.getTasksNamed('testRemoveTasksMatching2')) == 1
  1033. tm.removeTasksMatching('testRemoveTasksMatching*')
  1034. assert len(tm.getTasksNamed('testRemoveTasksMatching1')) == 0
  1035. assert len(tm.getTasksNamed('testRemoveTasksMatching2')) == 0
  1036. tm.add(_testRemoveTasksMatching, 'testRemoveTasksMatching1a')
  1037. tm.add(_testRemoveTasksMatching, 'testRemoveTasksMatching2a')
  1038. assert len(tm.getTasksNamed('testRemoveTasksMatching1a')) == 1
  1039. assert len(tm.getTasksNamed('testRemoveTasksMatching2a')) == 1
  1040. tm.removeTasksMatching('testRemoveTasksMatching?a')
  1041. assert len(tm.getTasksNamed('testRemoveTasksMatching1a')) == 0
  1042. assert len(tm.getTasksNamed('testRemoveTasksMatching2a')) == 0
  1043. _testRemoveTasksMatching = None
  1044. tm._checkMemLeaks()
  1045. # create Task object and add to mgr
  1046. l = []
  1047. def _testTaskObj(task, l=l):
  1048. l.append(None)
  1049. return task.cont
  1050. t = Task(_testTaskObj)
  1051. tm.add(t, 'testTaskObj')
  1052. tm.step()
  1053. assert len(l) == 1
  1054. tm.step()
  1055. assert len(l) == 2
  1056. tm.remove('testTaskObj')
  1057. tm.step()
  1058. assert len(l) == 2
  1059. _testTaskObj = None
  1060. tm._checkMemLeaks()
  1061. # remove Task via task.remove()
  1062. l = []
  1063. def _testTaskObjRemove(task, l=l):
  1064. l.append(None)
  1065. return task.cont
  1066. t = Task(_testTaskObjRemove)
  1067. tm.add(t, 'testTaskObjRemove')
  1068. tm.step()
  1069. assert len(l) == 1
  1070. tm.step()
  1071. assert len(l) == 2
  1072. t.remove()
  1073. tm.step()
  1074. assert len(l) == 2
  1075. del t
  1076. _testTaskObjRemove = None
  1077. tm._checkMemLeaks()
  1078. """
  1079. # this test fails, and it's not clear what the correct behavior should be.
  1080. # sort passed to Task.__init__ is always overridden by taskMgr.add()
  1081. # even if no sort is specified, and calling Task.setSort() has no
  1082. # effect on the taskMgr's behavior.
  1083. # set/get Task sort
  1084. l = []
  1085. def _testTaskObjSort(arg, task, l=l):
  1086. l.append(arg)
  1087. return task.cont
  1088. t1 = Task(_testTaskObjSort, sort=1)
  1089. t2 = Task(_testTaskObjSort, sort=2)
  1090. tm.add(t1, 'testTaskObjSort1', extraArgs=['a',], appendTask=True)
  1091. tm.add(t2, 'testTaskObjSort2', extraArgs=['b',], appendTask=True)
  1092. tm.step()
  1093. assert len(l) == 2
  1094. assert l == ['a', 'b']
  1095. assert t1.getSort() == 1
  1096. assert t2.getSort() == 2
  1097. t1.setSort(3)
  1098. assert t1.getSort() == 3
  1099. tm.step()
  1100. assert len(l) == 4
  1101. assert l == ['a', 'b', 'b', 'a',]
  1102. t1.remove()
  1103. t2.remove()
  1104. tm.step()
  1105. assert len(l) == 4
  1106. del t1
  1107. del t2
  1108. _testTaskObjSort = None
  1109. tm._checkMemLeaks()
  1110. """
  1111. del l
  1112. tm.destroy()
  1113. del tm
  1114. if __debug__:
  1115. def checkLeak():
  1116. import sys
  1117. import gc
  1118. gc.enable()
  1119. from direct.showbase.DirectObject import DirectObject
  1120. class TestClass(DirectObject):
  1121. def doTask(self, task):
  1122. return task.done
  1123. obj = TestClass()
  1124. startRefCount = sys.getrefcount(obj)
  1125. print('sys.getrefcount(obj): %s' % sys.getrefcount(obj))
  1126. print('** addTask')
  1127. t = obj.addTask(obj.doTask, 'test')
  1128. print('sys.getrefcount(obj): %s' % sys.getrefcount(obj))
  1129. print('task.getRefCount(): %s' % t.getRefCount())
  1130. print('** removeTask')
  1131. obj.removeTask('test')
  1132. print('sys.getrefcount(obj): %s' % sys.getrefcount(obj))
  1133. print('task.getRefCount(): %s' % t.getRefCount())
  1134. print('** step')
  1135. taskMgr.step()
  1136. taskMgr.step()
  1137. taskMgr.step()
  1138. print('sys.getrefcount(obj): %s' % sys.getrefcount(obj))
  1139. print('task.getRefCount(): %s' % t.getRefCount())
  1140. print('** task release')
  1141. t = None
  1142. print('sys.getrefcount(obj): %s' % sys.getrefcount(obj))
  1143. assert sys.getrefcount(obj) == startRefCount