Task.py 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298
  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 as 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, method.__self__)
  502. task.setFunction(newMethod)
  503. # Found a match
  504. return 1
  505. return 0
  506. def replaceMethod(self, oldMethod, newFunction):
  507. numFound = 0
  508. for task in self.getAllTasks():
  509. numFound += self.__tryReplaceTaskMethod(task, oldMethod, newFunction)
  510. return numFound
  511. def popupControls(self):
  512. # Don't use a regular import, to prevent ModuleFinder from picking
  513. # it up as a dependency when building a .p3d package.
  514. TaskManagerPanel = importlib.import_module('direct.tkpanels.TaskManagerPanel')
  515. return TaskManagerPanel.TaskManagerPanel(self)
  516. def getProfileSession(self, name=None):
  517. # call to get a profile session that you can modify before passing to profileFrames()
  518. if name is None:
  519. name = 'taskMgrFrameProfile'
  520. # Defer this import until we need it: some Python
  521. # distributions don't provide the profile and pstats modules.
  522. PS = importlib.import_module('direct.showbase.ProfileSession')
  523. return PS.ProfileSession(name)
  524. def profileFrames(self, num=None, session=None, callback=None):
  525. if num is None:
  526. num = 1
  527. if session is None:
  528. session = self.getProfileSession()
  529. # make sure the profile session doesn't get destroyed before we're done with it
  530. session.acquire()
  531. self._frameProfileQueue.append((num, session, callback))
  532. def _doProfiledFrames(self, numFrames):
  533. for i in range(numFrames):
  534. result = self.step()
  535. return result
  536. def getProfileFrames(self):
  537. return self._profileFrames.get()
  538. def getProfileFramesSV(self):
  539. return self._profileFrames
  540. def setProfileFrames(self, profileFrames):
  541. self._profileFrames.set(profileFrames)
  542. if (not self._frameProfiler) and profileFrames:
  543. # import here due to import dependencies
  544. FP = importlib.import_module('direct.task.FrameProfiler')
  545. self._frameProfiler = FP.FrameProfiler()
  546. def getProfileTasks(self):
  547. return self._profileTasks.get()
  548. def getProfileTasksSV(self):
  549. return self._profileTasks
  550. def setProfileTasks(self, profileTasks):
  551. self._profileTasks.set(profileTasks)
  552. if (not self._taskProfiler) and profileTasks:
  553. # import here due to import dependencies
  554. TP = importlib.import_module('direct.task.TaskProfiler')
  555. self._taskProfiler = TP.TaskProfiler()
  556. def logTaskProfiles(self, name=None):
  557. if self._taskProfiler:
  558. self._taskProfiler.logProfiles(name)
  559. def flushTaskProfiles(self, name=None):
  560. if self._taskProfiler:
  561. self._taskProfiler.flush(name)
  562. def _setProfileTask(self, task):
  563. if self._taskProfileInfo.session:
  564. self._taskProfileInfo.session.release()
  565. self._taskProfileInfo.session = None
  566. self._taskProfileInfo = ScratchPad(
  567. taskFunc = task.getFunction(),
  568. taskArgs = task.getArgs(),
  569. task = task,
  570. profiled = False,
  571. session = None,
  572. )
  573. # Temporarily replace the task's own function with our
  574. # _profileTask method.
  575. task.setFunction(self._profileTask)
  576. task.setArgs([self._taskProfileInfo], True)
  577. def _profileTask(self, profileInfo, task):
  578. # This is called instead of the task function when we have
  579. # decided to profile a task.
  580. assert profileInfo.task == task
  581. # don't profile the same task twice in a row
  582. assert not profileInfo.profiled
  583. # Restore the task's proper function for next time.
  584. appendTask = False
  585. taskArgs = profileInfo.taskArgs
  586. if taskArgs and taskArgs[-1] == task:
  587. appendTask = True
  588. taskArgs = taskArgs[:-1]
  589. task.setArgs(taskArgs, appendTask)
  590. task.setFunction(profileInfo.taskFunc)
  591. # Defer this import until we need it: some Python
  592. # distributions don't provide the profile and pstats modules.
  593. PS = importlib.import_module('direct.showbase.ProfileSession')
  594. profileSession = PS.ProfileSession('profiled-task-%s' % task.getName(),
  595. Functor(profileInfo.taskFunc, *profileInfo.taskArgs))
  596. ret = profileSession.run()
  597. # set these values *after* profiling in case we're profiling the TaskProfiler
  598. profileInfo.session = profileSession
  599. profileInfo.profiled = True
  600. return ret
  601. def _hasProfiledDesignatedTask(self):
  602. # have we run a profile of the designated task yet?
  603. return self._taskProfileInfo.profiled
  604. def _getLastTaskProfileSession(self):
  605. return self._taskProfileInfo.session
  606. def _getRandomTask(self):
  607. # Figure out when the next frame is likely to expire, so we
  608. # won't grab any tasks that are sleeping for a long time.
  609. now = self.globalClock.getFrameTime()
  610. avgFrameRate = self.globalClock.getAverageFrameRate()
  611. if avgFrameRate < .00001:
  612. avgFrameDur = 0.
  613. else:
  614. avgFrameDur = (1. / self.globalClock.getAverageFrameRate())
  615. next = now + avgFrameDur
  616. # Now grab a task at random, until we find one that we like.
  617. tasks = self.mgr.getTasks()
  618. i = random.randrange(tasks.getNumTasks())
  619. task = tasks.getTask(i)
  620. while not isinstance(task, PythonTask) or \
  621. task.getWakeTime() > next:
  622. tasks.removeTask(i)
  623. i = random.randrange(tasks.getNumTasks())
  624. task = tasks.getTask(i)
  625. return task
  626. def __repr__(self):
  627. return str(self.mgr)
  628. # In the event we want to do frame time managment, this is the
  629. # function to replace or overload.
  630. def doYield(self, frameStartTime, nextScheduledTaskTime):
  631. pass
  632. """
  633. def doYieldExample(self, frameStartTime, nextScheduledTaskTime):
  634. minFinTime = frameStartTime + self.MaxEpochSpeed
  635. if nextScheduledTaskTime > 0 and nextScheduledTaskTime < minFinTime:
  636. print ' Adjusting Time'
  637. minFinTime = nextScheduledTaskTime
  638. delta = minFinTime - self.globalClock.getRealTime()
  639. while(delta > 0.002):
  640. print ' sleep %s'% (delta)
  641. time.sleep(delta)
  642. delta = minFinTime - self.globalClock.getRealTime()
  643. """
  644. if __debug__:
  645. # to catch memory leaks during the tests at the bottom of the file
  646. def _startTrackingMemLeaks(self):
  647. pass
  648. def _stopTrackingMemLeaks(self):
  649. pass
  650. def _checkMemLeaks(self):
  651. pass
  652. def _runTests(self):
  653. if __debug__:
  654. tm = TaskManager()
  655. tm.setClock(ClockObject())
  656. tm.setupTaskChain("default", tickClock = True)
  657. # check for memory leaks after every test
  658. tm._startTrackingMemLeaks()
  659. tm._checkMemLeaks()
  660. # run-once task
  661. l = []
  662. def _testDone(task, l=l):
  663. l.append(None)
  664. return task.done
  665. tm.add(_testDone, 'testDone')
  666. tm.step()
  667. assert len(l) == 1
  668. tm.step()
  669. assert len(l) == 1
  670. _testDone = None
  671. tm._checkMemLeaks()
  672. # remove by name
  673. def _testRemoveByName(task):
  674. return task.done
  675. tm.add(_testRemoveByName, 'testRemoveByName')
  676. assert tm.remove('testRemoveByName') == 1
  677. assert tm.remove('testRemoveByName') == 0
  678. _testRemoveByName = None
  679. tm._checkMemLeaks()
  680. # duplicate named tasks
  681. def _testDupNamedTasks(task):
  682. return task.done
  683. tm.add(_testDupNamedTasks, 'testDupNamedTasks')
  684. tm.add(_testDupNamedTasks, 'testDupNamedTasks')
  685. assert tm.remove('testRemoveByName') == 0
  686. _testDupNamedTasks = None
  687. tm._checkMemLeaks()
  688. # continued task
  689. l = []
  690. def _testCont(task, l = l):
  691. l.append(None)
  692. return task.cont
  693. tm.add(_testCont, 'testCont')
  694. tm.step()
  695. assert len(l) == 1
  696. tm.step()
  697. assert len(l) == 2
  698. tm.remove('testCont')
  699. _testCont = None
  700. tm._checkMemLeaks()
  701. # continue until done task
  702. l = []
  703. def _testContDone(task, l = l):
  704. l.append(None)
  705. if len(l) >= 2:
  706. return task.done
  707. else:
  708. return task.cont
  709. tm.add(_testContDone, 'testContDone')
  710. tm.step()
  711. assert len(l) == 1
  712. tm.step()
  713. assert len(l) == 2
  714. tm.step()
  715. assert len(l) == 2
  716. assert not tm.hasTaskNamed('testContDone')
  717. _testContDone = None
  718. tm._checkMemLeaks()
  719. # hasTaskNamed
  720. def _testHasTaskNamed(task):
  721. return task.done
  722. tm.add(_testHasTaskNamed, 'testHasTaskNamed')
  723. assert tm.hasTaskNamed('testHasTaskNamed')
  724. tm.step()
  725. assert not tm.hasTaskNamed('testHasTaskNamed')
  726. _testHasTaskNamed = None
  727. tm._checkMemLeaks()
  728. # task sort
  729. l = []
  730. def _testPri1(task, l = l):
  731. l.append(1)
  732. return task.cont
  733. def _testPri2(task, l = l):
  734. l.append(2)
  735. return task.cont
  736. tm.add(_testPri1, 'testPri1', sort = 1)
  737. tm.add(_testPri2, 'testPri2', sort = 2)
  738. tm.step()
  739. assert len(l) == 2
  740. assert l == [1, 2,]
  741. tm.step()
  742. assert len(l) == 4
  743. assert l == [1, 2, 1, 2,]
  744. tm.remove('testPri1')
  745. tm.remove('testPri2')
  746. _testPri1 = None
  747. _testPri2 = None
  748. tm._checkMemLeaks()
  749. # task extraArgs
  750. l = []
  751. def _testExtraArgs(arg1, arg2, l=l):
  752. l.extend([arg1, arg2,])
  753. return done
  754. tm.add(_testExtraArgs, 'testExtraArgs', extraArgs=[4,5])
  755. tm.step()
  756. assert len(l) == 2
  757. assert l == [4, 5,]
  758. _testExtraArgs = None
  759. tm._checkMemLeaks()
  760. # task appendTask
  761. l = []
  762. def _testAppendTask(arg1, arg2, task, l=l):
  763. l.extend([arg1, arg2,])
  764. return task.done
  765. tm.add(_testAppendTask, '_testAppendTask', extraArgs=[4,5], appendTask=True)
  766. tm.step()
  767. assert len(l) == 2
  768. assert l == [4, 5,]
  769. _testAppendTask = None
  770. tm._checkMemLeaks()
  771. # task uponDeath
  772. l = []
  773. def _uponDeathFunc(task, l=l):
  774. l.append(task.name)
  775. def _testUponDeath(task):
  776. return done
  777. tm.add(_testUponDeath, 'testUponDeath', uponDeath=_uponDeathFunc)
  778. tm.step()
  779. assert len(l) == 1
  780. assert l == ['testUponDeath']
  781. _testUponDeath = None
  782. _uponDeathFunc = None
  783. tm._checkMemLeaks()
  784. # task owner
  785. class _TaskOwner:
  786. def _addTask(self, task):
  787. self.addedTaskName = task.name
  788. def _clearTask(self, task):
  789. self.clearedTaskName = task.name
  790. to = _TaskOwner()
  791. l = []
  792. def _testOwner(task):
  793. return done
  794. tm.add(_testOwner, 'testOwner', owner=to)
  795. tm.step()
  796. assert getattr(to, 'addedTaskName', None) == 'testOwner'
  797. assert getattr(to, 'clearedTaskName', None) == 'testOwner'
  798. _testOwner = None
  799. del to
  800. _TaskOwner = None
  801. tm._checkMemLeaks()
  802. doLaterTests = [0,]
  803. # doLater
  804. l = []
  805. def _testDoLater1(task, l=l):
  806. l.append(1)
  807. def _testDoLater2(task, l=l):
  808. l.append(2)
  809. def _monitorDoLater(task, tm=tm, l=l, doLaterTests=doLaterTests):
  810. if task.time > .03:
  811. assert l == [1, 2,]
  812. doLaterTests[0] -= 1
  813. return task.done
  814. return task.cont
  815. tm.doMethodLater(.01, _testDoLater1, 'testDoLater1')
  816. tm.doMethodLater(.02, _testDoLater2, 'testDoLater2')
  817. doLaterTests[0] += 1
  818. # make sure we run this task after the doLaters if they all occur on the same frame
  819. tm.add(_monitorDoLater, 'monitorDoLater', sort=10)
  820. _testDoLater1 = None
  821. _testDoLater2 = None
  822. _monitorDoLater = None
  823. # don't check until all the doLaters are finished
  824. #tm._checkMemLeaks()
  825. # doLater sort
  826. l = []
  827. def _testDoLaterPri1(task, l=l):
  828. l.append(1)
  829. def _testDoLaterPri2(task, l=l):
  830. l.append(2)
  831. def _monitorDoLaterPri(task, tm=tm, l=l, doLaterTests=doLaterTests):
  832. if task.time > .02:
  833. assert l == [1, 2,]
  834. doLaterTests[0] -= 1
  835. return task.done
  836. return task.cont
  837. tm.doMethodLater(.01, _testDoLaterPri1, 'testDoLaterPri1', sort=1)
  838. tm.doMethodLater(.01, _testDoLaterPri2, 'testDoLaterPri2', sort=2)
  839. doLaterTests[0] += 1
  840. # make sure we run this task after the doLaters if they all occur on the same frame
  841. tm.add(_monitorDoLaterPri, 'monitorDoLaterPri', sort=10)
  842. _testDoLaterPri1 = None
  843. _testDoLaterPri2 = None
  844. _monitorDoLaterPri = None
  845. # don't check until all the doLaters are finished
  846. #tm._checkMemLeaks()
  847. # doLater extraArgs
  848. l = []
  849. def _testDoLaterExtraArgs(arg1, l=l):
  850. l.append(arg1)
  851. def _monitorDoLaterExtraArgs(task, tm=tm, l=l, doLaterTests=doLaterTests):
  852. if task.time > .02:
  853. assert l == [3,]
  854. doLaterTests[0] -= 1
  855. return task.done
  856. return task.cont
  857. tm.doMethodLater(.01, _testDoLaterExtraArgs, 'testDoLaterExtraArgs', extraArgs=[3,])
  858. doLaterTests[0] += 1
  859. # make sure we run this task after the doLaters if they all occur on the same frame
  860. tm.add(_monitorDoLaterExtraArgs, 'monitorDoLaterExtraArgs', sort=10)
  861. _testDoLaterExtraArgs = None
  862. _monitorDoLaterExtraArgs = None
  863. # don't check until all the doLaters are finished
  864. #tm._checkMemLeaks()
  865. # doLater appendTask
  866. l = []
  867. def _testDoLaterAppendTask(arg1, task, l=l):
  868. assert task.name == 'testDoLaterAppendTask'
  869. l.append(arg1)
  870. def _monitorDoLaterAppendTask(task, tm=tm, l=l, doLaterTests=doLaterTests):
  871. if task.time > .02:
  872. assert l == [4,]
  873. doLaterTests[0] -= 1
  874. return task.done
  875. return task.cont
  876. tm.doMethodLater(.01, _testDoLaterAppendTask, 'testDoLaterAppendTask',
  877. extraArgs=[4,], appendTask=True)
  878. doLaterTests[0] += 1
  879. # make sure we run this task after the doLaters if they all occur on the same frame
  880. tm.add(_monitorDoLaterAppendTask, 'monitorDoLaterAppendTask', sort=10)
  881. _testDoLaterAppendTask = None
  882. _monitorDoLaterAppendTask = None
  883. # don't check until all the doLaters are finished
  884. #tm._checkMemLeaks()
  885. # doLater uponDeath
  886. l = []
  887. def _testUponDeathFunc(task, l=l):
  888. assert task.name == 'testDoLaterUponDeath'
  889. l.append(10)
  890. def _testDoLaterUponDeath(arg1, l=l):
  891. return done
  892. def _monitorDoLaterUponDeath(task, tm=tm, l=l, doLaterTests=doLaterTests):
  893. if task.time > .02:
  894. assert l == [10,]
  895. doLaterTests[0] -= 1
  896. return task.done
  897. return task.cont
  898. tm.doMethodLater(.01, _testDoLaterUponDeath, 'testDoLaterUponDeath',
  899. uponDeath=_testUponDeathFunc)
  900. doLaterTests[0] += 1
  901. # make sure we run this task after the doLaters if they all occur on the same frame
  902. tm.add(_monitorDoLaterUponDeath, 'monitorDoLaterUponDeath', sort=10)
  903. _testUponDeathFunc = None
  904. _testDoLaterUponDeath = None
  905. _monitorDoLaterUponDeath = None
  906. # don't check until all the doLaters are finished
  907. #tm._checkMemLeaks()
  908. # doLater owner
  909. class _DoLaterOwner:
  910. def _addTask(self, task):
  911. self.addedTaskName = task.name
  912. def _clearTask(self, task):
  913. self.clearedTaskName = task.name
  914. doLaterOwner = _DoLaterOwner()
  915. l = []
  916. def _testDoLaterOwner(l=l):
  917. pass
  918. def _monitorDoLaterOwner(task, tm=tm, l=l, doLaterOwner=doLaterOwner,
  919. doLaterTests=doLaterTests):
  920. if task.time > .02:
  921. assert getattr(doLaterOwner, 'addedTaskName', None) == 'testDoLaterOwner'
  922. assert getattr(doLaterOwner, 'clearedTaskName', None) == 'testDoLaterOwner'
  923. doLaterTests[0] -= 1
  924. return task.done
  925. return task.cont
  926. tm.doMethodLater(.01, _testDoLaterOwner, 'testDoLaterOwner',
  927. owner=doLaterOwner)
  928. doLaterTests[0] += 1
  929. # make sure we run this task after the doLaters if they all occur on the same frame
  930. tm.add(_monitorDoLaterOwner, 'monitorDoLaterOwner', sort=10)
  931. _testDoLaterOwner = None
  932. _monitorDoLaterOwner = None
  933. del doLaterOwner
  934. _DoLaterOwner = None
  935. # don't check until all the doLaters are finished
  936. #tm._checkMemLeaks()
  937. # run the doLater tests
  938. while doLaterTests[0] > 0:
  939. tm.step()
  940. del doLaterTests
  941. tm._checkMemLeaks()
  942. # getTasks
  943. def _testGetTasks(task):
  944. return task.cont
  945. # No doLaterProcessor in the new world.
  946. assert len(tm.getTasks()) == 0
  947. tm.add(_testGetTasks, 'testGetTasks1')
  948. assert len(tm.getTasks()) == 1
  949. assert (tm.getTasks()[0].name == 'testGetTasks1' or
  950. tm.getTasks()[1].name == 'testGetTasks1')
  951. tm.add(_testGetTasks, 'testGetTasks2')
  952. tm.add(_testGetTasks, 'testGetTasks3')
  953. assert len(tm.getTasks()) == 3
  954. tm.remove('testGetTasks2')
  955. assert len(tm.getTasks()) == 2
  956. tm.remove('testGetTasks1')
  957. tm.remove('testGetTasks3')
  958. assert len(tm.getTasks()) == 0
  959. _testGetTasks = None
  960. tm._checkMemLeaks()
  961. # getDoLaters
  962. def _testGetDoLaters():
  963. pass
  964. assert len(tm.getDoLaters()) == 0
  965. tm.doMethodLater(.1, _testGetDoLaters, 'testDoLater1')
  966. assert len(tm.getDoLaters()) == 1
  967. assert tm.getDoLaters()[0].name == 'testDoLater1'
  968. tm.doMethodLater(.1, _testGetDoLaters, 'testDoLater2')
  969. tm.doMethodLater(.1, _testGetDoLaters, 'testDoLater3')
  970. assert len(tm.getDoLaters()) == 3
  971. tm.remove('testDoLater2')
  972. assert len(tm.getDoLaters()) == 2
  973. tm.remove('testDoLater1')
  974. tm.remove('testDoLater3')
  975. assert len(tm.getDoLaters()) == 0
  976. _testGetDoLaters = None
  977. tm._checkMemLeaks()
  978. # duplicate named doLaters removed via taskMgr.remove
  979. def _testDupNameDoLaters():
  980. pass
  981. # the doLaterProcessor is always running
  982. tm.doMethodLater(.1, _testDupNameDoLaters, 'testDupNameDoLater')
  983. tm.doMethodLater(.1, _testDupNameDoLaters, 'testDupNameDoLater')
  984. assert len(tm.getDoLaters()) == 2
  985. tm.remove('testDupNameDoLater')
  986. assert len(tm.getDoLaters()) == 0
  987. _testDupNameDoLaters = None
  988. tm._checkMemLeaks()
  989. # duplicate named doLaters removed via remove()
  990. def _testDupNameDoLatersRemove():
  991. pass
  992. # the doLaterProcessor is always running
  993. dl1 = tm.doMethodLater(.1, _testDupNameDoLatersRemove, 'testDupNameDoLaterRemove')
  994. dl2 = tm.doMethodLater(.1, _testDupNameDoLatersRemove, 'testDupNameDoLaterRemove')
  995. assert len(tm.getDoLaters()) == 2
  996. dl2.remove()
  997. assert len(tm.getDoLaters()) == 1
  998. dl1.remove()
  999. assert len(tm.getDoLaters()) == 0
  1000. _testDupNameDoLatersRemove = None
  1001. # nameDict etc. isn't cleared out right away with task.remove()
  1002. tm._checkMemLeaks()
  1003. # getTasksNamed
  1004. def _testGetTasksNamed(task):
  1005. return task.cont
  1006. assert len(tm.getTasksNamed('testGetTasksNamed')) == 0
  1007. tm.add(_testGetTasksNamed, 'testGetTasksNamed')
  1008. assert len(tm.getTasksNamed('testGetTasksNamed')) == 1
  1009. assert tm.getTasksNamed('testGetTasksNamed')[0].name == 'testGetTasksNamed'
  1010. tm.add(_testGetTasksNamed, 'testGetTasksNamed')
  1011. tm.add(_testGetTasksNamed, 'testGetTasksNamed')
  1012. assert len(tm.getTasksNamed('testGetTasksNamed')) == 3
  1013. tm.remove('testGetTasksNamed')
  1014. assert len(tm.getTasksNamed('testGetTasksNamed')) == 0
  1015. _testGetTasksNamed = None
  1016. tm._checkMemLeaks()
  1017. # removeTasksMatching
  1018. def _testRemoveTasksMatching(task):
  1019. return task.cont
  1020. tm.add(_testRemoveTasksMatching, 'testRemoveTasksMatching')
  1021. assert len(tm.getTasksNamed('testRemoveTasksMatching')) == 1
  1022. tm.removeTasksMatching('testRemoveTasksMatching')
  1023. assert len(tm.getTasksNamed('testRemoveTasksMatching')) == 0
  1024. tm.add(_testRemoveTasksMatching, 'testRemoveTasksMatching1')
  1025. tm.add(_testRemoveTasksMatching, 'testRemoveTasksMatching2')
  1026. assert len(tm.getTasksNamed('testRemoveTasksMatching1')) == 1
  1027. assert len(tm.getTasksNamed('testRemoveTasksMatching2')) == 1
  1028. tm.removeTasksMatching('testRemoveTasksMatching*')
  1029. assert len(tm.getTasksNamed('testRemoveTasksMatching1')) == 0
  1030. assert len(tm.getTasksNamed('testRemoveTasksMatching2')) == 0
  1031. tm.add(_testRemoveTasksMatching, 'testRemoveTasksMatching1a')
  1032. tm.add(_testRemoveTasksMatching, 'testRemoveTasksMatching2a')
  1033. assert len(tm.getTasksNamed('testRemoveTasksMatching1a')) == 1
  1034. assert len(tm.getTasksNamed('testRemoveTasksMatching2a')) == 1
  1035. tm.removeTasksMatching('testRemoveTasksMatching?a')
  1036. assert len(tm.getTasksNamed('testRemoveTasksMatching1a')) == 0
  1037. assert len(tm.getTasksNamed('testRemoveTasksMatching2a')) == 0
  1038. _testRemoveTasksMatching = None
  1039. tm._checkMemLeaks()
  1040. # create Task object and add to mgr
  1041. l = []
  1042. def _testTaskObj(task, l=l):
  1043. l.append(None)
  1044. return task.cont
  1045. t = Task(_testTaskObj)
  1046. tm.add(t, 'testTaskObj')
  1047. tm.step()
  1048. assert len(l) == 1
  1049. tm.step()
  1050. assert len(l) == 2
  1051. tm.remove('testTaskObj')
  1052. tm.step()
  1053. assert len(l) == 2
  1054. _testTaskObj = None
  1055. tm._checkMemLeaks()
  1056. # remove Task via task.remove()
  1057. l = []
  1058. def _testTaskObjRemove(task, l=l):
  1059. l.append(None)
  1060. return task.cont
  1061. t = Task(_testTaskObjRemove)
  1062. tm.add(t, 'testTaskObjRemove')
  1063. tm.step()
  1064. assert len(l) == 1
  1065. tm.step()
  1066. assert len(l) == 2
  1067. t.remove()
  1068. tm.step()
  1069. assert len(l) == 2
  1070. del t
  1071. _testTaskObjRemove = None
  1072. tm._checkMemLeaks()
  1073. """
  1074. # this test fails, and it's not clear what the correct behavior should be.
  1075. # sort passed to Task.__init__ is always overridden by taskMgr.add()
  1076. # even if no sort is specified, and calling Task.setSort() has no
  1077. # effect on the taskMgr's behavior.
  1078. # set/get Task sort
  1079. l = []
  1080. def _testTaskObjSort(arg, task, l=l):
  1081. l.append(arg)
  1082. return task.cont
  1083. t1 = Task(_testTaskObjSort, sort=1)
  1084. t2 = Task(_testTaskObjSort, sort=2)
  1085. tm.add(t1, 'testTaskObjSort1', extraArgs=['a',], appendTask=True)
  1086. tm.add(t2, 'testTaskObjSort2', extraArgs=['b',], appendTask=True)
  1087. tm.step()
  1088. assert len(l) == 2
  1089. assert l == ['a', 'b']
  1090. assert t1.getSort() == 1
  1091. assert t2.getSort() == 2
  1092. t1.setSort(3)
  1093. assert t1.getSort() == 3
  1094. tm.step()
  1095. assert len(l) == 4
  1096. assert l == ['a', 'b', 'b', 'a',]
  1097. t1.remove()
  1098. t2.remove()
  1099. tm.step()
  1100. assert len(l) == 4
  1101. del t1
  1102. del t2
  1103. _testTaskObjSort = None
  1104. tm._checkMemLeaks()
  1105. """
  1106. del l
  1107. tm.destroy()
  1108. del tm
  1109. if __debug__:
  1110. def checkLeak():
  1111. import sys
  1112. import gc
  1113. gc.enable()
  1114. from direct.showbase.DirectObject import DirectObject
  1115. class TestClass(DirectObject):
  1116. def doTask(self, task):
  1117. return task.done
  1118. obj = TestClass()
  1119. startRefCount = sys.getrefcount(obj)
  1120. print('sys.getrefcount(obj): %s' % sys.getrefcount(obj))
  1121. print('** addTask')
  1122. t = obj.addTask(obj.doTask, 'test')
  1123. print('sys.getrefcount(obj): %s' % sys.getrefcount(obj))
  1124. print('task.getRefCount(): %s' % t.getRefCount())
  1125. print('** removeTask')
  1126. obj.removeTask('test')
  1127. print('sys.getrefcount(obj): %s' % sys.getrefcount(obj))
  1128. print('task.getRefCount(): %s' % t.getRefCount())
  1129. print('** step')
  1130. taskMgr.step()
  1131. taskMgr.step()
  1132. taskMgr.step()
  1133. print('sys.getrefcount(obj): %s' % sys.getrefcount(obj))
  1134. print('task.getRefCount(): %s' % t.getRefCount())
  1135. print('** task release')
  1136. t = None
  1137. print('sys.getrefcount(obj): %s' % sys.getrefcount(obj))
  1138. assert sys.getrefcount(obj) == startRefCount