DistributedObject.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. """DistributedObject module: contains the DistributedObject class"""
  2. from pandac.PandaModules import *
  3. from direct.directnotify.DirectNotifyGlobal import directNotify
  4. from direct.distributed.DistributedObjectBase import DistributedObjectBase
  5. #from PyDatagram import PyDatagram
  6. #from PyDatagramIterator import PyDatagramIterator
  7. # Values for DistributedObject.activeState
  8. ESNew = 1
  9. ESDeleted = 2
  10. ESDisabling = 3
  11. ESDisabled = 4 # values here and lower are considered "disabled"
  12. ESGenerating = 5 # values here and greater are considered "generated"
  13. ESGenerated = 6
  14. class DistributedObject(DistributedObjectBase):
  15. """
  16. The Distributed Object class is the base class for all network based
  17. (i.e. distributed) objects. These will usually (always?) have a
  18. dclass entry in a *.dc file.
  19. """
  20. notify = directNotify.newCategory("DistributedObject")
  21. # A few objects will set neverDisable to 1... Examples are
  22. # localToon, and anything that lives in the UberZone. This
  23. # keeps them from being disabled when you change zones,
  24. # even to the quiet zone.
  25. neverDisable = 0
  26. DelayDeleteSerialGen = SerialNumGen()
  27. def __init__(self, cr):
  28. assert self.notify.debugStateCall(self)
  29. try:
  30. self.DistributedObject_initialized
  31. except:
  32. self.DistributedObject_initialized = 1
  33. DistributedObjectBase.__init__(self, cr)
  34. # Most DistributedObjects are simple and require no real
  35. # effort to load. Some, particularly actors, may take
  36. # some significant time to load; these we can optimize by
  37. # caching them when they go away instead of necessarily
  38. # deleting them. The object should set cacheable to 1 if
  39. # it needs to be optimized in this way.
  40. self.setCacheable(0)
  41. self._token2delayDeleteName = {}
  42. # This flag tells whether a delete has been requested on this
  43. # object.
  44. self.deleteImminent = 0
  45. # Keep track of our state as a distributed object. This
  46. # is only trustworthy if the inheriting class properly
  47. # calls up the chain for disable() and generate().
  48. self.activeState = ESNew
  49. # These are used by getCallbackContext() and doCallbackContext().
  50. self.__nextContext = 0
  51. self.__callbacks = {}
  52. # This is used by doneBarrier().
  53. self.__barrierContext = None
  54. ## TODO: This should probably be move to a derived class for CMU
  55. ## #zone of the distributed object, default to 0
  56. ## self.zone = 0
  57. if __debug__:
  58. def status(self, indent=0):
  59. """
  60. print out "doId(parentId, zoneId) className
  61. and conditionally show generated, disabled, neverDisable,
  62. or cachable"
  63. """
  64. spaces=' '*(indent+2)
  65. try:
  66. print "%s%s:"%(
  67. ' '*indent, self.__class__.__name__)
  68. print "%sfrom DistributedObject doId:%s, parent:%s, zone:%s"%(
  69. spaces,
  70. self.doId, self.parentId, self.zoneId),
  71. flags=[]
  72. if self.activeState == ESGenerated:
  73. flags.append("generated")
  74. if self.activeState < ESGenerating:
  75. flags.append("disabled")
  76. if self.neverDisable:
  77. flags.append("neverDisable")
  78. if self.cacheable:
  79. flags.append("cacheable")
  80. if len(flags):
  81. print "(%s)"%(" ".join(flags),),
  82. print
  83. except Exception, e: print "%serror printing status"%(spaces,), e
  84. def getAutoInterests(self):
  85. # returns the sub-zones under this object that are automatically
  86. # opened for us by the server.
  87. # have we already cached it?
  88. def _getAutoInterests(cls):
  89. # returns set of auto-interests for this class and all derived
  90. # have we already computed this class's autoInterests?
  91. if 'autoInterests' in cls.__dict__:
  92. autoInterests = cls.autoInterests
  93. else:
  94. autoInterests = set()
  95. # grab autoInterests from base classes
  96. for base in cls.__bases__:
  97. autoInterests.update(_getAutoInterests(base))
  98. # grab autoInterests from this class
  99. if cls.__name__ in self.cr.dclassesByName:
  100. dclass = self.cr.dclassesByName[cls.__name__]
  101. field = dclass.getFieldByName('AutoInterest')
  102. if field is not None:
  103. p = DCPacker()
  104. p.setUnpackData(field.getDefaultValue())
  105. len = p.rawUnpackUint16()/4
  106. for i in xrange(len):
  107. zone = int(p.rawUnpackUint32())
  108. autoInterests.add(zone)
  109. autoInterests.update(autoInterests)
  110. cls.autoInterests = autoInterests
  111. return set(autoInterests)
  112. autoInterests = _getAutoInterests(self.__class__)
  113. _getAutoInterests = None
  114. return list(autoInterests)
  115. def setNeverDisable(self, bool):
  116. assert bool == 1 or bool == 0
  117. self.neverDisable = bool
  118. def getNeverDisable(self):
  119. return self.neverDisable
  120. def setCacheable(self, bool):
  121. assert bool == 1 or bool == 0
  122. self.cacheable = bool
  123. def getCacheable(self):
  124. return self.cacheable
  125. def deleteOrDelay(self):
  126. if len(self._token2delayDeleteName) > 0:
  127. self.deleteImminent = 1
  128. # Object is delayDeleted. Clean up distributedObject state,
  129. # remove from repository tables, so that we won't crash if
  130. # another instance of the same object gets generated while
  131. # this instance is still delayDeleted.
  132. messenger.send(self.getDisableEvent())
  133. self.activeState = ESDisabled
  134. self._deactivate()
  135. else:
  136. self.disableAnnounceAndDelete()
  137. def getDelayDeleteCount(self):
  138. return len(self._token2delayDeleteName)
  139. def acquireDelayDelete(self, name):
  140. # Also see DelayDelete.py
  141. if self.getDelayDeleteCount() == 0:
  142. self.cr._addDelayDeletedDO(self)
  143. token = DistributedObject.DelayDeleteSerialGen.next()
  144. self._token2delayDeleteName[token] = name
  145. assert self.notify.debug(
  146. "delayDelete count for doId %s now %s" %
  147. (self.doId, len(self._token2delayDeleteName)))
  148. # Return the token, user must pass token to releaseDelayDelete
  149. return token
  150. def releaseDelayDelete(self, token):
  151. name = self._token2delayDeleteName.pop(token)
  152. assert self.notify.debug("releasing delayDelete '%s'" % name)
  153. if len(self._token2delayDeleteName) == 0:
  154. assert self.notify.debug(
  155. "delayDelete count for doId %s now 0" % (self.doId))
  156. self.cr._removeDelayDeletedDO(self)
  157. if self.deleteImminent:
  158. assert self.notify.debug(
  159. "delayDelete count for doId %s -- deleteImminent" %
  160. (self.doId))
  161. self.disable()
  162. self.delete()
  163. self._destroyDO()
  164. def getDelayDeleteNames(self):
  165. return self._token2delayDeleteName.values()
  166. def disableAnnounceAndDelete(self):
  167. self.disableAndAnnounce()
  168. self.delete()
  169. self._destroyDO()
  170. def getDisableEvent(self):
  171. return self.uniqueName("disable")
  172. def disableAndAnnounce(self):
  173. """
  174. Inheritors should *not* redefine this function.
  175. """
  176. # We must send the disable announce message *before* we
  177. # actually disable the object. That way, the various cleanup
  178. # tasks can run first and take care of restoring the object to
  179. # a normal, nondisabled state; and *then* the disable function
  180. # can properly disable it (for instance, by parenting it to
  181. # hidden).
  182. if self.activeState != ESDisabled:
  183. self.activeState = ESDisabling
  184. messenger.send(self.getDisableEvent())
  185. self.disable()
  186. self.activeState = ESDisabled
  187. self._deactivate()
  188. def announceGenerate(self):
  189. """
  190. Sends a message to the world after the object has been
  191. generated and all of its required fields filled in.
  192. """
  193. assert self.notify.debug('announceGenerate(): %s' % (self.doId))
  194. def _deactivate(self):
  195. # after this is called, the object is no longer an active DistributedObject
  196. # and it may be placed in the cache
  197. self.__callbacks = {}
  198. self.cr.closeAutoInterests(self)
  199. self.setLocation(0,0)
  200. self.cr.deleteObjectLocation(self, self.parentId, self.zoneId)
  201. def _destroyDO(self):
  202. # after this is called, the object is no longer a DistributedObject
  203. # but may still be used as a DelayDeleted object
  204. self.cr = None
  205. self.dclass = None
  206. def disable(self):
  207. """
  208. Inheritors should redefine this to take appropriate action on disable
  209. """
  210. assert self.notify.debug('disable(): %s' % (self.doId))
  211. pass
  212. def isDisabled(self):
  213. """
  214. Returns true if the object has been disabled and/or deleted,
  215. or if it is brand new and hasn't yet been generated.
  216. """
  217. return (self.activeState < ESGenerating)
  218. def isGenerated(self):
  219. """
  220. Returns true if the object has been fully generated by now,
  221. and not yet disabled.
  222. """
  223. assert self.notify.debugStateCall(self)
  224. return (self.activeState == ESGenerated)
  225. def delete(self):
  226. """
  227. Inheritors should redefine this to take appropriate action on delete
  228. """
  229. assert self.notify.debug('delete(): %s' % (self.doId))
  230. try:
  231. self.DistributedObject_deleted
  232. except:
  233. self.DistributedObject_deleted = 1
  234. def generate(self):
  235. """
  236. Inheritors should redefine this to take appropriate action on generate
  237. """
  238. assert self.notify.debugStateCall(self)
  239. self.activeState = ESGenerating
  240. # this has already been set at this point
  241. #self.cr.storeObjectLocation(self, self.parentId, self.zoneId)
  242. # semi-hack: we seem to be calling generate() more than once for objects that multiply-inherit
  243. if not hasattr(self, '_autoInterestHandle'):
  244. self.cr.openAutoInterests(self)
  245. def generateInit(self):
  246. """
  247. This method is called when the DistributedObject is first introduced
  248. to the world... Not when it is pulled from the cache.
  249. """
  250. self.activeState = ESGenerating
  251. def getDoId(self):
  252. """
  253. Return the distributed object id
  254. """
  255. return self.doId
  256. #This message was moved out of announce generate
  257. #to avoid ordering issues.
  258. def postGenerateMessage(self):
  259. if self.activeState != ESGenerated:
  260. self.activeState = ESGenerated
  261. messenger.send(self.uniqueName("generate"), [self])
  262. def updateRequiredFields(self, dclass, di):
  263. dclass.receiveUpdateBroadcastRequired(self, di)
  264. self.announceGenerate()
  265. self.postGenerateMessage()
  266. def updateAllRequiredFields(self, dclass, di):
  267. dclass.receiveUpdateAllRequired(self, di)
  268. self.announceGenerate()
  269. self.postGenerateMessage()
  270. def updateRequiredOtherFields(self, dclass, di):
  271. # First, update the required fields
  272. dclass.receiveUpdateBroadcastRequired(self, di)
  273. # Announce generate after updating all the required fields,
  274. # but before we update the non-required fields.
  275. self.announceGenerate()
  276. self.postGenerateMessage()
  277. dclass.receiveUpdateOther(self, di)
  278. def sendUpdate(self, fieldName, args = [], sendToId = None):
  279. if self.cr:
  280. dg = self.dclass.clientFormatUpdate(
  281. fieldName, sendToId or self.doId, args)
  282. self.cr.send(dg)
  283. else:
  284. self.notify.warning("sendUpdate failed, because self.cr is not set")
  285. def sendDisableMsg(self):
  286. self.cr.sendDisableMsg(self.doId)
  287. def sendDeleteMsg(self):
  288. self.cr.sendDeleteMsg(self.doId)
  289. def taskName(self, taskString):
  290. return ("%s-%s" % (taskString, self.doId))
  291. def uniqueName(self, idString):
  292. return ("%s-%s" % (idString, self.doId))
  293. def getCallbackContext(self, callback, extraArgs = []):
  294. # Some objects implement a back-and-forth handshake operation
  295. # with the AI via an arbitrary context number. This method
  296. # (coupled with doCallbackContext(), below) maps a Python
  297. # callback onto that context number so that client code may
  298. # easily call the method and wait for a callback, rather than
  299. # having to negotiate context numbers.
  300. # This method generates a new context number and stores the
  301. # callback so that it may later be called when the response is
  302. # returned.
  303. # This is intended to be called within derivations of
  304. # DistributedObject, not directly by other objects.
  305. context = self.__nextContext
  306. self.__callbacks[context] = (callback, extraArgs)
  307. # We assume the context number is passed as a uint16.
  308. self.__nextContext = (self.__nextContext + 1) & 0xffff
  309. return context
  310. def getCurrentContexts(self):
  311. # Returns a list of the currently outstanding contexts created
  312. # by getCallbackContext().
  313. return self.__callbacks.keys()
  314. def getCallback(self, context):
  315. # Returns the callback that was passed in to the previous
  316. # call to getCallbackContext.
  317. return self.__callbacks[context][0]
  318. def getCallbackArgs(self, context):
  319. # Returns the extraArgs that were passed in to the previous
  320. # call to getCallbackContext.
  321. return self.__callbacks[context][1]
  322. def doCallbackContext(self, context, args):
  323. # This is called after the AI has responded to the message
  324. # sent via getCallbackContext(), above. The context number is
  325. # looked up in the table and the associated callback is
  326. # issued.
  327. # This is intended to be called within derivations of
  328. # DistributedObject, not directly by other objects.
  329. tuple = self.__callbacks.get(context)
  330. if tuple:
  331. callback, extraArgs = tuple
  332. completeArgs = args + extraArgs
  333. if callback != None:
  334. callback(*completeArgs)
  335. del self.__callbacks[context]
  336. else:
  337. self.notify.warning("Got unexpected context from AI: %s" % (context))
  338. def setBarrierData(self, data):
  339. # This message is sent by the AI to tell us the barriers and
  340. # avIds for which the AI is currently waiting. The client
  341. # needs to look up its pending context in the table (and
  342. # ignore the other contexts). When the client is done
  343. # handling whatever it should handle in its current state, it
  344. # should call doneBarrier(), which will send the context
  345. # number back to the AI.
  346. for context, name, avIds in data:
  347. if base.localAvatar.doId in avIds:
  348. # We found localToon's id; stop here.
  349. self.__barrierContext = (context, name)
  350. assert self.notify.debug('setBarrierData(%s, %s)' % (context, name))
  351. return
  352. assert self.notify.debug('setBarrierData(%s)' % (None))
  353. self.__barrierContext = None
  354. def doneBarrier(self, name = None):
  355. # Tells the AI we have finished handling our task. If the
  356. # optional name parameter is specified, it must match the
  357. # barrier name specified on the AI, or the barrier is ignored.
  358. # This is used to ensure we are not clearing the wrong
  359. # barrier.
  360. # If this is None, it either means we have called
  361. # doneBarrier() twice, or we have not received a barrier
  362. # context from the AI. I think in either case it's ok to
  363. # silently ignore the error.
  364. if self.__barrierContext != None:
  365. context, aiName = self.__barrierContext
  366. if name == None or name == aiName:
  367. assert self.notify.debug('doneBarrier(%s, %s)' % (context, aiName))
  368. self.sendUpdate("setBarrierReady", [context])
  369. self.__barrierContext = None
  370. else:
  371. assert self.notify.debug('doneBarrier(%s) ignored; current barrier is %s' % (name, aiName))
  372. else:
  373. assert self.notify.debug('doneBarrier(%s) ignored; no active barrier.' % (name))
  374. def addInterest(self, zoneId, note="", event=None):
  375. return self.cr.addInterest(self.getDoId(), zoneId, note, event)
  376. def removeInterest(self, handle, event=None):
  377. return self.cr.removeInterest(handle, event)
  378. def b_setLocation(self, parentId, zoneId):
  379. self.d_setLocation(parentId, zoneId)
  380. self.setLocation(parentId, zoneId)
  381. def d_setLocation(self, parentId, zoneId):
  382. self.cr.sendSetLocation(self.doId, parentId, zoneId)
  383. def setLocation(self, parentId, zoneId):
  384. self.cr.storeObjectLocation(self, parentId, zoneId)
  385. def getLocation(self):
  386. try:
  387. if self.parentId == 0 and self.zoneId == 0:
  388. return None
  389. # This is a -1 stuffed into a uint32
  390. if self.parentId == 0xffffffff and self.zoneId == 0xffffffff:
  391. return None
  392. return (self.parentId, self.zoneId)
  393. except AttributeError:
  394. return None
  395. def getParentObj(self):
  396. if self.parentId is None:
  397. return None
  398. return self.cr.doId2do.get(self.parentId)
  399. def isLocal(self):
  400. # This returns true if the distributed object is "local,"
  401. # which means the client created it instead of the AI, and it
  402. # gets some other special handling. Normally, only the local
  403. # avatar class overrides this to return true.
  404. return self.cr and self.cr.isLocalId(self.doId)
  405. def updateZone(self, zoneId):
  406. self.cr.sendUpdateZone(self, zoneId)
  407. def isGridParent(self):
  408. # If this distributed object is a DistributedGrid return 1. 0 by default
  409. return 0
  410. def execCommand(self, string, mwMgrId, avId, zoneId):
  411. pass