Task.py 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299
  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__') or \
  331. hasattr(funcOrTask, 'cr_await') or \
  332. type(funcOrTask) == types.GeneratorType:
  333. # It's a function, coroutine, or something emulating a coroutine.
  334. task = PythonTask(funcOrTask)
  335. if name is None:
  336. name = getattr(funcOrTask, '__qualname__', None) or \
  337. getattr(funcOrTask, '__name__', None)
  338. else:
  339. self.notify.error(
  340. 'add: Tried to add a task that was not a Task or a func')
  341. if hasattr(task, 'setArgs'):
  342. # It will only accept arguments if it's a PythonTask.
  343. if extraArgs is None:
  344. extraArgs = []
  345. appendTask = True
  346. task.setArgs(extraArgs, appendTask)
  347. elif extraArgs is not None:
  348. self.notify.error(
  349. 'Task %s does not accept arguments.' % (repr(task)))
  350. if name is not None:
  351. task.setName(name)
  352. assert task.hasName()
  353. # For historical reasons, if priority is specified but not
  354. # sort, it really means sort.
  355. if priority is not None and sort is None:
  356. task.setSort(priority)
  357. else:
  358. if priority is not None:
  359. task.setPriority(priority)
  360. if sort is not None:
  361. task.setSort(sort)
  362. if taskChain is not None:
  363. task.setTaskChain(taskChain)
  364. if owner is not None:
  365. task.setOwner(owner)
  366. if uponDeath is not None:
  367. task.setUponDeath(uponDeath)
  368. return task
  369. def remove(self, taskOrName):
  370. """Removes a task from the task manager. The task is stopped,
  371. almost as if it had returned task.done. (But if the task is
  372. currently executing, it will finish out its current frame
  373. before being removed.) You may specify either an explicit
  374. Task object, or the name of a task. If you specify a name,
  375. all tasks with the indicated name are removed. Returns the
  376. number of tasks removed. """
  377. if isinstance(taskOrName, AsyncTask):
  378. return self.mgr.remove(taskOrName)
  379. elif isinstance(taskOrName, list):
  380. for task in taskOrName:
  381. self.remove(task)
  382. else:
  383. tasks = self.mgr.findTasks(taskOrName)
  384. return self.mgr.remove(tasks)
  385. def removeTasksMatching(self, taskPattern):
  386. """Removes all tasks whose names match the pattern, which can
  387. include standard shell globbing characters like \\*, ?, and [].
  388. See also :meth:`remove()`.
  389. Returns the number of tasks removed.
  390. """
  391. tasks = self.mgr.findTasksMatching(GlobPattern(taskPattern))
  392. return self.mgr.remove(tasks)
  393. def step(self):
  394. """Invokes the task manager for one frame, and then returns.
  395. Normally, this executes each task exactly once, though task
  396. chains that are in sub-threads or that have frame budgets
  397. might execute their tasks differently. """
  398. # Replace keyboard interrupt handler during task list processing
  399. # so we catch the keyboard interrupt but don't handle it until
  400. # after task list processing is complete.
  401. self.fKeyboardInterrupt = 0
  402. self.interruptCount = 0
  403. if signal:
  404. signal.signal(signal.SIGINT, self.keyboardInterruptHandler)
  405. startFrameTime = self.globalClock.getRealTime()
  406. self.mgr.poll()
  407. # This is the spot for an internal yield function
  408. nextTaskTime = self.mgr.getNextWakeTime()
  409. self.doYield(startFrameTime, nextTaskTime)
  410. # Restore default interrupt handler
  411. if signal:
  412. signal.signal(signal.SIGINT, signal.default_int_handler)
  413. if self.fKeyboardInterrupt:
  414. raise KeyboardInterrupt
  415. def run(self):
  416. """Starts the task manager running. Does not return until an
  417. exception is encountered (including KeyboardInterrupt). """
  418. if PandaSystem.getPlatform() == 'emscripten':
  419. return
  420. # Set the clock to have last frame's time in case we were
  421. # Paused at the prompt for a long time
  422. t = self.globalClock.getFrameTime()
  423. timeDelta = t - self.globalClock.getRealTime()
  424. self.globalClock.setRealTime(t)
  425. messenger.send("resetClock", [timeDelta])
  426. if self.resumeFunc != None:
  427. self.resumeFunc()
  428. if self.stepping:
  429. self.step()
  430. else:
  431. self.running = True
  432. while self.running:
  433. try:
  434. if len(self._frameProfileQueue):
  435. numFrames, session, callback = self._frameProfileQueue.pop(0)
  436. def _profileFunc(numFrames=numFrames):
  437. self._doProfiledFrames(numFrames)
  438. session.setFunc(_profileFunc)
  439. session.run()
  440. _profileFunc = None
  441. if callback:
  442. callback()
  443. session.release()
  444. else:
  445. self.step()
  446. except KeyboardInterrupt:
  447. self.stop()
  448. except SystemExit:
  449. self.stop()
  450. raise
  451. except IOError as ioError:
  452. code, message = self._unpackIOError(ioError)
  453. # Since upgrading to Python 2.4.1, pausing the execution
  454. # often gives this IOError during the sleep function:
  455. # IOError: [Errno 4] Interrupted function call
  456. # So, let's just handle that specific exception and stop.
  457. # All other IOErrors should still get raised.
  458. # Only problem: legit IOError 4s will be obfuscated.
  459. if code == 4:
  460. self.stop()
  461. else:
  462. raise
  463. except Exception as e:
  464. if self.extendedExceptions:
  465. self.stop()
  466. print_exc_plus()
  467. else:
  468. if (ExceptionVarDump.wantStackDumpLog and
  469. ExceptionVarDump.dumpOnExceptionInit):
  470. ExceptionVarDump._varDump__print(e)
  471. raise
  472. except:
  473. if self.extendedExceptions:
  474. self.stop()
  475. print_exc_plus()
  476. else:
  477. raise
  478. self.mgr.stopThreads()
  479. def _unpackIOError(self, ioError):
  480. # IOError unpack from http://www.python.org/doc/essays/stdexceptions/
  481. # this needs to be in its own method, exceptions that occur inside
  482. # a nested try block are not caught by the inner try block's except
  483. try:
  484. (code, message) = ioError
  485. except:
  486. code = 0
  487. message = ioError
  488. return code, message
  489. def stop(self):
  490. # Set a flag so we will stop before beginning next frame
  491. self.running = False
  492. def __tryReplaceTaskMethod(self, task, oldMethod, newFunction):
  493. if not isinstance(task, PythonTask):
  494. return 0
  495. method = task.getFunction()
  496. if (type(method) == types.MethodType):
  497. function = method.__func__
  498. else:
  499. function = method
  500. if (function == oldMethod):
  501. newMethod = types.MethodType(newFunction,
  502. method.__self__,
  503. method.__self__.__class__)
  504. task.setFunction(newMethod)
  505. # Found a match
  506. return 1
  507. return 0
  508. def replaceMethod(self, oldMethod, newFunction):
  509. numFound = 0
  510. for task in self.getAllTasks():
  511. numFound += self.__tryReplaceTaskMethod(task, oldMethod, newFunction)
  512. return numFound
  513. def popupControls(self):
  514. # Don't use a regular import, to prevent ModuleFinder from picking
  515. # it up as a dependency when building a .p3d package.
  516. TaskManagerPanel = importlib.import_module('direct.tkpanels.TaskManagerPanel')
  517. return TaskManagerPanel.TaskManagerPanel(self)
  518. def getProfileSession(self, name=None):
  519. # call to get a profile session that you can modify before passing to profileFrames()
  520. if name is None:
  521. name = 'taskMgrFrameProfile'
  522. # Defer this import until we need it: some Python
  523. # distributions don't provide the profile and pstats modules.
  524. PS = importlib.import_module('direct.showbase.ProfileSession')
  525. return PS.ProfileSession(name)
  526. def profileFrames(self, num=None, session=None, callback=None):
  527. if num is None:
  528. num = 1
  529. if session is None:
  530. session = self.getProfileSession()
  531. # make sure the profile session doesn't get destroyed before we're done with it
  532. session.acquire()
  533. self._frameProfileQueue.append((num, session, callback))
  534. def _doProfiledFrames(self, numFrames):
  535. for i in range(numFrames):
  536. result = self.step()
  537. return result
  538. def getProfileFrames(self):
  539. return self._profileFrames.get()
  540. def getProfileFramesSV(self):
  541. return self._profileFrames
  542. def setProfileFrames(self, profileFrames):
  543. self._profileFrames.set(profileFrames)
  544. if (not self._frameProfiler) and profileFrames:
  545. # import here due to import dependencies
  546. FP = importlib.import_module('direct.task.FrameProfiler')
  547. self._frameProfiler = FP.FrameProfiler()
  548. def getProfileTasks(self):
  549. return self._profileTasks.get()
  550. def getProfileTasksSV(self):
  551. return self._profileTasks
  552. def setProfileTasks(self, profileTasks):
  553. self._profileTasks.set(profileTasks)
  554. if (not self._taskProfiler) and profileTasks:
  555. # import here due to import dependencies
  556. TP = importlib.import_module('direct.task.TaskProfiler')
  557. self._taskProfiler = TP.TaskProfiler()
  558. def logTaskProfiles(self, name=None):
  559. if self._taskProfiler:
  560. self._taskProfiler.logProfiles(name)
  561. def flushTaskProfiles(self, name=None):
  562. if self._taskProfiler:
  563. self._taskProfiler.flush(name)
  564. def _setProfileTask(self, task):
  565. if self._taskProfileInfo.session:
  566. self._taskProfileInfo.session.release()
  567. self._taskProfileInfo.session = None
  568. self._taskProfileInfo = ScratchPad(
  569. taskFunc = task.getFunction(),
  570. taskArgs = task.getArgs(),
  571. task = task,
  572. profiled = False,
  573. session = None,
  574. )
  575. # Temporarily replace the task's own function with our
  576. # _profileTask method.
  577. task.setFunction(self._profileTask)
  578. task.setArgs([self._taskProfileInfo], True)
  579. def _profileTask(self, profileInfo, task):
  580. # This is called instead of the task function when we have
  581. # decided to profile a task.
  582. assert profileInfo.task == task
  583. # don't profile the same task twice in a row
  584. assert not profileInfo.profiled
  585. # Restore the task's proper function for next time.
  586. appendTask = False
  587. taskArgs = profileInfo.taskArgs
  588. if taskArgs and taskArgs[-1] == task:
  589. appendTask = True
  590. taskArgs = taskArgs[:-1]
  591. task.setArgs(taskArgs, appendTask)
  592. task.setFunction(profileInfo.taskFunc)
  593. # Defer this import until we need it: some Python
  594. # distributions don't provide the profile and pstats modules.
  595. PS = importlib.import_module('direct.showbase.ProfileSession')
  596. profileSession = PS.ProfileSession('profiled-task-%s' % task.getName(),
  597. Functor(profileInfo.taskFunc, *profileInfo.taskArgs))
  598. ret = profileSession.run()
  599. # set these values *after* profiling in case we're profiling the TaskProfiler
  600. profileInfo.session = profileSession
  601. profileInfo.profiled = True
  602. return ret
  603. def _hasProfiledDesignatedTask(self):
  604. # have we run a profile of the designated task yet?
  605. return self._taskProfileInfo.profiled
  606. def _getLastTaskProfileSession(self):
  607. return self._taskProfileInfo.session
  608. def _getRandomTask(self):
  609. # Figure out when the next frame is likely to expire, so we
  610. # won't grab any tasks that are sleeping for a long time.
  611. now = self.globalClock.getFrameTime()
  612. avgFrameRate = self.globalClock.getAverageFrameRate()
  613. if avgFrameRate < .00001:
  614. avgFrameDur = 0.
  615. else:
  616. avgFrameDur = (1. / self.globalClock.getAverageFrameRate())
  617. next = now + avgFrameDur
  618. # Now grab a task at random, until we find one that we like.
  619. tasks = self.mgr.getTasks()
  620. i = random.randrange(tasks.getNumTasks())
  621. task = tasks.getTask(i)
  622. while not isinstance(task, PythonTask) or \
  623. task.getWakeTime() > next:
  624. tasks.removeTask(i)
  625. i = random.randrange(tasks.getNumTasks())
  626. task = tasks.getTask(i)
  627. return task
  628. def __repr__(self):
  629. return str(self.mgr)
  630. # In the event we want to do frame time managment, this is the
  631. # function to replace or overload.
  632. def doYield(self, frameStartTime, nextScheduledTaskTime):
  633. pass
  634. """
  635. def doYieldExample(self, frameStartTime, nextScheduledTaskTime):
  636. minFinTime = frameStartTime + self.MaxEpochSpeed
  637. if nextScheduledTaskTime > 0 and nextScheduledTaskTime < minFinTime:
  638. print ' Adjusting Time'
  639. minFinTime = nextScheduledTaskTime
  640. delta = minFinTime - self.globalClock.getRealTime()
  641. while(delta > 0.002):
  642. print ' sleep %s'% (delta)
  643. time.sleep(delta)
  644. delta = minFinTime - self.globalClock.getRealTime()
  645. """
  646. if __debug__:
  647. # to catch memory leaks during the tests at the bottom of the file
  648. def _startTrackingMemLeaks(self):
  649. pass
  650. def _stopTrackingMemLeaks(self):
  651. pass
  652. def _checkMemLeaks(self):
  653. pass
  654. def _runTests(self):
  655. if __debug__:
  656. tm = TaskManager()
  657. tm.setClock(ClockObject())
  658. tm.setupTaskChain("default", tickClock = True)
  659. # check for memory leaks after every test
  660. tm._startTrackingMemLeaks()
  661. tm._checkMemLeaks()
  662. # run-once task
  663. l = []
  664. def _testDone(task, l=l):
  665. l.append(None)
  666. return task.done
  667. tm.add(_testDone, 'testDone')
  668. tm.step()
  669. assert len(l) == 1
  670. tm.step()
  671. assert len(l) == 1
  672. _testDone = None
  673. tm._checkMemLeaks()
  674. # remove by name
  675. def _testRemoveByName(task):
  676. return task.done
  677. tm.add(_testRemoveByName, 'testRemoveByName')
  678. assert tm.remove('testRemoveByName') == 1
  679. assert tm.remove('testRemoveByName') == 0
  680. _testRemoveByName = None
  681. tm._checkMemLeaks()
  682. # duplicate named tasks
  683. def _testDupNamedTasks(task):
  684. return task.done
  685. tm.add(_testDupNamedTasks, 'testDupNamedTasks')
  686. tm.add(_testDupNamedTasks, 'testDupNamedTasks')
  687. assert tm.remove('testRemoveByName') == 0
  688. _testDupNamedTasks = None
  689. tm._checkMemLeaks()
  690. # continued task
  691. l = []
  692. def _testCont(task, l = l):
  693. l.append(None)
  694. return task.cont
  695. tm.add(_testCont, 'testCont')
  696. tm.step()
  697. assert len(l) == 1
  698. tm.step()
  699. assert len(l) == 2
  700. tm.remove('testCont')
  701. _testCont = None
  702. tm._checkMemLeaks()
  703. # continue until done task
  704. l = []
  705. def _testContDone(task, l = l):
  706. l.append(None)
  707. if len(l) >= 2:
  708. return task.done
  709. else:
  710. return task.cont
  711. tm.add(_testContDone, 'testContDone')
  712. tm.step()
  713. assert len(l) == 1
  714. tm.step()
  715. assert len(l) == 2
  716. tm.step()
  717. assert len(l) == 2
  718. assert not tm.hasTaskNamed('testContDone')
  719. _testContDone = None
  720. tm._checkMemLeaks()
  721. # hasTaskNamed
  722. def _testHasTaskNamed(task):
  723. return task.done
  724. tm.add(_testHasTaskNamed, 'testHasTaskNamed')
  725. assert tm.hasTaskNamed('testHasTaskNamed')
  726. tm.step()
  727. assert not tm.hasTaskNamed('testHasTaskNamed')
  728. _testHasTaskNamed = None
  729. tm._checkMemLeaks()
  730. # task sort
  731. l = []
  732. def _testPri1(task, l = l):
  733. l.append(1)
  734. return task.cont
  735. def _testPri2(task, l = l):
  736. l.append(2)
  737. return task.cont
  738. tm.add(_testPri1, 'testPri1', sort = 1)
  739. tm.add(_testPri2, 'testPri2', sort = 2)
  740. tm.step()
  741. assert len(l) == 2
  742. assert l == [1, 2,]
  743. tm.step()
  744. assert len(l) == 4
  745. assert l == [1, 2, 1, 2,]
  746. tm.remove('testPri1')
  747. tm.remove('testPri2')
  748. _testPri1 = None
  749. _testPri2 = None
  750. tm._checkMemLeaks()
  751. # task extraArgs
  752. l = []
  753. def _testExtraArgs(arg1, arg2, l=l):
  754. l.extend([arg1, arg2,])
  755. return done
  756. tm.add(_testExtraArgs, 'testExtraArgs', extraArgs=[4,5])
  757. tm.step()
  758. assert len(l) == 2
  759. assert l == [4, 5,]
  760. _testExtraArgs = None
  761. tm._checkMemLeaks()
  762. # task appendTask
  763. l = []
  764. def _testAppendTask(arg1, arg2, task, l=l):
  765. l.extend([arg1, arg2,])
  766. return task.done
  767. tm.add(_testAppendTask, '_testAppendTask', extraArgs=[4,5], appendTask=True)
  768. tm.step()
  769. assert len(l) == 2
  770. assert l == [4, 5,]
  771. _testAppendTask = None
  772. tm._checkMemLeaks()
  773. # task uponDeath
  774. l = []
  775. def _uponDeathFunc(task, l=l):
  776. l.append(task.name)
  777. def _testUponDeath(task):
  778. return done
  779. tm.add(_testUponDeath, 'testUponDeath', uponDeath=_uponDeathFunc)
  780. tm.step()
  781. assert len(l) == 1
  782. assert l == ['testUponDeath']
  783. _testUponDeath = None
  784. _uponDeathFunc = None
  785. tm._checkMemLeaks()
  786. # task owner
  787. class _TaskOwner:
  788. def _addTask(self, task):
  789. self.addedTaskName = task.name
  790. def _clearTask(self, task):
  791. self.clearedTaskName = task.name
  792. to = _TaskOwner()
  793. l = []
  794. def _testOwner(task):
  795. return done
  796. tm.add(_testOwner, 'testOwner', owner=to)
  797. tm.step()
  798. assert getattr(to, 'addedTaskName', None) == 'testOwner'
  799. assert getattr(to, 'clearedTaskName', None) == 'testOwner'
  800. _testOwner = None
  801. del to
  802. _TaskOwner = None
  803. tm._checkMemLeaks()
  804. doLaterTests = [0,]
  805. # doLater
  806. l = []
  807. def _testDoLater1(task, l=l):
  808. l.append(1)
  809. def _testDoLater2(task, l=l):
  810. l.append(2)
  811. def _monitorDoLater(task, tm=tm, l=l, doLaterTests=doLaterTests):
  812. if task.time > .03:
  813. assert l == [1, 2,]
  814. doLaterTests[0] -= 1
  815. return task.done
  816. return task.cont
  817. tm.doMethodLater(.01, _testDoLater1, 'testDoLater1')
  818. tm.doMethodLater(.02, _testDoLater2, 'testDoLater2')
  819. doLaterTests[0] += 1
  820. # make sure we run this task after the doLaters if they all occur on the same frame
  821. tm.add(_monitorDoLater, 'monitorDoLater', sort=10)
  822. _testDoLater1 = None
  823. _testDoLater2 = None
  824. _monitorDoLater = None
  825. # don't check until all the doLaters are finished
  826. #tm._checkMemLeaks()
  827. # doLater sort
  828. l = []
  829. def _testDoLaterPri1(task, l=l):
  830. l.append(1)
  831. def _testDoLaterPri2(task, l=l):
  832. l.append(2)
  833. def _monitorDoLaterPri(task, tm=tm, l=l, doLaterTests=doLaterTests):
  834. if task.time > .02:
  835. assert l == [1, 2,]
  836. doLaterTests[0] -= 1
  837. return task.done
  838. return task.cont
  839. tm.doMethodLater(.01, _testDoLaterPri1, 'testDoLaterPri1', sort=1)
  840. tm.doMethodLater(.01, _testDoLaterPri2, 'testDoLaterPri2', sort=2)
  841. doLaterTests[0] += 1
  842. # make sure we run this task after the doLaters if they all occur on the same frame
  843. tm.add(_monitorDoLaterPri, 'monitorDoLaterPri', sort=10)
  844. _testDoLaterPri1 = None
  845. _testDoLaterPri2 = None
  846. _monitorDoLaterPri = None
  847. # don't check until all the doLaters are finished
  848. #tm._checkMemLeaks()
  849. # doLater extraArgs
  850. l = []
  851. def _testDoLaterExtraArgs(arg1, l=l):
  852. l.append(arg1)
  853. def _monitorDoLaterExtraArgs(task, tm=tm, l=l, doLaterTests=doLaterTests):
  854. if task.time > .02:
  855. assert l == [3,]
  856. doLaterTests[0] -= 1
  857. return task.done
  858. return task.cont
  859. tm.doMethodLater(.01, _testDoLaterExtraArgs, 'testDoLaterExtraArgs', extraArgs=[3,])
  860. doLaterTests[0] += 1
  861. # make sure we run this task after the doLaters if they all occur on the same frame
  862. tm.add(_monitorDoLaterExtraArgs, 'monitorDoLaterExtraArgs', sort=10)
  863. _testDoLaterExtraArgs = None
  864. _monitorDoLaterExtraArgs = None
  865. # don't check until all the doLaters are finished
  866. #tm._checkMemLeaks()
  867. # doLater appendTask
  868. l = []
  869. def _testDoLaterAppendTask(arg1, task, l=l):
  870. assert task.name == 'testDoLaterAppendTask'
  871. l.append(arg1)
  872. def _monitorDoLaterAppendTask(task, tm=tm, l=l, doLaterTests=doLaterTests):
  873. if task.time > .02:
  874. assert l == [4,]
  875. doLaterTests[0] -= 1
  876. return task.done
  877. return task.cont
  878. tm.doMethodLater(.01, _testDoLaterAppendTask, 'testDoLaterAppendTask',
  879. extraArgs=[4,], appendTask=True)
  880. doLaterTests[0] += 1
  881. # make sure we run this task after the doLaters if they all occur on the same frame
  882. tm.add(_monitorDoLaterAppendTask, 'monitorDoLaterAppendTask', sort=10)
  883. _testDoLaterAppendTask = None
  884. _monitorDoLaterAppendTask = None
  885. # don't check until all the doLaters are finished
  886. #tm._checkMemLeaks()
  887. # doLater uponDeath
  888. l = []
  889. def _testUponDeathFunc(task, l=l):
  890. assert task.name == 'testDoLaterUponDeath'
  891. l.append(10)
  892. def _testDoLaterUponDeath(arg1, l=l):
  893. return done
  894. def _monitorDoLaterUponDeath(task, tm=tm, l=l, doLaterTests=doLaterTests):
  895. if task.time > .02:
  896. assert l == [10,]
  897. doLaterTests[0] -= 1
  898. return task.done
  899. return task.cont
  900. tm.doMethodLater(.01, _testDoLaterUponDeath, 'testDoLaterUponDeath',
  901. uponDeath=_testUponDeathFunc)
  902. doLaterTests[0] += 1
  903. # make sure we run this task after the doLaters if they all occur on the same frame
  904. tm.add(_monitorDoLaterUponDeath, 'monitorDoLaterUponDeath', sort=10)
  905. _testUponDeathFunc = None
  906. _testDoLaterUponDeath = None
  907. _monitorDoLaterUponDeath = None
  908. # don't check until all the doLaters are finished
  909. #tm._checkMemLeaks()
  910. # doLater owner
  911. class _DoLaterOwner:
  912. def _addTask(self, task):
  913. self.addedTaskName = task.name
  914. def _clearTask(self, task):
  915. self.clearedTaskName = task.name
  916. doLaterOwner = _DoLaterOwner()
  917. l = []
  918. def _testDoLaterOwner(l=l):
  919. pass
  920. def _monitorDoLaterOwner(task, tm=tm, l=l, doLaterOwner=doLaterOwner,
  921. doLaterTests=doLaterTests):
  922. if task.time > .02:
  923. assert getattr(doLaterOwner, 'addedTaskName', None) == 'testDoLaterOwner'
  924. assert getattr(doLaterOwner, 'clearedTaskName', None) == 'testDoLaterOwner'
  925. doLaterTests[0] -= 1
  926. return task.done
  927. return task.cont
  928. tm.doMethodLater(.01, _testDoLaterOwner, 'testDoLaterOwner',
  929. owner=doLaterOwner)
  930. doLaterTests[0] += 1
  931. # make sure we run this task after the doLaters if they all occur on the same frame
  932. tm.add(_monitorDoLaterOwner, 'monitorDoLaterOwner', sort=10)
  933. _testDoLaterOwner = None
  934. _monitorDoLaterOwner = None
  935. del doLaterOwner
  936. _DoLaterOwner = None
  937. # don't check until all the doLaters are finished
  938. #tm._checkMemLeaks()
  939. # run the doLater tests
  940. while doLaterTests[0] > 0:
  941. tm.step()
  942. del doLaterTests
  943. tm._checkMemLeaks()
  944. # getTasks
  945. def _testGetTasks(task):
  946. return task.cont
  947. # No doLaterProcessor in the new world.
  948. assert len(tm.getTasks()) == 0
  949. tm.add(_testGetTasks, 'testGetTasks1')
  950. assert len(tm.getTasks()) == 1
  951. assert (tm.getTasks()[0].name == 'testGetTasks1' or
  952. tm.getTasks()[1].name == 'testGetTasks1')
  953. tm.add(_testGetTasks, 'testGetTasks2')
  954. tm.add(_testGetTasks, 'testGetTasks3')
  955. assert len(tm.getTasks()) == 3
  956. tm.remove('testGetTasks2')
  957. assert len(tm.getTasks()) == 2
  958. tm.remove('testGetTasks1')
  959. tm.remove('testGetTasks3')
  960. assert len(tm.getTasks()) == 0
  961. _testGetTasks = None
  962. tm._checkMemLeaks()
  963. # getDoLaters
  964. def _testGetDoLaters():
  965. pass
  966. assert len(tm.getDoLaters()) == 0
  967. tm.doMethodLater(.1, _testGetDoLaters, 'testDoLater1')
  968. assert len(tm.getDoLaters()) == 1
  969. assert tm.getDoLaters()[0].name == 'testDoLater1'
  970. tm.doMethodLater(.1, _testGetDoLaters, 'testDoLater2')
  971. tm.doMethodLater(.1, _testGetDoLaters, 'testDoLater3')
  972. assert len(tm.getDoLaters()) == 3
  973. tm.remove('testDoLater2')
  974. assert len(tm.getDoLaters()) == 2
  975. tm.remove('testDoLater1')
  976. tm.remove('testDoLater3')
  977. assert len(tm.getDoLaters()) == 0
  978. _testGetDoLaters = None
  979. tm._checkMemLeaks()
  980. # duplicate named doLaters removed via taskMgr.remove
  981. def _testDupNameDoLaters():
  982. pass
  983. # the doLaterProcessor is always running
  984. tm.doMethodLater(.1, _testDupNameDoLaters, 'testDupNameDoLater')
  985. tm.doMethodLater(.1, _testDupNameDoLaters, 'testDupNameDoLater')
  986. assert len(tm.getDoLaters()) == 2
  987. tm.remove('testDupNameDoLater')
  988. assert len(tm.getDoLaters()) == 0
  989. _testDupNameDoLaters = None
  990. tm._checkMemLeaks()
  991. # duplicate named doLaters removed via remove()
  992. def _testDupNameDoLatersRemove():
  993. pass
  994. # the doLaterProcessor is always running
  995. dl1 = tm.doMethodLater(.1, _testDupNameDoLatersRemove, 'testDupNameDoLaterRemove')
  996. dl2 = tm.doMethodLater(.1, _testDupNameDoLatersRemove, 'testDupNameDoLaterRemove')
  997. assert len(tm.getDoLaters()) == 2
  998. dl2.remove()
  999. assert len(tm.getDoLaters()) == 1
  1000. dl1.remove()
  1001. assert len(tm.getDoLaters()) == 0
  1002. _testDupNameDoLatersRemove = None
  1003. # nameDict etc. isn't cleared out right away with task.remove()
  1004. tm._checkMemLeaks()
  1005. # getTasksNamed
  1006. def _testGetTasksNamed(task):
  1007. return task.cont
  1008. assert len(tm.getTasksNamed('testGetTasksNamed')) == 0
  1009. tm.add(_testGetTasksNamed, 'testGetTasksNamed')
  1010. assert len(tm.getTasksNamed('testGetTasksNamed')) == 1
  1011. assert tm.getTasksNamed('testGetTasksNamed')[0].name == 'testGetTasksNamed'
  1012. tm.add(_testGetTasksNamed, 'testGetTasksNamed')
  1013. tm.add(_testGetTasksNamed, 'testGetTasksNamed')
  1014. assert len(tm.getTasksNamed('testGetTasksNamed')) == 3
  1015. tm.remove('testGetTasksNamed')
  1016. assert len(tm.getTasksNamed('testGetTasksNamed')) == 0
  1017. _testGetTasksNamed = None
  1018. tm._checkMemLeaks()
  1019. # removeTasksMatching
  1020. def _testRemoveTasksMatching(task):
  1021. return task.cont
  1022. tm.add(_testRemoveTasksMatching, 'testRemoveTasksMatching')
  1023. assert len(tm.getTasksNamed('testRemoveTasksMatching')) == 1
  1024. tm.removeTasksMatching('testRemoveTasksMatching')
  1025. assert len(tm.getTasksNamed('testRemoveTasksMatching')) == 0
  1026. tm.add(_testRemoveTasksMatching, 'testRemoveTasksMatching1')
  1027. tm.add(_testRemoveTasksMatching, 'testRemoveTasksMatching2')
  1028. assert len(tm.getTasksNamed('testRemoveTasksMatching1')) == 1
  1029. assert len(tm.getTasksNamed('testRemoveTasksMatching2')) == 1
  1030. tm.removeTasksMatching('testRemoveTasksMatching*')
  1031. assert len(tm.getTasksNamed('testRemoveTasksMatching1')) == 0
  1032. assert len(tm.getTasksNamed('testRemoveTasksMatching2')) == 0
  1033. tm.add(_testRemoveTasksMatching, 'testRemoveTasksMatching1a')
  1034. tm.add(_testRemoveTasksMatching, 'testRemoveTasksMatching2a')
  1035. assert len(tm.getTasksNamed('testRemoveTasksMatching1a')) == 1
  1036. assert len(tm.getTasksNamed('testRemoveTasksMatching2a')) == 1
  1037. tm.removeTasksMatching('testRemoveTasksMatching?a')
  1038. assert len(tm.getTasksNamed('testRemoveTasksMatching1a')) == 0
  1039. assert len(tm.getTasksNamed('testRemoveTasksMatching2a')) == 0
  1040. _testRemoveTasksMatching = None
  1041. tm._checkMemLeaks()
  1042. # create Task object and add to mgr
  1043. l = []
  1044. def _testTaskObj(task, l=l):
  1045. l.append(None)
  1046. return task.cont
  1047. t = Task(_testTaskObj)
  1048. tm.add(t, 'testTaskObj')
  1049. tm.step()
  1050. assert len(l) == 1
  1051. tm.step()
  1052. assert len(l) == 2
  1053. tm.remove('testTaskObj')
  1054. tm.step()
  1055. assert len(l) == 2
  1056. _testTaskObj = None
  1057. tm._checkMemLeaks()
  1058. # remove Task via task.remove()
  1059. l = []
  1060. def _testTaskObjRemove(task, l=l):
  1061. l.append(None)
  1062. return task.cont
  1063. t = Task(_testTaskObjRemove)
  1064. tm.add(t, 'testTaskObjRemove')
  1065. tm.step()
  1066. assert len(l) == 1
  1067. tm.step()
  1068. assert len(l) == 2
  1069. t.remove()
  1070. tm.step()
  1071. assert len(l) == 2
  1072. del t
  1073. _testTaskObjRemove = None
  1074. tm._checkMemLeaks()
  1075. """
  1076. # this test fails, and it's not clear what the correct behavior should be.
  1077. # sort passed to Task.__init__ is always overridden by taskMgr.add()
  1078. # even if no sort is specified, and calling Task.setSort() has no
  1079. # effect on the taskMgr's behavior.
  1080. # set/get Task sort
  1081. l = []
  1082. def _testTaskObjSort(arg, task, l=l):
  1083. l.append(arg)
  1084. return task.cont
  1085. t1 = Task(_testTaskObjSort, sort=1)
  1086. t2 = Task(_testTaskObjSort, sort=2)
  1087. tm.add(t1, 'testTaskObjSort1', extraArgs=['a',], appendTask=True)
  1088. tm.add(t2, 'testTaskObjSort2', extraArgs=['b',], appendTask=True)
  1089. tm.step()
  1090. assert len(l) == 2
  1091. assert l == ['a', 'b']
  1092. assert t1.getSort() == 1
  1093. assert t2.getSort() == 2
  1094. t1.setSort(3)
  1095. assert t1.getSort() == 3
  1096. tm.step()
  1097. assert len(l) == 4
  1098. assert l == ['a', 'b', 'b', 'a',]
  1099. t1.remove()
  1100. t2.remove()
  1101. tm.step()
  1102. assert len(l) == 4
  1103. del t1
  1104. del t2
  1105. _testTaskObjSort = None
  1106. tm._checkMemLeaks()
  1107. """
  1108. del l
  1109. tm.destroy()
  1110. del tm
  1111. if __debug__:
  1112. def checkLeak():
  1113. import sys
  1114. import gc
  1115. gc.enable()
  1116. from direct.showbase.DirectObject import DirectObject
  1117. class TestClass(DirectObject):
  1118. def doTask(self, task):
  1119. return task.done
  1120. obj = TestClass()
  1121. startRefCount = sys.getrefcount(obj)
  1122. print('sys.getrefcount(obj): %s' % sys.getrefcount(obj))
  1123. print('** addTask')
  1124. t = obj.addTask(obj.doTask, 'test')
  1125. print('sys.getrefcount(obj): %s' % sys.getrefcount(obj))
  1126. print('task.getRefCount(): %s' % t.getRefCount())
  1127. print('** removeTask')
  1128. obj.removeTask('test')
  1129. print('sys.getrefcount(obj): %s' % sys.getrefcount(obj))
  1130. print('task.getRefCount(): %s' % t.getRefCount())
  1131. print('** step')
  1132. taskMgr.step()
  1133. taskMgr.step()
  1134. taskMgr.step()
  1135. print('sys.getrefcount(obj): %s' % sys.getrefcount(obj))
  1136. print('task.getRefCount(): %s' % t.getRefCount())
  1137. print('** task release')
  1138. t = None
  1139. print('sys.getrefcount(obj): %s' % sys.getrefcount(obj))
  1140. assert sys.getrefcount(obj) == startRefCount