Task.py 49 KB

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