DoInterestManager.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. """
  2. The DoInterestManager keeps track of which parent/zones that we currently
  3. have interest in. When you want to "look" into a zone you add an interest
  4. to that zone. When you want to get rid of, or ignore, the objects in that
  5. zone, remove interest in that zone.
  6. p.s. A great deal of this code is just code moved from ClientRepository.py.
  7. """
  8. from panda3d.core import *
  9. from panda3d.direct import *
  10. from .MsgTypes import *
  11. from direct.showbase.PythonUtil import *
  12. from direct.showbase import DirectObject
  13. from .PyDatagram import PyDatagram
  14. from direct.directnotify.DirectNotifyGlobal import directNotify
  15. import types
  16. from direct.showbase.PythonUtil import report
  17. class InterestState:
  18. StateActive = 'Active'
  19. StatePendingDel = 'PendingDel'
  20. def __init__(self, desc, state, context, event, parentId, zoneIdList,
  21. eventCounter, auto=False):
  22. self.desc = desc
  23. self.state = state
  24. self.context = context
  25. # We must be ready to keep track of multiple events. If somebody
  26. # requested an interest to be removed and we get a second request
  27. # for removal of the same interest before we get a response for the
  28. # first interest removal, we now have two parts of the codebase
  29. # waiting for a response on the removal of a single interest.
  30. self.events = []
  31. self.eventCounter = eventCounter
  32. if event:
  33. self.addEvent(event)
  34. self.parentId = parentId
  35. self.zoneIdList = zoneIdList
  36. self.auto = auto
  37. def addEvent(self, event):
  38. self.events.append(event)
  39. self.eventCounter.num += 1
  40. def getEvents(self):
  41. return list(self.events)
  42. def clearEvents(self):
  43. self.eventCounter.num -= len(self.events)
  44. assert self.eventCounter.num >= 0
  45. self.events = []
  46. def sendEvents(self):
  47. for event in self.events:
  48. messenger.send(event)
  49. self.clearEvents()
  50. def setDesc(self, desc):
  51. self.desc = desc
  52. def isPendingDelete(self):
  53. return self.state == InterestState.StatePendingDel
  54. def __repr__(self):
  55. return 'InterestState(desc=%s, state=%s, context=%s, event=%s, parentId=%s, zoneIdList=%s)' % (
  56. self.desc, self.state, self.context, self.events, self.parentId, self.zoneIdList)
  57. class InterestHandle:
  58. """This class helps to ensure that valid handles get passed in to DoInterestManager funcs"""
  59. def __init__(self, id):
  60. self._id = id
  61. def asInt(self):
  62. return self._id
  63. def __eq__(self, other):
  64. if type(self) == type(other):
  65. return self._id == other._id
  66. return self._id == other
  67. def __repr__(self):
  68. return '%s(%s)' % (self.__class__.__name__, self._id)
  69. # context value for interest changes that have no complete event
  70. NO_CONTEXT = 0
  71. class DoInterestManager(DirectObject.DirectObject):
  72. """
  73. Top level Interest Manager
  74. """
  75. notify = directNotify.newCategory("DoInterestManager")
  76. InterestDebug = ConfigVariableBool('interest-debug', False)
  77. # 'handle' is a number that represents a single interest set that the
  78. # client has requested; the interest set may be modified
  79. _HandleSerialNum = 0
  80. # high bit is reserved for server interests
  81. _HandleMask = 0x7FFF
  82. # 'context' refers to a single request to change an interest set
  83. _ContextIdSerialNum = 100
  84. _ContextIdMask = 0x3FFFFFFF # avoid making Python create a long
  85. _interests = {}
  86. if __debug__:
  87. _debug_interestHistory = []
  88. _debug_maxDescriptionLen = 40
  89. _SerialGen = SerialNumGen()
  90. _SerialNum = serialNum()
  91. def __init__(self):
  92. assert DoInterestManager.notify.debugCall()
  93. DirectObject.DirectObject.__init__(self)
  94. self._addInterestEvent = uniqueName('DoInterestManager-Add')
  95. self._removeInterestEvent = uniqueName('DoInterestManager-Remove')
  96. self._noNewInterests = False
  97. self._completeDelayedCallback = None
  98. # keep track of request contexts that have not completed
  99. self._completeEventCount = ScratchPad(num=0)
  100. self._allInterestsCompleteCallbacks = []
  101. def __verbose(self):
  102. return self.InterestDebug or self.getVerbose()
  103. def _getAnonymousEvent(self, desc):
  104. return 'anonymous-%s-%s' % (desc, DoInterestManager._SerialGen.next())
  105. def setNoNewInterests(self, flag):
  106. self._noNewInterests = flag
  107. def noNewInterests(self):
  108. return self._noNewInterests
  109. def setAllInterestsCompleteCallback(self, callback):
  110. if ((self._completeEventCount.num == 0) and
  111. (self._completeDelayedCallback is None)):
  112. callback()
  113. else:
  114. self._allInterestsCompleteCallbacks.append(callback)
  115. def getAllInterestsCompleteEvent(self):
  116. return 'allInterestsComplete-%s' % DoInterestManager._SerialNum
  117. def resetInterestStateForConnectionLoss(self):
  118. DoInterestManager._interests.clear()
  119. self._completeEventCount = ScratchPad(num=0)
  120. if __debug__:
  121. self._addDebugInterestHistory("RESET", "", 0, 0, 0, [])
  122. def isValidInterestHandle(self, handle):
  123. # pass in a handle (or anything else) and this will return true if it is
  124. # still a valid interest handle
  125. if not isinstance(handle, InterestHandle):
  126. return False
  127. return handle.asInt() in DoInterestManager._interests
  128. def updateInterestDescription(self, handle, desc):
  129. iState = DoInterestManager._interests.get(handle.asInt())
  130. if iState:
  131. iState.setDesc(desc)
  132. def addInterest(self, parentId, zoneIdList, description, event=None):
  133. """
  134. Look into a (set of) zone(s).
  135. """
  136. assert DoInterestManager.notify.debugCall()
  137. handle = self._getNextHandle()
  138. # print 'base.cr.addInterest(',description,',',handle,'):',globalClock.getFrameCount()
  139. if self._noNewInterests:
  140. DoInterestManager.notify.warning(
  141. "addInterest: addingInterests on delete: %s" % (handle))
  142. return
  143. # make sure we've got parenting rules set in the DC
  144. if parentId not in (self.getGameDoId(),):
  145. parent = self.getDo(parentId)
  146. if not parent:
  147. DoInterestManager.notify.error(
  148. 'addInterest: attempting to add interest under unknown object %s' % parentId)
  149. else:
  150. if not parent.hasParentingRules():
  151. DoInterestManager.notify.error(
  152. 'addInterest: no setParentingRules defined in the DC for object %s (%s)'
  153. '' % (parentId, parent.__class__.__name__))
  154. if event:
  155. contextId = self._getNextContextId()
  156. else:
  157. contextId = 0
  158. # event = self._getAnonymousEvent('addInterest')
  159. DoInterestManager._interests[handle] = InterestState(
  160. description, InterestState.StateActive, contextId, event, parentId, zoneIdList, self._completeEventCount)
  161. if self.__verbose():
  162. print('CR::INTEREST.addInterest(handle=%s, parentId=%s, zoneIdList=%s, description=%s, event=%s)' % (
  163. handle, parentId, zoneIdList, description, event))
  164. self._sendAddInterest(handle, contextId, parentId, zoneIdList, description)
  165. if event:
  166. messenger.send(self._getAddInterestEvent(), [event])
  167. assert self.printInterestsIfDebug()
  168. return InterestHandle(handle)
  169. def addAutoInterest(self, parentId, zoneIdList, description):
  170. """
  171. Look into a (set of) zone(s).
  172. """
  173. assert DoInterestManager.notify.debugCall()
  174. handle = self._getNextHandle()
  175. if self._noNewInterests:
  176. DoInterestManager.notify.warning(
  177. "addInterest: addingInterests on delete: %s" % (handle))
  178. return
  179. # make sure we've got parenting rules set in the DC
  180. if parentId not in (self.getGameDoId(),):
  181. parent = self.getDo(parentId)
  182. if not parent:
  183. DoInterestManager.notify.error(
  184. 'addInterest: attempting to add interest under unknown object %s' % parentId)
  185. else:
  186. if not parent.hasParentingRules():
  187. DoInterestManager.notify.error(
  188. 'addInterest: no setParentingRules defined in the DC for object %s (%s)'
  189. '' % (parentId, parent.__class__.__name__))
  190. DoInterestManager._interests[handle] = InterestState(
  191. description, InterestState.StateActive, 0, None, parentId, zoneIdList, self._completeEventCount, True)
  192. if self.__verbose():
  193. print('CR::INTEREST.addInterest(handle=%s, parentId=%s, zoneIdList=%s, description=%s)' % (
  194. handle, parentId, zoneIdList, description))
  195. assert self.printInterestsIfDebug()
  196. return InterestHandle(handle)
  197. def removeInterest(self, handle, event = None):
  198. """
  199. Stop looking in a (set of) zone(s)
  200. """
  201. # print 'base.cr.removeInterest(',handle,'):',globalClock.getFrameCount()
  202. assert DoInterestManager.notify.debugCall()
  203. assert isinstance(handle, InterestHandle)
  204. existed = False
  205. if not event:
  206. event = self._getAnonymousEvent('removeInterest')
  207. handle = handle.asInt()
  208. if handle in DoInterestManager._interests:
  209. existed = True
  210. intState = DoInterestManager._interests[handle]
  211. if event:
  212. messenger.send(self._getRemoveInterestEvent(),
  213. [event, intState.parentId, intState.zoneIdList])
  214. if intState.isPendingDelete():
  215. self.notify.warning(
  216. 'removeInterest: interest %s already pending removal' %
  217. handle)
  218. # this interest is already pending delete, so let's just tack this
  219. # callback onto the list
  220. if event is not None:
  221. intState.addEvent(event)
  222. else:
  223. if len(intState.events) > 0:
  224. # we're not pending a removal, but we have outstanding events?
  225. # probably we are waiting for an add/alter complete.
  226. # should we send those events now?
  227. assert self.notify.warning('removeInterest: abandoning events: %s' %
  228. intState.events)
  229. intState.clearEvents()
  230. intState.state = InterestState.StatePendingDel
  231. contextId = self._getNextContextId()
  232. intState.context = contextId
  233. if event:
  234. intState.addEvent(event)
  235. self._sendRemoveInterest(handle, contextId)
  236. if not event:
  237. self._considerRemoveInterest(handle)
  238. if self.__verbose():
  239. print('CR::INTEREST.removeInterest(handle=%s, event=%s)' % (
  240. handle, event))
  241. else:
  242. DoInterestManager.notify.warning(
  243. "removeInterest: handle not found: %s" % (handle))
  244. assert self.printInterestsIfDebug()
  245. return existed
  246. def removeAutoInterest(self, handle):
  247. """
  248. Stop looking in a (set of) zone(s)
  249. """
  250. assert DoInterestManager.notify.debugCall()
  251. assert isinstance(handle, InterestHandle)
  252. existed = False
  253. handle = handle.asInt()
  254. if handle in DoInterestManager._interests:
  255. existed = True
  256. intState = DoInterestManager._interests[handle]
  257. if intState.isPendingDelete():
  258. self.notify.warning(
  259. 'removeInterest: interest %s already pending removal' %
  260. handle)
  261. # this interest is already pending delete, so let's just tack this
  262. # callback onto the list
  263. else:
  264. if len(intState.events) > 0:
  265. # we're not pending a removal, but we have outstanding events?
  266. # probably we are waiting for an add/alter complete.
  267. # should we send those events now?
  268. self.notify.warning('removeInterest: abandoning events: %s' %
  269. intState.events)
  270. intState.clearEvents()
  271. intState.state = InterestState.StatePendingDel
  272. self._considerRemoveInterest(handle)
  273. if self.__verbose():
  274. print('CR::INTEREST.removeAutoInterest(handle=%s)' % (handle))
  275. else:
  276. DoInterestManager.notify.warning(
  277. "removeInterest: handle not found: %s" % (handle))
  278. assert self.printInterestsIfDebug()
  279. return existed
  280. @report(types = ['args'], dConfigParam = 'guildmgr')
  281. def removeAIInterest(self, handle):
  282. """
  283. handle is NOT an InterestHandle. It's just a bare integer representing an
  284. AI opened interest. We're making the client close down this interest since
  285. the AI has trouble removing interests(that its opened) when the avatar goes
  286. offline. See GuildManager(UD) for how it's being used.
  287. """
  288. self._sendRemoveAIInterest(handle)
  289. def alterInterest(self, handle, parentId, zoneIdList, description=None,
  290. event=None):
  291. """
  292. Removes old interests and adds new interests.
  293. Note that when an interest is changed, only the most recent
  294. change's event will be triggered. Previous events are abandoned.
  295. If this is a problem, consider opening multiple interests.
  296. """
  297. assert DoInterestManager.notify.debugCall()
  298. assert isinstance(handle, InterestHandle)
  299. #assert not self._noNewInterests
  300. handle = handle.asInt()
  301. if self._noNewInterests:
  302. DoInterestManager.notify.warning(
  303. "alterInterest: addingInterests on delete: %s" % (handle))
  304. return
  305. exists = False
  306. if event is None:
  307. event = self._getAnonymousEvent('alterInterest')
  308. if handle in DoInterestManager._interests:
  309. if description is not None:
  310. DoInterestManager._interests[handle].desc = description
  311. else:
  312. description = DoInterestManager._interests[handle].desc
  313. # are we overriding an existing change?
  314. if DoInterestManager._interests[handle].context != NO_CONTEXT:
  315. DoInterestManager._interests[handle].clearEvents()
  316. contextId = self._getNextContextId()
  317. DoInterestManager._interests[handle].context = contextId
  318. DoInterestManager._interests[handle].parentId = parentId
  319. DoInterestManager._interests[handle].zoneIdList = zoneIdList
  320. DoInterestManager._interests[handle].addEvent(event)
  321. if self.__verbose():
  322. print('CR::INTEREST.alterInterest(handle=%s, parentId=%s, zoneIdList=%s, description=%s, event=%s)' % (
  323. handle, parentId, zoneIdList, description, event))
  324. self._sendAddInterest(handle, contextId, parentId, zoneIdList, description, action='modify')
  325. exists = True
  326. assert self.printInterestsIfDebug()
  327. else:
  328. DoInterestManager.notify.warning(
  329. "alterInterest: handle not found: %s" % (handle))
  330. return exists
  331. def openAutoInterests(self, obj):
  332. if hasattr(obj, '_autoInterestHandle'):
  333. # must be multiple inheritance
  334. self.notify.debug('openAutoInterests(%s): interests already open' % obj.__class__.__name__)
  335. return
  336. autoInterests = obj.getAutoInterests()
  337. obj._autoInterestHandle = None
  338. if not len(autoInterests):
  339. return
  340. obj._autoInterestHandle = self.addAutoInterest(obj.doId, autoInterests, '%s-autoInterest' % obj.__class__.__name__)
  341. def closeAutoInterests(self, obj):
  342. if not hasattr(obj, '_autoInterestHandle'):
  343. # must be multiple inheritance
  344. self.notify.debug('closeAutoInterests(%s): interests already closed' % obj)
  345. return
  346. if obj._autoInterestHandle is not None:
  347. self.removeAutoInterest(obj._autoInterestHandle)
  348. del obj._autoInterestHandle
  349. # events for InterestWatcher
  350. def _getAddInterestEvent(self):
  351. return self._addInterestEvent
  352. def _getRemoveInterestEvent(self):
  353. return self._removeInterestEvent
  354. def _getInterestState(self, handle):
  355. return DoInterestManager._interests[handle]
  356. def _getNextHandle(self):
  357. handle = DoInterestManager._HandleSerialNum
  358. while True:
  359. handle = (handle + 1) & DoInterestManager._HandleMask
  360. # skip handles that are already in use
  361. if handle not in DoInterestManager._interests:
  362. break
  363. DoInterestManager.notify.warning(
  364. 'interest %s already in use' % handle)
  365. DoInterestManager._HandleSerialNum = handle
  366. return DoInterestManager._HandleSerialNum
  367. def _getNextContextId(self):
  368. contextId = DoInterestManager._ContextIdSerialNum
  369. while True:
  370. contextId = (contextId + 1) & DoInterestManager._ContextIdMask
  371. # skip over the 'no context' id
  372. if contextId != NO_CONTEXT:
  373. break
  374. DoInterestManager._ContextIdSerialNum = contextId
  375. return DoInterestManager._ContextIdSerialNum
  376. def _considerRemoveInterest(self, handle):
  377. """
  378. Consider whether we should cull the interest set.
  379. """
  380. assert DoInterestManager.notify.debugCall()
  381. if handle in DoInterestManager._interests:
  382. if DoInterestManager._interests[handle].isPendingDelete():
  383. # make sure there is no pending event for this interest
  384. if DoInterestManager._interests[handle].context == NO_CONTEXT:
  385. assert len(DoInterestManager._interests[handle].events) == 0
  386. del DoInterestManager._interests[handle]
  387. if __debug__:
  388. def printInterestsIfDebug(self):
  389. if DoInterestManager.notify.getDebug():
  390. self.printInterests()
  391. return 1 # for assert
  392. def _addDebugInterestHistory(self, action, description, handle,
  393. contextId, parentId, zoneIdList):
  394. if description is None:
  395. description = ''
  396. DoInterestManager._debug_interestHistory.append(
  397. (action, description, handle, contextId, parentId, zoneIdList))
  398. DoInterestManager._debug_maxDescriptionLen = max(
  399. DoInterestManager._debug_maxDescriptionLen, len(description))
  400. def printInterestHistory(self):
  401. print("***************** Interest History *************")
  402. format = '%9s %' + str(DoInterestManager._debug_maxDescriptionLen) + 's %6s %6s %9s %s'
  403. print(format % (
  404. "Action", "Description", "Handle", "Context", "ParentId",
  405. "ZoneIdList"))
  406. for i in DoInterestManager._debug_interestHistory:
  407. print(format % tuple(i))
  408. print("Note: interests with a Context of 0 do not get" \
  409. " done/finished notices.")
  410. def printInterestSets(self):
  411. print("******************* Interest Sets **************")
  412. format = '%6s %' + str(DoInterestManager._debug_maxDescriptionLen) + 's %11s %11s %8s %8s %8s'
  413. print(format % (
  414. "Handle", "Description",
  415. "ParentId", "ZoneIdList",
  416. "State", "Context",
  417. "Event"))
  418. for id, state in DoInterestManager._interests.items():
  419. if len(state.events) == 0:
  420. event = ''
  421. elif len(state.events) == 1:
  422. event = state.events[0]
  423. else:
  424. event = state.events
  425. print(format % (id, state.desc,
  426. state.parentId, state.zoneIdList,
  427. state.state, state.context,
  428. event))
  429. print("************************************************")
  430. def printInterests(self):
  431. self.printInterestHistory()
  432. self.printInterestSets()
  433. def _sendAddInterest(self, handle, contextId, parentId, zoneIdList, description,
  434. action=None):
  435. """
  436. Part of the new otp-server code.
  437. handle is a client-side created number that refers to
  438. a set of interests. The same handle number doesn't
  439. necessarily have any relationship to the same handle
  440. on another client.
  441. """
  442. assert DoInterestManager.notify.debugCall()
  443. if __debug__:
  444. if isinstance(zoneIdList, list):
  445. zoneIdList.sort()
  446. if action is None:
  447. action = 'add'
  448. self._addDebugInterestHistory(
  449. action, description, handle, contextId, parentId, zoneIdList)
  450. if parentId == 0:
  451. DoInterestManager.notify.error(
  452. 'trying to set interest to invalid parent: %s' % parentId)
  453. datagram = PyDatagram()
  454. # Add message type
  455. datagram.addUint16(CLIENT_ADD_INTEREST)
  456. datagram.addUint16(handle)
  457. datagram.addUint32(contextId)
  458. datagram.addUint32(parentId)
  459. if isinstance(zoneIdList, list):
  460. vzl = list(zoneIdList)
  461. vzl.sort()
  462. uniqueElements(vzl)
  463. for zone in vzl:
  464. datagram.addUint32(zone)
  465. else:
  466. datagram.addUint32(zoneIdList)
  467. self.send(datagram)
  468. def _sendRemoveInterest(self, handle, contextId):
  469. """
  470. handle is a client-side created number that refers to
  471. a set of interests. The same handle number doesn't
  472. necessarily have any relationship to the same handle
  473. on another client.
  474. """
  475. assert DoInterestManager.notify.debugCall()
  476. assert handle in DoInterestManager._interests
  477. datagram = PyDatagram()
  478. # Add message type
  479. datagram.addUint16(CLIENT_REMOVE_INTEREST)
  480. datagram.addUint16(handle)
  481. if contextId != 0:
  482. datagram.addUint32(contextId)
  483. self.send(datagram)
  484. if __debug__:
  485. state = DoInterestManager._interests[handle]
  486. self._addDebugInterestHistory(
  487. "remove", state.desc, handle, contextId,
  488. state.parentId, state.zoneIdList)
  489. def _sendRemoveAIInterest(self, handle):
  490. """
  491. handle is a bare int, NOT an InterestHandle. Use this to
  492. close an AI opened interest.
  493. """
  494. datagram = PyDatagram()
  495. # Add message type
  496. datagram.addUint16(CLIENT_REMOVE_INTEREST)
  497. datagram.addUint16((1<<15) + handle)
  498. self.send(datagram)
  499. def cleanupWaitAllInterestsComplete(self):
  500. if self._completeDelayedCallback is not None:
  501. self._completeDelayedCallback.destroy()
  502. self._completeDelayedCallback = None
  503. def queueAllInterestsCompleteEvent(self, frames=5):
  504. # wait for N frames, if no new interests, send out all-done event
  505. # calling this is OK even if there are no pending interest completes
  506. def checkMoreInterests():
  507. # if there are new interests, cancel this delayed callback, another
  508. # will automatically be scheduled when all interests complete
  509. # print 'checkMoreInterests(',self._completeEventCount.num,'):',globalClock.getFrameCount()
  510. return self._completeEventCount.num > 0
  511. def sendEvent():
  512. messenger.send(self.getAllInterestsCompleteEvent())
  513. for callback in self._allInterestsCompleteCallbacks:
  514. callback()
  515. self._allInterestsCompleteCallbacks = []
  516. self.cleanupWaitAllInterestsComplete()
  517. self._completeDelayedCallback = FrameDelayedCall(
  518. 'waitForAllInterestCompletes',
  519. callback=sendEvent,
  520. frames=frames,
  521. cancelFunc=checkMoreInterests)
  522. checkMoreInterests = None
  523. sendEvent = None
  524. def handleInterestDoneMessage(self, di):
  525. """
  526. This handles the interest done messages and may dispatch an event
  527. """
  528. assert DoInterestManager.notify.debugCall()
  529. handle = di.getUint16()
  530. contextId = di.getUint32()
  531. if self.__verbose():
  532. print('CR::INTEREST.interestDone(handle=%s)' % handle)
  533. DoInterestManager.notify.debug(
  534. "handleInterestDoneMessage--> Received handle %s, context %s" % (
  535. handle, contextId))
  536. if handle in DoInterestManager._interests:
  537. eventsToSend = []
  538. # if the context matches, send out the event
  539. if contextId == DoInterestManager._interests[handle].context:
  540. DoInterestManager._interests[handle].context = NO_CONTEXT
  541. # the event handlers may call back into the interest manager. Send out
  542. # the events after we're once again in a stable state.
  543. #DoInterestManager._interests[handle].sendEvents()
  544. eventsToSend = list(DoInterestManager._interests[handle].getEvents())
  545. DoInterestManager._interests[handle].clearEvents()
  546. else:
  547. DoInterestManager.notify.debug(
  548. "handleInterestDoneMessage--> handle: %s: Expecting context %s, got %s" % (
  549. handle, DoInterestManager._interests[handle].context, contextId))
  550. if __debug__:
  551. state = DoInterestManager._interests[handle]
  552. self._addDebugInterestHistory(
  553. "finished", state.desc, handle, contextId, state.parentId,
  554. state.zoneIdList)
  555. self._considerRemoveInterest(handle)
  556. for event in eventsToSend:
  557. messenger.send(event)
  558. else:
  559. DoInterestManager.notify.warning(
  560. "handleInterestDoneMessage: handle not found: %s" % (handle))
  561. # if there are no more outstanding interest-completes, send out global all-done event
  562. if self._completeEventCount.num == 0:
  563. self.queueAllInterestsCompleteEvent()
  564. assert self.printInterestsIfDebug()
  565. if __debug__:
  566. import unittest
  567. class AsyncTestCase(unittest.TestCase):
  568. def setCompleted(self):
  569. self._async_completed = True
  570. def isCompleted(self):
  571. return getattr(self, '_async_completed', False)
  572. class AsyncTestSuite(unittest.TestSuite):
  573. pass
  574. class AsyncTestLoader(unittest.TestLoader):
  575. suiteClass = AsyncTestSuite
  576. class AsyncTextTestRunner(unittest.TextTestRunner):
  577. def run(self, testCase):
  578. result = self._makeResult()
  579. startTime = time.time()
  580. test(result)
  581. stopTime = time.time()
  582. timeTaken = stopTime - startTime
  583. result.printErrors()
  584. self.stream.writeln(result.separator2)
  585. run = result.testsRun
  586. self.stream.writeln("Ran %d test%s in %.3fs" %
  587. (run, run != 1 and "s" or "", timeTaken))
  588. self.stream.writeln()
  589. if not result.wasSuccessful():
  590. self.stream.write("FAILED (")
  591. failed, errored = map(len, (result.failures, result.errors))
  592. if failed:
  593. self.stream.write("failures=%d" % failed)
  594. if errored:
  595. if failed: self.stream.write(", ")
  596. self.stream.write("errors=%d" % errored)
  597. self.stream.writeln(")")
  598. else:
  599. self.stream.writeln("OK")
  600. return result
  601. class TestInterestAddRemove(AsyncTestCase, DirectObject.DirectObject):
  602. def testInterestAdd(self):
  603. event = uniqueName('InterestAdd')
  604. self.acceptOnce(event, self.gotInterestAddResponse)
  605. self.handle = base.cr.addInterest(base.cr.GameGlobalsId, 100, 'TestInterest', event=event)
  606. def gotInterestAddResponse(self):
  607. event = uniqueName('InterestRemove')
  608. self.acceptOnce(event, self.gotInterestRemoveResponse)
  609. base.cr.removeInterest(self.handle, event=event)
  610. def gotInterestRemoveResponse(self):
  611. self.setCompleted()
  612. def runTests():
  613. suite = unittest.makeSuite(TestInterestAddRemove)
  614. unittest.AsyncTextTestRunner(verbosity=2).run(suite)