DistributedObjectAI.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. """DistributedObjectAI module: contains the DistributedObjectAI class"""
  2. from direct.directnotify.DirectNotifyGlobal import directNotify
  3. from direct.distributed.DistributedObjectBase import DistributedObjectBase
  4. from direct.showbase import PythonUtil
  5. from pandac.PandaModules import *
  6. #from PyDatagram import PyDatagram
  7. #from PyDatagramIterator import PyDatagramIterator
  8. class DistributedObjectAI(DistributedObjectBase):
  9. notify = directNotify.newCategory("DistributedObjectAI")
  10. QuietZone = 1
  11. def __init__(self, air):
  12. try:
  13. self.DistributedObjectAI_initialized
  14. except:
  15. self.DistributedObjectAI_initialized = 1
  16. DistributedObjectBase.__init__(self, air)
  17. self.accountName=''
  18. # Record the repository
  19. self.air = air
  20. # Record our distributed class
  21. className = self.__class__.__name__
  22. self.dclass = self.air.dclassesByName[className]
  23. # init doId pre-allocated flag
  24. self.__preallocDoId = 0
  25. # used to track zone changes across the quiet zone
  26. # NOTE: the quiet zone is defined in OTP, but we need it
  27. # here.
  28. self.lastNonQuietZone = None
  29. self._DOAI_requestedDelete = False
  30. # These are used to implement beginBarrier().
  31. self.__nextBarrierContext = 0
  32. self.__barriers = {}
  33. self.__generated = False
  34. # reference count for multiple inheritance
  35. self.__generates = 0
  36. self._zoneData = None
  37. # Uncomment if you want to debug DO leaks
  38. #def __del__(self):
  39. # """
  40. # For debugging purposes, this just prints out what got deleted
  41. # """
  42. # print ("Destructing: " + self.__class__.__name__)
  43. if __debug__:
  44. def status(self, indent=0):
  45. """
  46. print out doId(parentId, zoneId) className
  47. and conditionally show generated, disabled, neverDisable,
  48. or cachable
  49. """
  50. spaces=' '*(indent+2)
  51. try:
  52. print "%s%s:"%(
  53. ' '*indent, self.__class__.__name__)
  54. print "%sfrom DistributedObject doId:%s, parent:%s, zone:%s"%(
  55. spaces,
  56. self.doId, self.parentId, self.zoneId),
  57. flags=[]
  58. if self.__generated:
  59. flags.append("generated")
  60. if self.air == None:
  61. flags.append("deleted")
  62. if len(flags):
  63. print "(%s)"%(" ".join(flags),),
  64. print
  65. except Exception, e: print "%serror printing status"%(spaces,), e
  66. def getDeleteEvent(self):
  67. # this is sent just before we get deleted
  68. if hasattr(self, 'doId'):
  69. return 'distObjDelete-%s' % self.doId
  70. return None
  71. def sendDeleteEvent(self):
  72. # this is called just before we get deleted
  73. delEvent = self.getDeleteEvent()
  74. if delEvent:
  75. messenger.send(delEvent)
  76. def getCacheable(self):
  77. """ This method exists only to mirror the similar method on
  78. DistributedObject. AI objects aren't cacheable. """
  79. return False
  80. def deleteOrDelay(self):
  81. """ This method exists only to mirror the similar method on
  82. DistributedObject. AI objects don't have delayDelete, they
  83. just get deleted immediately. """
  84. self.delete()
  85. def getDelayDeleteCount(self):
  86. return 0
  87. def delete(self):
  88. """
  89. Inheritors should redefine this to take appropriate action on delete
  90. Note that this may be called multiple times if a class inherits
  91. from DistributedObjectAI more than once.
  92. """
  93. self.__generates -= 1
  94. if self.__generates < 0:
  95. self.notify.debug('DistributedObjectAI: delete() called more times than generate()')
  96. if self.__generates == 0:
  97. # prevent this code from executing multiple times
  98. if self.air is not None:
  99. # self.doId may not exist. The __dict__ syntax works around that.
  100. assert self.notify.debug('delete(): %s' % (self.__dict__.get("doId")))
  101. if not self._DOAI_requestedDelete:
  102. # this logs every delete that was not requested by us.
  103. # TODO: this currently prints warnings for deletes of objects
  104. # that we did not create. We need to add a 'locally created'
  105. # flag to every object to filter these out.
  106. """
  107. DistributedObjectAI.notify.warning(
  108. 'delete() called but requestDelete never called for %s: %s'
  109. % (self.__dict__.get('doId'), self.__class__.__name__))
  110. """
  111. """
  112. # print a stack trace so we can detect whether this is the
  113. # result of a network msg.
  114. # this is slow.
  115. from direct.showbase.PythonUtil import StackTrace
  116. DistributedObjectAI.notify.warning(
  117. 'stack trace: %s' % StackTrace())
  118. """
  119. self._DOAI_requestedDelete = False
  120. self.releaseZoneData()
  121. # Clean up all the pending barriers.
  122. for barrier in self.__barriers.values():
  123. barrier.cleanup()
  124. self.__barriers = {}
  125. self.air.stopTrackRequestDeletedDO(self)
  126. # DCR: I've re-enabled this block of code so that Toontown's
  127. # AI won't leak channels.
  128. # Let me know if it causes trouble.
  129. ### Asad: As per Roger's suggestion, turn off the following
  130. ### block until a solution is thought out of how to prevent
  131. ### this delete message or to handle this message better
  132. # TODO: do we still need this check?
  133. if not hasattr(self, "doNotDeallocateChannel"):
  134. if self.air and not hasattr(self.air, "doNotDeallocateChannel"):
  135. if self.air.minChannel <= self.doId <= self.air.maxChannel:
  136. self.air.deallocateChannel(self.doId)
  137. self.air = None
  138. self.parentId = None
  139. self.zoneId = None
  140. self.__generated = False
  141. def isDeleted(self):
  142. """
  143. Returns true if the object has been deleted,
  144. or if it is brand new and hasnt yet been generated.
  145. """
  146. return self.air == None
  147. def isGenerated(self):
  148. """
  149. Returns true if the object has been generated
  150. """
  151. return self.__generated
  152. def getDoId(self):
  153. """
  154. Return the distributed object id
  155. """
  156. return self.doId
  157. def preAllocateDoId(self):
  158. """
  159. objects that need to have a doId before they are generated
  160. can call this to pre-allocate a doId for the object
  161. """
  162. assert not self.__preallocDoId
  163. self.doId = self.air.allocateChannel()
  164. self.__preallocDoId = 1
  165. def announceGenerate(self):
  166. """
  167. Called after the object has been generated and all
  168. of its required fields filled in. Overwrite when needed.
  169. """
  170. pass
  171. def addInterest(self, zoneId, note="", event=None):
  172. self.air.addInterest(self.doId, zoneId, note, event)
  173. def b_setLocation(self, parentId, zoneId):
  174. self.d_setLocation(parentId, zoneId)
  175. self.setLocation(parentId, zoneId)
  176. def d_setLocation(self, parentId, zoneId):
  177. self.air.sendSetLocation(self, parentId, zoneId)
  178. def setLocation(self, parentId, zoneId):
  179. # Prevent Duplicate SetLocations for being Called
  180. if (self.parentId == parentId) and (self.zoneId == zoneId):
  181. return
  182. oldParentId = self.parentId
  183. oldZoneId = self.zoneId
  184. self.air.storeObjectLocation(self, parentId, zoneId)
  185. if ((oldParentId != parentId) or
  186. (oldZoneId != zoneId)):
  187. self.releaseZoneData()
  188. messenger.send(self.getZoneChangeEvent(), [zoneId, oldZoneId])
  189. # if we are not going into the quiet zone, send a 'logical' zone
  190. # change message
  191. if zoneId != DistributedObjectAI.QuietZone:
  192. lastLogicalZone = oldZoneId
  193. if oldZoneId == DistributedObjectAI.QuietZone:
  194. lastLogicalZone = self.lastNonQuietZone
  195. self.handleLogicalZoneChange(zoneId, lastLogicalZone)
  196. self.lastNonQuietZone = zoneId
  197. def getLocation(self):
  198. try:
  199. if self.parentId <= 0 and self.zoneId <= 0:
  200. return None
  201. # This is a -1 stuffed into a uint32
  202. if self.parentId == 0xffffffff and self.zoneId == 0xffffffff:
  203. return None
  204. return (self.parentId, self.zoneId)
  205. except AttributeError:
  206. return None
  207. def postGenerateMessage(self):
  208. self.__generated = True
  209. messenger.send(self.uniqueName("generate"), [self])
  210. def updateRequiredFields(self, dclass, di):
  211. dclass.receiveUpdateBroadcastRequired(self, di)
  212. self.announceGenerate()
  213. self.postGenerateMessage()
  214. def updateAllRequiredFields(self, dclass, di):
  215. dclass.receiveUpdateAllRequired(self, di)
  216. self.announceGenerate()
  217. self.postGenerateMessage()
  218. def updateRequiredOtherFields(self, dclass, di):
  219. dclass.receiveUpdateBroadcastRequired(self, di)
  220. # Announce generate after updating all the required fields,
  221. # but before we update the non-required fields.
  222. self.announceGenerate()
  223. self.postGenerateMessage()
  224. dclass.receiveUpdateOther(self, di)
  225. def updateAllRequiredOtherFields(self, dclass, di):
  226. dclass.receiveUpdateAllRequired(self, di)
  227. # Announce generate after updating all the required fields,
  228. # but before we update the non-required fields.
  229. self.announceGenerate()
  230. self.postGenerateMessage()
  231. dclass.receiveUpdateOther(self, di)
  232. def sendSetZone(self, zoneId):
  233. self.air.sendSetZone(self, zoneId)
  234. def startMessageBundle(self, name):
  235. self.air.startMessageBundle(name)
  236. def sendMessageBundle(self):
  237. self.air.sendMessageBundle(self.doId)
  238. def getZoneChangeEvent(self):
  239. # this event is generated whenever this object changes zones.
  240. # arguments are newZoneId, oldZoneId
  241. # includes the quiet zone.
  242. return DistributedObjectAI.staticGetZoneChangeEvent(self.doId)
  243. def getLogicalZoneChangeEvent(self):
  244. # this event is generated whenever this object changes to a
  245. # non-quiet-zone zone.
  246. # arguments are newZoneId, oldZoneId
  247. # does not include the quiet zone.
  248. return DistributedObjectAI.staticGetLogicalZoneChangeEvent(self.doId)
  249. @staticmethod
  250. def staticGetZoneChangeEvent(doId):
  251. return 'DOChangeZone-%s' % doId
  252. @staticmethod
  253. def staticGetLogicalZoneChangeEvent(doId):
  254. return 'DOLogicalChangeZone-%s' % doId
  255. def handleLogicalZoneChange(self, newZoneId, oldZoneId):
  256. """this function gets called as if we never go through the
  257. quiet zone. Note that it is called once you reach the newZone,
  258. and not at the time that you leave the oldZone."""
  259. messenger.send(self.getLogicalZoneChangeEvent(),
  260. [newZoneId, oldZoneId])
  261. def getZoneData(self):
  262. # Call this to get an AIZoneData object for the current zone.
  263. # This class will hold onto it as self._zoneData
  264. # setLocation destroys self._zoneData if we move away to
  265. # a different zone
  266. if self._zoneData is None:
  267. from otp.ai.AIZoneData import AIZoneData
  268. self._zoneData = AIZoneData(self.air, self.parentId, self.zoneId)
  269. return self._zoneData
  270. def releaseZoneData(self):
  271. # You can call this to release any AIZoneData object that we might be
  272. # holding onto. If we're the last one for the current zone, the data
  273. # will be destroyed (render, collision traverser, etc.)
  274. # Note that the AIZoneData object that we're holding will be destroyed
  275. # automatically when we move away or are destroyed.
  276. if self._zoneData is not None:
  277. self._zoneData.destroy()
  278. self._zoneData = None
  279. def getRender(self):
  280. # note that this will return a different node if we change zones
  281. #return self.air.getRender(self.zoneId)
  282. return self.getZoneData().getRender()
  283. def getNonCollidableParent(self):
  284. return self.getZoneData().getNonCollidableParent()
  285. def getParentMgr(self):
  286. #return self.air.getParentMgr(self.zoneId)
  287. return self.getZoneData().getParentMgr()
  288. def getCollTrav(self, *args, **kArgs):
  289. return self.getZoneData().getCollTrav(*args, **kArgs)
  290. def sendUpdate(self, fieldName, args = []):
  291. assert self.notify.debugStateCall(self)
  292. if self.air:
  293. self.air.sendUpdate(self, fieldName, args)
  294. def GetPuppetConnectionChannel(self, doId):
  295. return doId + (1L << 32)
  296. def GetAccountConnectionChannel(self, doId):
  297. return doId + (3L << 32)
  298. def GetAccountIDFromChannelCode(self, channel):
  299. return channel >> 32
  300. def GetAvatarIDFromChannelCode(self, channel):
  301. return channel & 0xffffffffL
  302. def sendUpdateToAvatarId(self, avId, fieldName, args):
  303. assert self.notify.debugStateCall(self)
  304. channelId = self.GetPuppetConnectionChannel(avId)
  305. self.sendUpdateToChannel(channelId, fieldName, args)
  306. def sendUpdateToAccountId(self, accountId, fieldName, args):
  307. assert self.notify.debugStateCall(self)
  308. channelId = self.GetAccountConnectionChannel(accountId)
  309. self.sendUpdateToChannel(channelId, fieldName, args)
  310. def sendUpdateToChannel(self, channelId, fieldName, args):
  311. assert self.notify.debugStateCall(self)
  312. if self.air:
  313. self.air.sendUpdateToChannel(self, channelId, fieldName, args)
  314. def generateWithRequired(self, zoneId, optionalFields=[]):
  315. assert self.notify.debugStateCall(self)
  316. # have we already allocated a doId?
  317. if self.__preallocDoId:
  318. self.__preallocDoId = 0
  319. return self.generateWithRequiredAndId(
  320. self.doId, zoneId, optionalFields)
  321. # The repository is the one that really does the work
  322. parentId = self.air.districtId
  323. self.air.generateWithRequired(self, parentId, zoneId, optionalFields)
  324. self.generate()
  325. self.announceGenerate()
  326. self.postGenerateMessage()
  327. # this is a special generate used for estates, or anything else that
  328. # needs to have a hard coded doId as assigned by the server
  329. def generateWithRequiredAndId(self, doId, parentId, zoneId, optionalFields=[]):
  330. assert self.notify.debugStateCall(self)
  331. # have we already allocated a doId?
  332. if self.__preallocDoId:
  333. assert doId == self.doId
  334. self.__preallocDoId = 0
  335. # The repository is the one that really does the work
  336. self.air.generateWithRequiredAndId(self, doId, parentId, zoneId, optionalFields)
  337. self.generate()
  338. self.announceGenerate()
  339. self.postGenerateMessage()
  340. def generateOtpObject(self, parentId, zoneId, optionalFields=[], doId=None):
  341. assert self.notify.debugStateCall(self)
  342. # have we already allocated a doId?
  343. if self.__preallocDoId:
  344. assert doId is None or doId == self.doId
  345. doId=self.doId
  346. self.__preallocDoId = 0
  347. # Assign it an id
  348. if doId is None:
  349. self.doId = self.air.allocateChannel()
  350. else:
  351. self.doId = doId
  352. # Put the new DO in the dictionaries
  353. self.air.addDOToTables(self, location=(parentId, zoneId))
  354. # Send a generate message
  355. self.sendGenerateWithRequired(self.air, parentId, zoneId, optionalFields)
  356. self.generate()
  357. self.announceGenerate()
  358. self.postGenerateMessage()
  359. def generate(self):
  360. """
  361. Inheritors should put functions that require self.zoneId or
  362. other networked info in this function.
  363. """
  364. assert self.notify.debugStateCall(self)
  365. self.__generates += 1
  366. def generateInit(self, repository=None):
  367. """
  368. First generate (not from cache).
  369. """
  370. assert self.notify.debugStateCall(self)
  371. def generateTargetChannel(self, repository):
  372. """
  373. Who to send this to for generate messages
  374. """
  375. if hasattr(self, "dbObject"):
  376. return self.doId
  377. return repository.serverId
  378. def sendGenerateWithRequired(self, repository, parentId, zoneId, optionalFields=[]):
  379. assert self.notify.debugStateCall(self)
  380. dg = self.dclass.aiFormatGenerate(
  381. self, self.doId, parentId, zoneId,
  382. #repository.serverId,
  383. self.generateTargetChannel(repository),
  384. repository.ourChannel,
  385. optionalFields)
  386. repository.send(dg)
  387. def initFromServerResponse(self, valDict):
  388. assert self.notify.debugStateCall(self)
  389. # This is a special method used for estates, etc., which get
  390. # their fields set from the database indirectly by way of the
  391. # AI. The input parameter is a dictionary of field names to
  392. # datagrams that describes the initial field values from the
  393. # database.
  394. dclass = self.dclass
  395. for key, value in valDict.items():
  396. # Update the field
  397. dclass.directUpdate(self, key, value)
  398. def requestDelete(self):
  399. assert self.notify.debugStateCall(self)
  400. if not self.air:
  401. doId = "none"
  402. if hasattr(self, "doId"):
  403. doId = self.doId
  404. self.notify.warning(
  405. "Tried to delete a %s (doId %s) that is already deleted" %
  406. (self.__class__, doId))
  407. return
  408. self.air.requestDelete(self)
  409. self.air.startTrackRequestDeletedDO(self)
  410. self._DOAI_requestedDelete = True
  411. def taskName(self, taskString):
  412. return ("%s-%s" % (taskString, self.doId))
  413. def uniqueName(self, idString):
  414. return ("%s-%s" % (idString, self.doId))
  415. def validate(self, avId, bool, msg):
  416. if not bool:
  417. self.air.writeServerEvent('suspicious', avId, msg)
  418. self.notify.warning('validate error: avId: %s -- %s' % (avId, msg))
  419. return bool
  420. def beginBarrier(self, name, avIds, timeout, callback):
  421. # Begins waiting for a set of avatars. When all avatars in
  422. # the list have reported back in or the callback has expired,
  423. # calls the indicated callback with the list of avatars that
  424. # made it through. There may be multiple barriers waiting
  425. # simultaneously on different lists of avatars, although they
  426. # should have different names.
  427. from otp.ai import Barrier
  428. context = self.__nextBarrierContext
  429. # We assume the context number is passed as a uint16.
  430. self.__nextBarrierContext = (self.__nextBarrierContext + 1) & 0xffff
  431. assert self.notify.debug('beginBarrier(%s, %s, %s, %s)' % (context, name, avIds, timeout))
  432. if avIds:
  433. barrier = Barrier.Barrier(
  434. name, self.uniqueName(name), avIds, timeout,
  435. doneFunc = PythonUtil.Functor(
  436. self.__barrierCallback, context, callback))
  437. self.__barriers[context] = barrier
  438. # Send the context number to each involved client.
  439. self.sendUpdate("setBarrierData", [self.getBarrierData()])
  440. else:
  441. # No avatars; just call the callback immediately.
  442. callback(avIds)
  443. return context
  444. def getBarrierData(self):
  445. # Returns the barrier data formatted for sending to the
  446. # clients. This lists all of the current outstanding barriers
  447. # and the avIds waiting for them.
  448. data = []
  449. for context, barrier in self.__barriers.items():
  450. avatars = barrier.pendingAvatars
  451. if avatars:
  452. data.append((context, barrier.name, avatars))
  453. return data
  454. def ignoreBarrier(self, context):
  455. # Aborts a previously-set barrier. The context is the return
  456. # value from the previous call to beginBarrier().
  457. barrier = self.__barriers.get(context)
  458. if barrier:
  459. barrier.cleanup()
  460. del self.__barriers[context]
  461. def setBarrierReady(self, context):
  462. # Generated by the clients to check in after a beginBarrier()
  463. # call.
  464. avId = self.air.getAvatarIdFromSender()
  465. assert self.notify.debug('setBarrierReady(%s, %s)' % (context, avId))
  466. barrier = self.__barriers.get(context)
  467. if barrier == None:
  468. # This may be None if a client was slow and missed an
  469. # earlier timeout. Too bad.
  470. return
  471. barrier.clear(avId)
  472. def __barrierCallback(self, context, callback, avIds):
  473. assert self.notify.debug('barrierCallback(%s, %s)' % (context, avIds))
  474. # The callback that is generated when a barrier is completed.
  475. barrier = self.__barriers.get(context)
  476. if barrier:
  477. barrier.cleanup()
  478. del self.__barriers[context]
  479. callback(avIds)
  480. else:
  481. self.notify.warning("Unexpected completion from barrier %s" % (context))
  482. def isGridParent(self):
  483. # If this distributed object is a DistributedGrid return 1. 0 by default
  484. return 0
  485. def execCommand(self, string, mwMgrId, avId, zoneId):
  486. pass
  487. def _retrieveCachedData(self):
  488. """ This is a no-op on the AI. """
  489. pass