DistributedObjectUD.py 22 KB

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