class TestApplication: def __init__(self): self.setupPhysics() self.clock_ = ClockObject() def sim(self): while True: try: time.sleep(LOOP_DELAY) self.clock_.tick() self.physics_world_.doPhysics(self.clock_.getDt(), 5, 1.0/180.0) # printing location of first box print "Box 0: %s"%(str(self.boxes_[0].getPos())) except KeyboardInterrupt: print "Simulation finished" sys.exit() def setupPhysics(self): # setting up physics world and parent node path self.physics_world_ = BulletWorld() self.world_node_ = NodePath() self.physics_world_.setGravity(Vec3(0, 0, -9.81)) # setting up ground self.ground_ = self.world_node_.attachNewNode(BulletRigidBodyNode('Ground')) self.ground_.node().addShape(BulletPlaneShape(Vec3(0, 0, 1), 0)) self.ground_.setPos(0,0,0) self.ground_.setCollideMask(BitMask32.allOn()) self.physics_world_.attachRigidBody(self.ground_.node()) self.boxes_ = [] num_boxes = 20 side_length = 0.2 size = Vec3(side_length,side_length,side_length) start_pos = Vec3(-num_boxes*side_length,0,10) for i in range(0,20): self.addBox("name %i"%(i),size,start_pos + Vec3(i*2*side_length,0,0)) def addBox(self,name,size,pos): # Box (dynamic) box = self.world_node_.attachNewNode(BulletRigidBodyNode(name)) box.node().setMass(1.0) box.node().addShape(BulletBoxShape(size)) box.setPos(pos) box.setCollideMask(BitMask32.allOn()) self.physics_world_.attachRigidBody(box.node()) self.boxes_.append(box)
class Game(ShowBase): def __init__(self): ShowBase.__init__(self) self.setBackgroundColor(0.2,0.2,0.2) self.accept("escape", self.taskMgr.stop) #self.accept("mouse1", self.onClick) #self.accept("mouse2", self.onClick2) self.globalClock = ClockObject() self.addLight() self.liner = LineDrawer(self) self.taskMgr.add(self.update, "update") def update(self, task): self.globalClock.tick() t = self.globalClock.getFrameTime() #print t dt = self.globalClock.getDt() return task.cont def addLight(self): self.render.clearLight() self.lightCenter = self.render.attachNewNode(PandaNode("center")) #self.lightCenter.setCompass() # ambient light self.ambientLight = AmbientLight('ambientLight') self.ambientLight.setColor(Vec4(0.5,0.5,0.5, 1)) self.alight = self.lightCenter.attachNewNode(self.ambientLight) self.render.setLight(self.alight) # point light self.pointlight = PointLight("pLight") self.light = self.lightCenter.attachNewNode(self.pointlight) self.pointlight.setColor(Vec4(0.8,0.8,0.8,1)) self.light.setPos(0,0,2) self.render.setLight(self.light) # directional light self.dirlight = DirectionalLight("dLight") self.dlight = self.lightCenter.attachNewNode(self.dirlight) self.dirlight.setColor(Vec4(0.8,0.8,0.8,1)) self.dirlight.setShadowCaster(True) self.dlight.setPos(0,0,5) self.dlight.lookAt(5,10,0) self.render.setLight(self.dlight) self.render.setShaderAuto()
class Game(ShowBase): def __init__(self): ShowBase.__init__(self) self.setBackgroundColor(0.2, 0.2, 0.2) self.accept("escape", self.taskMgr.stop) #self.accept("mouse1", self.onClick) #self.accept("mouse2", self.onClick2) self.globalClock = ClockObject() self.addLight() self.liner = LineDrawer(self) self.taskMgr.add(self.update, "update") def update(self, task): self.globalClock.tick() t = self.globalClock.getFrameTime() #print t dt = self.globalClock.getDt() return task.cont def addLight(self): self.render.clearLight() self.lightCenter = self.render.attachNewNode(PandaNode("center")) #self.lightCenter.setCompass() # ambient light self.ambientLight = AmbientLight('ambientLight') self.ambientLight.setColor(Vec4(0.5, 0.5, 0.5, 1)) self.alight = self.lightCenter.attachNewNode(self.ambientLight) self.render.setLight(self.alight) # point light self.pointlight = PointLight("pLight") self.light = self.lightCenter.attachNewNode(self.pointlight) self.pointlight.setColor(Vec4(0.8, 0.8, 0.8, 1)) self.light.setPos(0, 0, 2) self.render.setLight(self.light) # directional light self.dirlight = DirectionalLight("dLight") self.dlight = self.lightCenter.attachNewNode(self.dirlight) self.dirlight.setColor(Vec4(0.8, 0.8, 0.8, 1)) self.dirlight.setShadowCaster(True) self.dlight.setPos(0, 0, 5) self.dlight.lookAt(5, 10, 0) self.render.setLight(self.dlight) self.render.setShaderAuto()
def __init__(self): ShowBase.__init__(self) self.setBackgroundColor(0.2, 0.2, 0.2) self.accept("escape", self.taskMgr.stop) #self.accept("mouse1", self.onClick) #self.accept("mouse2", self.onClick2) self.globalClock = ClockObject() self.addLight() self.liner = LineDrawer(self) self.taskMgr.add(self.update, "update")
def _doCallback(self, callback, taskName, task): assert self.notify.debugCall() self.__taskNames.remove(taskName) self._taskStartTime = ClockObject.getGlobalClock().getRealTime() callback() self._taskStartTime = None return Task.done
def __init__(self, scene, size=(800, 600), zNear=0.1, zFar=1000.0, fov=40.0, shadowing=False, interactive=True, showPosition=False, cameraMask=None): super(Viewer, self).__init__() self.__dict__.update(scene=scene, size=size, fov=fov, shadowing=shadowing, zNear=zNear, zFar=zFar, interactive=interactive, showPosition=showPosition, cameraMask=cameraMask) if cameraMask is not None: self.cam.node().setCameraMask(self.cameraMask) lens = self.cam.node().getLens() lens.setFov(self.fov) lens.setNear(self.zNear) lens.setFar(self.zFar) # Change window size wp = WindowProperties() wp.setSize(size[0], size[1]) wp.setTitle("Viewer") wp.setCursorHidden(True) self.win.requestProperties(wp) self.disableMouse() self.time = 0 self.centX = self.win.getProperties().getXSize() / 2 self.centY = self.win.getProperties().getYSize() / 2 # key controls self.forward = False self.backward = False self.fast = 1.0 self.left = False self.right = False self.up = False self.down = False self.up = False self.down = False # sensitivity settings self.movSens = 2 self.movSensFast = self.movSens * 5 self.sensX = self.sensY = 0.2 self.cam.setP(self.cam, 0) self.cam.setR(0) # reset mouse to start position: self.win.movePointer(0, int(self.centX), int(self.centY)) # Reparent the scene to render. self.scene.scene.reparentTo(self.render) # Task self.globalClock = ClockObject.getGlobalClock() self.taskMgr.add(self.update, 'viewer-update') self._addDefaultLighting() self._setupEvents()
def __init__(self): """initialise the engine""" ShowBase.__init__(self) base.camLens.setNearFar(1.0, 10000) base.camLens.setFov(75) a = 33 base.camera.setPos(0,-a,a+3)#80) # collision base.cTrav = CollisionTraverser("base collision traverser") base.cHandler = CollisionHandlerEvent() base.cPusher = CollisionHandlerPusher() base.cQueue = CollisionHandlerQueue() base.globalClock=ClockObject.getGlobalClock() base.cHandler.addInPattern('%fn-into-%in') base.cHandler.addOutPattern('%fn-out-%in') base.cHandler.addAgainPattern('%fn-again-%in') # ai init base.AIworld = AIWorld(render) # 3d manager base.audio3d = Audio3DManager(base.sfxManagerList[0], camera) self.monsters = [] self.accept('c',self._create) base.enableParticles()
def __init__(self): ShowBase.__init__(self) self.clock_ = ClockObject() self.setupInput() taskMgr.add(self.update,"update")
def _scheduleNextProfile(self): self._profileCounter += 1 self._timeElapsed = self._profileCounter * self._period #assert isInteger(self._timeElapsed) time = self._startTime + self._timeElapsed # vary the actual delay between profiles by a random amount to prevent interaction # with periodic events jitter = self._jitter if jitter is None: jitter = normalDistrib(-self._jitterMagnitude, self._jitterMagnitude) time += jitter else: time -= jitter jitter = None self._jitter = jitter sessionId = serialNum() session = taskMgr.getProfileSession('FrameProfile-%s' % sessionId) self._id2session[sessionId] = session taskMgr.profileFrames(num=1, session=session, callback=Functor(self._analyzeResults, sessionId)) # schedule the next profile delay = max(time - ClockObject.getGlobalClock().getFrameTime(), 0.) self._task = taskMgr.doMethodLater(delay, self._scheduleNextProfileDoLater, 'FrameProfiler-%s' % serialNum())
def __init__(self, houseId, suncgDatasetRoot=None, size=(256, 256), debug=False, depth=False, realtime=False, dt=0.1, cameraTransform=None): self.__dict__.update(houseId=houseId, suncgDatasetRoot=suncgDatasetRoot, size=size, debug=debug, depth=depth, realtime=realtime, dt=dt, cameraTransform=cameraTransform) self.scene = SunCgSceneLoader.loadHouseFromJson(houseId, suncgDatasetRoot) agentRadius = 0.1 agentHeight = 1.6 if self.cameraTransform is None: self.cameraTransform = TransformState.makePos(LVector3f(0.0, 0.0, agentHeight/2.0 - agentRadius)) self.renderWorld = Panda3dRenderer(self.scene, size, shadowing=False, depth=depth, cameraTransform=self.cameraTransform) self.physicWorld = Panda3dBulletPhysics(self.scene, suncgDatasetRoot, debug=debug, objectMode='box', agentRadius=agentRadius, agentHeight=agentHeight, agentMass=60.0, agentMode='capsule') self.clock = ClockObject.getGlobalClock() self.worlds = { "physics": self.physicWorld, "render": self.renderWorld, } self.agent = self.scene.agents[0] self.agentRbNp = self.agent.find('**/+BulletRigidBodyNode') self.labeledNavMap = None self.occupancyMapCoord = None
def updateDialTask(self, state): # Update value currT = ClockObject.getGlobalClock().getFrameTime() dt = currT - state.lastTime self.set(self.value + self.knobSF * dt) state.lastTime = currT return Task.cont
def updatePlugIn(steerPlugIn, task): """custom update task for plug-ins""" global steerVehicles, vehicleAnimCtls # call update for plug-in dt = ClockObject.get_global_clock().get_dt() steerPlugIn.update(dt) # handle vehicle's animation for i in range(len(vehicleAnimCtls)): # get current velocity size currentVelSize = steerVehicles[i].get_speed() if currentVelSize > 0.0: if currentVelSize < 4.0: animOnIdx = 0 else: animOnIdx = 1 animOffIdx = (animOnIdx + 1) % 2 # Off anim (0:walk, 1:run) if vehicleAnimCtls[i][animOffIdx].is_playing(): vehicleAnimCtls[i][animOffIdx].stop() # On amin (0:walk, 1:run) vehicleAnimCtls[i][animOnIdx].set_play_rate( currentVelSize / animRateFactor[animOnIdx]) if not vehicleAnimCtls[i][animOnIdx].is_playing(): vehicleAnimCtls[i][animOnIdx].loop(True) else: # stop any animation vehicleAnimCtls[i][0].stop() vehicleAnimCtls[i][1].stop() # return task.cont
def updateStatusReadout(self, status, color=None): if status: # add new status line, first check to see if it already exists alreadyExists = False for currLine in self.statusLines: if status == currLine[1]: alreadyExists = True break if not alreadyExists: time = ClockObject.getGlobalClock().getRealTime() + 15 self.statusLines.append([time, status, color]) # update display of new status lines self.statusReadout.reparentTo(aspect2d) statusText = "" lastColor = None for currLine in self.statusLines: statusText += currLine[1] + '\n' lastColor = currLine[2] self.statusReadout.setText(statusText) if lastColor: self.statusReadout.textNode.setCardColor(lastColor[0], lastColor[1], lastColor[2], lastColor[3]) self.statusReadout.textNode.setCardAsMargin(0.1, 0.1, 0.1, 0.1) else: self.statusReadout.textNode.setCardColor(1, 1, 1, 1) self.statusReadout.textNode.setCardAsMargin(0.1, 0.1, 0.1, 0.1)
def __init__(self): self.config = getConfigShowbase() vfs = VirtualFileSystem.getGlobalPtr() self.eventMgr = eventMgr self.messenger = messenger self.bboard = bulletinBoard self.taskMgr = taskMgr self.AISleep = self.config.GetFloat('ai-sleep', 0.04) Task.TaskManager.taskTimerVerbose = self.config.GetBool( 'task-timer-verbose', 0) Task.TaskManager.extendedExceptions = self.config.GetBool( 'extended-exceptions', 0) self.sfxManagerList = None self.musicManager = None self.jobMgr = jobMgr self.hidden = NodePath('hidden') self.graphicsEngine = GraphicsEngine.getGlobalPtr() globalClock = ClockObject.getGlobalClock() self.trueClock = TrueClock.getGlobalPtr() globalClock.setRealTime(self.trueClock.getShortTime()) globalClock.setAverageFrameRateInterval(30.0) globalClock.tick() taskMgr.globalClock = globalClock __builtins__['ostream'] = Notify.out() __builtins__['globalClock'] = globalClock __builtins__['vfs'] = vfs __builtins__['hidden'] = self.hidden self.restart()
def __init__(self): ShowBase.__init__(self) self.Clock = ClockObject.getGlobalClock() self._alive = True self._connected = False self._display_region = self.cam.getNode(0).getDisplayRegion(0) # Main menu and environment. self.LOBBY = Lobby(self) # <- self.ENV = Environment(self) # <- self.PRE_VIEW = Pre_View(self) # <- self.DISPLAY = self.LOBBY self.SYS = None self.SIM = Simulator(_sim.MAX_LOCAL_BODIES) self.servers = [] self.sys_recipes = self.__refresh_Sys_Recipes() # Player and main objects. ## self.PLAYER = Player() # <- self.UEH = Default_UEH() # <- self.setBackgroundColor(0,0,0) self.disableMouse() # Network. '''self.host = socket.gethostbyname(socket.gethostname()) self.tcp_addr = (self.host, CLIENT_TCP_PORT) self.udp_addr = (self.host, CLIENT_UDP_PORT) ## self.tcp_req_addr = (self.host, CLIENT_REQUEST_PORT) self.proxy_tcp_addr = None ## self.client_proxy_tcp_addr''' # Main loop. taskMgr.add(self._main_loop_, "main_loop", appendTask=True, sort=0) # <- taskMgr.doMethodLater(1/_net.BROADCAST_HZ, self._state_, "state_loop")
def _setEnabled(self, enabled): if enabled: self.notify.info('frame profiler started') self._startTime = ClockObject.getGlobalClock().getFrameTime() self._profileCounter = 0 self._jitter = None self._period2aggregateProfile = {} self._id2session = {} self._id2task = {} # don't profile process startup self._task = taskMgr.doMethodLater( self._period, self._scheduleNextProfileDoLater, 'FrameProfilerStart-%s' % serialNum()) else: self._task.remove() del self._task for session in self._period2aggregateProfile.values(): session.release() del self._period2aggregateProfile for task in self._id2task.values(): task.remove() del self._id2task for session in self._id2session.values(): session.release() del self._id2session self.notify.info('frame profiler stopped')
class TimeIt: def __init__(self, msg="", rnd=3): self._msg = msg self._rnd = rnd self._clock = ClockObject() def __enter__(self): self._start_dt = self._clock.getRealTime() return self def __exit__(self, *e_info): self._dur = self._clock.getRealTime()-self._start_dt if self._msg: print("{}: {}".format(self._msg, round(self._dur, self._rnd))) for attr in self.__dict__: if attr.startswith("_"): continue print(" {}: {}".format(attr, self.__dict__[attr]))
def updateNavMesh(navMesh, task): """custom path finding update task to correct panda's Z to stay on floor""" global crowdAgent # call update for navMesh dt = ClockObject.get_global_clock().get_dt() navMesh.update(dt) # handle crowd agents' animation for i in range(NUMAGENTS): # get current velocity size currentVelSize = crowdAgent[i].get_actual_velocity().length() if currentVelSize > 0.0: # walk agentAnimCtls[i][0].set_play_rate(currentVelSize / rateFactor) if not agentAnimCtls[i][0].is_playing(): agentAnimCtls[i][0].loop(True) else: # check if crowd agent is on off mesh connection if crowdAgent[i].get_traversing_state( ) == RNCrowdAgent.STATE_OFFMESH: # off-balance if not agentAnimCtls[i][1].is_playing(): agentAnimCtls[i][1].loop(True) else: # stop any animation agentAnimCtls[i][0].stop() agentAnimCtls[i][1].stop() # return task.cont
def postInit(self): # # initialize game content # # camera base.camLens.setNearFar(1.0, 10000) base.camLens.setFov(75) a = 33 base.camera.setPos(0, -a, a + 3) #80) # collision base.cTrav = CollisionTraverser("base collision traverser") base.cHandler = CollisionHandlerEvent() base.cPusher = CollisionHandlerPusher() base.cQueue = CollisionHandlerQueue() base.globalClock = ClockObject.getGlobalClock() base.cHandler.addInPattern('%fn-into-%in') base.cHandler.addOutPattern('%fn-out-%in') base.cHandler.addAgainPattern('%fn-again-%in') # ai init base.AIworld = AIWorld(render) # 3d manager base.audio3d = Audio3DManager(base.sfxManagerList[0], camera) # manager self.archiveManager = ArchiveManager() self.mapManager = MapManager() self.initHeroInfo = None # Lock self.lock = threading.Lock() self.gameThread = None self.filters = CommonFilters(base.win, base.cam) # UI self.menu = Menu() self.option = Option() self.archive = Archive() self.death = Death() # self.oobe() #self.Archive_status = 0 # self.menuMusic = loader.loadMusic("assets/audio/menuMusic.ogg") # self.menuMusic.setLoop(True) # self.fightMusic = loader.loadMusic("assets/audio/fightMusic.ogg") # self.fightMusic.setLoop(True) # base.audio3d = Audio3DManager(base.sfxManagerList[0], camera) self.titleVideo, self.titleCard = loadVideo('title.mp4') self.isInited = False self.isSkip = False self.isRenew = False # # Event handling # self.accept("escape", self.__escape) # # Start with the menu # self.request("Menu")
def __init__(self): self.loadDefaultConfig() self.loadLocalConfig() if ConfigVariableBool("want-pstats", False): PStatClient.connect() # Set up some global objects self.globalClock = ClockObject.getGlobalClock() # We will manually manage the clock self.globalClock.setMode(ClockObject.MSlave) builtins.globalClock = self.globalClock self.vfs = VirtualFileSystem.getGlobalPtr() # For tasks that run every application frame self.taskMgr = TaskManagerGlobal.taskMgr builtins.taskMgr = self.taskMgr # For tasks that run every simulation tick self.simTaskMgr = Task.TaskManager() self.simTaskMgr.mgr = AsyncTaskManager("sim") builtins.simTaskmgr = self.simTaskMgr self.eventMgr = EventManagerGlobal.eventMgr builtins.eventMgr = self.eventMgr self.messenger = MessengerGlobal.messenger builtins.messenger = self.messenger self.loader = Loader(self) builtins.loader = self.loader builtins.base = self # What is the current frame number? self.frameCount = 0 # Time at beginning of current frame self.frameTime = self.globalClock.getRealTime() # How long did the last frame take. self.deltaTime = 0 # # Variables pertaining to simulation ticks. # self.prevRemainder = 0 self.remainder = 0 # What is the current overall simulation tick? self.tickCount = 0 # How many ticks are we going to run this frame? self.totalTicksThisFrame = 0 # How many ticks have we run so far this frame? self.currentTicksThisFrame = 0 # What tick are we currently on this frame? self.currentFrameTick = 0 # How many simulations ticks are we running per-second? self.ticksPerSec = 60 self.intervalPerTick = 1.0 / self.ticksPerSec
def __init__(self, scene, size=(800, 600), zNear=0.1, zFar=1000.0, fov=40.0, shadowing=False, showPosition=False, cameraTransform=None, cameraMask=None): ShowBase.__init__(self) self.__dict__.update(scene=scene, size=size, fov=fov, zNear=zNear, zFar=zFar, shadowing=shadowing, showPosition=showPosition, cameraTransform=cameraTransform, cameraMask=cameraMask) # Find agent and reparent camera to it self.agent = self.scene.scene.find('**/agents/agent*/+BulletRigidBodyNode') self.camera.reparentTo(self.agent) if self.cameraTransform is not None: self.camera.setTransform(cameraTransform) if cameraMask is not None: self.cam.node().setCameraMask(self.cameraMask) lens = self.cam.node().getLens() lens.setFov(self.fov) lens.setNear(self.zNear) lens.setFar(self.zFar) # Change window size wp = WindowProperties() wp.setSize(size[0], size[1]) wp.setTitle("Controller") wp.setCursorHidden(True) self.win.requestProperties(wp) self.disableMouse() self.time = 0 self.centX = wp.getXSize() / 2 self.centY = wp.getYSize() / 2 self.win.movePointer(0, int(self.centX), int(self.centY)) # key controls self.forward = False self.backward = False self.fast = 2.0 self.left = False self.right = False # sensitivity settings self.movSens = 2 self.movSensFast = self.movSens * 5 self.sensX = self.sensY = 0.2 # Reparent the scene to render. self.scene.scene.reparentTo(self.render) self.render.setAntialias(AntialiasAttrib.MAuto) # Task self.globalClock = ClockObject.getGlobalClock() self.taskMgr.add(self.update, 'controller-update') self._addDefaultLighting() self._setupEvents()
class TimeIt: def __init__(self, msg=""): self.__msg = msg self.__clock = ClockObject() def __enter__(self): self.__start_dt = self.__clock.getRealTime() return self def __exit__(self, *e_info): self.__dur = round(self.__clock.getRealTime()-self.__start_dt, 3) if self.__msg: print() print("{}: {}".format(self.__msg, self.__dur, 3)) for attr in self.__dict__: if attr.startswith("_TimeIt__"): continue print(" {}: {}".format(attr, round(self.__dict__[attr], 3))) self.total_time = self.__dur
def step(self, task): distance = ClockObject.getGlobalClock().getDt() * self.speed rotMat = Mat3.rotateMatNormaxis(self.avatar.getH(), Vec3.up()) step = Vec3(rotMat.xform(Vec3.forward() * distance)) self.avatar.setFluidPos(Point3(self.avatar.getPos() + step)) return Task.cont
def startCallback(self, t, callback): if self.started: self.stop() self.callback = callback self.finalT = t self.startT = ClockObject.getGlobalClock().getFrameTime() self.currT = 0.0 taskMgr.add(self.__timerTask, self.name + '-run') self.started = 1
def taskTimeLeft(self): """returns True if there is time left for the current task callback to run without going over the allotted timeslice""" if self._taskStartTime is None: # we must not be in a task callback, we must be running in non-threaded # mode return True return (ClockObject.getGlobalClock().getRealTime() - self._taskStartTime) < self.__timeslice
def mouseDown(self, event): """ Begin mouse interaction """ # Exectute user redefinable callback function (if any) self['relief'] = SUNKEN if self['preCallback']: self['preCallback'](*self['callbackData']) self.velocitySF = 0.0 self.updateTask = taskMgr.add(self.updateFloaterTask, 'updateFloater') self.updateTask.lastTime = ClockObject.getGlobalClock().getFrameTime()
def takeHit(self, entry): ENEMY_STOPPED = 2 index = int(entry.getFromNode().getTag('enemy')) if self.world.enemies[index].phase != ENEMY_STOPPED and ClockObject.getGlobalClock().getLongTime() - self.lastCollision > INVULN_TIME: self.lastCollision = ClockObject.getGlobalClock().getLongTime() self.health = self.health - 1 self.screamSound.play() self.world.livesSprites[self.health].setImage('images/healthicon_depleted.png') self.world.livesSprites[self.health].setTransparency(TransparencyAttrib.MAlpha) # print "Health: " + str(self.health) self.blinkStart = -1 taskMgr.add(self.blink, "blinking") #If health = 0, we need to do something if self.health <= 0: # print "YOU ARE DEAD!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" self.dead = True
def updateFloaterTask(self, state): """ Update floaterWidget value based on current scaleFactor Adjust for time to compensate for fluctuating frame rates """ currT = ClockObject.getGlobalClock().getFrameTime() dt = currT - state.lastTime self.set(self.value + self.velocitySF * dt) state.lastTime = currT return Task.cont
def play(self, node, time=0.0, loop=0): if self.xyzNurbsCurve is None and self.hprNurbsCurve is None: print('Mopath: Mopath has no curves') return self.node = node self.loop = loop self.stop() t = taskMgr.add(self.__playTask, self.name + '-play') t.currentTime = time t.lastTime = ClockObject.getGlobalClock().getFrameTime()
def sendHeartbeat(self): datagram = PyDatagram() # Add message type datagram.addUint16(CLIENT_HEARTBEAT_CMU) # Send it! self.send(datagram) self.lastHeartbeat = ClockObject.getGlobalClock().getRealTime() # This is important enough to consider flushing immediately # (particularly if we haven't run readerPollTask recently). self.considerFlush()
def getListenerVelocity(self): """ Get the velocity of the listener. """ if self.listener_vel is not None: return self.listener_vel elif self.listener_target is not None: clock = ClockObject.getGlobalClock() return self.listener_target.getPosDelta(self.root) / clock.getDt() else: return VBase3(0, 0, 0)
class Throttle: def __init__(self, hz): if hz < 1: hz = 1.0 self.clock = ClockObject() self.max_dur = 1.0/float(hz) def __enter__(self): self.start_dt = self.clock.getRealTime() return self def __exit__(self, *e_info): e_dt = self.clock.getRealTime() dur = e_dt-self.start_dt pause = self.max_dur-dur while pause > 0.0: sleep(pause) dt = self.clock.getRealTime() pause -= dt-e_dt e_dt = dt
def play(self, task): if not self.playList: return Task.done fLoop = self.loopVar.get() currT = ClockObject.getGlobalClock().getFrameTime() deltaT = currT - self.lastT self.lastT = currT for actorControl in self.playList: # scale time by play rate value actorControl.play(deltaT * actorControl.playRate, fLoop) return Task.cont
def __timerTask(self, task): t = ClockObject.getGlobalClock().getFrameTime() te = t - self.startT self.currT = te if te >= self.finalT: if self.callback is not None: self.callback() else: from direct.showbase.MessengerGlobal import messenger messenger.send(self.name) return Task.done return Task.cont
def __init__(self, base, numberOfPlayers): self.base = base self.render = base.render self.taskMgr = base.taskMgr self.loader = base.loader self.windowEventSetup() # Create separate nodes so that shaders apply to # stuff in the worldRender but not the outsideWorldRender self.worldRender = render.attachNewNode("world") self.outsideWorldRender = render.attachNewNode("world") self.base.setFrameRateMeter(True) self.globalClock = ClockObject.getGlobalClock() self.globalClock.setMode(ClockObject.MLimited) self.globalClock.setFrameRate(60) self.base.disableMouse() if not 0 < numberOfPlayers < 5: raise ValueError("Number of players must be from 1 to 4") self.numberOfPlayers = numberOfPlayers self.createLights() self.initialisePhysics(debug=False) # Load the default arena self.level = Level("01.json", self) # disable default cam so that we can have multiplayer base.camNode.setActive(False) # moved player setup out to its own method self.setupPlayers(self.numberOfPlayers) # Set up shaders for shadows and cartoon outline self.setupShaders() # Create an audio manager. This is attached to the camera for # player 1, so sounds close to other players might not be very # loud self.audioManager = Audio3DManager.Audio3DManager(self.base.sfxManagerList[0], self.playerCameras[0]) # Distance should be in m, not feet self.audioManager.setDistanceFactor(3.28084) # Now initialise audio for all vehicles that were # previously set up. We can't just create the audio manager # first because we need the player 1 camera for vehicle in self.playerVehicles: vehicle.initialiseSound(self.audioManager) self.initialiseCollisionInfo()
def _doThreadCallback(self, thread, taskName, task): assert self.notify.debugCall() self._taskStartTime = ClockObject.getGlobalClock().getRealTime() thread.run() self._taskStartTime = None if thread.isFinished(): thread._destroy() self.__taskNames.remove(taskName) self.__threads.remove(thread) return Task.done else: return Task.cont
def __init__(self): ShowBase.__init__(self) self.setupRendering() self.setupControls() self.setupPhysics() self.clock_ = ClockObject() self.controlled_obj_index_ = 0 self.kinematic_mode_ = False # Task taskMgr.add(self.update, 'updateWorld')
def updateStatusReadoutTimeouts(self, task=None): removalList = [] for currLine in self.statusLines: if ClockObject.getGlobalClock().getRealTime() >= currLine[0]: removalList.append(currLine) for currRemoval in removalList: self.statusLines.remove(currRemoval) self.updateStatusReadout(None) # perform doMethodLater again after delay # This crashes when CTRL-C'ing, so this is a cheap hack. #return 2 from direct.task import Task return Task.again
def __init__(self): ShowBase.__init__(self) self.setBackgroundColor(0.2,0.2,0.2) self.accept("escape", self.taskMgr.stop) #self.accept("mouse1", self.onClick) #self.accept("mouse2", self.onClick2) self.globalClock = ClockObject() self.addLight() self.liner = LineDrawer(self) self.taskMgr.add(self.update, "update")
def move_enemies_task(self, task): # pylint: disable=unused-argument """The task that handles enemy movement.""" if self.game_state != "active": return Task.cont for enemy in set(self.enemies): if not enemy.generated: enemy.generate(self.terrain.path_finder, self.base.loader, self.terrain.geom_node, self.terrain.get_tile) if not enemy.check_active(): self.enemies.remove(enemy) continue # enemy.model.setPos(self.player.pos) enemy.move(ClockObject.getGlobalClock().getDt()) return Task.cont
def __init__(self,name = 'TestApplication', cam_step = 0.05, cam_zoom = 4): ShowBase.__init__(self) self.cam_step_ = cam_step self.cam_zoom_ = cam_zoom self.name_ = name self.setupRendering() self.setupResources() self.setupControls() self.setupPhysics() self.clock_ = ClockObject() # Task taskMgr.add(self.update, 'updateWorld')
def __init__(self,name ='TestGameBase'): # configure to use group-mask collision filtering mode in the bullet physics world loadPrcFileData('', 'bullet-filter-algorithm groups-mask') ShowBase.__init__(self) self.name_ = name self.setupRendering() self.setupResources() self.setupControls() self.setupScene() self.clock_ = ClockObject() self.delta_time_accumulator_ = 0.0 # Used to keep simulation time consistent (See https://www.panda3d.org/manual/index.php/Simulating_the_Physics_World) self.desired_frame_rate_ = TestGameBase.__DESIRED_FRAME_RATE__ # Task taskMgr.add(self.update, 'updateWorld')
def __init__(self, graphicsInterface): ShowBase.__init__(self) # This is available as a global, but pylint gives an undefined-variable # warning if we use it that way. Looking at # https://www.panda3d.org/manual/index.php/ShowBase # I would have thought we could reference it as either # self.globalClock, direct.showbase.ShowBase.globalClock, or possibly # direct.showbase.globalClock, but none of those seems to work. To # avoid the pylint warnings, create self.globalClock manually. self.globalClock = ClockObject.getGlobalClock() self.graphicsInterface = graphicsInterface # Mapping from gids to entities. self.entities = {} # Set up event handling. self.mouseState = {} self.keys = {} self.setupEventHandlers() # Set up camera control. self.cameraHolder = self.render.attachNewNode('CameraHolder') self.cameraHolder.setPos(0, 0, 100) self.prevCameraHpr = (0, -80, 0) self.usingCustomCamera = True self.setCameraCustom() self.prevMousePos = None self.selectionBox = None self.selectionBoxNode = None self.selectionBoxOrigin = None # TODO[#3]: Magic numbers bad. self.resourceDisplay = OnscreenText(pos=(-0.98,.9), align=TextNode.ALeft, mayChange=True) # Define the ground plane by a normal (+z) and a point (the origin). self.groundPlane = core.Plane(core.Vec3(0, 0, 1), core.Point3(0, 0, 0)) self.graphicsInterface.graphicsReady(self)
def __init__(self, graphicsInterface, backend, gameState): ShowBase.__init__(self) self.graphicsInterface = graphicsInterface self.backend = backend self.gameState = gameState self.groundNodes = None self.firstTick = True # This is available as a global, but pylint gives an undefined-variable # warning if we use it that way. Looking at # https://www.panda3d.org/manual/index.php/ShowBase # I would have thought we could reference it as either # self.globalClock, direct.showbase.ShowBase.globalClock, or possibly # direct.showbase.globalClock, but none of those seems to work. To # avoid the pylint warnings, create self.globalClock manually. self.globalClock = ClockObject.getGlobalClock() # Set up event handling. self.mouseState = {} self.keys = {} self.setupEventHandlers() # Set up camera control. self.cameraHolder = self.render.attachNewNode('CameraHolder') self.cameraHolder.setPos(0, 0, 100) self.prevCameraHpr = (0, -80, 0) self.usingCustomCamera = True self.setCameraCustom() self.prevMousePos = None self.selectionBox = None self.selectionBoxNode = None self.selectionBoxOrigin = None # Define the ground plane by a normal (+z) and a point (the origin). self.groundPlane = core.Plane(core.Vec3(0, 0, 1), core.Point3(0, 0, 0)) graphicsInterface.graphicsReady(self)
def __init__(self): self.globalClock = ClockObject.getGlobalClock() # self.delta is the relative delta from our clock to the # server's clock. self.delta = 0 # self.uncertainty represents the number of seconds plus or # minus in which we are confident our delta matches the # server's actual time. The initial value, None, represents # infinity--we have no idea. self.uncertainty = None # self.lastResync is the time at which self.uncertainty # was measured. It is important to remember because our # uncertainty increases over time (due to relative clock # drift). self.lastResync = 0.0 self.accept("resetClock", self.__resetClock)
def getSoundVelocity(self, sound): """ Get the velocity of the sound. """ if sound in self.vel_dict: vel = self.vel_dict[sound] if vel is not None: return vel for known_object in list(self.sound_dict.keys()): if self.sound_dict[known_object].count(sound): node_path = known_object.getNodePath() if not node_path: # The node has been deleted. del self.sound_dict[known_object] continue clock = ClockObject.getGlobalClock() return node_path.getPosDelta(self.root) / clock.getDt() return VBase3(0, 0, 0)
def __init__(self): ShowBase.__init__(self) # game objects self.controlled_obj_index_ = 0 self.level_sectors_ = [] self.controlled_objects_ = [] # active objects self.active_sector_ = None self.setupRendering() self.setupControls() self.setupPhysics() self.clock_ = ClockObject() self.kinematic_mode_ = False # Task logging.info("TestSectors demo started") taskMgr.add(self.update, 'updateWorld')
def _physics_(self, alive, sys): sim_throttle = Throttle(_sim.HZ) sys_root = self.__init_Sim_System(self.sys_recipe) dir_vec = LVector3d(0,0,0) clock = ClockObject.getGlobalClock() G = _phys.G def apply_physics(body, parent, dt): if parent: # Find distance and direction from body to its parent. dir_vec.set(*body['POS']-parent['POS']) dist = dir_vec.length() dir_vec.normalize() # Apply parent's gravity. F = (G*(parent['mass']+body['mass'])) / (dist**2) body['delta_vec'] = -dir_vec * F * dt body['VEC'] += body['delta_vec'] + parent['delta_vec'] body['POS'] += body['VEC'] * dt # Update self.BODIES. b = self.BODIES[body['name']] pos, vec, hpr, rot = body['POS'], body['VEC'], body['HPR'], body['ROT'] b['x'].value, b['y'].value, b['z'].value = pos.x, pos.y, pos.z b['vx'].value, b['vy'].value, b['vz'].value = vec.x, vec.y, vec.z b['h'].value, b['p'].value, b['r'].value = hpr.x, hpr.y, hpr.z b['rh'].value, b['rp'].value, b['rr'].value = rot.x, rot.y, rot.z for sat in body['bodies']: apply_physics(sat, body, dt) p_time = 0 dt = 0 while alive.value: with sim_throttle: ## with TimeIt() as tt: c_time = clock.getRealTime() dt = c_time - p_time apply_physics(sys_root, None, dt) p_time = c_time
__all__ = [] from .ShowBase import ShowBase, WindowControls from direct.directnotify.DirectNotifyGlobal import directNotify, giveNotify from panda3d.core import VirtualFileSystem, Notify, ClockObject, PandaSystem from panda3d.core import ConfigPageManager, ConfigVariableManager from panda3d.core import NodePath, PGTop from panda3d.direct import get_config_showbase config = get_config_showbase() __dev__ = config.GetBool('want-dev', __debug__) vfs = VirtualFileSystem.getGlobalPtr() ostream = Notify.out() globalClock = ClockObject.getGlobalClock() cpMgr = ConfigPageManager.getGlobalPtr() cvMgr = ConfigVariableManager.getGlobalPtr() pandaSystem = PandaSystem.getGlobalPtr() # This is defined here so GUI elements can be instantiated before ShowBase. aspect2d = NodePath(PGTop("aspect2d")) # Set direct notify categories now that we have config directNotify.setDconfigLevels() def run(): assert ShowBase.notify.warning("run() is deprecated, use base.run() instead") base.run() def inspect(anObject):
class TestApplication(ShowBase): def __init__(self): ShowBase.__init__(self) self.setupRendering() self.setupControls() self.setupPhysics() self.clock_ = ClockObject() self.controlled_obj_index_ = 0 self.kinematic_mode_ = False # Task taskMgr.add(self.update, 'updateWorld') def setupRendering(self): self.setBackgroundColor(0.1, 0.1, 0.8, 1) self.setFrameRateMeter(True) # Light alight = AmbientLight('ambientLight') alight.setColor(Vec4(0.5, 0.5, 0.5, 1)) alightNP = self.render.attachNewNode(alight) dlight = DirectionalLight('directionalLight') dlight.setDirection(Vec3(1, 1, -1)) dlight.setColor(Vec4(0.7, 0.7, 0.7, 1)) dlightNP = self.render.attachNewNode(dlight) self.render.clearLight() self.render.setLight(alightNP) self.render.setLight(dlightNP) def setupControls(self): # Input (Events) self.accept('escape', self.doExit) self.accept('r', self.doReset) self.accept('f1', self.toggleWireframe) self.accept('f2', self.toggleTexture) self.accept('f3', self.toggleDebug) self.accept('f5', self.doScreenshot) self.accept('n', self.selectNextControlledObject) self.accept('k',self.toggleKinematicMode) self.accept('p',self.printInfo) self.accept('q',self.zoomIn) self.accept('a',self.zoomOut) self.accept('s',self.toggleRightLeft) # Inputs (Polling) self.input_state_ = InputState() self.input_state_.watchWithModifiers("right","arrow_right") self.input_state_.watchWithModifiers('left', 'arrow_left') self.input_state_.watchWithModifiers('jump', 'arrow_up') self.input_state_.watchWithModifiers('stop', 'arrow_down') self.input_state_.watchWithModifiers('roll_right', 'c') self.input_state_.watchWithModifiers('roll_left', 'z') self.input_state_.watchWithModifiers('roll_stop', 'x') self.title = addTitle("Panda3D: Sprite Animation") self.inst1 = addInstructions(0.06, "ESC: Quit") self.inst2 = addInstructions(0.12, "Up/Down: Jump/Stop") self.inst3 = addInstructions(0.18, "Left/Right: Move Left / Move Rigth") self.inst4 = addInstructions(0.24, "z/x/c : Rotate Left/ Rotate Stop / Rotate Right") self.inst5 = addInstructions(0.30, "n: Select Next Character") self.inst6 = addInstructions(0.36, "k: Toggle Kinematic Mode") self.inst7 = addInstructions(0.42, "q/a: Zoom in / Zoom out") self.inst7 = addInstructions(0.48, "s: Toggle Rigth|Left ") self.inst7 = addInstructions(0.54, "p: Print Info") def printInfo(self): self.sprt_animator_.printInfo() def setupPhysics(self): # setting up physics world and parent node path self.physics_world_ = BulletWorld() self.world_node_ = self.render.attachNewNode('world') self.cam.reparentTo(self.world_node_) self.physics_world_.setGravity(Vec3(0, 0, -9.81)) self.debug_node_ = self.world_node_.attachNewNode(BulletDebugNode('Debug')) self.debug_node_.show() self.debug_node_.node().showWireframe(True) self.debug_node_.node().showConstraints(True) self.debug_node_.node().showBoundingBoxes(False) self.debug_node_.node().showNormals(True) # setting up ground self.ground_ = self.world_node_.attachNewNode(BulletRigidBodyNode('Ground')) self.ground_.node().addShape(BulletPlaneShape(Vec3(0, 0, 1), 0)) self.ground_.setPos(0,0,0) self.ground_.setCollideMask(BitMask32.allOn()) self.physics_world_.attachRigidBody(self.ground_.node()) self.object_nodes_ = [] self.controlled_objects_=[] num_boxes = 20 side_length = 0.2 size = Vec3(0.5*side_length,0.5*side_length,0.5*side_length) start_pos = Vec3(-num_boxes*side_length,0,6) """ # creating boxes box_visual = loader.loadModel('models/box.egg') box_visual.clearModelNodes() box_visual.setTexture(loader.loadTexture('models/wood.png')) bounds = box_visual.getTightBounds() # start of box model scaling extents = Vec3(bounds[1] - bounds[0]) scale_factor = side_length/max([extents.getX(),extents.getY(),extents.getZ()]) box_visual.setScale((scale_factor,scale_factor ,scale_factor)) # end of box model scaling for i in range(0,20): self.addBox("name %i"%(i),size,start_pos + Vec3(i*side_length,0,0),box_visual) start_pos = Vec3(-num_boxes*side_length,0,8) for i in range(0,20): self.addBox("name %i"%(i),size,start_pos + Vec3(i*2*side_length,0,0),box_visual) """ # creating sprite animator sprt_animator = SpriteAnimator('hiei_run') if not sprt_animator.loadImage(SPRITE_IMAGE_DETAILS[0], # file path SPRITE_IMAGE_DETAILS[1], # columns SPRITE_IMAGE_DETAILS[2], # rows SPRITE_IMAGE_DETAILS[3], # scale x SPRITE_IMAGE_DETAILS[4], # scale y SPRITE_IMAGE_DETAILS[5]): # frame rate print "Error loading image %s"%(SPRITE_IMAGE_DETAILS[0]) sys.exit(1) self.sprt_animator_ = sprt_animator # creating Mobile Character Box size = Vec3(0.5,0.2,1) mbox_visual = loader.loadModel('models/box.egg') bounds = mbox_visual.getTightBounds() extents = Vec3(bounds[1] - bounds[0]) scale_factor = 1/max([extents.getX(),extents.getY(),extents.getZ()]) mbox_visual.setScale(size.getX()*scale_factor,size.getY()*scale_factor,size.getZ()*scale_factor) mbox = self.world_node_.attachNewNode(BulletRigidBodyNode('CharacterBox')) mbox.node().addShape(BulletBoxShape(size/2)) mbox.node().setMass(1.0) mbox.node().setLinearFactor((1,0,1)) mbox.node().setAngularFactor((0,1,0)) mbox.setCollideMask(BitMask32.allOn()) mbox_visual.instanceTo(mbox) mbox_visual.hide() mbox.setPos(Vec3(1,0,size.getZ()+1)) bounds = sprt_animator.getTightBounds() extents = Vec3(bounds[1] - bounds[0]) scale_factor = size.getZ()/extents.getZ() sprt_animator.setScale(scale_factor,1,scale_factor) sprt_animator.reparentTo(mbox) bounds = sprt_animator.getTightBounds() print "Sprite Animator bounds %s , %s"%(str(bounds[1]),str(bounds[0])) self.physics_world_.attachRigidBody(mbox.node()) self.object_nodes_.append(mbox) self.controlled_objects_.append(mbox) # creating sphere diameter = 0.4 sphere_visual = loader.loadModel('models/ball.egg') bounds = sphere_visual.getTightBounds() # start of model scaling extents = Vec3(bounds[1] - bounds[0]) scale_factor = diameter/max([extents.getX(),extents.getY(),extents.getZ()]) sphere_visual.clearModelNodes() sphere_visual.setScale(scale_factor,scale_factor,scale_factor) # end of model scaling sphere_visual.setTexture(loader.loadTexture('models/bowl.jpg')) sphere = self.world_node_.attachNewNode(BulletRigidBodyNode('Sphere')) sphere.node().addShape(BulletSphereShape(0.5*diameter)) sphere.node().setMass(1.0) sphere.node().setLinearFactor((1,0,1)) sphere.node().setAngularFactor((0,1,0)) sphere.setCollideMask(BitMask32.allOn()) sphere_visual.instanceTo(sphere) sphere.setPos(Vec3(0,0,size.getZ()+1)) self.physics_world_.attachRigidBody(sphere.node()) self.object_nodes_.append(sphere) self.controlled_objects_.append(sphere) self.setupLevel() def addBox(self,name,size,pos,visual): # Box (dynamic) box = self.world_node_.attachNewNode(BulletRigidBodyNode(name)) box.node().setMass(1.0) box.node().addShape(BulletBoxShape(size)) box.setPos(pos) box.setCollideMask(BitMask32.allOn()) box.node().setLinearFactor((1,0,1)) box.node().setAngularFactor((0,1,0)) visual.instanceTo(box) self.physics_world_.attachRigidBody(box.node()) self.object_nodes_.append(box) def setupLevel(self): # (left, top, length ,depth(y) ,height) platform_details =[ (-20, 4, 20, 4, 1 ), (-2, 5, 10, 4, 1 ), ( 4 , 2 , 16, 4, 1.4), (-4 , 1, 10, 4, 1), ( 16, 6, 30, 4, 1) ] for i in range(0,len(platform_details)): p = platform_details[i] topleft = (p[0],p[1]) size = Vec3(p[2],p[3],p[4]) self.addPlatform(topleft, size,'Platform%i'%(i)) def addPlatform(self,topleft,size,name): # Visual visual = loader.loadModel('models/box.egg') visual.setTexture(loader.loadTexture('models/iron.jpg')) bounds = visual.getTightBounds() extents = Vec3(bounds[1] - bounds[0]) scale_factor = 1/max([extents.getX(),extents.getY(),extents.getZ()]) visual.setScale(size.getX()*scale_factor,size.getY()*scale_factor,size.getZ()*scale_factor) # Box (static) platform = self.world_node_.attachNewNode(BulletRigidBodyNode(name)) platform.node().setMass(0) platform.node().addShape(BulletBoxShape(size/2)) platform.setPos(Vec3(topleft[0] + 0.5*size.getX(),0,topleft[1]-0.5*size.getZ())) platform.setCollideMask(BitMask32.allOn()) visual.instanceTo(platform) self.physics_world_.attachRigidBody(platform.node()) self.object_nodes_.append(platform) def update(self, task): self.clock_.tick() dt = self.clock_.getDt() self.processInput(dt) self.physics_world_.doPhysics(dt, 5, 1.0/180.0) self.updateCamera() return task.cont def processInput(self,dt): activate = False obj = self.controlled_objects_[self.controlled_obj_index_] if self.kinematic_mode_: obj.node().setKinematic(True) return else: obj.node().setKinematic(False) vel = obj.node().getLinearVelocity() w = obj.node().getAngularVelocity() if self.input_state_.isSet('right'): vel.setX(2) activate = True if self.input_state_.isSet('left'): vel.setX(-2) activate = True if self.input_state_.isSet('jump'): vel.setZ(4) activate = True if self.input_state_.isSet('stop'): vel.setX(0) if self.input_state_.isSet('roll_right'): w.setY(ROTATIONAl_SPEED) activate = True if self.input_state_.isSet('roll_left'): w.setY(-ROTATIONAl_SPEED) activate = True if self.input_state_.isSet('roll_stop'): w.setY(0) if activate : obj.node().setActive(True,True) obj.node().setLinearVelocity(vel) obj.node().setAngularVelocity(w) def updateCamera(self): if len(self.controlled_objects_) > 0: obj = self.controlled_objects_[self.controlled_obj_index_] self.cam.setPos(obj,0, -CAM_DISTANCE, 0) self.cam.lookAt(obj.getPos()) def cleanup(self): for i in range(0,len(self.object_nodes_)): rb = self.object_nodes_[i] self.physics_world_.removeRigidBody(rb.node()) self.object_nodes_ = [] self.controlled_objects_ = [] self.physics_world_.removeRigidBody(self.ground_.node()) self.ground_ = None self.physics_world_ = None self.debug_node_ = None self.sprt_animator_ = None self.cam.reparentTo(self.render) self.world_node_.removeNode() self.world_node_ = None # _____HANDLER_____ def zoomIn(self): global CAM_DISTANCE CAM_DISTANCE-=4 def zoomOut(self): global CAM_DISTANCE CAM_DISTANCE+=4 def toggleKinematicMode(self): self.kinematic_mode_ = not self.kinematic_mode_ print "Kinematic Mode %s"%('ON' if self.kinematic_mode_ else 'OFF') def toggleRightLeft(self): self.sprt_animator_.faceRight(not self.sprt_animator_.facing_right_) def selectNextControlledObject(self): self.controlled_obj_index_+=1 if self.controlled_obj_index_ >= len(self.controlled_objects_): self.controlled_obj_index_ = 0 # reset def doExit(self): self.cleanup() sys.exit(1) def doReset(self): self.cleanup() self.setupPhysics() def toggleDebug(self): if self.debug_node_.isHidden(): self.debug_node_.show() else: self.debug_node_.hide() def doScreenshot(self): self.screenshot('Bullet')
class TestGameBase(ShowBase): __CAM_ZOOM__ = 1 __CAM_STEP__ = 0.2 __CAM_ORIENT_STEP__ = 4.0 __BACKGROUND_IMAGE_PACKAGE__ = 'platformer_core' __BACKGROUND_IMAGE_PATH__ = rospack.RosPack().get_path(__BACKGROUND_IMAGE_PACKAGE__) + '/resources/backgrounds/' + 'sky02.png' __BACKGROUND_POSITION__ = Vec3(0,100,0) __BACKGROUND_SCALE__ = 0.2 __DESIRED_FRAME_RATE__ = 1.0/60.0 def __init__(self,name ='TestGameBase'): # configure to use group-mask collision filtering mode in the bullet physics world loadPrcFileData('', 'bullet-filter-algorithm groups-mask') ShowBase.__init__(self) self.name_ = name self.setupRendering() self.setupResources() self.setupControls() self.setupScene() self.clock_ = ClockObject() self.delta_time_accumulator_ = 0.0 # Used to keep simulation time consistent (See https://www.panda3d.org/manual/index.php/Simulating_the_Physics_World) self.desired_frame_rate_ = TestGameBase.__DESIRED_FRAME_RATE__ # Task taskMgr.add(self.update, 'updateWorld') def setupRendering(self): self.setBackgroundColor(0.1, 0.1, 0.8, 1) self.setFrameRateMeter(True) # Light alight = AmbientLight('ambientLight') alight.setColor(Vec4(0.5, 0.5, 0.5, 1)) alightNP = self.render.attachNewNode(alight) dlight = DirectionalLight('directionalLight') dlight.setDirection(Vec3(1, 1, -1)) dlight.setColor(Vec4(0.7, 0.7, 0.7, 1)) dlightNP = self.render.attachNewNode(dlight) self.render.clearLight() self.render.setLight(alightNP) self.render.setLight(dlightNP) self.setupBackgroundImage() def setupBackgroundImage(self): image_file = Filename(TestGameBase.__BACKGROUND_IMAGE_PATH__) # check if image can be loaded img_head = PNMImageHeader() if not img_head.readHeader(image_file ): raise IOError("PNMImageHeader could not read file %s. Try using absolute filepaths"%(image_file.c_str())) sys.exit() # Load the image with a PNMImage w = img_head.getXSize() h = img_head.getYSize() img = PNMImage(w,h) #img.alphaFill(0) img.read(image_file) texture = Texture() texture.setXSize(w) texture.setYSize(h) texture.setZSize(1) texture.load(img) texture.setWrapU(Texture.WM_border_color) # gets rid of odd black edges around image texture.setWrapV(Texture.WM_border_color) texture.setBorderColor(LColor(0,0,0,0)) # creating CardMaker to hold the texture cm = CardMaker('background') cm.setFrame(-0.5*w,0.5*w,-0.5*h,0.5*h) # This configuration places the image's topleft corner at the origin (left, right, bottom, top) background_np = NodePath(cm.generate()) background_np.setTexture(texture) background_np.reparentTo(self.render) background_np.setPos(TestGameBase.__BACKGROUND_POSITION__) background_np.setScale(TestGameBase.__BACKGROUND_SCALE__) def setupControls(self): # Input (Events) self.accept('escape', self.exit) self.accept('r', self.doReset) self.accept('f1', self.toggleDebug) self.accept('f2', self.toggleTexture) self.accept('f3', self.toggleWireframe) self.accept('f5', self.doScreenshot) self.input_state_ = InputState() button_map = {'a' : KeyboardButtons.KEY_A , 'q' : KeyboardButtons.KEY_Q,'escape' : KeyboardButtons.KEY_ESC, 'f1' : KeyboardButtons.KEY_F1, 'e': KeyboardButtons.KEY_E,'w': KeyboardButtons.KEY_W} self.input_manager_ = KeyboardController(self.input_state_, button_map) # Creating directional moves self.input_manager_.addMove(Move('UP',[KeyboardButtons.DPAD_UP],False,lambda : self.moveCamUp())) self.input_manager_.addMove(Move('DOWN',[KeyboardButtons.DPAD_DOWN],False,lambda : self.moveCamDown())) self.input_manager_.addMove(Move('LEFT',[KeyboardButtons.DPAD_LEFT],False,lambda : self.moveCamLeft())) self.input_manager_.addMove(Move('RIGHT',[KeyboardButtons.DPAD_RIGHT],False,lambda : self.moveCamRight())) self.input_manager_.addMove(Move('ROTATE_LEFT',[KeyboardButtons.KEY_E],False,lambda : self.rotateCamZCounterClockwise())) self.input_manager_.addMove(Move('ROTATE_RIGHT',[KeyboardButtons.KEY_W],False,lambda : self.rotateCamZClockwise())) self.input_manager_.addMove(Move('ZoomIn',[KeyboardButtons.KEY_Q],False,lambda : self.zoomIn())) self.input_manager_.addMove(Move('ZoomOut',[KeyboardButtons.KEY_A],False,lambda : self.zoomOut())) self.title = self.createTitle("Panda3D: " + self.name_) self.instructions_ = [ self.createInstruction(0.06, "ESC: Quit"), self.createInstruction(0.12, "Up/Down: Move Camera Up/Down"), self.createInstruction(0.18, "Left/Right: Move Camera Left / Rigth"), self.createInstruction(0.24, "q/a: Zoom in / Zoom out"), self.createInstruction(0.30, "F1: Toggle Debug"), self.createInstruction(0.36, "F2: Toggle Texture"), self.createInstruction(0.42, "F3: Toggle Wireframe"), self.createInstruction(0.48, "F5: Screenshot") ] def setupScene(self): self.level_ = TestLevel('ground-zero') self.level_.reparentTo(self.render) # enable debug visuals self.debug_node_ = self.level_.attachNewNode(BulletDebugNode('Debug')) self.debug_node_.node().showWireframe(True) self.debug_node_.node().showConstraints(True) self.debug_node_.node().showBoundingBoxes(False) self.debug_node_.node().showNormals(True) self.level_.getPhysicsWorld().setDebugNode(self.debug_node_.node()) self.debug_node_.hide() self.cam.reparentTo(self.level_) self.cam.setPos(self.level_,0, -TestGameBase.__CAM_ZOOM__*24, TestGameBase.__CAM_STEP__*25) self.camera_controller_ = CameraController(self.cam) def setupResources(self): pass def cleanup(self): self.level_.detachNode() self.level_ = None self.input_manager_ = None def update(self,task): self.clock_.tick() dt = self.clock_.getDt() self.delta_time_accumulator_ += dt while self.delta_time_accumulator_ > self.desired_frame_rate_: self.delta_time_accumulator_ -= self.desired_frame_rate_ self.level_.update(self.desired_frame_rate_) self.input_manager_.update(self.desired_frame_rate_) self.camera_controller_.update(self.desired_frame_rate_) StateMachine.processEvents() return task.cont # __ CAM_METHODS __ def moveCamUp(self): self.cam.setPos(self.cam.getPos() + Vec3(0, 0,TestGameBase.__CAM_STEP__)) def moveCamDown(self): self.cam.setPos(self.cam.getPos() + Vec3(0, 0,-TestGameBase.__CAM_STEP__)) def moveCamRight(self): self.cam.setPos(self.cam.getPos() + Vec3(TestGameBase.__CAM_STEP__,0,0)) def moveCamLeft(self): self.cam.setPos(self.cam.getPos() + Vec3(-TestGameBase.__CAM_STEP__,0,0)) def rotateCamZClockwise(self): self.cam.setH(self.cam.getH() + TestGameBase.__CAM_ORIENT_STEP__) def rotateCamZCounterClockwise(self): self.cam.setH(self.cam.getH() + -TestGameBase.__CAM_ORIENT_STEP__) def zoomIn(self): self.cam.setY(self.cam.getY()+TestGameBase.__CAM_ZOOM__) def zoomOut(self): self.cam.setY(self.cam.getY()-TestGameBase.__CAM_ZOOM__) def toggleDebug(self): if self.debug_node_.isHidden(): self.debug_node_.show() else: self.debug_node_.hide() def doReset(self): logging.warn("Reset Not implemented") pass def doScreenshot(self): self.screenshot('Pand3d') # __ END OF CAM METHODS __ # SUPPORT METHODS def createInstruction(self,pos, msg): return OnscreenText(text=msg, style=1, fg=(1, 1, 1, 1), scale=.05, shadow=(0, 0, 0, 1), parent=base.a2dTopLeft, pos=(0.08, -pos - 0.04), align=TextNode.ALeft) # Function to put title on the screen. def createTitle(self,text): return OnscreenText(text=text, style=1, fg=(1, 1, 1, 1), scale=.08, parent=base.a2dBottomRight, align=TextNode.ARight, pos=(-0.1, 0.09), shadow=(0, 0, 0, 1)) def exit(self): self.cleanup() sys.exit(1)
def __init__(self, msg=""): self.__msg = msg self.__clock = ClockObject()
def update_bullet(self, task): dt = ClockObject.getGlobalClock().getDt() self.bullet_world.doPhysics(dt) return task.cont
class TestApplication(ShowBase): def __init__(self): ShowBase.__init__(self) # game objects self.controlled_obj_index_ = 0 self.level_sectors_ = [] self.controlled_objects_ = [] # active objects self.active_sector_ = None self.setupRendering() self.setupControls() self.setupPhysics() self.clock_ = ClockObject() self.kinematic_mode_ = False # Task logging.info("TestSectors demo started") taskMgr.add(self.update, 'updateWorld') def setupRendering(self): self.setBackgroundColor(0.1, 0.1, 0.8, 1) self.setFrameRateMeter(True) # Light alight = AmbientLight('ambientLight') alight.setColor(Vec4(0.5, 0.5, 0.5, 1)) alightNP = self.render.attachNewNode(alight) dlight = DirectionalLight('directionalLight') dlight.setDirection(Vec3(1, 1, -1)) dlight.setColor(Vec4(0.7, 0.7, 0.7, 1)) dlightNP = self.render.attachNewNode(dlight) self.render.clearLight() self.render.setLight(alightNP) self.render.setLight(dlightNP) self.setupBackgroundImage() def setupBackgroundImage(self): image_file = Filename(rospack.RosPack().get_path(BACKGROUND_IMAGE_PACKAGE) + '/resources/backgrounds/' + BACKGROUND_IMAGE_PATH) # check if image can be loaded img_head = PNMImageHeader() if not img_head.readHeader(image_file ): raise IOError, "PNMImageHeader could not read file %s. Try using absolute filepaths"%(image_file.c_str()) sys.exit() # Load the image with a PNMImage w = img_head.getXSize() h = img_head.getYSize() img = PNMImage(w,h) #img.alphaFill(0) img.read(image_file) texture = Texture() texture.setXSize(w) texture.setYSize(h) texture.setZSize(1) texture.load(img) texture.setWrapU(Texture.WM_border_color) # gets rid of odd black edges around image texture.setWrapV(Texture.WM_border_color) texture.setBorderColor(LColor(0,0,0,0)) # creating CardMaker to hold the texture cm = CardMaker('background') cm.setFrame(-0.5*w,0.5*w,-0.5*h,0.5*h) # This configuration places the image's topleft corner at the origin (left, right, bottom, top) background_np = NodePath(cm.generate()) background_np.setTexture(texture) background_np.reparentTo(self.render) background_np.setPos(BACKGROUND_POSITION) background_np.setScale(BACKGROUND_IMAGE_SCALE) def setupControls(self): # Input (Events) self.accept('escape', self.doExit) self.accept('r', self.doReset) self.accept('f1', self.toggleWireframe) self.accept('f2', self.toggleTexture) self.accept('f3', self.toggleDebug) self.accept('f5', self.doScreenshot) self.accept('n', self.selectNextControlledObject) self.accept('k', self.toggleKinematicMode) # Inputs (Polling) self.input_state_ = InputState() self.input_state_.watchWithModifiers("right","arrow_right") self.input_state_.watchWithModifiers('left', 'arrow_left') self.input_state_.watchWithModifiers('jump', 'arrow_up') self.input_state_.watchWithModifiers('stop', 'arrow_down') self.input_state_.watchWithModifiers('roll_right', 'c') self.input_state_.watchWithModifiers('roll_left', 'z') self.input_state_.watchWithModifiers('roll_stop', 'x') self.title = addTitle("Panda3D: Kinematic Objects") self.inst1 = addInstructions(0.06, "ESC: Quit") self.inst2 = addInstructions(0.12, "Up/Down: Jump/Stop") self.inst3 = addInstructions(0.18, "Left/Right: Move Left / Move Rigth") self.inst4 = addInstructions(0.24, "z/x/c : Rotate Left/ Rotate Stop / Rotate Right") self.inst5 = addInstructions(0.30, "n: Select Next Character") self.inst6 = addInstructions(0.36, "k: Toggle Kinematic Mode") self.inst7 = addInstructions(0.42, "f1: Toggle Wireframe") self.inst8 = addInstructions(0.48, "f2: Toggle Texture") self.inst9 = addInstructions(0.54, "f3: Toggle BulletDebug") self.inst10 = addInstructions(0.60, "f5: Capture Screenshot") def processCollisions(self): contact_manifolds = self.physics_world_.getManifolds() for cm in contact_manifolds: node0 = cm.getNode0() node1 = cm.getNode1() col_mask1 = node0.getIntoCollideMask() col_mask2 = node1.getIntoCollideMask() if (col_mask1 == col_mask2) and \ (col_mask1 == SECTOR_ENTERED_BITMASK) and \ self.active_sector_.getSectorPlaneNode().getName() != node0.getName(): logging.info('Collision between %s and %s'%(node0.getName(),node1.getName())) sector = [s for s in self.level_sectors_ if s.getSectorPlaneNode().getName() == node0.getName()] sector = [s for s in self.level_sectors_ if s.getSectorPlaneNode().getName() == node1.getName()] + sector self.switchToSector(sector[0]) logging.info("Sector %s entered"%(self.active_sector_.getName())) def switchToSector(self,sector): obj_index = self.controlled_obj_index_ character_obj = self.controlled_objects_[obj_index] if self.active_sector_ is not None: self.active_sector_.releaseCharacter() character_obj.setY(sector,0) character_obj.setH(sector,0) self.active_sector_ = sector self.active_sector_.constrainCharacter(character_obj) self.active_sector_.enableDetection(False) sectors = [s for s in self.level_sectors_ if s != self.active_sector_] for s in sectors: s.enableDetection(True) def setupPhysics(self): # setting up physics world and parent node path self.physics_world_ = BulletWorld() self.world_node_ = self.render.attachNewNode('world') self.cam.reparentTo(self.world_node_) self.physics_world_.setGravity(Vec3(0, 0, -9.81)) self.debug_node_ = self.world_node_.attachNewNode(BulletDebugNode('Debug')) self.debug_node_.node().showWireframe(True) self.debug_node_.node().showConstraints(True) self.debug_node_.node().showBoundingBoxes(True) self.debug_node_.node().showNormals(True) self.physics_world_.setDebugNode(self.debug_node_.node()) self.debug_node_.hide() # setting up collision groups self.physics_world_.setGroupCollisionFlag(GAME_OBJECT_BITMASK.getLowestOnBit(),GAME_OBJECT_BITMASK.getLowestOnBit(),True) self.physics_world_.setGroupCollisionFlag(SECTOR_ENTERED_BITMASK.getLowestOnBit(),SECTOR_ENTERED_BITMASK.getLowestOnBit(),True) self.physics_world_.setGroupCollisionFlag(GAME_OBJECT_BITMASK.getLowestOnBit(),SECTOR_ENTERED_BITMASK.getLowestOnBit(),False) # setting up ground self.ground_ = self.world_node_.attachNewNode(BulletRigidBodyNode('Ground')) self.ground_.node().addShape(BulletPlaneShape(Vec3(0, 0, 1), 0)) self.ground_.setPos(0,0,0) self.ground_.setCollideMask(GAME_OBJECT_BITMASK) self.physics_world_.attachRigidBody(self.ground_.node()) # creating level objects self.setupLevelSectors() # creating controlled objects diameter = 0.4 sphere_visual = loader.loadModel('models/ball.egg') bounds = sphere_visual.getTightBounds() # start of model scaling extents = Vec3(bounds[1] - bounds[0]) scale_factor = diameter/max([extents.getX(),extents.getY(),extents.getZ()]) sphere_visual.clearModelNodes() sphere_visual.setScale(scale_factor,scale_factor,scale_factor) # end of model scaling sphere_visual.setTexture(loader.loadTexture('models/bowl.jpg'),1) sphere = NodePath(BulletRigidBodyNode('Sphere')) sphere.node().addShape(BulletSphereShape(0.5*diameter)) sphere.node().setMass(1.0) #sphere.node().setLinearFactor((1,0,1)) #sphere.node().setAngularFactor((0,1,0)) sphere.setCollideMask(GAME_OBJECT_BITMASK) sphere_visual.instanceTo(sphere) self.physics_world_.attachRigidBody(sphere.node()) self.controlled_objects_.append(sphere) sphere.reparentTo(self.world_node_) sphere.setPos(self.level_sectors_[0],Vec3(0,0,diameter+10)) sphere.setHpr(self.level_sectors_[0],Vec3(0,0,0)) # creating bullet ghost for detecting entry into other sectors player_ghost = sphere.attachNewNode(BulletGhostNode('player-ghost-node')) ghost_box_shape = BulletSphereShape(PLAYER_GHOST_DIAMETER/2) ghost_box_shape.setMargin(SECTOR_COLLISION_MARGIN) ghost_sphere_shape = BulletSphereShape(PLAYER_GHOST_DIAMETER*0.5) ghost_sphere_shape.setMargin(SECTOR_COLLISION_MARGIN) player_ghost.node().addShape(ghost_box_shape) player_ghost.setPos(sphere,Vec3(0,0,0)) player_ghost.node().setIntoCollideMask(SECTOR_ENTERED_BITMASK) self.physics_world_.attach(player_ghost.node()) # creating mobile box size = Vec3(0.2,0.2,0.4) mbox_visual = loader.loadModel('models/box.egg') bounds = mbox_visual.getTightBounds() extents = Vec3(bounds[1] - bounds[0]) scale_factor = 1/max([extents.getX(),extents.getY(),extents.getZ()]) mbox_visual.setScale(size.getX()*scale_factor,size.getY()*scale_factor,size.getZ()*scale_factor) mbox = NodePath(BulletRigidBodyNode('MobileBox')) mbox.node().addShape(BulletBoxShape(size/2)) mbox.node().setMass(1.0) #mbox.node().setLinearFactor((1,0,1)) #mbox.node().setAngularFactor((0,1,0)) mbox.setCollideMask(GAME_OBJECT_BITMASK) mbox_visual.instanceTo(mbox) self.physics_world_.attachRigidBody(mbox.node()) self.controlled_objects_.append(mbox) mbox.reparentTo(self.level_sectors_[0]) mbox.setPos(Vec3(1,0,size.getZ()+1)) # switching to sector 1 self.switchToSector(self.level_sectors_[0]) def setupLevelSectors(self): start_pos = Vec3(0,-20,0) for i in range(0,4): sector = Sector('sector' + str(i),self.physics_world_) sector.reparentTo(self.world_node_) #sector.setHpr(Vec3(60*(i+1),0,0)) sector.setHpr(Vec3(90*i,0,0)) sector.setPos(sector,Vec3(0,-20,i*4)) self.level_sectors_.append(sector) sector.setup() def update(self, task): self.clock_.tick() dt = self.clock_.getDt() self.processInput(dt) self.physics_world_.doPhysics(dt, 5, 1.0/180.0) self.processCollisions() self.updateCamera() return task.cont def processInput(self,dt): activate = False obj = self.controlled_objects_[self.controlled_obj_index_] if self.kinematic_mode_: obj.node().setKinematic(True) return else: obj.node().setKinematic(False) vel = self.active_sector_.getRelativeVector(self.world_node_,obj.node().getLinearVelocity()) w = self.active_sector_.getRelativeVector(self.world_node_, obj.node().getAngularVelocity()) vel.setY(0) #w.setX(0) #w.setZ(0) if self.input_state_.isSet('right'): vel.setX(2) activate = True if self.input_state_.isSet('left'): vel.setX(-2) activate = True if self.input_state_.isSet('jump'): vel.setZ(4) activate = True if self.input_state_.isSet('stop'): vel.setX(0) if self.input_state_.isSet('roll_right'): w.setY(ROTATIONAl_SPEED) activate = True if self.input_state_.isSet('roll_left'): w.setY(-ROTATIONAl_SPEED) activate = True if self.input_state_.isSet('roll_stop'): w.setY(0) if activate : obj.node().setActive(True,True) vel = self.world_node_.getRelativeVector(self.active_sector_,vel) w = self.world_node_.getRelativeVector(self.active_sector_,w) obj.node().setLinearVelocity(vel) obj.node().setAngularVelocity(w) #logging.info("Linear Velocity: %s"%(str(vel))) def updateCamera(self): if len(self.controlled_objects_) > 0: obj = self.controlled_objects_[self.controlled_obj_index_] self.cam.setPos(self.active_sector_,obj.getPos(self.active_sector_)) self.cam.setY(self.active_sector_,-CAM_DISTANCE/1) self.cam.lookAt(obj.getParent(),obj.getPos()) def cleanup(self): for i in range(0,len(self.controlled_objects_)): rb = self.controlled_objects_[i] self.physics_world_.removeRigidBody(rb.node()) rb.removeNode() self.object_nodes_ = [] self.controlled_objects_ = [] self.physics_world_.removeRigidBody(self.ground_.node()) self.ground_ = None self.physics_world_ = None self.debug_node_ = None self.cam.reparentTo(self.render) self.world_node_.removeNode() self.world_node_ = None # _____HANDLER_____ def toggleKinematicMode(self): self.kinematic_mode_ = not self.kinematic_mode_ print "Kinematic Mode %s"%('ON' if self.kinematic_mode_ else 'OFF') def selectNextControlledObject(self): self.controlled_obj_index_+=1 if self.controlled_obj_index_ >= len(self.controlled_objects_): self.controlled_obj_index_ = 0 # reset def doExit(self): self.cleanup() sys.exit(1) def doReset(self): self.cleanup() self.setupPhysics() def toggleDebug(self): if self.debug_node_.isHidden(): self.debug_node_.show() else: self.debug_node_.hide() def doScreenshot(self): self.screenshot('Bullet')
def __init__(self): self.setupPhysics() self.clock_ = ClockObject()
def __init__(self, msg="", rnd=3): self._msg = msg self._rnd = rnd self._clock = ClockObject()
def __init__(self, hz): if hz < 1: hz = 1.0 self.clock = ClockObject() self.max_dur = 1.0/float(hz)