DistributedObjectAI.py 21 KB

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