DistributedObject.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. """DistributedObject module: contains the DistributedObject class"""
  2. from direct.directnotify.DirectNotifyGlobal import directNotify
  3. from direct.distributed.DistributedObjectBase import DistributedObjectBase
  4. #from PyDatagram import PyDatagram
  5. #from PyDatagramIterator import PyDatagramIterator
  6. # Values for DistributedObject.activeState
  7. ESNew = 1
  8. ESDeleted = 2
  9. ESDisabling = 3
  10. ESDisabled = 4 # values here and lower are considered "disabled"
  11. ESGenerating = 5 # values here and greater are considered "generated"
  12. ESGenerated = 6
  13. class DistributedObject(DistributedObjectBase):
  14. """
  15. The Distributed Object class is the base class for all network based
  16. (i.e. distributed) objects. These will usually (always?) have a
  17. dclass entry in a *.dc file.
  18. """
  19. notify = directNotify.newCategory("DistributedObject")
  20. # A few objects will set neverDisable to 1... Examples are
  21. # localToon, and anything that lives in the UberZone. This
  22. # keeps them from being disabled when you change zones,
  23. # even to the quiet zone.
  24. neverDisable = 0
  25. def __init__(self, cr):
  26. assert self.notify.debugStateCall(self)
  27. try:
  28. self.DistributedObject_initialized
  29. except:
  30. self.DistributedObject_initialized = 1
  31. DistributedObjectBase.__init__(self, cr)
  32. # Most DistributedObjects are simple and require no real
  33. # effort to load. Some, particularly actors, may take
  34. # some significant time to load; these we can optimize by
  35. # caching them when they go away instead of necessarily
  36. # deleting them. The object should set cacheable to 1 if
  37. # it needs to be optimized in this way.
  38. self.setCacheable(0)
  39. # This count tells whether the object can be deleted right away,
  40. # or not.
  41. self.delayDeleteCount = 0
  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 setNeverDisable(self, bool):
  85. assert((bool == 1) or (bool == 0))
  86. self.neverDisable = bool
  87. def getNeverDisable(self):
  88. return self.neverDisable
  89. def setCacheable(self, bool):
  90. assert((bool == 1) or (bool == 0))
  91. self.cacheable = bool
  92. def getCacheable(self):
  93. return self.cacheable
  94. def deleteOrDelay(self):
  95. if self.delayDeleteCount > 0:
  96. self.deleteImminent = 1
  97. else:
  98. self.disableAnnounceAndDelete()
  99. def delayDelete(self, flag):
  100. # Flag should be 0 or 1, meaning increment or decrement count
  101. # Also see DelayDelete.py
  102. if (flag == 1):
  103. self.delayDeleteCount += 1
  104. elif (flag == 0):
  105. self.delayDeleteCount -= 1
  106. else:
  107. self.notify.error("Invalid flag passed to delayDelete: " + str(flag))
  108. if (self.delayDeleteCount < 0):
  109. self.notify.error("Somebody decremented delayDelete for doId %s without incrementing"
  110. % (self.doId))
  111. elif (self.delayDeleteCount == 0):
  112. assert(self.notify.debug("delayDeleteCount for doId %s now 0"
  113. % (self.doId)))
  114. if self.deleteImminent:
  115. assert(self.notify.debug("delayDeleteCount for doId %s -- deleteImminent"
  116. % (self.doId)))
  117. self.disableAnnounceAndDelete()
  118. else:
  119. self.notify.debug("delayDeleteCount for doId %s now %s"
  120. % (self.doId, self.delayDeleteCount))
  121. # Return the count just for kicks
  122. return self.delayDeleteCount
  123. def disableAnnounceAndDelete(self):
  124. self.disableAndAnnounce()
  125. self.delete()
  126. def disableAndAnnounce(self):
  127. """
  128. Inheritors should *not* redefine this function.
  129. """
  130. # We must send the disable announce message *before* we
  131. # actually disable the object. That way, the various cleanup
  132. # tasks can run first and take care of restoring the object to
  133. # a normal, nondisabled state; and *then* the disable function
  134. # can properly disable it (for instance, by parenting it to
  135. # hidden).
  136. if self.activeState != ESDisabled:
  137. self.activeState = ESDisabling
  138. messenger.send(self.uniqueName("disable"))
  139. self.disable()
  140. def announceGenerate(self):
  141. """
  142. Sends a message to the world after the object has been
  143. generated and all of its required fields filled in.
  144. """
  145. assert(self.notify.debug('announceGenerate(): %s' % (self.doId)))
  146. if self.activeState != ESGenerated:
  147. self.activeState = ESGenerated
  148. messenger.send(self.uniqueName("generate"), [self])
  149. def disable(self):
  150. """
  151. Inheritors should redefine this to take appropriate action on disable
  152. """
  153. assert(self.notify.debug('disable(): %s' % (self.doId)))
  154. if self.activeState != ESDisabled:
  155. self.activeState = ESDisabled
  156. self.__callbacks = {}
  157. #self.cr.deleteObjectLocation(self.doId, self.parentId, self.zoneId)
  158. self.setLocation(None, None)
  159. # TODO: disable my children
  160. def isDisabled(self):
  161. """
  162. Returns true if the object has been disabled and/or deleted,
  163. or if it is brand new and hasn't yet been generated.
  164. """
  165. return (self.activeState < ESGenerating)
  166. def isGenerated(self):
  167. """
  168. Returns true if the object has been fully generated by now,
  169. and not yet disabled.
  170. """
  171. assert self.notify.debugStateCall(self)
  172. return (self.activeState == ESGenerated)
  173. def delete(self):
  174. """
  175. Inheritors should redefine this to take appropriate action on delete
  176. """
  177. assert(self.notify.debug('delete(): %s' % (self.doId)))
  178. try:
  179. self.DistributedObject_deleted
  180. except:
  181. self.DistributedObject_deleted = 1
  182. self.cr = None
  183. self.dclass = None
  184. def generate(self):
  185. """
  186. Inheritors should redefine this to take appropriate action on generate
  187. """
  188. assert self.notify.debugStateCall(self)
  189. self.activeState = ESGenerating
  190. # this has already been set at this point
  191. #self.cr.storeObjectLocation(self.doId, self.parentId, self.zoneId)
  192. def generateInit(self):
  193. """
  194. This method is called when the DistributedObject is first introduced
  195. to the world... Not when it is pulled from the cache.
  196. """
  197. self.activeState = ESGenerating
  198. def getDoId(self):
  199. """
  200. Return the distributed object id
  201. """
  202. return self.doId
  203. def updateRequiredFields(self, dclass, di):
  204. dclass.receiveUpdateBroadcastRequired(self, di)
  205. self.announceGenerate()
  206. def updateAllRequiredFields(self, dclass, di):
  207. dclass.receiveUpdateAllRequired(self, di)
  208. self.announceGenerate()
  209. def updateRequiredOtherFields(self, dclass, di):
  210. # First, update the required fields
  211. dclass.receiveUpdateBroadcastRequired(self, di)
  212. # Announce generate after updating all the required fields,
  213. # but before we update the non-required fields.
  214. self.announceGenerate()
  215. dclass.receiveUpdateOther(self, di)
  216. def sendUpdate(self, fieldName, args = [], sendToId = None):
  217. if self.cr:
  218. dg = self.dclass.clientFormatUpdate(
  219. fieldName, sendToId or self.doId, args)
  220. self.cr.send(dg)
  221. else:
  222. self.notify.warning("sendUpdate failed, because self.cr is not set")
  223. def sendDisableMsg(self):
  224. self.cr.sendDisableMsg(self.doId)
  225. def sendDeleteMsg(self):
  226. self.cr.sendDeleteMsg(self.doId)
  227. def taskName(self, taskString):
  228. return (taskString + "-" + str(self.getDoId()))
  229. def uniqueName(self, idString):
  230. return (idString + "-" + str(self.getDoId()))
  231. def getCallbackContext(self, callback, extraArgs = []):
  232. # Some objects implement a back-and-forth handshake operation
  233. # with the AI via an arbitrary context number. This method
  234. # (coupled with doCallbackContext(), below) maps a Python
  235. # callback onto that context number so that client code may
  236. # easily call the method and wait for a callback, rather than
  237. # having to negotiate context numbers.
  238. # This method generates a new context number and stores the
  239. # callback so that it may later be called when the response is
  240. # returned.
  241. # This is intended to be called within derivations of
  242. # DistributedObject, not directly by other objects.
  243. context = self.__nextContext
  244. self.__callbacks[context] = (callback, extraArgs)
  245. # We assume the context number is passed as a uint16.
  246. self.__nextContext = (self.__nextContext + 1) & 0xffff
  247. return context
  248. def getCurrentContexts(self):
  249. # Returns a list of the currently outstanding contexts created
  250. # by getCallbackContext().
  251. return self.__callbacks.keys()
  252. def getCallback(self, context):
  253. # Returns the callback that was passed in to the previous
  254. # call to getCallbackContext.
  255. return self.__callbacks[context][0]
  256. def getCallbackArgs(self, context):
  257. # Returns the extraArgs that were passed in to the previous
  258. # call to getCallbackContext.
  259. return self.__callbacks[context][1]
  260. def doCallbackContext(self, context, args):
  261. # This is called after the AI has responded to the message
  262. # sent via getCallbackContext(), above. The context number is
  263. # looked up in the table and the associated callback is
  264. # issued.
  265. # This is intended to be called within derivations of
  266. # DistributedObject, not directly by other objects.
  267. tuple = self.__callbacks.get(context)
  268. if tuple:
  269. callback, extraArgs = tuple
  270. completeArgs = args + extraArgs
  271. if callback != None:
  272. callback(*completeArgs)
  273. del self.__callbacks[context]
  274. else:
  275. self.notify.warning("Got unexpected context from AI: %s" % (context))
  276. def setBarrierData(self, data):
  277. # This message is sent by the AI to tell us the barriers and
  278. # avIds for which the AI is currently waiting. The client
  279. # needs to look up its pending context in the table (and
  280. # ignore the other contexts). When the client is done
  281. # handling whatever it should handle in its current state, it
  282. # should call doneBarrier(), which will send the context
  283. # number back to the AI.
  284. for context, name, avIds in data:
  285. if base.localAvatar.doId in avIds:
  286. # We found localToon's id; stop here.
  287. self.__barrierContext = (context, name)
  288. assert(self.notify.debug('setBarrierData(%s, %s)' % (context, name)))
  289. return
  290. assert(self.notify.debug('setBarrierData(%s)' % (None)))
  291. self.__barrierContext = None
  292. def doneBarrier(self, name = None):
  293. # Tells the AI we have finished handling our task. If the
  294. # optional name parameter is specified, it must match the
  295. # barrier name specified on the AI, or the barrier is ignored.
  296. # This is used to ensure we are not clearing the wrong
  297. # barrier.
  298. # If this is None, it either means we have called
  299. # doneBarrier() twice, or we have not received a barrier
  300. # context from the AI. I think in either case it's ok to
  301. # silently ignore the error.
  302. if self.__barrierContext != None:
  303. context, aiName = self.__barrierContext
  304. if name == None or name == aiName:
  305. assert(self.notify.debug('doneBarrier(%s, %s)' % (context, aiName)))
  306. self.sendUpdate("setBarrierReady", [context])
  307. self.__barrierContext = None
  308. else:
  309. assert(self.notify.debug('doneBarrier(%s) ignored; current barrier is %s' % (name, aiName)))
  310. else:
  311. assert(self.notify.debug('doneBarrier(%s) ignored; no active barrier.' % (name)))
  312. def addInterest(self, zoneId, note="", event=None):
  313. self.cr.addInterest(self.getDoId(), zoneId, note, event)
  314. def b_setLocation(self, parentId, zoneId):
  315. self.d_setLocation(parentId, zoneId)
  316. self.setLocation(parentId, zoneId)
  317. def d_setLocation(self, parentId, zoneId):
  318. self.cr.sendSetLocation(self.doId, parentId, zoneId)
  319. def setLocation(self, parentId, zoneId):
  320. self.cr.storeObjectLocation(self.doId, parentId, zoneId)
  321. def getLocation(self):
  322. try:
  323. if self.parentId == 0 and self.zoneId == 0:
  324. return None
  325. # This is a -1 stuffed into a uint32
  326. if self.parentId == 0xffffffff and self.zoneId == 0xffffffff:
  327. return None
  328. return (self.parentId, self.zoneId)
  329. except AttributeError:
  330. return None
  331. def handleChildArrive(self, childObj, zoneId):
  332. self.notify.debugCall()
  333. # A new child has just setLocation beneath us. Give us a
  334. # chance to run code when a new child sets location to us. For
  335. # example, we may want to scene graph reparent the child to
  336. # some subnode we own.
  337. ## zone=self.children.setdefault(zoneId, {})
  338. ## zone[childObj.doId]=childObj
  339. # Inheritors should override
  340. pass
  341. def handleChildLeave(self, childObj, zoneId):
  342. self.notify.debugCall()
  343. # A child is about to setLocation away from us. Give us a
  344. # chance to run code just before a child sets location away from us.
  345. ## zone=self.children[zoneId]
  346. ## del zone[childObj.doId]
  347. ## if not len(zone):
  348. ## del self.children[zoneId]
  349. # Inheritors should override
  350. pass
  351. def getParentObj(self):
  352. if self.parentId is None:
  353. return None
  354. return self.cr.doId2do.get(self.parentId)
  355. def isLocal(self):
  356. # This returns true if the distributed object is "local,"
  357. # which means the client created it instead of the AI, and it
  358. # gets some other special handling. Normally, only the local
  359. # avatar class overrides this to return true.
  360. return self.cr and self.cr.isLocalId(self.doId)
  361. def updateZone(self, zoneId):
  362. self.cr.sendUpdateZone(self, zoneId)
  363. def isGridParent(self):
  364. # If this distributed object is a DistributedGrid return 1. 0 by default
  365. return 0