def enterClosing(self, ts): doorFrameHoleRight = self.findDoorNode('doorFrameHoleRight') if doorFrameHoleRight.isEmpty(): self.notify.warning('enterClosing(): did not find doorFrameHoleRight') return rightDoor = self.findDoorNode('rightDoor') if rightDoor.isEmpty(): self.notify.warning('enterClosing(): did not find rightDoor') return otherNP = self.getDoorNodePath() trackName = 'doorClose-%d' % self.doId if self.rightSwing: h = 100 else: h = -100 self.finishDoorTrack() self.doorTrack = Sequence(LerpHprInterval(nodePath=rightDoor, duration=1.0, hpr=VBase3(0, 0, 0), startHpr=VBase3(h, 0, 0), other=otherNP, blendType='easeInOut'), Func(doorFrameHoleRight.hide), Func(self.hideIfHasFlat, rightDoor), SoundInterval(self.closeSfx, node=rightDoor), name=trackName) self.doorTrack.start(ts) if hasattr(self, 'done'): zoneId = self.otherZoneId if self.doorType == DoorTypes.EXT_STANDARD: whereTo = 'house' else: whereTo = 'estate' request = {'loader': 'safeZoneLoader', 'where': whereTo, 'how': 'doorIn', 'hoodId': ToontownGlobals.MyEstate, 'zoneId': zoneId, 'shardId': None, 'avId': -1, 'allowRedirect': 0, 'doorDoId': self.otherDoId} messenger.send('doorDoneEvent', [request])
def __on_joystick_polling(self, task): for ev in pygame.event.get(): if ev.type is pygame.JOYBUTTONDOWN: name = 'joystick%d-button%d' % (ev.joy, ev.button) messenger.send(name) print name elif ev.type is pygame.JOYBUTTONUP: name = 'joystick%d-button%d-up' % (ev.joy, ev.button) messenger.send(name) elif ev.type is pygame.JOYAXISMOTION: name = 'joystick%d-axis%d' % (ev.joy, ev.axis) messenger.send(name, [ev.value]) elif ev.type is pygame.JOYBALLMOTION: name = 'joystick%d-ball%d' % (ev.joy, ev.hat) messenger.send(name, [ev.rel]) elif ev.type is pygame.JOYHATMOTION: name = 'joystick%d-hat%d' % (ev.joy, ev.hat) messenger.send(name, [ev.value]) #print name return task.cont
def update_gaming(self): # out('client update',frame_no=self.frame_no) void=True self.frame_no+=1 GEntity.frame_no=self.frame_no #process data from server (server's update included) for d in self.proxy.new_data: void=False #some of them are to be processed here if network.stc_start_game in d: out('network.stc_start_game') self.screen.frame.start_game() elif network.stc_end_game in d: out('network.stc_end_game') self.demand('Stats') #if etc #the rest is given to the gframe, responsible for the graphic stuff else: self.screen.frame.process_server_input(d) if void: if len(self.fake_keypresses): messenger.send(self.fake_keypresses[0]) self.fake_keypresses.pop(0) for o in __builtin__.dispose_list:o.dispose() __builtin__.dispose_list=[]
def quickSaveButton(self): '''quicksave the data''' self.menu.hide() self.button_quicksave['state'] = DGG.DISABLED self.button_quickload['state'] = DGG.DISABLED if self._currentDump: messenger.send('quick_save', [self._currentDump,self._currentMessage])
def setupWindow(self, windowType, x, y, width, height, parent): """ Applies the indicated window parameters to the prc settings, for future windows; or applies them directly to the main window if the window has already been opened. This is called by the browser. """ if self.started and base.win: # If we've already got a window, this must be a # resize/reposition request. wp = WindowProperties() if x or y or windowType == 'embedded': wp.setOrigin(x, y) if width or height: wp.setSize(width, height) if windowType == 'embedded': wp.setParentWindow(parent) wp.setFullscreen(False) base.win.requestProperties(wp) self.windowProperties = wp return # If we haven't got a window already, start 'er up. Apply the # requested setting to the prc file, and to the default # WindowProperties structure. self.__clearWindowProperties() if windowType == 'hidden': data = 'window-type none\n' else: data = 'window-type onscreen\n' wp = WindowProperties.getDefault() wp.clearParentWindow() wp.clearOrigin() wp.clearSize() wp.setFullscreen(False) if windowType == 'fullscreen': wp.setFullscreen(True) if windowType == 'embedded': wp.setParentWindow(parent) if x or y or windowType == 'embedded': wp.setOrigin(x, y) if width or height: wp.setSize(width, height) self.windowProperties = wp self.windowPrc = loadPrcFileData("setupWindow", data) WindowProperties.setDefault(wp) self.gotWindow = True # Send this call to the main thread; don't call it directly. messenger.send('AppRunner_startIfReady', taskChain = 'default')
def enterGame(self,isNew): print '进入游戏状态' if isNew: print '新建游戏' messenger.send("serious_new_game") else: print '读取游戏' messenger.send("serious_load_game")
def add(self, w, x, y, z): n = core.NodePath('designation') n.setPos(x, y, z) n.setShader(self.shader) n.setShaderInput('color', core.Vec4(0.5, 1.0, 0.5, 0.5)) self.model.instanceTo(n) messenger.send('designation-add', [x, y, z, n])
def test_hold_joystick_right(self): """ test that if required to hold for reward, actually requires hold """ self.cb.inc_js_goal() messenger.send('x_axis', [1]) self.assertFalse(self.cb.reward_on) messenger.send('x_axis', [1]) self.assertTrue(self.cb.reward_on)
def focus_on(self, target, radius): self.__objectToFocus = target self.__radius = radius self.__objectPrevPos = target.getPos() targetPos = target.getPos() cameraPos = self.__camToCtrl.getPos() #print "The Pos of Camera : ", cameraPos #print "The Pos of Target : ", targetPos ctVector = cameraPos - targetPos ctvLen = ctVector.length() ctVector.normalize() #print "The e Vector : ", ctVector disOffset = math.fabs(ctvLen - radius) #print "The Distance Offset : ", disOffset if ctvLen > radius: cameraPos -= ctVector * disOffset elif ctvLen < radius: cameraPos += ctVector * disOffset #print "The Camera Move To : ", cameraPos self.__camCurrX = cameraPos[0] self.__camCurrY = cameraPos[1] self.__camCurrZ = cameraPos[2] self.__camToCtrl.setPos(cameraPos) self.__camToCtrl.lookAt(target) self.__update_directionsVector() self.turn_off_ctrl_options( options = [CAM_MOVE_FORWARD, CAM_MOVE_BACKWARD, CAM_MOVE_LEFT, CAM_MOVE_RIGHT, CAM_MOVE_UP, CAM_MOVE_DOWN, CAM_ROTATE_H_CW, CAM_ROTATE_H_CCW, CAM_ROTATE_P_CW, CAM_ROTATE_P_CCW, CAM_ROTATE_R_CW, CAM_ROTATE_R_CCW]) messenger.send("update_camera")
def run(self): t = self.globalClock.getFrameTime() timeDelta = t - self.globalClock.getRealTime() self.globalClock.setRealTime(t) messenger.send('resetClock', [timeDelta]) if self.resumeFunc != None: self.resumeFunc() if self.stepping: self.step() else: self.running = True while self.running: try: if len(self._frameProfileQueue): numFrames, session, callback = self._frameProfileQueue.pop() def _profileFunc(numFrames = numFrames): self._doProfiledFrames(numFrames) session.setFunc(_profileFunc) session.run() _profileFunc = None if callback: callback() session.release() else: self.step() except KeyboardInterrupt: self.stop() except IOError as ioError: code, message = self._unpackIOError(ioError) if code == 4: self.stop() else: raise except Exception as e: if self.extendedExceptions: self.stop() print_exc_plus() else: if ExceptionVarDump.wantStackDumpLog and ExceptionVarDump.dumpOnExceptionInit: ExceptionVarDump._varDump__print(e) raise except: if self.extendedExceptions: self.stop() print_exc_plus() else: raise self.mgr.stopThreads() return
def enterClosing(self, ts): doorFrameHoleRight = self.findDoorNode("doorFrameHoleRight") if doorFrameHoleRight.isEmpty(): self.notify.warning("enterClosing(): did not find doorFrameHoleRight") return rightDoor = self.findDoorNode("rightDoor") if rightDoor.isEmpty(): self.notify.warning("enterClosing(): did not find rightDoor") return otherNP = self.getDoorNodePath() trackName = "doorClose-%d" % self.doId if self.rightSwing: h = 100 else: h = -100 self.finishDoorTrack() self.doorTrack = Sequence( LerpHprInterval( nodePath=rightDoor, duration=1.0, hpr=VBase3(0, 0, 0), startHpr=VBase3(h, 0, 0), other=otherNP, blendType="easeInOut", ), Func(doorFrameHoleRight.hide), Func(self.hideIfHasFlat, rightDoor), SoundInterval(self.closeSfx, node=rightDoor), name=trackName, ) self.doorTrack.start(ts) if hasattr(self, "done"): base.cr.playGame.hood.loader.setHouse(self.houseId) zoneId = self.otherZoneId if self.doorType == DoorTypes.EXT_STANDARD: whereTo = "house" else: whereTo = "estate" request = { "loader": "safeZoneLoader", "where": whereTo, "how": "doorIn", "hoodId": ToontownGlobals.MyEstate, "zoneId": zoneId, "shardId": None, "avId": -1, "allowRedirect": 0, "doorDoId": self.otherDoId, } messenger.send("doorDoneEvent", [request]) return
def _update(self, task): newevents = [] for gpidx, gamepad in enumerate(self._gamepads): for axis in p3d.InputDevice.Axis: state = gamepad.findAxis(axis) if state and abs(state.value) > self.gamepad_deadzone: axisname = str(axis).lower().replace('.', '_') event = f'gamepad{gpidx}-{axisname}' messenger.send(event, [state.value]) if state.value > 0: event = f'{event}-pos' else: event = f'{event}-neg' newevents.append(event) if event not in self._prev_gamepad_events: messenger.send(event) else: messenger.send(f'{event}-repeat') for prevevent in self._prev_gamepad_events: if prevevent not in newevents: messenger.send(f'{prevevent}-up') self._prev_gamepad_events = newevents return task.cont
def set_block(self, x, y, z, form, substance, hidden, update_hidden=True): if (x, y, z) not in self: return False old = self.blocks[(x, y, z)] new = (form, substance, hidden) if old != new: self.blocks[(x, y, z)] = new messenger.send('block-update', [(x, y, z)]) if update_hidden: for dx, dy, dz in DIRECTIONS.values(): self.update_hidden(x + dx, y + dy, z + dz)
def destroy(self): messenger.send(self._getDestroyEvent()) self.ignoreAll() if self._pruneContainersJob is not None: jobMgr.remove(self._pruneContainersJob) self._pruneContainersJob = None if self._checkContainersJob is not None: jobMgr.remove(self._checkContainersJob) self._checkContainersJob = None jobMgr.remove(self._findContainersJob) self._findContainersJob = None del self._id2ref del self._index2containerId2len del self._index2delay
def enterClosing(self, ts): doorFrameHoleRight = self.findDoorNode('doorFrameHoleRight') if doorFrameHoleRight.isEmpty(): self.notify.warning( 'enterClosing(): did not find doorFrameHoleRight') return else: rightDoor = self.findDoorNode('rightDoor') if rightDoor.isEmpty(): self.notify.warning('enterClosing(): did not find rightDoor') return otherNP = self.getDoorNodePath() trackName = 'doorClose-%d' % self.doId if self.rightSwing: h = 100 else: h = -100 self.finishDoorTrack() self.doorTrack = Sequence(LerpHprInterval(nodePath=rightDoor, duration=1.0, hpr=VBase3(0, 0, 0), startHpr=VBase3(h, 0, 0), other=otherNP, blendType='easeInOut'), Func(doorFrameHoleRight.hide), Func(self.hideIfHasFlat, rightDoor), SoundInterval(self.closeSfx, node=rightDoor), name=trackName) self.doorTrack.start(ts) if hasattr(self, 'done'): base.cr.playGame.hood.loader.setHouse(self.houseId) zoneId = self.otherZoneId if self.doorType == DoorTypes.EXT_STANDARD: whereTo = 'house' else: whereTo = 'estate' request = { 'loader': 'safeZoneLoader', 'where': whereTo, 'how': 'doorIn', 'hoodId': ToontownGlobals.MyEstate, 'zoneId': zoneId, 'shardId': None, 'avId': -1, 'allowRedirect': 0, 'doorDoId': self.otherDoId } messenger.send('doorDoneEvent', [request]) return
def __exitCurrent(self, argList): """ Exit the current state """ assert self.__internalStateInFlux assert ClassicFSM.notify.debug( "[%s]: exiting %s" % (self.__name, self.__currentState.getName())) self.__currentState.exit(argList) # Only send the state change event if we are inspecting it # If this event turns out to be generally useful, we can # turn it on all the time, but for now nobody else is using it if self.inspecting: messenger.send(self.getName() + '_' + self.__currentState.getName() + '_exited') self.__currentState = None
def deleteOrDelay(self): if len(self._token2delayDeleteName) > 0: if not self._delayDeleted: self._delayDeleted = 1 # Object is delayDeleted. Clean up DistributedObject state, # remove from repository tables, so that we won't crash if # another instance of the same object gets generated while # this instance is still delayDeleted. messenger.send(self.getDelayDeleteEvent()) if len(self._token2delayDeleteName) > 0: self.delayDelete() if len(self._token2delayDeleteName) > 0: self._deactivateDO() else: self.disableAnnounceAndDelete()
def stopCollect(self): self.ignore(self._interestMgr._getAddInterestEvent()) self.ignore(self._interestMgr._getRemoveInterestEvent()) mustCollect = self._mustCollect del self._mustCollect if not self._gotEvent: if mustCollect: logFunc = self.notify.error else: logFunc = self.notify.warning logFunc('%s: empty interest-complete set' % self.getName()) self.destroy() messenger.send(self.getDoneEvent()) else: self.accept(self.getDoneEvent(), self.destroy)
def load(self): self.notify.debug('load') if not self.house_loaded: if self.houseType >= len(self.cr.playGame.hood.loader.houseModels): self.houseType = HouseGlobals.HOUSE_DEFAULT houseModel = self.cr.playGame.hood.loader.houseModels[self.houseType] self.house = houseModel.copyTo(self.cr.playGame.hood.loader.houseNode[self.housePosInd]) self.house_loaded = 1 self.cr.playGame.hood.loader.houseId2house[self.doId] = self.house if self.houseType == HouseGlobals.HOUSE_DEFAULT: self.__setHouseColor() if self.houseType == HouseGlobals.HOUSE_DEFAULT or self.houseType == HouseGlobals.HOUSE_TEST: self.__setupDoor() else: self.__setupDoorCustom() messenger.send('houseLoaded-%d' % self.doId)
def __playTask(self, task): time = globalClock.getFrameTime() dTime = time - task.lastTime task.lastTime = time if self.loop: cTime = (task.currentTime + dTime) % self.getMaxT() else: cTime = task.currentTime + dTime if self.loop == 0 and cTime > self.getMaxT(): self.stop() messenger.send(self.name + '-done') self.node = None return task.done self.goTo(self.node, cTime) task.currentTime = cTime return task.cont
def load(self): self.notify.debug('load') if not self.house_loaded: if self.houseType >= len(self.cr.playGame.hood.loader.houseModels): self.houseType = HouseGlobals.HOUSE_DEFAULT houseModel = self.cr.playGame.hood.loader.houseModels[self.houseType] self.house = houseModel.copyTo(self.cr.playGame.hood.loader.houseNode[self.housePosInd]) self.house_loaded = 1 self.cr.playGame.hood.loader.houseId2house[self.doId] = self.house if self.houseType == HouseGlobals.HOUSE_DEFAULT: self.__setHouseColor() if self.houseType == HouseGlobals.HOUSE_DEFAULT or self.houseType == HouseGlobals.HOUSE_TEST: self.__setupDoor() else: self.__setupDoorCustom() messenger.send('houseLoaded-%d' % self.doId)
def __downloadPackageTask(self, task): """ This task runs on the aysynchronous task chain; each pass, it extracts one package from self.needsDownload and downloads it. """ while True: self.packageLock.acquire() try: # If we're done downloading, stop the task. if self.state == self.S_done or not self.needsDownload: self.downloadTask = None self.packageLock.release() yield task.done; return assert self.state == self.S_started pp = self.needsDownload[0] del self.needsDownload[0] except: self.packageLock.release() raise self.packageLock.release() # Now serve this one package. eventName = 'PackageInstaller-%s-packageStarted' % self.uniqueId messenger.send(eventName, [pp], taskChain = 'default') if not pp.package.hasPackage: for token in pp.package.downloadPackageGenerator(self.appRunner.http): if token == pp.package.stepContinue: yield task.cont else: break if token != pp.package.stepComplete: pc = PStatCollector(':App:PackageInstaller:donePackage:%s' % (pp.package.packageName)) pc.start() self.__donePackage(pp, False) pc.stop() yield task.cont continue # Successfully downloaded and installed. pc = PStatCollector(':App:PackageInstaller:donePackage:%s' % (pp.package.packageName)) pc.start() self.__donePackage(pp, True) pc.stop()
def dispatchMessages(self): if self.walk: messenger.send("walk", [-0.1]) elif self.reverse: messenger.send("reverse", [0.1]) if self.left: messenger.send("turn", [0.8]) elif self.right: messenger.send("turn", [-0.8])
def __downloadPackageTask(self, task): """ This task runs on the aysynchronous task chain; each pass, it extracts one package from self.needsDownload and downloads it. """ while True: self.packageLock.acquire() try: # If we're done downloading, stop the task. if self.state == self.S_done or not self.needsDownload: self.downloadTask = None self.packageLock.release() yield task.done; return assert self.state == self.S_started pp = self.needsDownload[0] del self.needsDownload[0] except: self.packageLock.release() raise self.packageLock.release() # Now serve this one package. eventName = 'PackageInstaller-%s-packageStarted' % self.uniqueId messenger.send(eventName, [pp], taskChain = 'default') if not pp.package.hasPackage: for token in pp.package.downloadPackageGenerator(self.appRunner.http): if token == pp.package.stepContinue: yield task.cont else: break if token != pp.package.stepComplete: pc = PStatCollector(':App:PackageInstaller:donePackage:%s' % (pp.package.packageName)) pc.start() self.__donePackage(pp, False) pc.stop() yield task.cont continue # Successfully downloaded and installed. pc = PStatCollector(':App:PackageInstaller:donePackage:%s' % (pp.package.packageName)) pc.start() self.__donePackage(pp, True) pc.stop()
def handleInterestDoneMessage(self, di): """ This handles the interest done messages and may dispatch an event """ assert DoInterestManager.notify.debugCall() if ConfigVariableBool('astron-support', True): contextId = di.getUint32() handle = di.getUint16() else: handle = di.getUint16() contextId = di.getUint32() if self.__verbose(): print('CR::INTEREST.interestDone(handle=%s)' % handle) DoInterestManager.notify.debug( "handleInterestDoneMessage--> Received handle %s, context %s" % (handle, contextId)) if handle in DoInterestManager._interests: eventsToSend = [] # if the context matches, send out the event if contextId == DoInterestManager._interests[handle].context: DoInterestManager._interests[handle].context = NO_CONTEXT # the event handlers may call back into the interest manager. Send out # the events after we're once again in a stable state. #DoInterestManager._interests[handle].sendEvents() eventsToSend = list( DoInterestManager._interests[handle].getEvents()) DoInterestManager._interests[handle].clearEvents() else: DoInterestManager.notify.debug( "handleInterestDoneMessage--> handle: %s: Expecting context %s, got %s" % (handle, DoInterestManager._interests[handle].context, contextId)) if __debug__: state = DoInterestManager._interests[handle] self._addDebugInterestHistory("finished", state.desc, handle, contextId, state.parentId, state.zoneIdList) self._considerRemoveInterest(handle) for event in eventsToSend: messenger.send(event) else: DoInterestManager.notify.warning( "handleInterestDoneMessage: handle not found: %s" % (handle)) # if there are no more outstanding interest-completes, send out global all-done event if self._completeEventCount.num == 0: self.queueAllInterestsCompleteEvent() assert self.printInterestsIfDebug()
def windowEvent(self, win): if win != self.win: # This event isn't about our window. return properties = win.getProperties() if properties != self._ShowBase__prevWindowProperties: # pylint: disable=access-member-before-definition self._ShowBase__prevWindowProperties = properties # pylint: disable=access-member-before-definition self.notify.debug("Got window event: %s" % (repr(properties))) if not properties.getOpen(): # If the user closes the main window, we should exit. self.notify.info("User closed main window.") self.userExit() if properties.getForeground() and not self.mainWinForeground: self.mainWinForeground = 1 elif not properties.getForeground() and self.mainWinForeground: self.mainWinForeground = 0 if properties.getMinimized() and not self.mainWinMinimized: # If the main window is minimized, throw an event to # stop the music. self.mainWinMinimized = 1 messenger.send('PandaPaused') elif not properties.getMinimized() and self.mainWinMinimized: # If the main window is restored, throw an event to # restart the music. self.mainWinMinimized = 0 messenger.send('PandaRestarted') # If we have not forced the aspect ratio, let's see if it has # changed and update the camera lenses and aspect2d parameters self.adjustWindowAspectRatio(self.getAspectRatio()) if win.hasSize() and win.getSbsLeftYSize() != 0: self.pixel2d.setScale(2.0 / win.getSbsLeftXSize(), 1.0, 2.0 / win.getSbsLeftYSize()) if self.wantRender2dp: self.pixel2dp.setScale(2.0 / win.getSbsLeftXSize(), 1.0, 2.0 / win.getSbsLeftYSize()) else: xsize, ysize = self.getSize() if xsize > 0 and ysize > 0: self.pixel2d.setScale(2.0 / xsize, 1.0, 2.0 / ysize) if self.wantRender2dp: self.pixel2dp.setScale(2.0 / xsize, 1.0, 2.0 / ysize)
def dispatchMessages(self): if self.__new_game: messenger.send("NewGame") print '已经发送 new game' self.endNewGame() elif self.__load_game: messenger.send("LoadGame") self.endLoadGame() if self.__description: messenger.send("Description") self.endDescription() elif self.__exit: messenger.send("Exit") self.endExit() if self.__select: messenger.send("ChangeMenu") self.endSelect()
def move(self, position=None): # print 'square move' # print 'square position', position if not position: # print 'trying to get a auto position' try: position = self.pos.next() # print position except StopIteration: # print('stop iterating!') messenger.send("s") # Switch to manual and wait # need to set a position position = (0, self.depth, 0) # self.close() # print position self.square.setPos(Point3(position))
def move(self, position=None): # print 'square move' # print 'square position', position if not position: # print 'trying to get a auto position' try: position = self.pos.next() # print position except StopIteration: # print('stop iterating!') messenger.send("s") # Switch to manual and wait # need to set a position position = (0, self.depth, 0) # self.close() # print position self.square.setPos(Point3(position))
def __connected(self): self.notify.info('Connected successfully.') # Listen to our channel... self.registerForChannel(self.ourChannel) # If we're configured with a State Server, register a post-remove to # clean up whatever objects we own on this server should we unexpectedly # fall over and die. if self.serverId: dg = PyDatagram() dg.addServerHeader(self.serverId, self.ourChannel, STATESERVER_DELETE_AI_OBJECTS) dg.addChannel(self.ourChannel) self.addPostRemove(dg) messenger.send('airConnected') self.handleConnected()
def __gotPhaseComplete(self): """ A hook added to a phaseComplete message. When all phaseCompletes have been sent, trigger the allPhasesComplete message. """ if self.allPhasesComplete: # Already sent. return for phaseData in self.phaseData.values(): if not phaseData.complete: # More to come later. return # All phases are now complete. Tell the world. self.allPhasesComplete = True print "launcherAllPhasesComplete" messenger.send("launcherAllPhasesComplete", taskChain='default')
def _PhaseData__nextCallback(self, currentCallback, currentTaskChain): if currentCallback: currentCallback() if self.postProcessCallbacks: (callback, taskChain) = self.postProcessCallbacks[0] del self.postProcessCallbacks[0] if taskChain != currentTaskChain: print 'switching to %s' % taskChain taskMgr.add(self._PhaseData__nextCallback, 'phaseCallback-%s' % self.phase, taskChain=taskChain, extraArgs=[callback, taskChain]) return None self.complete = True messenger.send('phaseComplete-%s' % self.phase, taskChain='default')
def __getDescFileTask(self, task): """ This task runs on the aysynchronous task chain; each pass, it extracts one package from self.needsDescFile and downloads its desc file. On success, it adds the package to self.needsDownload. """ self.packageLock.acquire() try: # If we've finished all of the packages that need desc # files, stop the task. if not self.needsDescFile: self.descFileTask = None eventName = 'PackageInstaller-%s-allHaveDesc' % self.uniqueId messenger.send(eventName, taskChain = 'default') return task.done pp = self.needsDescFile[0] del self.needsDescFile[0] finally: self.packageLock.release() # Now serve this one package. if not pp.checkDescFile(): if not pp.getDescFile(self.appRunner.http): self.__donePackage(pp, False) return task.cont # This package is now ready to be downloaded. We always add # it to needsDownload, even if it's already downloaded, to # guarantee ordering of packages. self.packageLock.acquire() try: # Also add any packages required by this one. for packageName, version, host in pp.package.requires: pp2 = self.PendingPackage(packageName, version, host) self.__internalAddPackage(pp2) self.needsDownload.append(pp) finally: self.packageLock.release() return task.cont
def addInterest(self, parentId, zoneIdList, description, event=None): """ Look into a (set of) zone(s). """ assert DoInterestManager.notify.debugCall() handle = self._getNextHandle() # print 'base.cr.addInterest(',description,',',handle,'):',globalClock.getFrameCount() if self._noNewInterests: DoInterestManager.notify.warning( "addInterest: addingInterests on delete: %s" % (handle)) return # make sure we've got parenting rules set in the DC if parentId not in (self.getGameDoId(), ): parent = self.getDo(parentId) if not parent: DoInterestManager.notify.error( 'addInterest: attempting to add interest under unknown object %s' % parentId) else: if not parent.hasParentingRules(): DoInterestManager.notify.error( 'addInterest: no setParentingRules defined in the DC for object %s (%s)' '' % (parentId, parent.__class__.__name__)) if event: contextId = self._getNextContextId() else: contextId = 0 # event = self._getAnonymousEvent('addInterest') DoInterestManager._interests[handle] = InterestState( description, InterestState.StateActive, contextId, event, parentId, zoneIdList, self._completeEventCount) if self.__verbose(): print( 'CR::INTEREST.addInterest(handle=%s, parentId=%s, zoneIdList=%s, description=%s, event=%s)' % (handle, parentId, zoneIdList, description, event)) self._sendAddInterest(handle, contextId, parentId, zoneIdList, description) if event: messenger.send(self._getAddInterestEvent(), [event]) assert self.printInterestsIfDebug() return InterestHandle(handle)
def __getDescFileTask(self, task): """ This task runs on the aysynchronous task chain; each pass, it extracts one package from self.needsDescFile and downloads its desc file. On success, it adds the package to self.needsDownload. """ self.packageLock.acquire() try: # If we've finished all of the packages that need desc # files, stop the task. if not self.needsDescFile: self.descFileTask = None eventName = 'PackageInstaller-%s-allHaveDesc' % self.uniqueId messenger.send(eventName, taskChain = 'default') return task.done pp = self.needsDescFile[0] del self.needsDescFile[0] finally: self.packageLock.release() # Now serve this one package. if not pp.checkDescFile(): if not pp.getDescFile(self.appRunner.http): self.__donePackage(pp, False) return task.cont # This package is now ready to be downloaded. We always add # it to needsDownload, even if it's already downloaded, to # guarantee ordering of packages. self.packageLock.acquire() try: # Also add any packages required by this one. for packageName, version, host in pp.package.requires: pp2 = self.PendingPackage(packageName, version, host) self.__internalAddPackage(pp2) self.needsDownload.append(pp) finally: self.packageLock.release() return task.cont
def load(self): self.notify.debug('load') if not self.house_loaded: if self.housePosInd == 1: houseModelIndex = base.config.GetInt('want-custom-house', HouseGlobals.HOUSE_DEFAULT) else: houseModelIndex = HouseGlobals.HOUSE_DEFAULT houseModelIndex = base.config.GetInt('want-custom-house-all', houseModelIndex) houseModel = self.cr.playGame.hood.loader.houseModels[houseModelIndex] self.house = houseModel.copyTo(self.cr.playGame.hood.loader.houseNode[self.housePosInd]) self.house_loaded = 1 self.cr.playGame.hood.loader.houseId2house[self.doId] = self.house if houseModelIndex == HouseGlobals.HOUSE_DEFAULT: self.__setHouseColor() if houseModelIndex == HouseGlobals.HOUSE_DEFAULT: self.__setupDoor() else: self.__setupDoorCustom() messenger.send('houseLoaded-%d' % self.doId)
def disableAndAnnounce(self): """ Inheritors should *not* redefine this function. """ # We must send the disable announce message *before* we # actually disable the object. That way, the various cleanup # tasks can run first and take care of restoring the object to # a normal, nondisabled state; and *then* the disable function # can properly disable it (for instance, by parenting it to # hidden). if self.activeState != ESDisabled: self.activeState = ESDisabling messenger.send(self.getDisableEvent()) self.disable() self.activeState = ESDisabled if not self._delayDeleted: # if the object is DelayDeleted, _deactivateDO has # already been called self._deactivateDO()
def load(self): self.notify.debug('load') if not self.house_loaded: if self.housePosInd == 1: houseModelIndex = base.config.GetInt('want-custom-house', HouseGlobals.HOUSE_DEFAULT) else: houseModelIndex = HouseGlobals.HOUSE_DEFAULT houseModelIndex = base.config.GetInt('want-custom-house-all', houseModelIndex) houseModel = self.cr.playGame.hood.loader.houseModels[houseModelIndex] self.house = houseModel.copyTo(self.cr.playGame.hood.loader.houseNode[self.housePosInd]) self.house_loaded = 1 self.cr.playGame.hood.loader.houseId2house[self.doId] = self.house if houseModelIndex == HouseGlobals.HOUSE_DEFAULT: self.__setHouseColor() if houseModelIndex == HouseGlobals.HOUSE_DEFAULT: self.__setupDoor() else: self.__setupDoorCustom() messenger.send('houseLoaded-%d' % self.doId)
def setLocation(self, parentId, zoneId): # Prevent Duplicate SetLocations for being Called if self.parentId == parentId and self.zoneId == zoneId: return oldParentId = self.parentId oldZoneId = self.zoneId self.air.storeObjectLocation(self, parentId, zoneId) if oldParentId != parentId or oldZoneId != zoneId: self.releaseZoneData() messenger.send(self.getZoneChangeEvent(), [zoneId, oldZoneId]) # if we are not going into the quiet zone, send a 'logical' zone # change message if zoneId != DistributedObjectAI.QuietZone: lastLogicalZone = oldZoneId if oldZoneId == DistributedObjectAI.QuietZone: lastLogicalZone = self.lastNonQuietZone self.handleLogicalZoneChange(zoneId, lastLogicalZone) self.lastNonQuietZone = zoneId
def handleAvatarControls(self, task): """ Check on the arrow keys and update the avatar. """ # get the button states: jump = inputState.isSet("forward") if self.lifter.isOnGround(): if self.isAirborne: self.isAirborne = 0 assert self.debugPrint("isAirborne 0 due to isOnGround() true") impact = self.lifter.getImpactVelocity() messenger.send("jumpLand") assert self.isAirborne == 0 self.priorParent = Vec3.zero() else: if self.isAirborne == 0: assert self.debugPrint("isAirborne 1 due to isOnGround() false") self.isAirborne = 1 return Task.cont
async def __transition(self, newState, *args): assert self.state assert self.notify.debug("%s to state %s." % (self._name, newState)) self.oldState = self.state self.newState = newState self.state = None try: if not self.__callFromToFunc(self.oldState, self.newState, *args): result = self.__callExitFunc(self.oldState) if isinstance(result, types.CoroutineType): await result result = self.__callEnterFunc(self.newState, *args) if isinstance(result, types.CoroutineType): await result except: # If we got an exception during the enter or exit methods, # go directly to state "InternalError" and raise up the # exception. This might leave things a little unclean # since we've partially transitioned, but what can you do? self.state = 'InternalError' del self.oldState del self.newState raise if self._broadcastStateChanges: messenger.send(self.getStateChangeEvent()) self.state = newState del self.oldState del self.newState if self.__requestQueue: request, fut = self.__requestQueue.pop(0) assert self.notify.debug("%s continued queued request." % (self._name)) await request() fut.set_result(None)
def dispatch_message(self, event, partMessage = None): if self.__eventMessageMap.has_key(event) is False: return msgs = self.__eventMessageMap[event] if partMessage == None: for msg in msgs: messenger.send(msg) else: for msg in partMessage: if msg in msgs: messenger.send(msg)
def checkForGarbageLeaks(): gc.collect() numGarbage = len(gc.garbage) if numGarbage > 0 and config.GetBool('auto-garbage-logging', 0): if numGarbage != _CFGLGlobals.LastNumGarbage: print("") gr = GarbageReport('found garbage', threaded=False, collect=False) print("") _CFGLGlobals.LastNumGarbage = numGarbage _CFGLGlobals.LastNumCycles = gr.getNumCycles() messenger.send(GarbageCycleCountAnnounceEvent, [gr.getDesc2numDict()]) gr.destroy() notify = directNotify.newCategory("GarbageDetect") if config.GetBool('allow-garbage-cycles', 1): func = notify.warning else: func = notify.error func('%s garbage cycles found, see info above' % _CFGLGlobals.LastNumCycles) return numGarbage
def __nextCallback(self, currentCallback, currentTaskChain): # Perform the callback's function. if currentCallback: currentCallback() # Grab the next callback off the list, and execute it. if self.postProcessCallbacks: callback, taskChain = self.postProcessCallbacks[0] del self.postProcessCallbacks[0] if taskChain != currentTaskChain: # Switch to the next task chain. print "switching to %s" % (taskChain) taskMgr.add(self.__nextCallback, 'phaseCallback-%s' % (self.phase), taskChain=taskChain, extraArgs=[callback, taskChain]) return # No more callbacks. Send the phaseComplete event. self.complete = True messenger.send('phaseComplete-%s' % (self.phase), taskChain='default')
def deselect(self, nodePath): """ Deselect the specified node path """ # Get this pointer id = nodePath.get_key() # See if it is in the selected dictionary dnp = self.getSelectedDict(id) if dnp: # It was selected: # Hide its bounding box dnp.dehighlight() # Remove it from the selected dictionary del self.selectedDict[id] if dnp in self.selectedList: # [gjeon] self.selectedList.remove(dnp) # And keep track of it in the deselected dictionary self.deselectedDict[id] = dnp # Send a message messenger.send('DIRECT_deselectedNodePath', [dnp]) # Update cluster servers if this is a cluster client if base.direct.clusterMode == 'client': cluster.deselectNodePath(dnp) return dnp
def set(self, name, isActive, inputSource=None): assert self.debugPrint("set(name=%s, isActive=%s, inputSource=%s)" % (name, isActive, inputSource)) # inputSource is a string that identifies where this input change # is coming from (like 'WASD', 'ArrowKeys', etc.) # Each unique inputSource is allowed to influence this input item # once: it's either 'active' or 'not active'. If at least one source # activates this input item, the input item is considered to be active if inputSource is None: inputSource = 'anonymous' if isActive: self._state.setdefault(name, set()) self._state[name].add(inputSource) else: if name in self._state: self._state[name].discard(inputSource) if len(self._state[name]) == 0: del self._state[name] # We change the name before sending it because this may # be the same name that messenger used to call InputState.set() # this avoids running in circles: messenger.send(self.getEventName(name), [self.isSet(name)])
def addDamage(self, sender, dmg): ''' Adds a specified amount to this entity Can be negative or positive If self.health < 0 call delete self ''' #get shooter for scoring purposes shooter = sender.owner # TODO make pretty death self.health -= dmg if self.damagedSound is not None: self.damagedSound.play() if self.health <= 0: #if shooter was player, add to score if shooter is base.player: if shooter.team is self.team: base.player.score -= 15 else: base.player.score += 15 #if player, end game if self is base.player: messenger.send('Leave-Game') self.kill()
def __setState(self, newState, *args): # Internal function to change unconditionally to the indicated # state. assert self._state assert self.notify.debug("%s to state %s." % (self._name, newState)) self.oldState = self._state self.newState = newState self._state = None try: if not self.__callFromToFunc(self.oldState, self.newState, *args): self.__callExitFunc(self.oldState) self.__callEnterFunc(self.newState, *args) except: # If we got an exception during the enter or exit methods, # go directly to state "InternalError" and raise up the # exception. This might leave things a little unclean # since we've partially transitioned, but what can you do? self._state = 'InternalError' del self.oldState del self.newState raise if self._broadcastStateChanges: messenger.send(self.getStateChangeEvent()) self._state = newState del self.oldState del self.newState if self.__requestQueue: request = self.__requestQueue.pop(0) assert self.notify.debug("%s continued queued request." % (self._name)) request()
def __donePackage(self, pp, success): """ Marks the indicated package as done, either successfully or otherwise. """ assert not pp.done if success: pc = PStatCollector(':App:PackageInstaller:install:%s' % (pp.package.packageName)) pc.start() pp.package.installPackage(self.appRunner) pc.stop() self.packageLock.acquire() try: pp.done = True pp.success = success if success: self.done.append(pp) else: self.failed.append(pp) finally: self.packageLock.release() eventName = 'PackageInstaller-%s-packageDone' % self.uniqueId messenger.send(eventName, [pp], taskChain = 'default')
def __donePackage(self, pp, success): """ Marks the indicated package as done, either successfully or otherwise. """ assert not pp.done if success: pc = PStatCollector(':App:PackageInstaller:install:%s' % (pp.package.packageName)) pc.start() pp.package.installPackage(self.appRunner) pc.stop() self.packageLock.acquire() try: pp.done = True pp.success = success if success: self.done.append(pp) else: self.failed.append(pp) finally: self.packageLock.release() eventName = 'PackageInstaller-%s-packageDone' % self.uniqueId messenger.send(eventName, [pp], taskChain = 'default')
def __enemy_move_to_player(self, enemy, task): player = self.get_actor(self.__roleMgr.get_role_model("PlayerRole")) enemyId = self.get_resId(enemy) enemyRole = self.__roleMgr.get_role_by_model(enemyId) playerPos = player.getPos() enemyPos = enemy.getPos() playerPos.setZ(0) enemyPos.setZ(0) v = playerPos - enemyPos if v.length() > enemyRole.get_attr_value("attackRange"): if enemyRole.get_attr_value("currState") == "attacking": messenger.send("enemy_attack-up") enemyRole.set_attr_value("currState", "closing") messenger.send("enemy_run") enemyRunSpeed = enemyRole.get_attr_value("runSpeed") * 1.5 dt = self.__clock.getDt() c = math.cos(enemy.getH() * math.pi / 180 - math.pi / 2) s = math.sin(enemy.getH() * math.pi / 180 - math.pi / 2) enemy.setX(enemy.getX() + c * dt * enemyRunSpeed) enemy.setY(enemy.getY() + s * dt * enemyRunSpeed) else: if enemyRole.get_attr_value("currState") == "closing": enemyRole.set_attr_value("currState", "attacking") messenger.send("enemy_run-up") messenger.send("enemy_attack") return task.cont
def test_hold_release_joystick_no_reward(self): """ test that if we are required to hold, but don't hold long enough, and release instead, no reward. """ # make goal longer self.cb.inc_js_goal() messenger.send('x_axis', [1]) self.assertFalse(self.cb.reward_on) messenger.send('x_axis', [0]) self.assertFalse(self.cb.reward_on) messenger.send('x_axis', [1]) self.assertFalse(self.cb.reward_on)
def run(self): # this is run on a separate thread so it can sit in a loop waiting to receive messages while True: try: topic = self.sub.socket.recv_string() data = self.sub.socket.recv_pyobj() # print(data) # this is a duplication at the moment, but provides an intermediate processing stage, may be useful later if 'load' in data: messenger.send('stimulus_loader', [data]) elif 'live' in data: messenger.send('stimulus_update', [data]) else: messenger.send('stimulus', [data]) except Exception as e: print(e)
def announceGenerate(self): DistributedObject.DistributedObject.announceGenerate(self) messenger.send('setBuilding-' + str(self.doId))
def processCommand(self,command): '''Process a StoryCommand @param command: The StoryCommand to deal with ''' def seval(strs): return self.scriptEval(strs) #Mark read if not runtime_data.read_text.has_key(command.fileLoc): runtime_data.read_text[command.fileLoc] = {} if not runtime_data.read_text[command.fileLoc].has_key(command.index): already_read = False self.stopSkipping() else: already_read = True runtime_data.read_text[command.fileLoc][command.index] = True if already_read: self.button_skip['state'] = DGG.NORMAL else: self.button_skip['state'] = DGG.DISABLED self.storyView.clearQuickItems() #clear out quick items name = '' continuous = False is_script = False is_selection = False spaceCutter = space_cutter hidingtext = False voiceFlag = False #it will be True if voice is stopped in this line of command #used for disable cross voice of different command lines #but enable one command line with multiple voices autoSaving = False #Mark if autosaving is needed at the end of this step autoSavingInfo = '' #read command line if command.command: commands = command.command.split(',') comm = '' for item in commands: comm = item.strip() if comm: messenger.send('sogalcommand',[comm]) #allow other tools to deal with it @UndefinedVariable #名字设置命令 if comm.startswith('name ') or comm.startswith('name='): nameCutter = re.compile(ur'name *=?',re.UNICODE) name = nameCutter.split(comm,1)[1].strip() #改变文本框格式命令 elif comm.startswith('textboxstyle '): if self.gameTextBox: self.gameTextBox.setTextBoxStyle(spaceCutter.split(comm, 1)[1]) self.gameTextBox.applyStyle() #文本框分段命令 elif comm == 'p': if self.gameTextBox: self.gameTextBox.paragraphSparator() elif comm == 'c': continuous = True elif comm.startswith('wait '): temp = spaceCutter.split(comm,1) if len(temp) > 1: self.sceneWait(seval(temp[1])) #文本框属性设置命令 elif comm.startswith('textbox '): temp = spaceCutter.split(comm,2) if temp[1] == 'apply': self.gameTextBox.applyTextBoxProperties() elif len(temp)>=3: self.gameTextBox.setTextBoxProperty(temp[1],seval(temp[2])) else: safeprint('Not enough: ' + comm) #背景设置命令 elif comm.startswith('bg '): temp = spaceCutter.split(comm,2) if len(temp) >= 3: fadein = seval(temp[2]) else: fadein = 0 self.storyView.changeBackground(temp[1],fadein) #图片显示命令 elif comm.startswith('p '): temp = spaceCutter.split(comm,6) if len(temp) >= 7: fadein = seval(temp[6]) else: fadein = 0 if len(temp) >= 6: scale = seval(temp[5]) else: scale = 1 if len(temp) >= 5: location = (seval(temp[3]),0,seval(temp[4])) else: if self.storyView.itemEntries.has_key(temp[1]): location = self.storyView.itemEntries[temp[1]].pos else: location = (0,0,0) svie = StoryViewItemEntry(temp[1],temp[2],SVIC.FG,pos = location,scale = (scale,scale,scale),color = (1,1,1,1),fadein = fadein) self.storyView.newItem(svie) elif comm.startswith('del '): temp = spaceCutter.split(comm,2) if len(temp)>=3: self.storyView.deleteItem(temp[1], seval(temp[2])) else: self.storyView.deleteItem(temp[1]) elif comm.startswith('ploc '): temp = spaceCutter.split(comm,5) if len(temp) >= 5: location = (seval(temp[2]),seval(temp[3]),seval(temp[4])) else: location = (seval(temp[2]),0,seval(temp[3])) if len(temp) >= 6: fadein = seval(temp[5]) else: fadein = 0 self.storyView.changePosColorScale(temp[1], pos = location,time = fadein) elif comm.startswith('pcolor '): temp = spaceCutter.split(comm,6) color = (seval(temp[2]),seval(temp[3]),seval(temp[4]),seval(temp[5])) if len(temp) >= 7: fadein = seval(temp[6]) else: fadein = 0 self.storyView.changePosColorScale(temp[1], color = color, time = fadein) elif comm.startswith('pscale '): temp = spaceCutter.split(comm,5) if len(temp) >= 5: scale = (seval(temp[2]),seval(temp[3]),seval(temp[4])) else: scale = (seval(temp[2]),seval(temp[2]),seval(temp[2])) if len(temp) == 6: fadein = seval(temp[5]) elif len(temp) == 4: fadein = seval(temp[3]) else: fadein = 0 self.storyView.changePosColorScale(temp[1], scale = scale, time = fadein) elif comm.startswith('o3d '): temp = spaceCutter.split(comm) svie = StoryViewItemEntry(temp[1],temp[2],SVIC.O3D,pos = (seval(temp[3]),seval(temp[4]),seval(temp[5])) ,scale = (seval(temp[10]),seval(temp[11]),seval(temp[12])),color = (seval(temp[6]),seval(temp[7]),seval(temp[8]),seval(temp[9]))) self.storyView.newItem(svie) elif comm.startswith('o2d '): temp = spaceCutter.split(comm) svie = StoryViewItemEntry(temp[1],temp[2],SVIC.O2D,pos = (seval(temp[3]),seval(temp[4]),seval(temp[5])) ,scale = (seval(temp[10]),seval(temp[11]),seval(temp[12])),color = (seval(temp[6]),seval(temp[7]),seval(temp[8]),seval(temp[9]))) self.storyView.newItem(svie) elif comm.startswith('pa '): temp = spaceCutter.split(comm) if len(temp) >= 8: fadein = seval(temp[7]) else: fadein = 0 svie = StoryViewItemEntry(temp[1],temp[2],SVIC.AFG,pos = (seval(temp[3]),0,seval(temp[4])) ,scale = (seval(temp[5]),1,seval(temp[6])),fadein = fadein) self.storyView.newItem(svie) elif comm == 'clear': hidingtext = True self.storyView.clear() elif comm.startswith('clear '): hidingtext = True temp = spaceCutter.split(comm,2) if len(temp)>=3: self.storyView.clear(seval(temp[1]),temp[2]) elif len(temp)==2: self.storyView.clear(seval(temp[1])) else: self.storyView.clear() elif comm.startswith('delbg '): temp = spaceCutter.split(comm,1) if len('temp')>=2: self.storyView.deleteItem('__bg__', seval(temp[1])) else: self.storyView.deleteItem('__bg__') elif comm.startswith('qp '): temp = spaceCutter.split(comm,3) svie = StoryViewItemEntry('quickitem',temp[1],SVIC.FG, pos = (seval(temp[2]),0,seval(temp[3])), quickitem = True ) self.storyView.newItem(svie) elif comm.startswith('v '): if not voiceFlag: self.audioPlayer.stopVoice() voiceFlag = True temp = spaceCutter.split(comm , 2) if len(temp)>=3: volume = seval(temp[2]) else: volume = 1 self.audioPlayer.playVoice(temp[1],volume) elif comm.startswith('se '): temp = spaceCutter.split(comm , 2) if len(temp)>=3: volume = seval(temp[2]) else: volume = 1 self.audioPlayer.playSound(temp[1],volume) elif comm == 'vstop': self.audioPlayer.stopVoice() voiceFlag = True elif comm == 'sestop': self.audioPlayer.stopSound() elif comm.startswith('bgm '): temp = spaceCutter.split(comm , 4) if len(temp)>=3: fadein = seval(temp[2]) else: fadein = 0 if len(temp)>=4: volume = seval(temp[3]) else: volume = 1 if len(temp)>=5: loop = bool(seval(temp[4])) else: loop = True self.audioPlayer.playBGM(temp[1], fadein=fadein, volume=volume, loop=loop) elif comm.startswith('env '): temp = spaceCutter.split(comm , 4) if len(temp)>=3: fadein = seval(temp[2]) else: fadein = 0 if len(temp)>=4: volume = seval(temp[3]) else: volume = 1 if len(temp)>=5: loop = bool(seval(temp[4])) else: loop = True self.audioPlayer.playENV(temp[1], fadein=fadein, volume=volume, loop=loop) elif comm.startswith('bgmstop ') or comm == 'bgmstop': temp = spaceCutter.split(comm , 1) if len(temp)>=2: fadeout = seval(temp[1]) else: fadeout = 0 self.audioPlayer.stopBGM(fadeout) elif comm.startswith('envstop ') or comm == 'envstop': temp = spaceCutter.split(comm , 1) if len(temp)>=2: fadeout = seval(temp[1]) else: fadeout = 0 self.audioPlayer.stopENV(fadeout) elif comm.startswith('audiostop ') or comm == 'audiostop': temp = spaceCutter.split(comm , 1) if len(temp)>=2: fadeout = seval(temp[1]) else: fadeout = 0 self.audioPlayer.stopAll(fadeout) elif comm == 'script': is_script = True elif comm.startswith('script '): temp = spaceCutter.split(comm , 1) self.runScriptFile(temp[1]) elif comm == 'choice' or comm.startswith('choice '): ''' Selection ''' is_selection = True temp = spaceCutter.split(comm, 1) if len(temp) > 1: striped = temp[1].strip() if striped: self.pushText(text = striped, speaker = None, needInput = False, read = already_read) elif comm.startswith('jump '): temp = spaceCutter.split(comm , 1) self.beginScene(temp[1].strip()) elif comm.startswith('expand '): temp = spaceCutter.split(comm , 1) self.expandScene(temp[1].strip()) elif comm.startswith('goto '): temp = spaceCutter.split(comm , 1) self.goto(temp[1].strip()) elif comm.startswith('theme '): temp = spaceCutter.split(comm , 1) self.reloadTheme(temp[1].strip()) elif comm == 'autosave' or comm.startswith('autosave '): if self.step > 0: autoSaving = True temp = spaceCutter.split(comm , 1) if len(temp) > 1: autoSavingInfo = temp[1] else: if comm: safeprint('extra command: ' + comm) if command.text: if is_script: self.runScript(command.text) elif is_selection: ''' If encountered a selection ''' choiceList = [] enablesList = [] textlines = command.text.splitlines() for tl in textlines: if tl.startswith('--'): #--means disabled text = tl[2:] enablesList.append(False) else: text = tl enablesList.append(True) choiceList.append(text) self.showSelection(choiceList = choiceList, enablesList = enablesList) else: self.pushText(text = command.text, speaker = name, continuous = continuous, read = already_read) else: if hidingtext: self.gameTextBox.hide() #better to hide the textbox when 'vclear' if self.gameTextBox.newText: runtime_data.RuntimeData.latest_text = self.gameTextBox.newText if runtime_data.RuntimeData.latest_text: self._currentMessage = runtime_data.RuntimeData.latest_text #Autosave if autoSaving: if autoSavingInfo: self.autoSave(autoSavingInfo) else: self.autoSave()
def autoSave(self,info = ''): if not info: info = self._currentMessage messenger.send('auto_save',[self._currentDump,info])
def enterGame_setup(self): self.screen.open_game_setup() self.acceptOnce(self.screen.frame.sgn_start, self.demand, extraArgs=['Gaming']) if ConfigVariableBool('dev-mode').getValue(): messenger.send(self.screen.frame.sgn_start)
def __confirmedQuickLoad(self): messenger.send('quick_load') # @UndefinedVariable
def setP3DFilename(self, p3dFilename, tokens, argv, instanceId, interactiveConsole, p3dOffset = 0): """ Called by the browser to specify the p3d file that contains the application itself, along with the web tokens and/or command-line arguments. Once this method has been called, the application is effectively started. """ # One day we will have support for multiple instances within a # Python session. Against that day, we save the instance ID # for this instance. self.instanceId = instanceId self.tokens = tokens self.argv = argv # We build up a token dictionary with care, so that if a given # token appears twice in the token list, we record only the # first value, not the second or later. This is consistent # with the internal behavior of the core API. self.tokenDict = {} for token, keyword in tokens: self.tokenDict.setdefault(token, keyword) # Also store the arguments on sys, for applications that # aren't instance-ready. sys.argv = argv # That means we now know the altHost in effect. self.altHost = self.tokenDict.get('alt_host', None) # Tell the browser that Python is up and running, and ready to # respond to queries. self.notifyRequest('onpythonload') # Now go load the applet. fname = Filename.fromOsSpecific(p3dFilename) vfs = VirtualFileSystem.getGlobalPtr() if not vfs.exists(fname): raise ArgumentError, "No such file: %s" % (p3dFilename) fname.makeAbsolute() mf = Multifile() if p3dOffset == 0: if not mf.openRead(fname): raise ArgumentError, "Not a Panda3D application: %s" % (p3dFilename) else: if not mf.openRead(fname, p3dOffset): raise ArgumentError, "Not a Panda3D application: %s at offset: %s" % (p3dFilename, p3dOffset) # Now load the p3dInfo file. self.p3dInfo = None self.p3dPackage = None self.p3dConfig = None self.allowPythonDev = False i = mf.findSubfile('p3d_info.xml') if i >= 0 and hasattr(PandaModules, 'readXmlStream'): stream = mf.openReadSubfile(i) self.p3dInfo = PandaModules.readXmlStream(stream) mf.closeReadSubfile(stream) if self.p3dInfo: self.p3dPackage = self.p3dInfo.FirstChildElement('package') if self.p3dPackage: self.p3dConfig = self.p3dPackage.FirstChildElement('config') xhost = self.p3dPackage.FirstChildElement('host') while xhost: self.__readHostXml(xhost) xhost = xhost.NextSiblingElement('host') if self.p3dConfig: allowPythonDev = self.p3dConfig.Attribute('allow_python_dev') if allowPythonDev: self.allowPythonDev = int(allowPythonDev) guiApp = self.p3dConfig.Attribute('gui_app') if guiApp: self.guiApp = int(guiApp) trueFileIO = self.p3dConfig.Attribute('true_file_io') if trueFileIO: self.trueFileIO = int(trueFileIO) # The interactiveConsole flag can only be set true if the # application has allow_python_dev set. if not self.allowPythonDev and interactiveConsole: raise StandardError, "Impossible, interactive_console set without allow_python_dev." self.interactiveConsole = interactiveConsole if self.allowPythonDev: # Set the fps text to remind the user that # allow_python_dev is enabled. ConfigVariableString('frame-rate-meter-text-pattern').setValue('allow_python_dev %0.1f fps') if self.guiApp: initAppForGui() self.initPackedAppEnvironment() # Mount the Multifile under self.multifileRoot. vfs.mount(mf, self.multifileRoot, vfs.MFReadOnly) VFSImporter.reloadSharedPackages() self.loadMultifilePrcFiles(mf, self.multifileRoot) self.gotP3DFilename = True # Send this call to the main thread; don't call it directly. messenger.send('AppRunner_startIfReady', taskChain = 'default')
def __confirmedLastChoice(self): if runtime_data.RuntimeData.last_choice: messenger.send('load_memory',[runtime_data.RuntimeData.last_choice]) # @UndefinedVariable