def __init__(self): self.setAI() self.keyMap = {"left": 0, "right": 0, "forward": 0, "backward": 0, "cam-left": 0, "cam-right": 0} base.win.setClearColor(Vec4(0, 0, 0, 1)) # the menu self.loadAudio() self.showMenu() # keyboard and mouse events self.accept("escape", sys.exit) self.accept("w", self.setKey, ["forward", 1]) self.accept("a", self.setKey, ["left", 1]) self.accept("s", self.setKey, ["backward", 1]) self.accept("d", self.setKey, ["right", 1]) self.accept("w-up", self.setKey, ["forward", 0]) self.accept("a-up", self.setKey, ["left", 0]) self.accept("s-up", self.setKey, ["backward", 0]) self.accept("d-up", self.setKey, ["right", 0]) self.accept("arrow_left", self.setKey, ["cam-left", 1]) self.accept("arrow_left-up", self.setKey, ["cam-left", 0]) self.accept("arrow_right", self.setKey, ["cam-right", 1]) self.accept("arrow_right-up", self.setKey, ["cam-right", 0]) # create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(0.3, 0.3, 0.3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight))
def __init__(self): # call superclass init (no implicit chaining) ShowBase.__init__(self) self.pnode = loader.loadModel("models/queen") self.pnode.reparentTo(render) self.pnode.setPos(0, 5, -1) self.pnode.setH(-60) self.pnode2 = loader.loadModel("models/pawn") self.pnode2.reparentTo(self.pnode) self.pnode2.setScale(0.5) self.ground = 1.2 self.pnode2.setPos(1, 0, self.ground) self.vz = 0 self.vx = 0 self.vy = 0 ############ lighting ############# alight = AmbientLight('alight') alight.setColor((.7, .3, .3, 1)) self.alnp = render.attachNewNode(alight) render.setLight(self.alnp) slight = DirectionalLight('slight') slight.setColor((1, .5, .5, 1)) slight.setDirection(LVector3(-0.8, 0, 0)) self.slnp = render.attachNewNode(slight) render.setLight(self.slnp) taskMgr.add(self.update, "update")
def __init__(self): base.setBackgroundColor(0.1, 0.1, 0.8, 1) base.setFrameRateMeter(True) base.cam.setPos(0, -60, 20) base.cam.lookAt(0, 0, 0) # Light alight = AmbientLight('ambientLight') alight.setColor(Vec4(0.5, 0.5, 0.5, 1)) alightNP = render.attachNewNode(alight) dlight = DirectionalLight('directionalLight') dlight.setDirection(Vec3(1, 1, -1)) dlight.setColor(Vec4(0.7, 0.7, 0.7, 1)) dlightNP = render.attachNewNode(dlight) render.clearLight() render.setLight(alightNP) render.setLight(dlightNP) # Input 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) # Task taskMgr.add(self.update, 'updateWorld') # Physics self.setup()
def createLighting(self): #creates lighting for the scene aLightVal = 0.3 dLightVal1 = -5 dLightVal2 = 5 #set up the ambient light ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(aLightVal, aLightVal, aLightVal, 1)) ambientLight1 = AmbientLight("ambientLight1") ambientLight1.setColor(Vec4(aLightVal, aLightVal, aLightVal, 1)) ambientLight2 = AmbientLight("ambientLight2") ambientLight2.setColor(Vec4(aLightVal, aLightVal, aLightVal, 1)) #sets a directional light directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(dLightVal1, dLightVal1, dLightVal1)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(0, 0, 0, 1)) #sets a directional light directionalLight1 = DirectionalLight("directionalLight2") directionalLight1.setDirection(Vec3(dLightVal2, dLightVal1, dLightVal1)) directionalLight1.setColor(Vec4(1, 1, 1, 1)) directionalLight1.setSpecularColor(Vec4(1, 1, 1, 1)) #attaches lights to scene render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(ambientLight1)) render.setLight(render.attachNewNode(ambientLight1)) render.setLight(render.attachNewNode(directionalLight)) render.setLight(render.attachNewNode(directionalLight1))
def setupLights(self): # Sets up some default lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor((.4, .4, .35, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(LVector3(0, 8, -2.5)) directionalLight.setColor((0.9, 0.8, 0.9, 1)) render.setLight(render.attachNewNode(directionalLight)) render.setLight(render.attachNewNode(ambientLight))
def loadSimpleLighting(self): ambientLight = AmbientLight( "ambientLight" ) ambientLight.setColor( Vec4(.8, .8, .8, 1) ) directionalLight = DirectionalLight( "directionalLight" ) directionalLight.setDirection( Vec3( 0, 45, -45 ) ) directionalLight.setColor( Vec4( 0.2, 0.2, 0.2, 0.6 ) ) render.setLight(render.attachNewNode( directionalLight ) ) render.setLight(render.attachNewNode( ambientLight ) )
def setupLights(self): #This function sets up some default lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.8, .8, .8, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(0, 45, -45)) directionalLight.setColor(Vec4(0.2, 0.2, 0.2, 1)) render.setLight(render.attachNewNode(directionalLight)) render.setLight(render.attachNewNode(ambientLight))
def setupLight(self): ambientLight = AmbientLight("ambientLight") ambientLight.setColor((.8, .8, .8, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(LVector3(0, 45, -45)) directionalLight.setColor((0.2, 0.2, 0.2, 1)) render.setLight(render.attachNewNode(directionalLight)) render.setLight(render.attachNewNode(ambientLight))
def setupLights(self): ambientLight = AmbientLight("ambientLight") ambientLight.setColor((.8, .8, .75, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(LVector3(0, 0, -2.5)) directionalLight.setColor((0.9, 0.8, 0.9, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight))
def __init__(self): __builtin__.main = self self.taskMgr = taskMgr self.base = base # Connect to the server self.cManager = ConnectionManager() self.startConnection() self.characters = dict() self.cpList = dict() base.win.setClearColor(Vec4(0,0,0,1)) self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) self.environ.setPos(0,0,0) self.ralphStartPos = self.environ.find("**/start_point").getPos() # Create a floater object. We use the "floater" as a temporary # variable in a variety of calculations. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) self.accept("escape", sys.exit) # Login as 'CPHandler' # Temporary workaround, can add a seperate request/response for client/NPC client logins later self.name = "CPHandler" factionId = 0 self.cManager.sendRequest(Constants.CMSG_AUTH, [self.name, factionId]) # Create two control points cp1 = ControlPoint(1, -107.575, 0.6066, 0.490075, 10, RED) cp2 = ControlPoint(2, -100.575, -35.6066, 0.090075, 10, BLUE) self.cpList[1] = cp1 self.cpList[2] = cp2 taskMgr.doMethodLater(0.1, self.refresh, "heartbeat") taskMgr.doMethodLater(1, self.CPHandler, 'CPHandler') # Set up the camera base.disableMouse() #base.camera.setPos(self.character.actor.getX(),self.character.actor.getY()+10,2) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight))
def setup_lights(self): ambientLight = AmbientLight('ambient') ambientLight.setColor( Vec4( .5, .5, .5, 1 ) ) render.setLight(render.attachNewNode(ambientLight)) directionalLight = DirectionalLight('directional') directionalLight.setDirection( Vec3( -10, 10, -25 ) ) directionalLight.setColor( Vec4( .1, .1, .1, 1 ) ) render.setLight(render.attachNewNode(directionalLight))
def light(self): ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight))
def setupLights(self): ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.4, .4, .35, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3( 0, 8, -2.5 ) ) directionalLight.setColor(Vec4( 0.9, 0.8, 0.9, 1 ) ) #Set lighting on teapot so spark doesn't get affected self.t.setLight(self.t.attachNewNode(directionalLight)) self.t.setLight(self.t.attachNewNode(ambientLight))
def setupLights(self): ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(0.4, 0.4, 0.35, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(0, 8, -2.5)) directionalLight.setColor(Vec4(0.9, 0.8, 0.9, 1)) render.setLight(render.attachNewNode(directionalLight)) render.setLight(render.attachNewNode(directionalLight)) self.env.setLightOff()
def __init__(self, aCol, dDir, dCol): render.setAttrib(LightRampAttrib.makeHdr1()) ambientLight = AmbientLight("ambientLight") ambientLight.setColor(aCol) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(dDir) directionalLight.setColor(dCol) directionalLight.setSpecularColor(Vec4(2.0, 2.0, 2.0, 0)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight))
def setupLights(self): #This is one area I know hardly anything about. I really don't know how to get this to behave nicely. #The black pieces are hardly distinguishable. ambientLight = AmbientLight( "ambientLight" ) ambientLight.setColor( Vec4(.8, .8, .8, 1) ) directionalLight = DirectionalLight( "directionalLight" ) directionalLight.setDirection( Vec3( 0, 45, -45 ) ) directionalLight.setColor( Vec4( 0.2, 0.2, 0.2, 1 ) ) render.setLight(render.attachNewNode( directionalLight ) ) render.setLight(render.attachNewNode( ambientLight ) )
def __init__(self): base.win.setClearColor(Vec4(0,0,0,1)) # Network Setup print "before" self.cManager = ConnectionManager(self) self.startConnection() print "after" # Set up the environment # self.environ = loader.loadModel("models/square") self.environ.reparentTo(render) self.environ.setPos(0,0,0) self.environ.setScale(100,100,1) self.moon_tex = loader.loadTexture("models/moon_1k_tex.jpg") self.environ.setTexture(self.moon_tex, 1) self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # add spheres earth = Earth(self) sun = Sun(self) venus = Venus(self) controls = Control() chat = Chat(self) player = Ralph(self) # player = Panda(self) # player = Car(self) taskMgr.add(player.move,"moveTask" ) taskMgr.add(sun.rotatePlanets,"rotateSun", extraArgs = [self.player], appendTask = True) taskMgr.add(earth.rotatePlanets,"rotateEarth", extraArgs = [self.player], appendTask = True) taskMgr.add(venus.rotatePlanets,"rotateVenus", extraArgs = [self.player], appendTask = True) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight))
def init(self): # window setup base.win.setClearColor(Vec4(0, 0, 0, 1)) # display instructions addTitle("CS454 HW2") addInstructions(0.95, "[ESC]: Quit") addInstructions(0.90, "[Mouse Move]: Move camera") addInstructions(0.85, "[Mouse Wheel]: Zoom camera") addInstructions(0.80, "[W,A,S,D]: Move character") addInstructions(0.75, "[T]: Open chat box") addInstructions(0.70, "[Y]: Open whisper box") addInstructions(0.65, "[Up,Down]: Select whisper target") addInstructions(0.60, "[Tab]: Show players") # create environment environ = loader.loadModel("models/square") environ.reparentTo(render) environ.setPos(0, 0, 0) environ.setScale(100, 100, 1) environ.setTexture(loader.loadTexture("models/moon_1k_tex.jpg"), 1) # create lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(0.3, 0.3, 0.3, 1)) render.setLight(render.attachNewNode(ambientLight)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(directionalLight)) # accept special keys base.accept("escape", self.exit) base.accept("shift-escape", self.exit) # create spheres sun = Sphere(self, "sun") sun.model.setPos(-15, -15, 8) earth = Sphere(self, "earth") earth.model.setPos(-12, 12, 5) venus = Sphere(self, "venus") venus.model.setPos(10, 10, 3.5) # track game entities self.character = None self.player = None self.camera = None self.characters = {} self.chat = Chat(self) self.playerList = PlayerList(self)
def setupLights(self): ambientLight = AmbientLight("ambiengtLight") ambientLight.setColor((0.4, 0.4, 0.35, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(LVector3(0, 8, -2.5)) directionalLight.setColor((0.9, 0.8, 0.9, 1)) directionalLight.setColor((0.9, 0.8, 0.9, 1)) self.teapot.setLight(self.teapot.attachNewNode(directionalLight)) self.teapot.setLight(self.teapot.attachNewNode(ambientLight))
def __init__(self): base.setBackgroundColor(0.1, 0.1, 0.5, 1) base.setFrameRateMeter(True) base.cam.setPos(0, -20, 5) base.cam.lookAt(0, 0, 0) base.disableMouse() self.zoom = 50; self.viewPoint = "FRONT" # Light alight = AmbientLight('ambientLight') alight.setColor(Vec4(0.5, 0.5, 0.5, 1)) alightNP = render.attachNewNode(alight) dlight = DirectionalLight('directionalLight') dlight.setDirection(Vec3(1, 1, -1)) dlight.setColor(Vec4(0.7, 0.7, 0.7, 1)) dlightNP = render.attachNewNode(dlight) render.clearLight() render.setLight(alightNP) render.setLight(dlightNP) #bot self.ankleJont = 0 self.foot = 0 self.kneeJoint = 0 self.hipKneeJoint = 0 # Input 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('enter', self.doShoot) self.accept('a',self.setAngleMax) self.accept('o',self.setAngleMin) self.accept('1', self.setViewPointTOP) self.accept('2', self.setViewPointFRONT) self.accept('3', self.setViewPointLEFT) self.accept('4', self.setViewPointDIAG) self.accept('b', self.setZoomInc) self.accept('m', self.setZoomDec) # Task taskMgr.add(self.update, 'updateWorld') # Physics self.setup()
def setupLights(self): # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight1 = DirectionalLight("directionalLight") directionalLight1.setDirection(Vec3(5, 5, -5)) directionalLight1.setColor(Vec4(1, 1, 1, 1)) directionalLight1.setSpecularColor(Vec4(1, 1, 1, 1)) directionalLight2 = DirectionalLight("directionalLight") directionalLight2.setDirection(Vec3(5, -5, -5)) directionalLight2.setColor(Vec4(1, 1, 1, 1)) directionalLight2.setSpecularColor(Vec4(1, 1, 1, 1)) directionalLight3 = DirectionalLight("directionalLight") directionalLight3.setDirection(Vec3(-5, -5, -5)) directionalLight3.setColor(Vec4(1, 1, 1, 1)) directionalLight3.setSpecularColor(Vec4(1, 1, 1, 1)) directionalLight4 = DirectionalLight("directionalLight") directionalLight4.setDirection(Vec3(-5, 5, -5)) directionalLight4.setColor(Vec4(1, 1, 1, 1)) directionalLight4.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight1)) render.setLight(render.attachNewNode(directionalLight2)) render.setLight(render.attachNewNode(directionalLight3)) render.setLight(render.attachNewNode(directionalLight4))
def setupLights(self): # Light alight = AmbientLight('ambientLight') alight.setColor(Vec4(0.5, 0.5, 0.5, 1)) alightNP = render.attachNewNode(alight) dlight = DirectionalLight('directionalLight') dlight.setDirection(Vec3(1, 1, -1)) dlight.setColor(Vec4(0.7, 0.7, 0.7, 1)) dlightNP = render.attachNewNode(dlight) self.render.clearLight() self.render.setLight(alightNP) self.render.setLight(dlightNP)
def setupLights(self): #Create some lights and add them to the scene. By setting the lights on #render they affect the entire scene #Check out the lighting tutorial for more information on lights ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.4, .4, .35, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(0, 8, -2.5)) directionalLight.setColor(Vec4(0.9, 0.8, 0.9, 1)) render.setLight(render.attachNewNode(directionalLight)) render.setLight(render.attachNewNode(ambientLight)) #Explicitly set the environment to not be lit self.env.setLightOff()
def __init__(self): base.setBackgroundColor(0.1, 0.1, 0.8, 1) base.setFrameRateMeter(True) base.cam.setPos(0, -20, 4) base.cam.lookAt(0, 0, 0) # Light alight = AmbientLight('ambientLight') alight.setColor(Vec4(0.5, 0.5, 0.5, 1)) alightNP = render.attachNewNode(alight) dlight = DirectionalLight('directionalLight') dlight.setDirection(Vec3(1, 1, -1)) dlight.setColor(Vec4(0.7, 0.7, 0.7, 1)) dlightNP = render.attachNewNode(dlight) render.clearLight() render.setLight(alightNP) render.setLight(dlightNP) # Input 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('1', self.doSelect, [0,]) self.accept('2', self.doSelect, [1,]) self.accept('3', self.doSelect, [2,]) self.accept('4', self.doSelect, [3,]) self.accept('5', self.doSelect, [4,]) self.accept('6', self.doSelect, [5,]) inputState.watchWithModifiers('forward', 'w') inputState.watchWithModifiers('left', 'a') inputState.watchWithModifiers('reverse', 's') inputState.watchWithModifiers('right', 'd') inputState.watchWithModifiers('turnLeft', 'q') inputState.watchWithModifiers('turnRight', 'e') # Task taskMgr.add(self.update, 'updateWorld') # Physics self.setup()
def __init__(self): self.root = render.attachNewNode("Root") base.setBackgroundColor(0,0,0) # This code puts the standard title and instruction text on screen self.title = OnscreenText(text="Ball In Maze", style=1, fg=(1,1,0,1), pos=(0.7,-0.95), scale = .07) self.instructions = OnscreenText(text="Press Esc to exit", pos = (-1.3, .95), fg=(1,1,0,1), align = TextNode.ALeft, scale = .05) self.central_msg = OnscreenText(text="", pos = (0, 0), fg=(1, 1, 0, 1), scale = .1 ) self.central_msg.hide() self.accept("escape", sys.exit) # Escape quits base.disableMouse() # Disable mouse-based camera control camera.setPosHpr(0, 0, 25, 0, -90, 0) # Place the camera # Load the maze and place it in the scene self.maze = loader.loadModel("models/maze") self.maze.reparentTo(render) # Load the ball and attach it to the scene # It is on a root dummy node so that we can rotate the ball itself without # rotating the ray that will be attached to it self.ballRoot = render.attachNewNode("ballRoot") self.ball = loader.loadModel("models/ball") self.ball.reparentTo(self.ballRoot) # This section deals with lighting for the ball. Only the ball was lit # because the maze has static lighting pregenerated by the modeler ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.55, .55, .55, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(0, 0, -1)) directionalLight.setColor(Vec4(0.375, 0.375, 0.375, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) self.ballRoot.setLight(render.attachNewNode(ambientLight)) self.ballRoot.setLight(render.attachNewNode(directionalLight)) # This section deals with adding a specular highlight to the ball to make # it look shiny m = Material() m.setSpecular(Vec4(1,1,1,1)) m.setShininess(96) self.ball.setMaterial(m, 1)
def init_lights(self): print("-- init lights") # Light alight = AmbientLight('ambientLight') alight.setColor(Vec4(0.1, 0.1, 0.1, 1)) alightNP = render.attachNewNode(alight) dlight = DirectionalLight('directionalLight') dlight.setDirection(Vec3(1, 1, -1)) dlight.setColor(Vec4(0.7, 0.7, 0.7, 1)) dlightNP = render.attachNewNode(dlight) render.clearLight() render.setLight(alightNP) render.setLight(dlightNP)
def start(self, myPlayerName, players): """ Takes a list of player names and positions, initializes the players and sets up the scene """ # Load the environment model. self.levelNode = render.attachNewNode("Level node") self.level = LevelContainer(self.levelName) self.level.render(self.levelNode, base.loader) self.levelNode.setAttrib(ShadeModelAttrib.make(ShadeModelAttrib.MFlat)) base.win.setClearColor(Vec4(0,0,0,1)) self.title = addTitle("PushBack") self.players = dict() self.playersNode = render.attachNewNode("Players Root Node") self.healthbar = DirectWaitBar(range=1.0, barColor=(1.0, 0.0, 0.0, 1.0), value=1.0, frameSize=(-0.45,0.45,1.0,0.98)) base.disableMouse() base.cam.reparentTo(self.playersNode) base.cam.setCompass() base.cam.setH(0) base.cam.setZ(CAM_HEIGHT) base.cam.setY(-CAM_HEIGHT) base.cam.setP(-CAM_ANGLE) ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight)) skins = ["stony_green", "stony_red", "stony_blue", "bonbon_blue","bonbon_green", "red", "pushette", "blue"] for player in players: print "Init player %s" % player[0] p = Player(player[0]) p.reparentTo(self.playersNode) p.setPos(player[1]) p.setColor(skins.pop()) self.players[player[0]] = p if myPlayerName == player[0]: self.myPlayer = p base.cam.reparentTo(self.myPlayer)
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 __init__(self): base.setBackgroundColor(0.1, 0.1, 0.8, 1) base.setFrameRateMeter(True) base.cam.setPos(0, -20, 4) base.cam.lookAt(0, 0, 0) # Light alight = AmbientLight("ambientLight") alight.setColor(Vec4(0.5, 0.5, 0.5, 1)) alightNP = render.attachNewNode(alight) dlight = DirectionalLight("directionalLight") dlight.setDirection(Vec3(1, 1, -1)) dlight.setColor(Vec4(0.7, 0.7, 0.7, 1)) dlightNP = render.attachNewNode(dlight) render.clearLight() render.setLight(alightNP) render.setLight(dlightNP) # Input 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('space', self.doJump) # self.accept('c', self.doCrouch) inputState.watchWithModifiers("forward", "w") inputState.watchWithModifiers("left", "a") inputState.watchWithModifiers("reverse", "s") inputState.watchWithModifiers("right", "d") inputState.watchWithModifiers("turnLeft", "q") inputState.watchWithModifiers("turnRight", "e") # Task taskMgr.add(self.update, "updateWorld") # Physics self.setup()
def __init__(self): base.setBackgroundColor(0.1, 0.1, 0.8, 1) base.setFrameRateMeter(True) base.cam.setPos(0, -10, 5) base.cam.lookAt(0, 0, 0.2) # Light alight = AmbientLight('ambientLight') alight.setColor(Vec4(0.5, 0.5, 0.5, 1)) alightNP = render.attachNewNode(alight) dlight = DirectionalLight('directionalLight') dlight.setDirection(Vec3(1, 1, -1)) dlight.setColor(Vec4(0.7, 0.7, 0.7, 1)) dlightNP = render.attachNewNode(dlight) render.clearLight() render.setLight(alightNP) render.setLight(dlightNP) # Input 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) inputState.watchWithModifiers('up', 'w') inputState.watchWithModifiers('left', 'a') inputState.watchWithModifiers('down', 's') inputState.watchWithModifiers('right', 'd') # Task taskMgr.add(self.update, 'updateWorld') # Physics self.setup()
def __init__(self): #Load switch model self.glowswitch = loader.loadModel("glowswitch") self.sphere=self.glowswitch.find("**/sphere") #finds a subcomponent of the .egg model... sphere is the name of the sphere geometry in the .egg file self.glowswitch.reparentTo(render) base.disableMouse() #mouse-controlled camera cannot be moved within the program camera.setPosHpr( 0, -6.5, 1.4, 0, -2, 0) #Light up everything an equal amount ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.95, .95, 1.05, 1)) render.setLight(render.attachNewNode(ambientLight)) #Add lighting that only casts light on one side of everything in the scene directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(.2, .2, .2, .1)) #keepin it dim directionalLight.setSpecularColor(Vec4(0.2, 0.2, 0.2, 0.2)) render.setLight(render.attachNewNode(directionalLight)) #initalize sequence variable self.ChangeColorSeq = Sequence(Wait(.1)) #start with blue by default self.changeOrbColor(.1,0,.6,.3,.2,1) #^(R min, Gmin, Bmin, Rmax, Gmax, Bmax) #user controls #note that changing the color means it will "pulse" that color and therefore needs a range of color values self.accept("1", self.changeOrbColor,[.6,.1,.1,1,.3,.3]) #change orb color to red self.accept("2", self.changeOrbColor,[.1,.6,.1,.3,1,.3])#change orb color to green self.accept("3", self.changeOrbColor,[.1,0,.6,.3,.2,1]) #change orb color to blue self.accept("escape", sys.exit) instructions = OnscreenText(text="1: Change to red \n2: Change to Green \n3: Change to Blue \nEsc: Exit", fg=(1,1,1,1), pos = (-1.3, -.82), scale = .05, align = TextNode.ALeft)
def loadBall(self): self.ballRoot = render.attachNewNode("ballRoot") self.ball = load_model("ball") self.ball.reparentTo(self.ballRoot) self.ball_tex = load_tex("pokeball.png") self.ball.setTexture(self.ball_tex,1) self.ball.setScale(0.8) # Find the collision sphere for the ball in egg. self.ballSphere = self.ball.find("**/ball") self.ballSphere.node().setFromCollideMask(BitMask32.bit(0)) self.ballSphere.node().setIntoCollideMask(BitMask32.allOff()) #self.ballSphere.show() # Now we create a ray to cast down at the ball. self.ballGroundRay = CollisionRay() self.ballGroundRay.setOrigin(0,0,10) self.ballGroundRay.setDirection(0,0,-1) # Collision solids go in CollisionNode self.ballGroundCol = CollisionNode('groundRay') self.ballGroundCol.addSolid(self.ballGroundRay) self.ballGroundCol.setFromCollideMask(BitMask32.bit(1)) self.ballGroundCol.setIntoCollideMask(BitMask32.allOff()) self.ballGroundColNp = self.ballRoot.attachNewNode(self.ballGroundCol) # light ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.55, .55, .55, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(0,0,-1)) directionalLight.setColor(Vec4(0.375,0.375,0.375,1)) directionalLight.setSpecularColor(Vec4(1,1,1,1)) self.ballRoot.setLight(render.attachNewNode(ambientLight)) self.ballRoot.setLight(render.attachNewNode(directionalLight)) # material to the ball m = Material() m.setSpecular(Vec4(1,1,1,1)) m.setShininess(96) self.ball.setMaterial(m,1)
def initialize(self): Viewport.initialize(self) self.flyCam = FlyCam(self) self.lens.setFov(90) self.lens.setNearFar(0.1, 5000) # Set a default camera position + angle self.camera.setPos(193, 247, 124) self.camera.setHpr(143, -18, 0) from panda3d.core import DirectionalLight, AmbientLight dlight = DirectionalLight('dlight') dlight.setColor((0.35, 0.35, 0.35, 1)) dlnp = self.doc.render.attachNewNode(dlight) direction = -Vec3(1, 2, 3).normalized() dlight.setDirection(direction) self.doc.render.setLight(dlnp) self.dlnp = dlnp alight = AmbientLight('alight') alight.setColor((0.65, 0.65, 0.65, 1)) alnp = self.doc.render.attachNewNode(alight) self.doc.render.setLight(alnp)
def __init__(self): base.setBackgroundColor(0.1, 0.1, 0.8, 1) base.setFrameRateMeter(True) base.cam.setPos(0, -40, 10) base.cam.lookAt(0, 0, 5) # Light alight = AmbientLight('ambientLight') alight.setColor(Vec4(0.5, 0.5, 0.5, 1)) alightNP = render.attachNewNode(alight) dlight = DirectionalLight('directionalLight') dlight.setDirection(Vec3(1, 1, -1)) dlight.setColor(Vec4(0.7, 0.7, 0.7, 1)) dlightNP = render.attachNewNode(dlight) render.clearLight() render.setLight(alightNP) render.setLight(dlightNP) # Input 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('1', self.doShoot, [True]) self.accept('2', self.doShoot, [False]) # Task taskMgr.add(self.update, 'updateWorld') # Physics self.setup()
def __init__(self): self.individuos = [] base.setBackgroundColor(0.1, 0.1, 0.8, 1) base.setFrameRateMeter(True) base.cam.setPos(0, -40, 10) base.cam.lookAt(0, 0, 5) # Light alight = AmbientLight('ambientLight') alight.setColor(Vec4(0.5, 0.5, 0.5, 1)) alightNP = render.attachNewNode(alight) dlight = DirectionalLight('directionalLight') dlight.setDirection(Vec3(1, 1, -1)) dlight.setColor(Vec4(0.7, 0.7, 0.7, 1)) dlightNP = render.attachNewNode(dlight) render.clearLight() render.setLight(alightNP) render.setLight(dlightNP) # Input 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('arrow_right-repeat', self.doMove) # Task # https://www.panda3d.org/manual/?title=Tasks taskMgr.add(self.update, 'updateWorld') # Physics self.setup()
def __init__(self): # Setup window size, title and so on load_prc_file_data( "", """ win-size 1600 900 window-title Render Pipeline - Roaming Ralph Demo """) if alt: ShowBase.__init__(self) self.render_pipeline = render_pipeline self.render_pipeline.create(self) else: # ------ Begin of render pipeline code (else case) ------ # Insert the pipeline path to the system path, this is required to be # able to import the pipeline classes #pipeline_path = "../../" # Just a special case for my development setup, so I don't accidentally # commit a wrong path. You can remove this in your own programs. #if not os.path.isfile(os.path.join(pipeline_path, "setup.py")): pipeline_path = "../tobsprRenderPipeline" sys.path.insert(0, pipeline_path) from rpcore import RenderPipeline, SpotLight self.render_pipeline = RenderPipeline() self.render_pipeline.create(self) # ------ End of render pipeline code, thats it! ------ # Set time of day self.render_pipeline.daytime_mgr.time = "7:40" # Use a special effect for rendering the scene, this is because the # roaming ralph model has no normals or valid materials self.render_pipeline.set_effect( render, "roaming_ralph_pipeline_scene-effect.yaml", {}, sort=250) self.keyMap = { "left": 0, "right": 0, "forward": 0, "backward": 0, "cam-left": 0, "cam-right": 0 } self.speed = 1.0 base.win.setClearColor(Vec4(0, 0, 0, 1)) # Post the instructions self.inst1 = addInstructions(0.95, "[ESC] Quit") self.inst4 = addInstructions(0.90, "[W] Run Ralph Forward") self.inst4 = addInstructions(0.85, "[S] Run Ralph Backward") self.inst2 = addInstructions(0.80, "[A] Rotate Ralph Left") self.inst3 = addInstructions(0.75, "[D] Rotate Ralph Right") self.inst6 = addInstructions(0.70, "[Left Arrow] Rotate Camera Left") self.inst7 = addInstructions(0.65, "[Right Arrow] Rotate Camera Right") # Set up the environment # # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel( "roaming_ralph_pipeline_resources/world") self.environ.reparentTo(render) self.environ.setPos(0, 0, 0) # Remove wall nodes self.environ.find("**/wall").remove_node() # Create the main character, Ralph self.ralph = Actor( "roaming_ralph_pipeline_resources/ralph", { "run": "roaming_ralph_pipeline_resources/ralph-run", "walk": "roaming_ralph_pipeline_resources/ralph-walk" }) self.ralph.reparentTo(render) self.ralph.setScale(.2) self.ralph.setPos(Vec3(-110.9, 29.4, 1.8)) # Create a floater object. We use the "floater" as a temporary # variable in a variety of calculations. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # Accept the control keys for movement and rotation self.accept("escape", sys.exit) self.accept("a", self.setKey, ["left", 1]) self.accept("d", self.setKey, ["right", 1]) self.accept("w", self.setKey, ["forward", 1]) self.accept("s", self.setKey, ["backward", 1]) self.accept("arrow_left", self.setKey, ["cam-left", 1]) self.accept("arrow_right", self.setKey, ["cam-right", 1]) self.accept("a-up", self.setKey, ["left", 0]) self.accept("d-up", self.setKey, ["right", 0]) self.accept("w-up", self.setKey, ["forward", 0]) self.accept("s-up", self.setKey, ["backward", 0]) self.accept("arrow_left-up", self.setKey, ["cam-left", 0]) self.accept("arrow_right-up", self.setKey, ["cam-right", 0]) self.accept("=", self.adjustSpeed, [0.25]) self.accept("+", self.adjustSpeed, [0.25]) self.accept("-", self.adjustSpeed, [-0.25]) taskMgr.add(self.move, "moveTask") # Game state variables self.isMoving = False # Set up the camera base.disableMouse() base.camera.setPos(self.ralph.getX() + 10, self.ralph.getY() + 10, 2) base.camLens.setFov(80) # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. One ray will # start above ralph's head, and the other will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal. self.cTrav = CollisionTraverser() self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0, 0, 1000) self.ralphGroundRay.setDirection(0, 0, -1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0)) self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff()) self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol) self.ralphGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler) self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0, 0, 1000) self.camGroundRay.setDirection(0, 0, -1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(BitMask32.bit(0)) self.camGroundCol.setIntoCollideMask(BitMask32.allOff()) self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Uncomment this line to see the collision rays #self.ralphGroundColNp.show() #self.camGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring #self.cTrav.showCollisions(render) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight))
def __init__(self): ## Add the default values to the dictionary. self.keyMap = {"left":0, "right":0, "forward":0, \ "boost":0, "strafeL":0, "strafeR":0, \ "cam-left":0, "cam-right":0} base.win.setClearColor(Vec4(0, 0, 0, 1)) self.jump = False self.jumped = False # Post the instructions self.title = addTitle( "Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)") self.inst1 = addInstructions(0.95, "[ESC]: Quit") self.inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left") self.inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right") self.inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward") self.inst6 = addInstructions(0.70, "[A]: Rotate Camera Left") self.inst7 = addInstructions(0.65, "[D]: Rotate Camera Right") self.inst8 = addInstructions(0.60, "[B]: Ralph Boost") self.inst9 = addInstructions(0.55, "[V]: Strafe Left") self.inst10 = addInstructions(0.50, "[N]: Strafe Right") # Set up the environment # # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) self.environ.setPos(0, 0, 0) ## Stops the sound as soon as the world renders ## Note:Sound won't play very long becasue the game takes seconds to compile and load ## Remove loading screen after world is rendered and ready to go. loadingText.cleanup() mySound.stop() # Create the main character, Ralph ralphStartPos = self.environ.find("**/start_point").getPos() self.ralph = Actor("models/ralph", { "run": "models/ralph-run", "walk": "models/ralph-walk" }) self.ralph.reparentTo(render) self.ralph.setScale(.2) self.ralph.setPos(ralphStartPos) # Create a floater object. We use the "floater" as a temporary # variable in a variety of calculations. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # Accept the control keys for movement and rotation self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", 1]) self.accept("arrow_right", self.setKey, ["right", 1]) self.accept("arrow_up", self.setKey, ["forward", 1]) self.accept("a", self.setKey, ["cam-left", 1]) self.accept("d", self.setKey, ["cam-right", 1]) self.accept("b", self.setKey, ["boost", 1]) self.accept("v", self.setKey, ["strafeL", 1]) self.accept("n", self.setKey, ["strafeR", 1]) ## -up to signify what happens when you let go of the key self.accept("b-up", self.setKey, ["boost", 0]) self.accept("v-up", self.setKey, ["strafeL", 0]) self.accept("n-up", self.setKey, ["strafeR", 0]) self.accept("arrow_left-up", self.setKey, ["left", 0]) self.accept("arrow_right-up", self.setKey, ["right", 0]) self.accept("arrow_up-up", self.setKey, ["forward", 0]) self.accept("a-up", self.setKey, ["cam-left", 0]) self.accept("d-up", self.setKey, ["cam-right", 0]) taskMgr.add(self.move, "moveTask") # Game state variables self.isMoving = False # Set up the camera base.disableMouse() base.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2) # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. One ray will # start above ralph's head, and the other will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal. self.cTrav = CollisionTraverser() self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0, 0, 1000) self.ralphGroundRay.setDirection(0, 0, -1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0)) self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff()) self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol) self.ralphGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler) self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0, 0, 1000) self.camGroundRay.setDirection(0, 0, -1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(BitMask32.bit(0)) self.camGroundCol.setIntoCollideMask(BitMask32.allOff()) self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Uncomment this line to see the collision rays #self.ralphGroundColNp.show() #self.camGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring #self.cTrav.showCollisions(render) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight))
def __init__(self): self.keyMap = { "left": 0, "right": 0, "forward": 0, "cam-left": 0, "cam-right": 0 } base.win.setClearColor(Vec4(0, 0, 0, 1)) self.speed = 0 self.font_digital = loader.loadFont('font/SFDigitalReadout-Heavy.ttf') # Speedometer self.speed_img = OnscreenImage(image="models/speedometer.png", scale=.5, pos=(1.1, 0, -.95)) self.speed_img.setTransparency(TransparencyAttrib.MAlpha) OnscreenText(text="km\n/h", style=1, fg=(1, 1, 1, 1), font=self.font_digital, scale=.07, pos=(1.25, -.92)) # Display Speed self.display_speed = OnscreenText(text=str(self.speed), style=1, fg=(1, 1, 1, 1), pos=(1.3, -0.95), align=TextNode.ARight, scale=.07, font=self.font_digital) # Health Bar self.bars = {'H': 100, 'EH': 0, 'A': 0} # bk_text = "This is my Demo" # self.textObject = OnscreenText(text = bk_text, pos = (0.55,-0.05),scale = 0.07,fg=(1,0.5,0.5,1),align=TextNode.ACenter,mayChange=1) self.Health_bar = DirectWaitBar(text="", value=100, pos=(0.280, 0, 0.475), barColor=(1, 0, 0, 1), frameSize=(0, .705, .3, .35)) self.EHealth_bar = DirectWaitBar(text="", value=0, pos=(1, 0, 0.475), barColor=(0, 1, 0, 1), frameSize=(0, .23, .3, .35), range=50) self.Armour_bar = DirectWaitBar(text="", value=0, pos=(.43, 0, .593), barColor=(159, 0, 255, 1), frameSize=(0, .8, .3, .35)) # self.bar = DirectWaitBar(text = "hi", # value = 0, # range = 500, # pos = ( 0,0,0), # barColor = (0.97,0,0,1), # frameSize = (-0.3,0.3,0.5,0.8), # text_mayChange = 1, # text_shadow =(0,0,0,0.8), # text_fg = (0.9,0.9,0.9,1), # text_scale = 0.025, # text_pos = (0,0.01,0)) def getHealthStatus(): return self.bars def displayBars(): health = getHealthStatus() self.Health_bar['value'] = health['H'] self.EHealth_bar['value'] = health['EH'] self.Armour_bar['value'] = health['A'] def armourPickup(): self.bars['A'] += 25 displayBars() def healthPickup(): self.bars['EH'] += 25 displayBars() def decHealth(): self.bars['H'] -= 10 displayBars() # Post the instructions self.frame = OnscreenImage(image="models/gframe.png", pos=(0, 0, 0), scale=(1.25, 1, 1)) self.frame.setTransparency(TransparencyAttrib.MAlpha) # self.title = addTitle("Panda3D Tutorial: Roaming Ralph (Walking on the Moon)") self.inst1 = addInstructions(0.95, "[ESC]: Quit") self.inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left") self.inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right") self.inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward") self.inst6 = addInstructions(0.70, "[A]: Rotate Camera Left") self.inst7 = addInstructions(0.65, "[S]: Rotate Camera Right") # Set up the environment # self.environ = loader.loadModel("models/square") self.environ.reparentTo(render) self.environ.setPos(0, 0, 0) self.environ.setScale(100, 100, 1) self.moon_tex = loader.loadTexture("models/moon_1k_tex.jpg") self.environ.setTexture(self.moon_tex, 1) # Create the main character, Ralph self.ralph = Actor("models/ralph", { "run": "models/ralph-run", "walk": "models/ralph-walk" }) self.ralph.reparentTo(render) self.ralph.setScale(.2) self.ralph.setPos(0, 0, 0) # Create a floater object. We use the "floater" as a temporary # variable in a variety of calculations. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # Accept the control keys for movement and rotation self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", 1]) self.accept("arrow_right", self.setKey, ["right", 1]) self.accept("arrow_up", self.setKey, ["forward", 1]) self.accept("a", self.setKey, ["cam-left", 1]) self.accept("s", self.setKey, ["cam-right", 1]) self.accept("arrow_left-up", self.setKey, ["left", 0]) self.accept("arrow_right-up", self.setKey, ["right", 0]) self.accept("arrow_up-up", self.setKey, ["forward", 0]) self.accept("a-up", self.setKey, ["cam-left", 0]) self.accept("s-up", self.setKey, ["cam-right", 0]) self.accept("h", decHealth) self.accept("j", healthPickup) self.accept("k", armourPickup) taskMgr.add(self.move, "moveTask") taskMgr.doMethodLater(.1, self.show_speed, 'updateSpeed') # Game state variables self.isMoving = False # Set up the camera base.disableMouse() base.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight)) self.audioManager = Audio(self) self.audioManager.startAudioManager() self.audioManager.initialiseSound(self.ralph)
class ReflectiveBody(StellarBody): def __init__(self, *args, **kwargs): shadow = kwargs.pop('shadow', True) self.albedo = kwargs.pop('albedo', 0.5) StellarBody.__init__(self, *args, **kwargs) self.sunLight = None self.has_shadow_map = False self.has_shadows = False self.has_shadows_persistent = False self.cast_shadows = False self.custom_shadows = False self.shadow_caster = None self.shadow_camera = None if (shadow or self.ring is not None) and settings.allow_shadows: self.has_shadow_map = True if self.surface is not None: self.custom_shadows = self.surface.shader is not None def is_emissive(self): return False def create_surface(self): StellarBody.create_surface(self) self.custom_shadows = self.surface.shader is not None def get_abs_magnitude(self): luminosity = self.get_luminosity() * self.get_phase() if luminosity > 0.0: return lum_to_abs_mag(luminosity) else: return 99.0 def get_luminosity(self): if self.star is None or self.distance_to_star is None: return 0.0 star_power = self.star.get_luminosity() area = 4 * pi * self.distance_to_star * self.distance_to_star * 1000 * 1000 if area > 0.0: irradiance = star_power / area surface = 4 * pi * self.get_apparent_radius() * self.get_apparent_radius() * 1000 * 1000 received_energy = irradiance * surface reflected_energy = received_energy * self.albedo return reflected_energy else: print("No area") return 0.0 def get_phase(self): if self.vector_to_obs is None or self.vector_to_star is None: return 0.0 angle = self.vector_to_obs.dot(self.vector_to_star) phase = (1.0 + angle) / 2.0 return phase def check_cast_shadow_on(self, body): position = self.get_local_position() body_position = body.get_local_position() pa = body_position - position distance_vector = pa - self.vector_to_star * self.vector_to_star.dot(pa) distance = distance_vector.length() projected = self.vector_to_star * self.vector_to_star.dot(body_position) face = self.vector_to_star.dot(projected - position) return face < 0.0 and distance < self.get_apparent_radius() + body.get_apparent_radius() def update(self, time): StellarBody.update(self, time) self.cast_shadows = False if self.ring is not None and self.visible and self.resolved and self.in_view: self.has_shadows = True self.cast_shadows = True #Only support shadows in a Simple System primary = self.parent.primary if primary is None: return if primary == self: for child in self.parent.children: if child != self and child.has_shadow_map and child.visible and child.resolved and child.in_view: if self.check_cast_shadow_on(child): child.has_shadows = True self.cast_shadows = True else: if isinstance(primary, ReflectiveBody) and primary.has_shadow_map and primary.visible and primary.resolved and primary.in_view: if self.check_cast_shadow_on(primary): primary.has_shadows = True self.cast_shadows = True def create_shadow_caster(self): if self.custom_shadows: print("Create custom shadow caster for", self.get_name()) self.shadow_caster = ShadowCaster(settings.shadow_size) self.shadow_caster.create() self.shadow_camera = self.shadow_caster.node #TODO: should be done in surface self.surface.appearance.set_shadow(self.shadow_caster) if self.surface.instance_ready: self.surface.shader.apply(self.surface.shape, self.surface.appearance) if self.ring is not None: self.ring.appearance.set_shadow(self.shadow_caster) if self.ring.instance_ready: self.ring.shader.apply(self.ring.shape, self.ring.appearance) else: print("Create Panda3D shadow caster") self.dir_light.setShadowCaster(True, settings.shadow_size, settings.shadow_size) self.shadow_caster = self.dir_light self.shadow_camera = self.dir_light if settings.debug_shadow_frustum: self.shadow_camera.showFrustum() self.shadow_camera.set_camera_mask(DrawMask(1)) def update_shadow_caster(self): radius = self.get_extend() / settings.scale self.shadow_caster.get_lens().set_film_size(radius * 2.1, radius * 2.1) self.shadow_caster.get_lens().setNear(-self.context.observer.infinity) self.shadow_caster.get_lens().setFar(self.context.observer.infinity) self.shadow_caster.get_lens().set_view_vector(LVector3(*-self.vector_to_star), LVector3.up()) if self.custom_shadows: self.shadow_caster.set_pos(self.sunLight.getPos()) def remove_shadow_caster(self): if self.custom_shadows: if self.shadow_caster is not None: print("Remove custom shadow caster", self.get_name()) self.shadow_caster.remove() #TODO: Temporary until all dangling instance references have been removed self.surface.appearance.set_shadow(None) self.surface.shader.apply(self.surface.shape, self.surface.appearance) if self.ring is not None: self.ring.appearance.set_shadow(None) self.ring.shader.apply(self.ring.shape, self.ring.appearance) else: self.dir_light.setShadowCaster(False) self.shadow_caster = None self.shadow_camera = None def create_light(self): print("Create light for", self.get_name()) self.dir_light = DirectionalLight('sunLight') self.dir_light.setDirection(LVector3(*-self.vector_to_star)) self.dir_light.setColor((1, 1, 1, 1)) self.sunLight = self.context.world.attachNewNode(self.dir_light) self.set_light(self.sunLight) def update_light(self, camera_pos): pos = self.get_local_position() + self.vector_to_star * self.get_extend() self.place_pos_only(self.sunLight, pos, camera_pos, self.distance_to_obs, self.vector_to_obs) self.dir_light.setDirection(LVector3(*-self.vector_to_star)) def remove_light(self): self.sunLight.remove_node() self.sunLight = None self.dir_light = None def create_components(self): StellarBody.create_components(self) if self.sunLight is None: self.create_light() self.update_shader() def update_components(self, camera_pos): if self.sunLight is not None: self.update_light(camera_pos) if self.shadow_caster is not None: self.update_shadow_caster() def remove_components(self): if self.shadow_caster is not None: self.remove_shadow_caster() #TODO: Temporary until all dangling instance references have been removed self.surface.appearance.set_shadow(None) self.update_shader() if self.sunLight is not None: self.remove_light() self.update_shader() StellarBody.remove_components(self) def check_and_update_instance(self, camera_pos, orientation, pointset): StellarBody.check_and_update_instance(self, camera_pos, orientation, pointset) if self.visible and self.in_view and self.resolved: if self.has_shadow_map and self.has_shadows and self.shadow_caster is None: self.create_shadow_caster() self.update_shader() if self.has_shadow_map and not self.has_shadows and self.shadow_caster is not None: self.remove_shadow_caster() self.update_shader() self.has_shadows_persistent = self.has_shadows self.has_shadows = False
def __init__(self): self.startvar = 0 self.startdialog = YesNoDialog(dialogName="START GAME", text="START GAME", command=self.endbox) self.timepass = model() self.timepass1 = model1() self.keyMap = {"left": 0, "right": 0, "forward": 0, "backward": 0} base.win.setClearColor(Vec4(0, 0, 0, 1)) # number of collectibles self.numObjects = 0 #music self.backmusic = base.loader.loadSfx("sounds/tales.mp3") self.backmusic.setLoop(True) self.backmusic.setVolume(0.2) self.backmusic.play() self.skatemusic = base.loader.loadSfx("sounds/skate.mp3") self.skatemusic.setVolume(.65) self.skatemusic.setLoop(True) self.bombmusic = base.loader.loadSfx("sounds/bomb.mp3") self.bombmusic.setVolume(.85) self.springmusic = base.loader.loadSfx("sounds/spring.mp3") self.springmusic.setVolume(.65) self.springmusic.setLoop(True) self.colmusic = base.loader.loadSfx("sounds/collect.mp3") self.colmusic.setVolume(.65) # print the number of objects printNumObj(self.numObjects) # Post the instructions # self.title = addTitle("Roaming Ralph (Edited by Adam Gressen)") # self.inst1 = addInstructions(0.95, "[ESC]: Quit") # self.inst2 = addInstructions(0.90, "[A]: Rotate Ralph Left") # self.inst3 = addInstructions(0.85, "[D]: Rotate Ralph Right") # self.inst4 = addInstructions(0.80, "[W]: Run Ralph Forward") # self.inst5 = addInstructions(0.75, "[S]: Run Ralph Backward") # self.inst6 = addInstructions(0.70, "[Space]: Run, Ralph, Run") # Set up the environment # # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) self.environ.setPos(0, 0, 0) # Timer to increment in the move task self.time = 0 # Get bounds of environment min, max = self.environ.getTightBounds() self.mapSize = max - min # Create the main character, Ralph self.ralphStartPos = self.environ.find("**/start_point").getPos() self.ralph = Actor( "models/ralph", { "run": "models/ralph-run", "jump": "models/ralph-jump", "walk": "models/ralph-walk" }) self.ralph.reparentTo(render) self.ralph.setScale(.30) self.ralph.setPos(self.ralphStartPos) #skate self.skate = loader.loadModel("models/Skateboard") self.skate.reparentTo(render) self.skate.setScale(.02) self.skate.setPos(-random.randint(38, 50), -random.randint(15, 37), -0.015) # ralph's health self.health = 100 #spring self.spring = loader.loadModel("models/spring") self.spring.reparentTo(render) self.spring.setScale(.8) self.spring.setPos(-random.randint(72, 78), -random.randint(10, 15), 6.715) # ralph's stamina self.stamina = 100 # Create a floater object. We use the "floater" as a temporary # variable in a variety of calculations. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # Accept the control keys for movement and rotation self.accept("escape", sys.exit) # these don't work well in combination with the space bar self.accept("arrow_left", self.setKey, ["left", 1]) self.accept("arrow_right", self.setKey, ["right", 1]) self.accept("arrow_up", self.setKey, ["forward", 1]) self.accept("arrow_down", self.setKey, ["backward", 1]) self.accept("arrow_left-up", self.setKey, ["left", 0]) self.accept("arrow_right-up", self.setKey, ["right", 0]) self.accept("arrow_up-up", self.setKey, ["forward", 0]) self.accept("arrow_down-up", self.setKey, ["backward", 0]) self.accept("a", self.setKey, ["left", 1]) self.accept("d", self.setKey, ["right", 1]) self.accept("w", self.setKey, ["forward", 1]) self.accept("s", self.setKey, ["backward", 1]) self.accept("a-up", self.setKey, ["left", 0]) self.accept("d-up", self.setKey, ["right", 0]) self.accept("w-up", self.setKey, ["forward", 0]) self.accept("s-up", self.setKey, ["backward", 0]) # Game state variables self.isMoving = False self.isRunning = False self.onboard = 0 self.boardtime = 0 self.onspring = 0 self.isjumping = False # Set up the camera base.disableMouse() #base.camera.setPos(self.ralph.getX(),self.ralph.getY()+10,2) base.camera.setPos(0, 0, 0) base.camera.reparentTo(self.ralph) base.camera.setPos(0, 40, 2) base.camera.lookAt(self.ralph) # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. One ray will # start above ralph's head, and the other will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal. base.cTrav = CollisionTraverser() self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0, 0, 300) self.ralphGroundRay.setDirection(0, 0, -1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0)) self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff()) self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol) self.ralphGroundHandler = CollisionHandlerQueue() base.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler) # camera ground collision handler self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0, 0, 300) self.camGroundRay.setDirection(0, 0, -1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(BitMask32.bit(0)) self.camGroundCol.setIntoCollideMask(BitMask32.allOff()) self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() base.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Place the health items self.placeHealthItems() # Place the collectibles self.placeCollectibles() # Place the bomb self.placebombItems() # Uncomment this line to show a visual representation of the # collisions occuring #base.cTrav.showCollisions(render) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight)) #print self.startvar taskMgr.add(self.move, "moveTask")
def __init__(self): ShowBase.__init__(self) self.dirTypes = ['heading', 'pitch', 'roll'] self.dirType = 0 # Display instructions add_title("Panda3D Tutorial: Portal Culling") add_instructions(0.06, "[Esc]: Quit") self.posText = add_instructions(0.12, "pos") self.anglesText = add_instructions(0.18, "angle") self.armHprText = add_instructions(0.24, "hpr") self.dirText = add_instructions(.30, self.dirTypes[0]) self.forearmText = add_instructions(0.36, "angle") self.baseText = add_instructions(0.42, "angle") """add_instructions(0.12, "[W]: Move Forward") add_instructions(0.18, "[A]: Move Left") add_instructions(0.24, "[S]: Move Right") add_instructions(0.30, "[D]: Move Back") add_instructions(0.36, "Arrow Keys: Look Around") add_instructions(0.42, "[F]: Toggle Wireframe") add_instructions(0.48, "[X]: Toggle X-Ray Mode") add_instructions(0.54, "[B]: Toggle Bounding Volumes")""" # Setup controls self.keys = {} for key in ['arrow_left', 'arrow_right', 'arrow_up', 'arrow_down', 'a', 'd', 'w', 's', 'q', 'e']: self.keys[key] = 0 self.accept(key, self.push_key, [key, 1]) self.accept('shift-%s' % key, self.push_key, [key, 1]) self.accept('%s-up' % key, self.push_key, [key, 0]) self.accept("b", self.push_key, ["Rleft", True]) self.accept("b-up", self.push_key, ["Rleft", False]) self.accept("n", self.push_key, ["Rright", True]) self.accept("n-up", self.push_key, ["Rright", False]) self.accept("h", self.push_key, ["Rforward", True]) self.accept("h-up", self.push_key, ["Rforward", False]) self.keys['Rleft'] = self.keys['Rright'] = self.keys['Rforward'] = 0 self.accept('escape', self.exitButton) self.accept('p', self.selectDir) self.accept('[', self.incDir, [-15]) self.accept(']', self.incDir, [15]) #self.disableMouse() # Setup camera lens = PerspectiveLens() lens.setFov(60) lens.setNear(0.01) lens.setFar(1000.0) self.cam.node().setLens(lens) self.camera.setPos(-50, 0, 0) self.pitch = 0.0 self.heading = 0 ambientLight = AmbientLight("ambientLight") ambientLight.setColor((.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection((-5, -5, -5)) directionalLight.setColor((1, 1, 1, 1)) directionalLight.setSpecularColor((1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight)) # Load level geometry self.level = self.loader.loadModel('models/theater') self.level.reparentTo(self.render) self.isMoving = False self.ralph = Actor("models/ralph", {"run": "models/ralph-run", "walk": "models/ralph-walk"}) self.ralph.reparentTo(render) self.ralph.setScale(.2) self.arms = [] idMap = {0:9, 1:11, 2:17, 3:27, 4:29} for node in self.level.get_children(): if not node.getName().startswith('arm'): continue arm = Actor("models/robotarm") self.arms.append(arm) arm.reparentTo(render) arm.setName(node.getName()) arm.setPos(node.getPos()) arm.setHpr(node.getHpr()) #arm.setScale(.2) tokens = node.getName().split('.') try: id = int(tokens[1]) except: id = 0 arm.baseID = idMap[id] arm.jointForearm = arm.controlJoint(None, "modelRoot", "forearm") arm.jointBase = arm.controlJoint(None, "modelRoot", "base") print node.getName(), str(node.getPos()), str(node.getHpr()) taskMgr.add(self.printLoc, "printLoc") taskMgr.add(self.monitorArms, "robot arms") self.taskMgr.add(self.update, 'main loop')
def __init__(self): base.setBackgroundColor(0.1, 0.1, 0.8, 1) base.setFrameRateMeter(True) base.cam.setPosHpr(0, 0, 25, 0, -90, 0) base.disableMouse() # Input self.accept('escape', self.exitGame) self.accept('f1', self.toggleWireframe) self.accept('f2', self.toggleTexture) self.accept('f3', self.toggleDebug) self.accept('f5', self.doScreenshot) # Setup scene 1: World self.debugNP = render.attachNewNode(BulletDebugNode('Debug')) self.debugNP.node().showWireframe(True) self.debugNP.node().showConstraints(True) self.debugNP.node().showBoundingBoxes(True) self.debugNP.node().showNormals(True) self.debugNP.show() self.world = BulletWorld() self.world.setGravity(Vec3(0, 0, -9.81)) self.world.setDebugNode(self.debugNP.node()) # Setup scene 2: Ball visNP = loader.loadModel('models/ball.egg') visNP.clearModelNodes() bodyNPs = BulletHelper.fromCollisionSolids(visNP, True) self.ballNP = bodyNPs[0] self.ballNP.reparentTo(render) self.ballNP.node().setMass(1.0) self.ballNP.setPos(4, -4, 1) self.ballNP.node().setDeactivationEnabled(False) visNP.reparentTo(self.ballNP) # Setup scene 3: Maze visNP = loader.loadModel('models/maze.egg') visNP.clearModelNodes() visNP.reparentTo(render) self.holes = [] self.maze = [] self.mazeNP = visNP bodyNPs = BulletHelper.fromCollisionSolids(visNP, True) for bodyNP in bodyNPs: bodyNP.reparentTo(render) if isinstance(bodyNP.node(), BulletRigidBodyNode): bodyNP.node().setMass(0.0) bodyNP.node().setKinematic(True) self.maze.append(bodyNP) elif isinstance(bodyNP.node(), BulletGhostNode): self.holes.append(bodyNP) # Lighting and material for the ball ambientLight = AmbientLight('ambientLight') ambientLight.setColor(Vec4(0.55, 0.55, 0.55, 1)) directionalLight = DirectionalLight('directionalLight') directionalLight.setDirection(Vec3(0, 0, -1)) directionalLight.setColor(Vec4(0.375, 0.375, 0.375, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) self.ballNP.setLight(render.attachNewNode(ambientLight)) self.ballNP.setLight(render.attachNewNode(directionalLight)) m = Material() m.setSpecular(Vec4(1, 1, 1, 1)) m.setShininess(96) self.ballNP.setMaterial(m, 1) # Startup self.startGame()
def __init__(self): # Set up the window, camera, etc. ShowBase.__init__(self) base.render.setAttrib(LightRampAttrib.makeHdr0()) # Configure depth pre-pass prepass_pass = lionrender.DepthScenePass() # Configure scene pass scene_fb_props = FrameBufferProperties() scene_fb_props.set_rgb_color(True) scene_fb_props.set_rgba_bits(8, 8, 8, 0) scene_fb_props.set_depth_bits(32) scene_pass = lionrender.ScenePass( frame_buffer_properties=scene_fb_props, clear_color=LColor(0.53, 0.80, 0.92, 1), share_depth_with=prepass_pass) scene_pass.node_path.set_depth_write(False) # Configure post processing filter_pass = lionrender.FilterPass(fragment_path='shaders/fsq.frag') filter_pass.node_path.set_shader_input('inputTexture', scene_pass.output) # Enable FXAA fxaa_pass = lionrender.FxaaFilterPass() fxaa_pass.node_path.set_shader_input('inputTexture', filter_pass.output) # Output result fxaa_pass.output_to(render2d) # This is used to store which keys are currently pressed. self.keyMap = { "left": 0, "right": 0, "forward": 0, "backward": 0, "cam-left": 0, "cam-right": 0, } # Post the instructions self.title = addTitle( "Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)") self.inst1 = addInstructions(0.06, "[ESC]: Quit") self.inst2 = addInstructions(0.12, "[Left Arrow]: Rotate Ralph Left") self.inst3 = addInstructions(0.18, "[Right Arrow]: Rotate Ralph Right") self.inst4 = addInstructions(0.24, "[Up Arrow]: Run Ralph Forward") self.inst5 = addInstructions(0.30, "[Down Arrow]: Walk Ralph Backward") self.inst6 = addInstructions(0.36, "[A]: Rotate Camera Left") self.inst7 = addInstructions(0.42, "[S]: Rotate Camera Right") # Set up the environment # # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) # We do not have a skybox, so we will just use a sky blue background color self.setBackgroundColor(0.53, 0.80, 0.92, 1) # Create the main character, Ralph ralphStartPos = self.environ.find("**/start_point").getPos() self.ralph = Actor("models/ralph", { "run": "models/ralph-run", "walk": "models/ralph-walk" }) self.ralph.reparentTo(render) self.ralph.setScale(.2) self.ralph.setPos(ralphStartPos + (0, 0, 1.5)) # Create a floater object, which floats 2 units above ralph. We # use this as a target for the camera to look at. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(self.ralph) self.floater.setZ(2.0) # Accept the control keys for movement and rotation self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", True]) self.accept("arrow_right", self.setKey, ["right", True]) self.accept("arrow_up", self.setKey, ["forward", True]) self.accept("arrow_down", self.setKey, ["backward", True]) self.accept("a", self.setKey, ["cam-left", True]) self.accept("s", self.setKey, ["cam-right", True]) self.accept("arrow_left-up", self.setKey, ["left", False]) self.accept("arrow_right-up", self.setKey, ["right", False]) self.accept("arrow_up-up", self.setKey, ["forward", False]) self.accept("arrow_down-up", self.setKey, ["backward", False]) self.accept("a-up", self.setKey, ["cam-left", False]) self.accept("s-up", self.setKey, ["cam-right", False]) self.accept("v", self.toggleCards) taskMgr.add(self.move, "moveTask") # Set up the camera self.disableMouse() self.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2) self.cTrav = CollisionTraverser() # Use a CollisionHandlerPusher to handle collisions between Ralph and # the environment. Ralph is added as a "from" object which will be # "pushed" out of the environment if he walks into obstacles. # # Ralph is composed of two spheres, one around the torso and one # around the head. They are slightly oversized since we want Ralph to # keep some distance from obstacles. self.ralphCol = CollisionNode('ralph') self.ralphCol.addSolid(CollisionSphere(center=(0, 0, 2), radius=1.5)) self.ralphCol.addSolid( CollisionSphere(center=(0, -0.25, 4), radius=1.5)) self.ralphCol.setFromCollideMask(CollideMask.bit(0)) self.ralphCol.setIntoCollideMask(CollideMask.allOff()) self.ralphColNp = self.ralph.attachNewNode(self.ralphCol) self.ralphPusher = CollisionHandlerPusher() self.ralphPusher.horizontal = True # Note that we need to add ralph both to the pusher and to the # traverser; the pusher needs to know which node to push back when a # collision occurs! self.ralphPusher.addCollider(self.ralphColNp, self.ralph) self.cTrav.addCollider(self.ralphColNp, self.ralphPusher) # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. One ray will # start above ralph's head, and the other will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0, 0, 9) self.ralphGroundRay.setDirection(0, 0, -1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(CollideMask.bit(0)) self.ralphGroundCol.setIntoCollideMask(CollideMask.allOff()) self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol) self.ralphGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler) self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0, 0, 9) self.camGroundRay.setDirection(0, 0, -1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(CollideMask.bit(0)) self.camGroundCol.setIntoCollideMask(CollideMask.allOff()) self.camGroundColNp = self.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Uncomment this line to see the collision rays #self.ralphColNp.show() #self.camGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring #self.cTrav.showCollisions(render) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor((.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection((-5, -5, -5)) directionalLight.setColor((1, 1, 1, 1)) directionalLight.setSpecularColor((1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight)) # Clean up texture attributes for texture in self.render.find_all_textures(): texture.set_format(Texture.F_srgb)
def __init__(self): self.room = loader.loadModel("models/world") self.room.reparentTo(render) self.room.setShaderAuto() #self.room.setScale(100,100,100) self.character = loader.loadModel("assets/characters/knight") self.character.reparentTo(render) self.character.setPos(0, 0, 0) self.character2 = loader.loadModel("assets/characters/king") self.character2.reparentTo(render) self.character2.setPos(0, 0, 0) self.character2.setColor((1, 0, 0, 1)) base.camera.reparentTo(self.character) base.camera.setPos(0, -50, 5) base.camera.lookAt(self.character) # Make the mouse invisible, turn off normal mouse controls base.disableMouse() props = WindowProperties() #props.setCursorHidden(True) base.win.requestProperties(props) # Set the current viewing target self.focus = Vec3(0, 0, 0) self.heading = 0 self.pitch = 0 self.mousex = 0 self.mousey = 0 self.last = 0 self.keys = { 'move forward': False, 'move backward': False, 'strafe left': False, 'strafe right': False, 'zoom-out': False } # Start the camera control task: taskMgr.add(self.controlCamera, "camera-task") self.accept("escape", sys.exit, [0]) #Define a keymap for 'WASD' Movement self.accept("w", self.setKeys, ['move forward', True]) self.accept("w-up", self.setKeys, ['move forward', False]) self.accept("s", self.setKeys, ['move backward', True]) self.accept("s-up", self.setKeys, ['move backward', False]) self.accept("a", self.setKeys, ['strafe left', True]) self.accept("a-up", self.setKeys, ['strafe left', False]) self.accept("d", self.setKeys, ['strafe right', True]) self.accept("d-up", self.setKeys, ['strafe right', False]) self.accept("q", self.setKeys, ['zoom-out', True]) self.accept("q-up", self.setKeys, ['zoom-out', False]) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor((.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection((-5, -5, -5)) directionalLight.setColor((1, 1, 1, 1)) directionalLight.setSpecularColor((1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight))
def __init__(self): # This code puts the standard title and instruction text on screen self.title = OnscreenText(text="Ball in Maze", style=1, fg=(1, 1, 1, 1), pos=(0.7, -0.95), scale=.07) self.instructions = OnscreenText(text="Press Esc to exit.", pos=(-1.3, .95), fg=(1, 1, 1, 1), align=TextNode.ALeft, scale=.05) base.setBackgroundColor(0, 0, 0) self.central_msg = OnscreenText(text="", pos=(0, 0), fg=(1, 1, 0, 1), scale=.1) self.central_msg.hide() self.accept("escape", sys.exit) # Escape quits base.disableMouse() # Disable mouse-based camera control camera.setPosHpr(0, 0, 25, 0, -90, 0) # Place the camera # Load the maze and place it in the scene self.maze = loader.loadModel("models/maze") self.maze.reparentTo(render) # Most times, you want collisions to be tested against invisible geometry # rather than every polygon. This is because testing against every polygon # in the scene is usually too slow. You can have simplified or approximate # geometry for the solids and still get good results. # # Sometimes you'll want to create and position your own collision solids in # code, but it's often easier to have them built automatically. This can be # done by adding special tags into an egg file. Check maze.egg and ball.egg # and look for lines starting with <Collide>. The part is brackets tells # Panda exactly what to do. Polyset means to use the polygons in that group # as solids, while Sphere tells panda to make a collision sphere around them # Keep means to keep the polygons in the group as visable geometry (good # for the ball, not for the triggers), and descend means to make sure that # the settings are applied to any subgroups. # # Once we have the collision tags in the models, we can get to them using # NodePath's find command # Find the collision node named wall_collide self.walls = self.maze.find("**/wall_collide") # Collision objects are sorted using BitMasks. BitMasks are ordinary numbers # with extra methods for working with them as binary bits. Every collision # solid has both a from mask and an into mask. Before Panda tests two # objects, it checks to make sure that the from and into collision masks # have at least one bit in common. That way things that shouldn't interact # won't. Normal model nodes have collision masks as well. By default they # are set to bit 20. If you want to collide against actual visable polygons, # set a from collide mask to include bit 20 # # For this example, we will make everything we want the ball to collide with # include bit 0 self.walls.node().setIntoCollideMask(BitMask32.bit(0)) # CollisionNodes are usually invisible but can be shown. Uncomment the next # line to see the collision walls # self.walls.show() # We will now find the triggers for the holes and set their masks to 0 as # well. We also set their names to make them easier to identify during # collisions self.loseTriggers = [] for i in range(6): trigger = self.maze.find("**/hole_collide" + str(i)) trigger.node().setIntoCollideMask(BitMask32.bit(0)) trigger.node().setName("loseTrigger") self.loseTriggers.append(trigger) # Uncomment this line to see the triggers # trigger.show() # Ground_collide is a single polygon on the same plane as the ground in the # maze. We will use a ray to collide with it so that we will know exactly # what height to put the ball at every frame. Since this is not something # that we want the ball itself to collide with, it has a different # bitmask. self.mazeGround = self.maze.find("**/ground_collide") self.mazeGround.node().setIntoCollideMask(BitMask32.bit(1)) # Load the ball and attach it to the scene # It is on a root dummy node so that we can rotate the ball itself without # rotating the ray that will be attached to it self.ballRoot = render.attachNewNode("ballRoot") self.ball = loader.loadModel("models/ball") self.ball.reparentTo(self.ballRoot) # Find the collison sphere for the ball which was created in the egg file # Notice that it has a from collision mask of bit 0, and an into collison # mask of no bits. This means that the ball can only cause collisions, not # be collided into self.ballSphere = self.ball.find("**/ball") self.ballSphere.node().setFromCollideMask(BitMask32.bit(0)) self.ballSphere.node().setIntoCollideMask(BitMask32.allOff()) # No we create a ray to start above the ball and cast down. This is to # Determine the height the ball should be at and the angle the floor is # tilting. We could have used the sphere around the ball itself, but it # would not be as reliable self.ballGroundRay = CollisionRay() # Create the ray self.ballGroundRay.setOrigin(0, 0, 10) # Set its origin self.ballGroundRay.setDirection(0, 0, -1) # And its direction # Collision solids go in CollisionNode self.ballGroundCol = CollisionNode( 'groundRay') # Create and name the node self.ballGroundCol.addSolid(self.ballGroundRay) # Add the ray self.ballGroundCol.setFromCollideMask( BitMask32.bit(1)) # Set its bitmasks self.ballGroundCol.setIntoCollideMask(BitMask32.allOff()) # Attach the node to the ballRoot so that the ray is relative to the ball # (it will always be 10 feet over the ball and point down) self.ballGroundColNp = self.ballRoot.attachNewNode(self.ballGroundCol) # Uncomment this line to see the ray # self.ballGroundColNp.show() # Finally, we create a CollisionTraverser. CollisionTraversers are what # do the job of calculating collisions self.cTrav = CollisionTraverser() # Collision traverservs tell collision handlers about collisions, and then # the handler decides what to do with the information. We are using a # CollisionHandlerQueue, which simply creates a list of all of the # collisions in a given pass. There are more sophisticated handlers like # one that sends events and another that tries to keep collided objects # apart, but the results are often better with a simple queue self.cHandler = CollisionHandlerQueue() # Now we add the collision nodes that can create a collision to the # traverser. The traverser will compare these to all others nodes in the # scene. There is a limit of 32 CollisionNodes per traverser # We add the collider, and the handler to use as a pair self.cTrav.addCollider(self.ballSphere, self.cHandler) self.cTrav.addCollider(self.ballGroundColNp, self.cHandler) # Collision traversers have a built in tool to help visualize collisions. # Uncomment the next line to see it. # self.cTrav.showCollisions(render) # This section deals with lighting for the ball. Only the ball was lit # because the maze has static lighting pregenerated by the modeler ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.55, .55, .55, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(0, 0, -1)) directionalLight.setColor(Vec4(0.375, 0.375, 0.375, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) self.ballRoot.setLight(render.attachNewNode(ambientLight)) self.ballRoot.setLight(render.attachNewNode(directionalLight)) # This section deals with adding a specular highlight to the ball to make # it look shiny m = Material() m.setSpecular(Vec4(1, 1, 1, 1)) m.setShininess(96) self.ball.setMaterial(m, 1) # Finally, we call start for more initialization self.start()
class RoamingRalphDemo(CosmoniumBase): def get_local_position(self): return base.camera.get_pos() def create_terrain_appearance(self): self.terrain_appearance.set_shadow(self.shadow_caster) def create_terrain_heightmap(self): self.heightmap = PatchedHeightmap('heightmap', self.noise_size, self.height_scale, self.size, self.size, True, ShaderHeightmapPatchFactory(self.noise)) def create_terrain_biome(self): self.biome = PatchedHeightmap('biome', self.biome_size, 1.0, self.size, self.size, False, ShaderHeightmapPatchFactory(self.biome_noise)) def create_terrain_shader(self): # control4 = HeightColorMap('colormap', # [ # ColormapLayer(0.00, top=LRGBColor(0, 0.1, 0.24)), # ColormapLayer(0.40, top=LRGBColor(0, 0.1, 0.24)), # ColormapLayer(0.49, top=LRGBColor(0, 0.6, 0.6)), # ColormapLayer(0.50, bottom=LRGBColor(0.9, 0.8, 0.6), top=LRGBColor(0.5, 0.4, 0.3)), # ColormapLayer(0.80, top=LRGBColor(0.2, 0.3, 0.1)), # ColormapLayer(0.90, top=LRGBColor(0.7, 0.6, 0.4)), # ColormapLayer(1.00, bottom=LRGBColor(1, 1, 1), top=LRGBColor(1, 1, 1)), # ]) appearance = DetailMap(self.terrain_control, self.heightmap, create_normals=True) data_source = [HeightmapDataSource(self.heightmap, PatchedGpuTextureSource, filtering=HeightmapDataSource.F_none), HeightmapDataSource(self.biome, PatchedGpuTextureSource, filtering=HeightmapDataSource.F_none), TextureDictionaryDataSource(self.terrain_appearance, TextureDictionaryDataSource.F_hash)] if settings.allow_tesselation: tesselation_control = ConstantTesselationControl(invert_v=False) else: tesselation_control = None if self.fog is not None: after_effects = [Fog(**self.fog)] else: after_effects = None self.terrain_shader = BasicShader(appearance=appearance, tesselation_control=tesselation_control, geometry_control=DisplacementGeometryControl(self.heightmap), data_source=data_source, after_effects=after_effects) def create_tile(self, x, y): self.terrain_shape.add_root_patch(x, y) def create_terrain(self): self.tile_factory = TileFactory(self.tile_density, self.size, self.has_water, self.water) self.terrain_shape = TiledShape(self.tile_factory, self.size, self.max_lod, lod_control=VertexSizeMaxDistancePatchLodControl(self.max_distance, self.max_vertex_size)) self.create_terrain_heightmap() self.create_terrain_biome() self.create_terrain_appearance() self.create_terrain_shader() self.terrain = HeightmapSurface( 'surface', 0, self.terrain_shape, self.heightmap, self.biome, self.terrain_appearance, self.terrain_shader, self.size, clickable=False, average=True) self.terrain.set_parent(self) self.terrain.create_instance() def toggle_water(self): if not self.has_water: return self.water.visible = not self.water.visible self.terrain_shape.check_settings() def get_height(self, position): height = self.terrain.get_height(position) if self.has_water and self.water.visible and height < self.water.level: height = self.water.level return height #Used by populator def get_height_patch(self, patch, u, v): height = self.terrain.get_height_patch(patch, u, v) if self.has_water and self.water.visible and height < self.water.level: height = self.water.level return height def skybox_init(self): skynode = base.cam.attachNewNode('skybox') self.skybox = loader.loadModel('ralph-data/models/rgbCube') self.skybox.reparentTo(skynode) self.skybox.setTextureOff(1) self.skybox.setShaderOff(1) self.skybox.setTwoSided(True) # make big enough to cover whole terrain, else there'll be problems with the water reflections self.skybox.setScale(1.5* self.size) self.skybox.setBin('background', 1) self.skybox.setDepthWrite(False) self.skybox.setDepthTest(False) self.skybox.setLightOff(1) self.skybox.setShaderOff(1) self.skybox.setFogOff(1) #self.skybox.setColor(.55, .65, .95, 1.0) self.skybox_color = LColor(pow(0.5, 1/2.2), pow(0.6, 1/2.2), pow(0.7, 1/2.2), 1.0) self.skybox.setColor(self.skybox_color) def objects_density_for_patch(self, patch): scale = 1 << patch.lod return int(self.objects_density / scale + 1.0) def create_populator(self): if settings.allow_instancing: TerrainPopulator = GpuTerrainPopulator else: TerrainPopulator = CpuTerrainPopulator self.rock_collection = TerrainPopulator(RockFactory(self), self.objects_density_for_patch, self.objects_density, RandomObjectPlacer(self)) self.tree_collection = TerrainPopulator(TreeFactory(self), self.objects_density_for_patch, self.objects_density, RandomObjectPlacer(self)) self.object_collection = MultiTerrainPopulator() self.object_collection.add_populator(self.rock_collection) self.object_collection.add_populator(self.tree_collection) def set_light_angle(self, angle): self.light_angle = angle self.light_quat.setFromAxisAngleRad(angle * pi / 180, LVector3.forward()) self.light_dir = self.light_quat.xform(LVector3.up()) cosA = self.light_dir.dot(LVector3.up()) self.vector_to_star = self.light_dir if self.shadow_caster is not None: self.shadow_caster.set_direction(-self.light_dir) if self.directionalLight is not None: self.directionalLight.setDirection(-self.light_dir) if cosA >= 0: coef = sqrt(cosA) self.light_color = (1, coef, coef, 1) self.directionalLight.setColor(self.light_color) self.skybox.setColor(self.skybox_color * cosA) else: self.light_color = (1, 0, 0, 1) self.directionalLight.setColor(self.light_color) self.skybox.setColor(self.skybox_color * 0) self.update() def update(self): self.object_collection.update_instance() self.terrain.update_instance(None, None) def apply_instance(self, instance): pass def create_instance_delayed(self): pass def get_apparent_radius(self): return 0 def get_name(self): return "terrain" def is_emissive(self): return False def __init__(self): CosmoniumBase.__init__(self) config = RalphConfigParser() (self.noise, self.biome_noise, self.terrain_control, self.terrain_appearance, self.water, self.fog) = config.load_and_parse('ralph-data/ralph.yaml') self.tile_density = 64 self.default_size = 128 self.max_vertex_size = 64 self.max_lod = 10 self.size = 128 * 8 self.max_distance = 1.001 * self.size * sqrt(2) self.noise_size = 512 self.biome_size = 128 self.noise_scale = 0.5 * self.size / self.default_size self.objects_density = int(25 * (1.0 * self.size / self.default_size) * (1.0 * self.size / self.default_size)) self.objects_density = 250 self.height_scale = 100 * 5.0 self.has_water = True self.fullscreen = False self.shadow_caster = None self.light_angle = None self.light_dir = LVector3.up() self.vector_to_star = self.light_dir self.light_quat = LQuaternion() self.light_color = (1.0, 1.0, 1.0, 1.0) self.directionalLight = None self.shadow_size = self.default_size / 8 self.shadow_box_length = self.height_scale self.observer = RalphCamera(self.cam, self.camLens) self.observer.init() self.distance_to_obs = float('inf') self.height_under = 0.0 self.scene_position = LVector3() self.scene_scale_factor = 1 self.scene_orientation = LQuaternion() #Size of an edge seen from 4 units above self.edge_apparent_size = (1.0 * self.size / self.tile_density) / (4.0 * self.observer.pixel_size) print("Apparent size:", self.edge_apparent_size) self.win.setClearColor((135.0/255, 206.0/255, 235.0/255, 1)) # This is used to store which keys are currently pressed. self.keyMap = { "left": 0, "right": 0, "forward": 0, "backward": 0, "cam-left": 0, "cam-right": 0, "cam-up": 0, "cam-down": 0, "sun-left": 0, "sun-right": 0, "turbo": 0} # Set up the environment # # Create some lighting self.vector_to_obs = base.cam.get_pos() self.vector_to_obs.normalize() if True: self.shadow_caster = ShadowCaster(1024) self.shadow_caster.create() self.shadow_caster.set_lens(self.shadow_size, -self.shadow_box_length / 2.0, self.shadow_box_length / 2.0, -self.light_dir) self.shadow_caster.set_pos(self.light_dir * self.shadow_box_length / 2.0) self.shadow_caster.bias = 0.1 else: self.shadow_caster = None self.ambientLight = AmbientLight("ambientLight") self.ambientLight.setColor((settings.global_ambient, settings.global_ambient, settings.global_ambient, 1)) self.directionalLight = DirectionalLight("directionalLight") self.directionalLight.setDirection(-self.light_dir) self.directionalLight.setColor(self.light_color) self.directionalLight.setSpecularColor(self.light_color) render.setLight(render.attachNewNode(self.ambientLight)) render.setLight(render.attachNewNode(self.directionalLight)) render.setShaderAuto() base.setFrameRateMeter(True) self.create_terrain() self.create_populator() self.terrain_shape.set_populator(self.object_collection) self.create_tile(0, 0) self.skybox_init() self.set_light_angle(45) # Create the main character, Ralph ralphStartPos = LPoint3() self.ralph = Actor("ralph-data/models/ralph", {"run": "ralph-data/models/ralph-run", "walk": "ralph-data/models/ralph-walk"}) self.ralph.reparentTo(render) self.ralph.setScale(.2) self.ralph.setPos(ralphStartPos + (0, 0, 0.5)) self.ralph_shape = InstanceShape(self.ralph) self.ralph_shape.parent = self self.ralph_shape.set_owner(self) self.ralph_shape.create_instance() self.ralph_appearance = ModelAppearance(self.ralph) self.ralph_appearance.set_shadow(self.shadow_caster) self.ralph_shader = BasicShader() self.ralph_appearance.bake() self.ralph_appearance.apply(self.ralph_shape, self.ralph_shader) self.ralph_shader.apply(self.ralph_shape, self.ralph_appearance) self.ralph_shader.update(self.ralph_shape, self.ralph_appearance) # Create a floater object, which floats 2 units above ralph. We # use this as a target for the camera to look at. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(self.ralph) self.floater.setZ(2.0) # Accept the control keys for movement and rotation self.accept("escape", sys.exit) self.accept("control-q", sys.exit) self.accept("arrow_left", self.setKey, ["left", True]) self.accept("arrow_right", self.setKey, ["right", True]) self.accept("arrow_up", self.setKey, ["forward", True]) self.accept("arrow_down", self.setKey, ["backward", True]) self.accept("shift", self.setKey, ["turbo", True]) self.accept("a", self.setKey, ["cam-left", True], direct=True) self.accept("s", self.setKey, ["cam-right", True], direct=True) self.accept("u", self.setKey, ["cam-up", True], direct=True) self.accept("u-up", self.setKey, ["cam-up", False]) self.accept("d", self.setKey, ["cam-down", True], direct=True) self.accept("d-up", self.setKey, ["cam-down", False]) self.accept("o", self.setKey, ["sun-left", True], direct=True) self.accept("o-up", self.setKey, ["sun-left", False]) self.accept("p", self.setKey, ["sun-right", True], direct=True) self.accept("p-up", self.setKey, ["sun-right", False]) self.accept("arrow_left-up", self.setKey, ["left", False]) self.accept("arrow_right-up", self.setKey, ["right", False]) self.accept("arrow_up-up", self.setKey, ["forward", False]) self.accept("arrow_down-up", self.setKey, ["backward", False]) self.accept("shift-up", self.setKey, ["turbo", False]) self.accept("a-up", self.setKey, ["cam-left", False]) self.accept("s-up", self.setKey, ["cam-right", False]) self.accept("w", self.toggle_water) self.accept("h", self.print_debug) self.accept("f2", self.connect_pstats) self.accept("f3", self.toggle_filled_wireframe) self.accept("shift-f3", self.toggle_wireframe) self.accept("f5", self.bufferViewer.toggleEnable) self.accept("f8", self.terrain_shape.dump_tree) self.accept('alt-enter', self.toggle_fullscreen) taskMgr.add(self.move, "moveTask") # Game state variables self.isMoving = False # Set up the camera self.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2) self.camera_height = 2.0 render.set_shader_input("camera", self.camera.get_pos()) self.cTrav = CollisionTraverser() self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0, 0, 9) self.ralphGroundRay.setDirection(0, 0, -1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(CollideMask.bit(0)) self.ralphGroundCol.setIntoCollideMask(CollideMask.allOff()) self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol) self.ralphGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler) # Uncomment this line to see the collision rays #self.ralphGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring #self.cTrav.showCollisions(render) #self.terrain_shape.test_lod(LPoint3d(*self.ralph.getPos()), self.distance_to_obs, self.pixel_size, self.terrain_appearance) #self.terrain_shape.update_lod(LPoint3d(*self.ralph.getPos()), self.distance_to_obs, self.pixel_size, self.terrain_appearance) #self.terrain.shape_updated() self.terrain.update_instance(LPoint3d(*self.ralph.getPos()), None) # Records the state of the arrow keys def setKey(self, key, value): self.keyMap[key] = value # Accepts arrow keys to move either the player or the menu cursor, # Also deals with grid checking and collision detection def move(self, task): # Get the time that elapsed since last frame. We multiply this with # the desired speed in order to find out with which distance to move # in order to achieve that desired speed. dt = globalClock.getDt() # If the camera-left key is pressed, move camera left. # If the camera-right key is pressed, move camera right. if self.keyMap["cam-left"]: self.camera.setX(self.camera, -20 * dt) if self.keyMap["cam-right"]: self.camera.setX(self.camera, +20 * dt) if self.keyMap["cam-up"]: self.camera_height *= (1 + 2 * dt) if self.keyMap["cam-down"]: self.camera_height *= (1 - 2 * dt) if self.camera_height < 1.0: self.camera_height = 1.0 if self.keyMap["sun-left"]: self.set_light_angle(self.light_angle + 30 * dt) if self.keyMap["sun-right"]: self.set_light_angle(self.light_angle - 30 * dt) # save ralph's initial position so that we can restore it, # in case he falls off the map or runs into something. startpos = self.ralph.getPos() # If a move-key is pressed, move ralph in the specified direction. delta = 25 if self.keyMap["turbo"]: delta *= 10 if self.keyMap["left"]: self.ralph.setH(self.ralph.getH() + 300 * dt) if self.keyMap["right"]: self.ralph.setH(self.ralph.getH() - 300 * dt) if self.keyMap["forward"]: self.ralph.setY(self.ralph, -delta * dt) if self.keyMap["backward"]: self.ralph.setY(self.ralph, delta * dt) #self.limit_pos(self.ralph) # If ralph is moving, loop the run animation. # If he is standing still, stop the animation. if self.keyMap["forward"] or self.keyMap["backward"] or self.keyMap["left"] or self.keyMap["right"]: if self.isMoving is False: self.ralph.loop("run") self.isMoving = True else: if self.isMoving: self.ralph.stop() self.ralph.pose("walk", 5) self.isMoving = False # If the camera is too far from ralph, move it closer. # If the camera is too close to ralph, move it farther. camvec = self.ralph.getPos() - self.camera.getPos() camvec.setZ(0) camdist = camvec.length() camvec.normalize() if camdist > 10.0: self.camera.setPos(self.camera.getPos() + camvec * (camdist - 10)) camdist = 10.0 if camdist < 5.0: self.camera.setPos(self.camera.getPos() - camvec * (5 - camdist)) camdist = 5.0 # Normally, we would have to call traverse() to check for collisions. # However, the class ShowBase that we inherit from has a task to do # this for us, if we assign a CollisionTraverser to self.cTrav. self.cTrav.traverse(render) if False: # Adjust ralph's Z coordinate. If ralph's ray hit anything, put # him back where he was last frame. entries = list(self.ralphGroundHandler.getEntries()) entries.sort(key=lambda x: x.getSurfacePoint(render).getZ()) if len(entries) > 0: self.ralph.setPos(startpos) ralph_height = self.get_height(self.ralph.getPos()) self.ralph.setZ(ralph_height) # Keep the camera at one foot above the terrain, # or two feet above ralph, whichever is greater. camera_height = self.get_height(self.camera.getPos()) + 1.0 if camera_height < ralph_height + self.camera_height: self.camera.setZ(ralph_height + self.camera_height) else: self.camera.setZ(camera_height) #self.limit_pos(self.camera) # The camera should look in ralph's direction, # but it should also try to stay horizontal, so look at # a floater which hovers above ralph's head. self.camera.lookAt(self.floater) #self.shadow_caster.set_pos(self.ralph.get_pos()) self.shadow_caster.set_pos(self.ralph.get_pos() - camvec * camdist + camvec * self.shadow_size / 2) render.set_shader_input("camera", self.camera.get_pos()) self.vector_to_obs = base.cam.get_pos() self.vector_to_obs.normalize() if self.isMoving: #self.terrain_shape.test_lod(LPoint3d(*self.ralph.getPos()), self.distance_to_obs, self.pixel_size, self.terrain_appearance) pass#self.terrain_shape.update_lod(LPoint3d(*self.ralph.getPos()), self.distance_to_obs, self.pixel_size, self.terrain_appearance) self.object_collection.update_instance() self.terrain.update_instance(LPoint3d(*self.ralph.getPos()), None) return task.cont def print_debug(self): print("Height:", self.get_height(self.ralph.getPos()), self.terrain.get_height(self.ralph.getPos())) print("Ralph:", self.ralph.get_pos()) print("Camera:", base.camera.get_pos())
def __init__(self): # Set up the window, camera, etc. ShowBase.__init__(self) # This is used to store which keys are currently pressed. self.keyMap = { "left": 0, "right": 0, "forward": 0, "backward": 0, "cam-left": 0, "cam-right": 0, } ########################################################################### self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) # We do not have a skybox, so we will just use a sky blue background color #self.setBackgroundColor(0.53, 0.80, 0.92, 1) self.setBackgroundColor(.1, .1, .1, 1) # Create the main character, person #personStartPos = self.environ.find("**/start_point").getPos() #self.person = Actor("models/panda", # {"run": "models/panda-walk", # "walk": "models/panda-walk"}) person2StartPos = self.environ.find("**/start_point").getPos() self.person2 = Actor("models/passenger_penguin", {"run": "models/passenger_penguin", "walk": "models/passenger_penguin"}) self.person2.reparentTo(render) self.person2.setScale(.1) self.person2.setPos(person2StartPos + (px, py, 1)) person3StartPos = self.environ.find("**/start_point").getPos() self.person3 = Actor("models/MagicBunny", {"run": "models/MagicBunny", "walk": "models/MagicBunny"}) #px = random.randint(-1,1) #py = random.randint(-1,1) self.person3.reparentTo(render) self.person3.setScale(.04) #self.person.setPos(personStartPos + (0, 0, 2)) self.person3.setPos(person3StartPos + (px/1.5+3, py/2, 0)) personStartPos = self.environ.find("**/start_point").getPos() self.person = Actor("models/panda", {"run": "models/panda-walk", "walk": "models/panda-walk"}) self.person.reparentTo(render) self.person.setScale(.1) self.person.setPos(personStartPos + (0, 0, 1.5)) self.person.loop("run") arenaStartPos = self.environ.find("**/start_point").getPos() self.arena = Actor("models/FarmHouse") self.arena.reparentTo(render) self.arena.setScale(.1) self.arena.setPos(arenaStartPos + (-1, 0, 0)) arena2StartPos = self.environ.find("**/start_point").getPos() self.arena2 = Actor("models/fence") self.arena2.reparentTo(render) self.arena2.setScale(5.9) self.arena.setPos(arenaStartPos + (px, py-12, 1)) self.arena2.setPos(arenaStartPos + (8, 5, -1)) arena2StartPos = self.environ.find("**/start_point").getPos() self.arena3 = Actor("models/gate") self.arena3.reparentTo(render) self.arena3.setScale(.01) self.arena3.setPos(arenaStartPos + (px/2+random.randint(12,15), py/2, -1)) self.arena4 = Actor("models/FarmHouse") self.arena4.reparentTo(render) self.arena4.setScale(.1) self.arena4.setPos(arenaStartPos + (px/3-random.randint(18,22), py/3, -1)) self.arena5 = Actor("models/gate") self.arena5.reparentTo(render) self.arena5.setScale(.008) self.arena5.setPos(arenaStartPos + (px/1.2-9, py/1.2, -1)) ##################################################################################################################################### base.enableParticles() self.t = loader.loadModel("teapot") # for the particle enhancer self.t.setScale(10) self.t.setPos(-10, -20, -1) self.t.reparentTo(render) #self.setupLights() self.p = ParticleEffect() self.p.setScale(1000) self.loadParticleConfig('smoke.ptf') # looks like a storm at night self.p.setScale(20) #################################################3 # Create a floater object, which floats 2 units above person. We # use this as a target for the camera to look at. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(self.person) self.floater.setZ(2.0) # Accept the control keys for movement and rotation taskMgr.add(self.move, "moveTask") # Set up the camera self.disableMouse() self.camera.setPos(self.person.getX(), self.person.getY() + 10, 2) self.cTrav = CollisionTraverser() self.personCol = CollisionNode('person') self.personCol.addSolid(CollisionSphere(center=(0, 0, 2), radius=1.5)) self.personCol.addSolid(CollisionSphere(center=(0, -0.25, 4), radius=1.5)) self.personCol.setFromCollideMask(CollideMask.bit(0)) self.personCol.setIntoCollideMask(CollideMask.allOff()) self.personColNp = self.person.attachNewNode(self.personCol) self.personPusher = CollisionHandlerPusher() self.personPusher.horizontal = True self.personPusher.addCollider(self.personColNp, self.person) self.cTrav.addCollider(self.personColNp, self.personPusher) self.personGroundRay = CollisionRay() self.personGroundRay.setOrigin(0, 0, 9) self.personGroundRay.setDirection(0, 0, -1) self.personGroundCol = CollisionNode('personRay') self.personGroundCol.addSolid(self.personGroundRay) self.personGroundCol.setFromCollideMask(CollideMask.bit(0)) self.personGroundCol.setIntoCollideMask(CollideMask.allOff()) self.personGroundColNp = self.person.attachNewNode(self.personGroundCol) self.personGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.personGroundColNp, self.personGroundHandler) self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0, 0, 9) self.camGroundRay.setDirection(0, 0, -1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(CollideMask.bit(0)) self.camGroundCol.setIntoCollideMask(CollideMask.allOff()) self.camGroundColNp = self.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor((.3, .3, .3, .2)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection((-5, -5, -5)) directionalLight.setColor((.2, .2, .2, 1)) directionalLight.setSpecularColor((.1, .1, .1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight))
class ReflectiveBody(StellarBody): def __init__(self, *args, **kwargs): self.albedo = kwargs.pop('albedo', 0.5) StellarBody.__init__(self, *args, **kwargs) self.sunLight = None def is_emissive(self): return False def get_abs_magnitude(self): luminosity = self.get_luminosity() * self.get_phase() if luminosity > 0.0: return lum_to_abs_mag(luminosity) else: return 99.0 def get_luminosity(self): if self.star is None or self.distance_to_star is None: return 0.0 star_power = self.star.get_luminosity() area = 4 * pi * self.distance_to_star * self.distance_to_star * 1000 * 1000 if area > 0.0: irradiance = star_power / area surface = 4 * pi * self.get_apparent_radius() * self.get_apparent_radius() * 1000 * 1000 received_energy = irradiance * surface reflected_energy = received_energy * self.albedo return reflected_energy else: print("No area") return 0.0 def get_phase(self): if self.vector_to_obs is None or self.vector_to_star is None: return 0.0 angle = self.vector_to_obs.dot(self.vector_to_star) phase = (1.0 + angle) / 2.0 return phase def check_cast_shadow_on(self, body): position = self.get_local_position() body_position = body.get_local_position() pa = body_position - position self_radius = self.get_apparent_radius() #TODO: should be refactored somehow self_ar = self.radius / pa.length() star_ar = self.star.get_apparent_radius() / (self.star._local_position - body_position).length() ar_ratio = star_ar / self_ar #TODO: No longer valid if we are using HDR if ar_ratio * ar_ratio > 255: #the shadow coef is smaller than the min change in pixel color #the umbra will have no visible impact return False distance_vector = pa - self.vector_to_star * self.vector_to_star.dot(pa) distance = distance_vector.length() projected = self.vector_to_star * self.vector_to_star.dot(body_position) face = self.vector_to_star.dot(projected - position) radius = (1 + ar_ratio) * self_radius + body.get_apparent_radius() return face < 0.0 and distance < radius def start_shadows_update(self): self.surface.start_shadows_update() #TODO: this should be done by looping over components if self.clouds is not None: self.clouds.start_shadows_update() if self.atmosphere is not None: self.atmosphere.start_shadows_update() def add_shadow_target(self, target): self.surface.add_shadow_target(target.surface) if target.clouds is not None: self.surface.add_shadow_target(target.clouds) if target.atmosphere is not None: self.surface.add_shadow_target(target.atmosphere) def end_shadows_update(self): self.surface.end_shadows_update() if self.clouds is not None: self.clouds.end_shadows_update() if self.atmosphere is not None: self.atmosphere.end_shadows_update() def create_light(self): print("Create light for", self.get_name()) self.dir_light = DirectionalLight('sunLight') self.dir_light.setDirection(LVector3(*-self.vector_to_star)) self.dir_light.setColor((1, 1, 1, 1)) self.sunLight = self.context.world.attachNewNode(self.dir_light) self.set_light(self.sunLight) def update_light(self, camera_pos): pos = self.get_local_position() + self.vector_to_star * self.get_extend() self.place_pos_only(self.sunLight, pos, camera_pos, self.distance_to_obs, self.vector_to_obs) self.dir_light.setDirection(LVector3(*-self.vector_to_star)) def remove_light(self): self.sunLight.remove_node() self.sunLight = None self.dir_light = None def configure_shape(self): StellarBody.configure_shape(self) self.surface.create_shadows() if self.ring is not None and self.surface is not None: #TODO: This should be in start_shadow_update... self.ring.shadow_caster.add_target(self.surface) if self.clouds is not None: self.ring.shadow_caster.add_target(self.clouds) self.ring.start_shadows_update() self.surface.shadow_caster.add_target(self.ring) self.ring.end_shadows_update() def create_components(self): StellarBody.create_components(self) if self.sunLight is None: self.create_light() self.update_shader() def update_components(self, camera_pos): if self.sunLight is not None: self.update_light(camera_pos) def remove_components(self): if self.sunLight is not None: self.remove_light() self.update_shader() StellarBody.remove_components(self)
def __init__(self): # Set up the window, camera, etc. ShowBase.__init__(self) # Set the background color to black self.win.setClearColor((0, 1, 1, 1)) # This is used to store which keys are currently pressed. self.keyMap = { "left": 0, "right": 0, "forward": 0, "cam-left": 0, "cam-right": 0, "backward": 0, "cam-up": 0, "cam-down": 0, "add-car": 0, "switch-mode":0, "mouse-click":0} # this is the egg that came with the module # environ = loader.loadModel("models/world") # this is the one I created using mountainMaker.py self.environ = loader.loadModel("TestMountain1") self.environ.reparentTo(render) self.car = loader.loadModel("TestCar") #self.car = loader.loadModel("testModel/ball") self.car.reparentTo(render) #instructions self.inst = [""]*5 self.setUpFlyingInstructions() # for adjusting so that the position is the center of the car self.adjustedXForCenter = 10/2 self.adjustedYForCenter = 20/2 # important for setting the size relative to everything else # found it here : https://www.panda3d.org/manual/index.php/Common_State_Changes # set the mode that the player is currently in self.mode = 0 self.modeFly = 0 self.modeRace = 1 # to ensure that when pressing h it only switches once each press self.hasSwitched = False self.carPositionX = 10 self.carPositionY = 10 self.carPositionZ = 100 # note for rotating camera: from this website: # https://www.panda3d.org/manual/index.php/Common_State_Changes # setHpr(Yaw, Pitch, Roll) # setting up initial conditions for which way camera is rotated self.carYaw = 0 self.carPitch = 0 self.setUpCarCollider() self.setUpMouseCollider() # make the rocks and other stuff that will show up self.objects = [] # Accept the control keys for movement and rotation #setting up keys for movement self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", True]) self.accept("arrow_right", self.setKey, ["right", True]) self.accept("arrow_up", self.setKey, ["forward", True]) self.accept("arrow_down", self.setKey, ["backward", True]) self.accept("arrow_left-up", self.setKey, ["left", False]) self.accept("arrow_right-up", self.setKey, ["right", False]) self.accept("arrow_up-up", self.setKey, ["forward", False]) self.accept("arrow_down-up", self.setKey, ["backward", False]) # adding car self.accept("mouse1", self.setKey, ["mouse-click", True]) self.accept("mouse1-up", self.setKey, ["mouse-click", False]) # setting up orientation of the camera self.accept("a", self.setKey, ["cam-left", True]) self.accept("s", self.setKey, ["cam-down", True]) self.accept("a-up", self.setKey, ["cam-left", False]) self.accept("s-up", self.setKey, ["cam-down", False]) self.accept("d", self.setKey, ["cam-right", True]) self.accept("d-up", self.setKey, ["cam-right", False]) self.accept("w", self.setKey, ["cam-up", True]) self.accept("w-up", self.setKey, ["cam-up", False]) # to switch between tasks self.accept("h", self.setKey, ["switch-mode", True]) self.accept("h-up", self.setKey, ["switch-mode", False]) taskMgr.add(self.move, "moveTask") # Game state variables self.isMoving = False self.cameraPositionX = 0 self.cameraPositionY = 0 self.cameraPositionZ = 0 # note for rotating camera: from this website: # https://www.panda3d.org/manual/index.php/Common_State_Changes # setHpr(Yaw, Pitch, Roll) # setting up initial conditions for which way camera is rotated self.cameraYaw = 0 self.cameraPitch = 0 # Set up the camera self.disableMouse() # should probably clean up these magic numbers self.camera.setPos(20, 20, 20) # Create some lighting # this is a part that is completely unchanged from demo ambientLight = AmbientLight("ambientLight") ambientLight.setColor((.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection((-5, -5, -5)) directionalLight.setColor((1, 1, 1, 1)) directionalLight.setSpecularColor((1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight))
class VisibleShip(ShipBase): editable = True def __init__(self, name, ship_object, radius): ShipBase.__init__(self, name) self.ship_object = ship_object self.radius = radius #TODO: Should be refactored with StellarBody ! self.shown = True self.visible = True self.resolved = True self.oid_color = LColor() self.world_body_center_offset = LVector3d() self.model_body_center_offset = LVector3d() self.light_color = LColor(1, 1, 1, 1) self.rel_position = None self.scene_rel_position = None self.distance_to_obs = None self.vector_to_obs = None self.vector_to_star = None self.star = None self.directional_light = None self.light_source = None self.scene_position = None self.scene_distance = None self.scene_scale_factor = None self.scene_orientation = None self.ship_object.set_parent(self) #TODO: Temporary workaround as some code need the shape to have an owner self.ship_object.set_owner(self) self.ship_object.set_scale(LVector3d(self.radius, self.radius, self.radius)) self.shadow_caster = None self.create_own_shadow_caster = True def check_settings(self): self.ship_object.check_settings() if self.shadow_caster is not None: self.shadow_caster.check_settings() def get_user_parameters(self): parameters = self.ship_object.get_user_parameters() group = ParametersGroup(self.get_name(), parameters) return group def update_user_parameters(self): self.ship_object.update_user_parameters() def get_apparent_radius(self): return self.radius def get_extend(self): return self.radius def get_local_position(self): return self._local_position #TODO: Should be refactored with StellarBody ! def create_light(self): print("Create light for", self.get_name()) self.directional_light = DirectionalLight('light_source') self.directional_light.setDirection(LVector3(*-self.vector_to_star)) self.directional_light.setColor((1, 1, 1, 1)) self.light_source = self.context.world.attachNewNode(self.directional_light) self.set_light(self.light_source) def update_light(self, camera_pos): if self.light_source is None: return pos = self.get_local_position() + self.vector_to_star * self.get_extend() self.place_pos_only(self.light_source, pos, camera_pos, self.distance_to_obs, self.vector_to_obs) self.directional_light.setDirection(LVector3(*-self.vector_to_star)) def remove_light(self): self.light_source.remove_node() self.light_source = None self.directional_light = None def update(self, time, dt): ShipBase.update(self, time, dt) self.ship_object.update(time, dt) def update_obs(self, observer): self.rel_position = self._local_position - observer._local_position self.distance_to_obs = self.rel_position.length() self.vector_to_obs = self.rel_position / self.distance_to_obs if self.context.nearest_system is not None: self.star = self.context.nearest_system.star self.vector_to_star = (self.star._local_position - self._local_position).normalized() if self.light_source is None: self.create_light() else: self.star = None self.vector_to_star = LVector3d.up() if self.light_source is not None: self.remove_light() self.ship_object.update_obs(observer) def check_visibility(self, pixel_size): self.ship_object.check_visibility(pixel_size) def update_shader(self): ShipBase.update_shader(self) self.ship_object.update_shader() def check_and_update_instance(self, camera_pos, camera_rot, pointset): self.scene_rel_position = self.rel_position self.scene_position, self.scene_distance, self.scene_scale_factor = self.calc_scene_params(self.rel_position, self._position, self.distance_to_obs, self.vector_to_obs) self.scene_orientation = self._orientation self.ship_object.check_and_update_instance(camera_pos, camera_rot, pointset) self.instance = self.ship_object.instance self.instance.hide(self.AllCamerasMask) self.instance.show(self.NearCameraMask) self.instance.show(self.WaterCameraMask) self.instance.show(self.ShadowCameraMask) self.update_light(camera_pos) if self.create_own_shadow_caster: if self.shadow_caster is None: self.shadow_caster = CustomShadowMapShadowCaster(self, None) self.shadow_caster.create() self.shadow_caster.update() self.ship_object.shadows.start_update() self.shadow_caster.add_target(self.ship_object) self.ship_object.shadows.end_update() def remove_instance(self): self.ship_object.remove_instance() self.instance = None if self.shadow_caster is not None: self.shadow_caster.remove() self.shadow_caster = None self.remove_light()
def initialize(self): self.timer = 0 base.enableParticles() #base.setFrameRateMeter(True) ########## # # SETUP COLLISION HANDLERS AND FLAMIE'S MODEL # ########## #Create the collision handlers in order to build the level. WALL_MASK = BitMask32.bit(2) FLOOR_MASK = BitMask32.bit(1) #Start up the collision system self.cTrav = CollisionTraverser() #Determine how collisions with walls will be handled self.wallHandler = CollisionHandlerPusher() self.bobbing = False #Setup flamie's model self.flamieNP = base.render.attachNewNode(ActorNode('flamieNP')) self.flamieNP.reparentTo(base.render) self.flamie = loader.loadModel('models/Flame/body') self.flamie.setScale(.5) self.flamie.setTransparency(TransparencyAttrib.MAlpha) self.flamie.setAlphaScale(0) self.flamie.reparentTo(self.flamieNP) self.flamie.setCollideMask(BitMask32.allOff()) flameLight = DirectionalLight("flameLight") fl = self.flamie.attachNewNode(flameLight) fl.setColor(255, 255, 255, 1) flameLight.setDirection((-5, -5, -5)) self.flamie.setLight(fl) self.flamie2 = loader.loadModel("models/p.obj") self.flamie2.setTexture(loader.loadTexture("models/flamie2D/f7.png")) self.flamie2.reparentTo(self.flamieNP) self.flamie2.setScale(4) self.flamie2OriZ = 2 self.flamie2.setPos(-6.5, 0, self.flamie2OriZ) #(length, depth, height) self.flamie2.setLight(fl) self.flamie2.setTransparency(TransparencyAttrib.MAlpha) self.flamieFire = PointLight('fire') self.flamieFire.setColor(VBase4(1,1,1,1)) self.flamieFire.setAttenuation((1,0,1)) plnp = render.attachNewNode(self.flamieFire) plnp.setPos(self.flamieNP.getPos()) self.flamielight = AmbientLight('light') self.flamielight.setColor(VBase4(1, 0.5, 0.6, 1)) self.flamielight = self.flamie2.attachNewNode(self.flamielight) self.flamie2.setLight(self.flamielight) self.flamie2.setLight(plnp) self.mayFlamieBob = True #self.flamie2.setAlphaScale(0.5) '''self.tree = loader.loadModel("models/p2.obj") self.tree.setTexture(loader.loadTexture("deadTree.png")) self.tree.reparentTo(render) self.tree.setScale(4) self.tree.setPos(25,25,0) #(length, depth, height) self.tree.setLight(fl) self.tree.setTransparency(TransparencyAttrib.MAlpha) self.treelight = AmbientLight('light') self.treelight.setColor(VBase4(0.9, 0.9, 0.6, 1)) self.treelight = self.tree.attachNewNode(self.treelight) self.tree.setLight(self.treelight)''' x = 150 y = 20 offset1 = 0 treeList2 = [loader.loadModel("models/p2.obj") for i in range(7)] for j in treeList2: k = random.randint(1, 100) if k%5 is 1 or k%5 is 2: j.setTexture(loader.loadTexture("deadTree.png")) else: j.setTexture(loader.loadTexture("tree.png")) j.reparentTo(render) j.setScale(random.randint(4,7)) j.setTransparency(TransparencyAttrib.MAlpha) j.setPos(x + 3*offset1, y + 4*offset1, 0) treelight = AmbientLight('light') treelight = j.attachNewNode(treelight) j.setLight(treelight) offset1 = offset1 + random.randint(4, 10) x = 4 y = 90 offset1 = 0 treeList2 = [loader.loadModel("models/p2.obj") for i in range(6)] for j in treeList2: k = random.randint(1, 100) if k%5 is 1 or k%5 is 2: j.setTexture(loader.loadTexture("deadTree.png")) else: j.setTexture(loader.loadTexture("tree.png")) j.reparentTo(render) j.setScale(random.randint(4,7)) j.setTransparency(TransparencyAttrib.MAlpha) j.setPos(x + 3*offset1, y + 4*offset1, 0) treelight = AmbientLight('light') treelight = j.attachNewNode(treelight) j.setLight(treelight) offset1 = offset1 + random.randint(4, 10) x = 3 y = 120 offset1 = 0 treeList2 = [loader.loadModel("models/p2.obj") for i in range(4)] for j in treeList2: k = random.randint(1, 100) if k%5 is 1 or k%5 is 2: j.setTexture(loader.loadTexture("deadTree.png")) else: j.setTexture(loader.loadTexture("tree.png")) j.reparentTo(render) j.setScale(random.randint(4,7)) j.setTransparency(TransparencyAttrib.MAlpha) j.setPos(x + 3*offset1, y + 4*offset1, 0) treelight = AmbientLight('light') treelight = j.attachNewNode(treelight) j.setLight(treelight) offset1 = offset1 + random.randint(4, 10) x = 200 y = 20 offset1 = 0 treeList2 = [loader.loadModel("models/p2.obj") for i in range(4)] for j in treeList2: k = random.randint(1, 100) if k%5 is 1 or k%5 is 2: j.setTexture(loader.loadTexture("deadTree.png")) else: j.setTexture(loader.loadTexture("tree.png")) j.reparentTo(render) j.setScale(random.randint(4,7)) j.setTransparency(TransparencyAttrib.MAlpha) j.setPos(x + 3*offset1, y + 4*offset1, 0) treelight = AmbientLight('light') treelight = j.attachNewNode(treelight) j.setLight(treelight) offset1 = offset1 + random.randint(4, 10) ### Something that should look like water ### w = loader.loadModel("models/flatP.obj") w.setTexture(loader.loadTexture("ice.png")) w.reparentTo(render) w.setScale(75) w.setTransparency(TransparencyAttrib.MAlpha) w.setAlphaScale(.7) w.setLight(treelight) w.setPos(-200, 0, -10) self.waterOrigiZ = -10 self.waterSecZ = -95 self.waterThirdZ = -120 self.water = w ### Reskying the sky ### w = loader.loadModel("models/biggerFlatP.obj") w.setTexture(loader.loadTexture("models/n2.jpg")) w.reparentTo(self.flamie2) w.setScale(15) w.setLight(treelight) w.setPos(-200, 450, -200) #(length, depth, height) #Give flamie gravity self.floorHandler = CollisionHandlerGravity() self.floorHandler.setGravity(9.81+100) self.floorHandler.setMaxVelocity(100) ########## # # GENERATING LEVEL PARTS # ########## self.ice_reset = () self.start = PlatformSeg(LVector3(0,0,0)) self.start.generateAllParts(render) self.checkpointCreator(70, 90, self.start.pos.z, 10) self.floater = False for p in self.start.parts: if isinstance(p, Prism): self.collisionBoxCreator(p.pos.x, p.pos.y, p.pos.z, p.len, p.wid, p.dep, 'terraincollision', 'wallcollision') if isinstance(p, Square): self.collisionBoxCreator(p.pos.x, p.pos.y, p.pos.z, p.len, p.wid, 3, 'terraincollision', 'wallcollision') if isinstance(p, IceCube): p.model.setCollideMask(BitMask32.allOff()) self.ice_reset += (p,) iceCubefloor= p.model.find("**/iceFloor") iceCubewall = p.model.find("**/iceWall") iceCubefloor.node().setIntoCollideMask(FLOOR_MASK) iceCubewall.node().setIntoCollideMask(WALL_MASK) self.lostWood = LostWood(LVector3(self.start.pos.x + 750, self.start.parts[0].pos.y + self.start.parts[0].wid, self.start.pos.z)) self.lostWood.generateAllParts(render) self.checkpointCreator(self.lostWood.pos.x+120, self.lostWood.pos.y+150, self.lostWood.pos.z,20) self.checkpointCreator(self.lostWood.parts[6].pos.x + self.lostWood.parts[6].len/2, self.lostWood.parts[6].pos.y + self.lostWood.parts[6].wid/2, self.lostWood.pos.z, 40) for p in self.lostWood.parts: if isinstance(p, Prism): self.collisionBoxCreator(p.pos.x, p.pos.y, p.pos.z, p.len, p.wid, p.dep, 'terraincollision', 'wallcollision') if isinstance(p, Square): self.collisionBoxCreator(p.pos.x, p.pos.y, p.pos.z, p.len, p.wid, 3, 'terraincollision', 'wallcollision') if isinstance(p, IceCube): p.model.setCollideMask(BitMask32.allOff()) self.ice_reset += (p,) iceCubefloor= p.model.find("**/iceFloor") iceCubewall = p.model.find("**/iceWall") iceCubefloor.node().setIntoCollideMask(FLOOR_MASK) iceCubewall.node().setIntoCollideMask(WALL_MASK) self.cave = Cave(LVector3(self.lostWood.pos.x + 1100, self.lostWood.pos.y + 2000, self.lostWood.pos.z - 50)) self.cave.generateAllParts(render) self.checkpointCreator(self.cave.thirdRoomParts[5].pos.x + self.cave.thirdRoomParts[5].len/2, self.cave.thirdRoomParts[5].pos.y + self.cave.thirdRoomParts[5].wid/2, self.cave.thirdRoomParts[5].pos.z, 30) for p in self.cave.parts: if isinstance(p, Prism): self.collisionBoxCreator(p.pos.x, p.pos.y, p.pos.z, p.len, p.wid, p.dep, 'terraincollision', 'wallcollision') if isinstance(p, Square): self.collisionBoxCreator(p.pos.x, p.pos.y, p.pos.z, p.len, p.wid, 3, 'terraincollision', 'wallcollision') if isinstance(p, IceCube): p.model.setCollideMask(BitMask32.allOff()) self.ice_reset += (p,) iceCubefloor= p.model.find("**/iceFloor") iceCubewall = p.model.find("**/iceWall") iceCubefloor.node().setIntoCollideMask(FLOOR_MASK) iceCubewall.node().setIntoCollideMask(WALL_MASK) self.end = End(LVector3(self.cave.thirdRoomParts[8].pos.x - 200, self.cave.thirdRoomParts[8].pos.y + self.cave.thirdRoomParts[8].wid, self.cave.thirdRoomParts[8].pos.z)) self.end.generate(render) self.collisionBoxCreator(self.end.floor.pos.x, self.end.floor.pos.y, self.end.floor.pos.z, self.end.floor.len, self.end.floor.wid, self.end.floor.dep, 'terraincollision', 'wallcollision') ######### # DRAWING THE CABIN AND FINAL CAMPFIRE ######### self.checkpointCreator(self.end.floor.pos.x + self.end.floor.len/2, self.end.floor.pos.y + self.end.floor.wid/2, self.end.floor.pos.z, 30) self.cabin = loader.loadModel("models/p2.obj") self.cabin.setTexture(loader.loadTexture("models/cabin.png")) self.cabin.setScale(50) self.cabin.reparentTo(render) self.cabin.setPos(self.end.floor.pos.x + self.end.floor.len/2, self.end.floor.pos.y + self.end.floor.wid/1.1, self.end.floor.pos.z) self.cabin.setTransparency(TransparencyAttrib.MAlpha) #Manually creating starting position. Copy and paste the first three parameters of the checkpoint you want to start at. self.startPos = LVector3(70, 90, self.start.pos.z) self.flamieNP.setPos(self.startPos) '''#Testing the tree model self.tree = loader.loadModel('models/Tree/log') self.tree.reparentTo(render) self.tree.setPos(-50,0,100) self.tree.setScale(2)''' '''#Add sky background self.sky = loader.loadModel('models/sphere.obj') self.sky.reparentTo(self.camera) self.sky.set_two_sided(True) self.skyTexture = loader.loadTexture("models/n2.jpg") self.sky.setTexture(self.skyTexture) self.sky.set_bin('background', 0) self.sky.set_depth_write(False) self.sky.set_compass()''' ########## # # CREATE FLAMIE'S COLLISION GEOMETRY # ########## #Give flamie a collision sphere in order to collide with walls flamieCollider = self.flamie.attachNewNode(CollisionNode('flamiecnode')) flamieCollider.node().addSolid(CollisionSphere(0,0,0,5)) flamieCollider.node().setFromCollideMask(WALL_MASK) flamieCollider.node().setIntoCollideMask(BitMask32.allOff()) self.wallHandler.addCollider(flamieCollider, self.flamieNP) self.cTrav.addCollider(flamieCollider, self.wallHandler) #Give flamie a collision ray to collide with the floor flamieRay = self.flamie.attachNewNode(CollisionNode('flamieRay')) flamieRay.node().addSolid(CollisionRay(0,0,8,0,0,-1)) flamieRay.node().setFromCollideMask(FLOOR_MASK) flamieRay.node().setIntoCollideMask(BitMask32.allOff()) self.floorHandler.addCollider(flamieRay, self.flamieNP) self.cTrav.addCollider(flamieRay, self.floorHandler) #Add a sensor that lets us melt ice cubes without standing on the cube. meltSensor = self.flamie.attachNewNode(CollisionNode('meltSensor')) cs = CollisionSphere(-2,0,10, 50) meltSensor.node().addSolid(cs) meltSensor.node().setFromCollideMask(WALL_MASK) meltSensor.node().setIntoCollideMask(BitMask32.allOff()) cs.setTangible(0) self.wallHandler.addCollider(meltSensor, self.flamieNP) self.cTrav.addCollider(meltSensor, self.wallHandler) self.wallHandler.addInPattern('%fn-into-%in') self.wallHandler.addAgainPattern('%fn-again-%in') self.accept('meltSensor-into-iceWall', self.melt) self.accept('meltSensor-again-iceWall', self.melt) self.accept('meltSensor-into-checkpointCol', self.newstart) #Add in an event handle to prevent the jumping glitch found on the bobbing ice cubes. self.floorHandler.addInPattern('%fn-into-%in') self.floorHandler.addAgainPattern('%fn-again-%in') self.floorHandler.addOutPattern('%fn-out-%in') self.accept('flamieRay-into-iceFloor', self.jittercancel) self.accept('flamieRay-again-iceFloor', self.jittercancel) self.accept('flamieRay-out-iceFloor', self.jittercanceloff) #Uncomment these lines to see flamie's collision geometry #flamieCollider.show() #flamieRay.show() #meltSensor.show() #Uncomment this line to see the actual collisions. #self.cTrav.showCollisions(render) #This plane is found at the very bottom of the level and adds global gravity. killfloor = CollisionPlane(Plane(Vec3(0,0,1), Point3(0,0,-1000))) killfloorCol = CollisionNode('kfcollision') killfloorCol.addSolid(killfloor) killfloorCol.setIntoCollideMask(BitMask32.bit(1)) killfloorColNp = self.render.attachNewNode(killfloorCol) #################### # # Setting light so that we could see the definition in the walls # #################### render.setShaderAuto() self.dlight = DirectionalLight('dlight') self.dlight.setColor(LVector4(0.3, 0.1, 0.7, 1)) dlnp = render.attachNewNode(self.dlight) dlnp.setHpr(90, 20, 0) render.setLight(dlnp) self.alight = render.attachNewNode(AmbientLight("Ambient")) self.alight.node().setColor(LVector4(0.5, 0.5, 1, .1)) render.setLight(self.alight) self.snow = loader.loadTexture("models/ground.jpg") #Create a floater object and have it float 2 units above fireball. #And use this as a target for the camera to focus on. #This idea is taken from the roaming ralph sample that came with the #Panda3D SDK. self.camFocus = NodePath(PandaNode("floater")) self.camFocus.reparentTo(render) self.camFocusCurrZ = self.flamie.getZ() + 10 #The camera is locked to the avatar so it always follows regardless of movement. self.camera.reparentTo(render) self.cameraTargetHeight = 8.0 self.cameraDistance = 100 self.cameraHeightModes = (self.start.parts[0].pos.z + 45, self.start.parts[0].pos.z + 125, self.camFocus.getZ() + 10, self.camFocus.getZ() + 150, self.end.floor.pos.z + 10) self.cameraHeight = self.cameraHeightModes[0]
def __init__(self): self.keyMap = { "left": 0, "right": 0, "forward": 0, "cam-left": 0, "cam-right": 0 } base.win.setClearColor(Vec4(0, 0, 0, 1)) self.speed = 0 self.font_digital = loader.loadFont('font/SFDigitalReadout-Heavy.ttf') # Speedometer self.speed_img = OnscreenImage(image="models/speedometer.png", scale=.5, pos=(1.1, 0, -.95)) self.speed_img.setTransparency(TransparencyAttrib.MAlpha) OnscreenText(text="km\n/h", style=1, fg=(1, 1, 1, 1), font=self.font_digital, scale=.07, pos=(1.25, -.92)) # Display Speed self.display_speed = OnscreenText(text=str(self.speed), style=1, fg=(1, 1, 1, 1), pos=(1.3, -0.95), align=TextNode.ARight, scale=.07, font=self.font_digital) # Health Bar self.bars = {'H': 100, 'EH': 0, 'A': 0} # bk_text = "This is my Demo" # self.textObject = OnscreenText(text = bk_text, pos = (0.55,-0.05),scale = 0.07,fg=(1,0.5,0.5,1),align=TextNode.ACenter,mayChange=1) self.Health_bar = DirectWaitBar(text="", value=100, pos=(0.280, 0, 0.475), barColor=(1, 0, 0, 1), frameSize=(0, .705, .3, .35)) self.EHealth_bar = DirectWaitBar(text="", value=0, pos=(1, 0, 0.475), barColor=(0, 1, 0, 1), frameSize=(0, .23, .3, .35), range=50) self.Armour_bar = DirectWaitBar(text="", value=0, pos=(.43, 0, .593), barColor=(159, 0, 255, 1), frameSize=(0, .8, .3, .35)) self.Health = DirectWaitBar(text="", value=100, barColor=(1, 0, 0, 1), frameSize=(-1, 1, .3, .5), scale=2) # create a frame # myFrame = DirectFrame(frameColor=(1, 0, 0, 1), # frameSize=(0, .8, 0, .2)) # self.bar = DirectWaitBar(text = "hi", # value = 0, # range = 500, # pos = ( 0,0,0), # barColor = (0.97,0,0,1), # frameSize = (-0.3,0.3,0.5,0.8), # text_mayChange = 1, # text_shadow =(0,0,0,0.8), # text_fg = (0.9,0.9,0.9,1), # text_scale = 0.025, # text_pos = (0,0.01,0)) def getHealthStatus(): return self.bars def displayBars(): health = getHealthStatus() self.Health_bar['value'] = health['H'] self.EHealth_bar['value'] = health['EH'] self.Armour_bar['value'] = health['A'] self.Health['value'] = health['H'] def armourPickup(): self.bars['A'] += 25 displayBars() def healthPickup(): self.bars['EH'] += 25 displayBars() def decHealth(): self.bars['H'] -= 10 displayBars() def initialiseSound(audioManager): """Start the engine sound and set collision sounds""" # Set sounds to play for collisions # self.collisionSound = CollisionSound( # nodePath=self.np, # sounds=["data/sounds/09.wav"], # thresholdForce=600.0, # maxForce=800000.0) # np - nodePath self.engineSound = audioManager.loadSfx("sound/engine.wav") audioManager.attachSoundToObject(self.engineSound, self.ralph) self.engineSound.setLoop(True) self.engineSound.setPlayRate(0.6) self.engineSound.play() # self.gearSpacing = (self.specs["sound"]["maxExpectedRotationRate"] / # self.specs["sound"]["numberOfGears"]) self.gearSpacing = (150 / 4) self.reversing = False # Post the instructions self.frame = OnscreenImage(image="models/gframe.png", pos=(0, 0, 0), scale=(1.25, 1, 1)) self.frame.setTransparency(TransparencyAttrib.MAlpha) # self.title = addTitle("Panda3D Tutorial: Roaming Ralph (Walking on the Moon)") self.inst1 = addInstructions(0.95, "[ESC]: Quit") self.inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left") self.inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right") self.inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward") self.inst6 = addInstructions(0.70, "[A]: Rotate Camera Left") self.inst7 = addInstructions(0.65, "[S]: Rotate Camera Right") # Set up the environment # self.environ = loader.loadModel("models/square") self.environ.reparentTo(render) self.environ.setPos(0, 0, 0) self.environ.setScale(100, 100, 1) self.moon_tex = loader.loadTexture("models/moon_1k_tex.jpg") self.environ.setTexture(self.moon_tex, 1) # Create the main character, Ralph self.ralph = Actor("models/ralph", { "run": "models/ralph-run", "walk": "models/ralph-walk" }) self.ralph.reparentTo(render) self.ralph.setScale(.2) self.ralph.setPos(0, 0, 0) # # Load and place the model # self.eNode = render.attachNewNode('enemyBaseNode') # self.eNode.setPos( 0,0,0 ) # self.model = loader.loadModel( 'models/ralph' ) # self.model.reparentTo( self.eNode ) # # Setup the rest of what the enemy needs # self.setupHealthBar() # self.Health.setBillboardAxis() # self.Health.setBillboardPointWorld() # self.Health.setBillboardPointEye() # self.Health.setLightOff() self.Health.setPos(0, 0, 5) self.Health.setBillboardPointEye() self.Health.setBin('fixed', 0) self.Health.setDepthWrite(False) self.Health.reparentTo(self.ralph) # myFrame.setPos(0, 0, 8) # myFrame.setBillboardPointEye() # myFrame.reparentTo(self.ralph) # self.Health.clearBillboard() # Create a floater object. We use the "floater" as a temporary # variable in a variety of calculations. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # Accept the control keys for movement and rotation self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", 1]) self.accept("arrow_right", self.setKey, ["right", 1]) self.accept("arrow_up", self.setKey, ["forward", 1]) self.accept("a", self.setKey, ["cam-left", 1]) self.accept("s", self.setKey, ["cam-right", 1]) self.accept("arrow_left-up", self.setKey, ["left", 0]) self.accept("arrow_right-up", self.setKey, ["right", 0]) self.accept("arrow_up-up", self.setKey, ["forward", 0]) self.accept("a-up", self.setKey, ["cam-left", 0]) self.accept("s-up", self.setKey, ["cam-right", 0]) self.accept("h", decHealth) self.accept("j", healthPickup) self.accept("k", armourPickup) taskMgr.add(self.move, "moveTask") taskMgr.doMethodLater(.1, self.show_speed, 'updateSpeed') # Game state variables self.isMoving = False # Set up the camera base.disableMouse() base.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight)) # 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( base.sfxManagerList[0], base.camera) # Distance should be in m, not feet self.audioManager.setDistanceFactor(3.28084) initialiseSound(self.audioManager) displayBars()
def __init__(self): ShowBase.__init__(self) # This is used to store which keys are currently pressed. self.keyMap = { "left": 0, "right": 0, "forward": 0, "back": 0, "up": 0} # Set up the environment # # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel("EggMod/SandPlan.egg") self.environ.reparentTo(render) self.environ.setScale(20) StartPos = LVector3(0,0,94) self.movint = loader.loadModel("EggMod/HailPar.egg") self.movint.reparentTo(render) self.movint.setScale(2) self.movint.setPos(StartPos + (0, 0, 0.5)) # Accept the control keys for movement and rotation self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", True]) self.accept("arrow_right", self.setKey, ["right", True]) self.accept("arrow_up", self.setKey, ["forward", True]) self.accept("arrow_down", self.setKey, ["back", True]) self.accept("f", self.setKey, ["up", True]) self.accept("arrow_left-up", self.setKey, ["left", False]) self.accept("arrow_right-up", self.setKey, ["right", False]) self.accept("arrow_up-up", self.setKey, ["forward", False]) self.accept("arrow_down-up", self.setKey, ["back", False]) self.accept("f-up", self.setKey, ["up", False]) self.mopan=Pmango() self.alin = LinearEulerIntegrator() self.mopan.attachLinearIntegrator(self.alin) self.arin = AngularEulerIntegrator() self.mopan.attachAngularIntegrator(self.arin) taskMgr.add(self.move, "moveTask") self.cTrav = CollisionTraverser() #base.cTrav.setRespectPrevTransform(True) self.actMove = NodePath("ActMove") self.actMove.reparentTo(render) self.an = ActorNode("BMova") self.anp = self.actMove.attachNewNode(self.an) self.mopan.attachPhysicalNode(self.an) self.movint.reparentTo(self.anp) self.anp.node().getPhysicsObject().setMass(1) #self.an.getPhysicsObject().setTerminalVelocity(1.0) self.dvi=0 self.grava=ForceNode('GravAll') self.grar=render.attachNewNode(self.grava) self.grdi=LinearVectorForce(0.0,-0.0,-8.0) #self.grdi.setMassDependent(1) self.grava.addForce(self.grdi) #Forces have to be added to force nodes and to # a physics manager self.mopan.addLinearForce(self.grdi) self.BMoveBalance = CollisionSphere(0, 0, -7.0, 1) self.BMoveBalanceNode = CollisionNode('BMove') self.BMoveBalanceNode.addSolid(self.BMoveBalance) self.BMoveBalancePath = self.movint.attachNewNode(self.BMoveBalanceNode) self.DinGro = PhysicsCollisionHandler() self.DinGro.setStaticFrictionCoef(1) self.DinGro.setDynamicFrictionCoef(2) self.DinGro.setAlmostStationarySpeed(0.1) self.DinGro.addCollider(self.BMoveBalancePath,self.anp) #Colliders use nodepaths for collisions instead of nodes self.cTrav.addCollider(self.BMoveBalancePath, self.DinGro) # Uncomment this line to see the collision rays self.BMoveBalancePath.show() # Uncomment this line to show a visual representation of the # collisions occuring self.cTrav.showCollisions(render) # Create some lighting directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection((-5, -5, -5)) render.setLight(render.attachNewNode(directionalLight))
def __init__(self, data_file='data/sample_labeled.csv', target_id=-1): self.read_ngsim_data(data_file) base.setBackgroundColor(0.1, 0.1, 0.8, 1) base.setFrameRateMeter(True) # globalClock.setMode(ClockObject.MForced); # self.frame_rate = int(1/self.dT); # globalClock.setFrameRate(self.frame_rate); # print(ConfigVariableDouble("clock-frame-rate")) # base.setFrameRateMeter(True) #TODO: move these to where they belong self.x_center = 36 self.lane_width = 12 self.timer = self.df.iloc[0].Global_Time self.idx = 0 self.ego_id = -1 self.target_ego_id = target_id self.score = 0 self.tot = 0 # road geometry generation #road=trail(100,50,40,0.2) # generating a circular lane track self.precision = 1 # length of a piece of centerLine self.texLength = 10 self.laneNum = 4 self.radiu = 500 # road=basicFreeWay(200,self.radiu,5,self.precision,4) # generating a piece of freeway road = straightCenter(np.array([self.x_center, 0]), math.pi / 2, 2000, 2) # generating a straight way self.segLine = road.getLine() # the centerLine self.road = roadGenerator(np.array([self.x_center, -1]), 12, 8, road.getFollowing(), self.segLine, -1, self.texLength, self.precision) # generate road polygon self.rightBound = self.road.rightPoints self.leftBound = self.road.leftPoints segLength = len(self.segLine) self.lines = [] for j in range(0, self.laneNum): line = [] for i in range(0, segLength): line.append( np.array([ self.rightBound[i][0] * (1 / 8 + j * 1 / 4) * 1 + self.leftBound[i][0] * (7 / 8 - j * 1 / 4) * 1, self.rightBound[i][1] * (1 / 8 + j * 1 / 4) + self.leftBound[i][1] * (7 / 8 - j * 1 / 4) ])) self.lines = self.lines + [line] #self.rightLine.append(self.segLine[i]/2+self.rightBound[i]/2) #self.leftLine.append(self.segLine[i]/2+self.leftBound[i]/2) node = self.road.getNode() # road texture # The lane number on texture pic should be consistent with data floorTex = loader.loadTexture('maps/6lane.jpg') floor = render.attachNewNode(node) floor.setTexture(floorTex) # floor.flattenStrong() # grass background generation '''floorTex1 = loader.loadTexture('maps/envir-ground.jpg') cm1 = CardMaker('') cm1.setFrame(-2, 2, -2, 2) floor1 = render.attachNewNode(PandaNode("floor1")) for y in range(400): for x in range(22): nn1 = floor1.attachNewNode(cm1.generate()) nn1.setP(-90) nn1.setPos((x - 10) * 4, (y - 20) * 4, -1.1) floor1.setTexture(floorTex1) floor1.flattenStrong()''' # initial automated vehicle self.initAV = [50, 0, 0] desiredV = 40 basicVehicleNum = 20 self.agents = [] # self.agents.append(planningAgent(20,5,desiredV,int(math.floor((self.initAV[1]+8)/4)),basicVehicleNum,self.radiu)) # initial agent # initial surrounding vehicle self.vehicles_maxload = 100 # for i in range(self.vehicles_maxload): # self.initSV.append([1000,0,v1]) # self.agents.append(laneKeepingAgent(20,20,self.initSV[-1][2],int(math.floor((self.initSV[-1][1]+8)/4)))) # initial camera base.cam.setPos(self.x_center + 300, 150, 300) base.cam.lookAt(self.x_center - 200, 300, -200) # Light alight = AmbientLight('ambientLight') alight.setColor(Vec4(0.5, 0.5, 0.5, 1)) alightNP = render.attachNewNode(alight) dlight = DirectionalLight('directionalLight') dlight.setDirection(Vec3(1, 1, -1)) dlight.setColor(Vec4(0.7, 0.7, 0.7, 1)) dlightNP = render.attachNewNode(dlight) render.clearLight() render.setLight(alightNP) render.setLight(dlightNP) # Input setup self.accept('escape', self.doExit) self.accept('f1', self.toggleWireframe) self.accept('f2', self.toggleTexture) self.accept('f3', self.toggleDebug) self.accept('f5', self.doScreenshot) # Task manager taskMgr.add(self.update, 'updateWorld') # Physics self.setup()
def __init__(self): # Initialize the ShowBase class from which we inherit, which will # create a window and set up everything we need for rendering into it. ShowBase.__init__(self) base.setBackgroundColor(0, 0, 0) self.accept("escape", sys.exit) # Escape quits self.disableMouse() camera.setPosHpr(0, 0, 0, 0, 0, 0) lens = PerspectiveLens() lens.setFov(90, 60) lens.setNear(0.01) lens.setFar(100000) self.cam.node().setLens(lens) self.ballSize = 0.025 self.cueLength = 0.2 # self.ballRoot = render.attachNewNode("ballRoot") # #self.ball = loader.loadModel("models/ball") # self.ball = loader.loadModel("models/ball_0_center.egg") # #self.ball = loader.loadModel("models/ball.dae") # self.ball.setScale(ballSize, ballSize, ballSize) # self.ball.reparentTo(self.ballRoot) # #print(self.ball.getBounds()) # #exit(1) # #self.ballSphere = self.ball.find("**/ball") # #print(self.ball.getScale()[0]) # cs = CollisionSphere(0, 0, 0, 1) # self.ballSphere = self.ball.attachNewNode(CollisionNode('ball')) # self.ballSphere.node().addSolid(cs) # self.ballSphere.node().setFromCollideMask(BitMask32.bit(0)) # self.ballSphere.node().setIntoCollideMask(BitMask32.bit(1)) self.sceneIndex = 0 self.planeInfo = PlaneScene(self.sceneIndex) self.planeScene = self.planeInfo.generateEggModel() self.planeScene.setTwoSided(True) self.planeScene.reparentTo(render) self.planeScene.hide() #get geometries from plane predictions planeTriangles, horizontalPlaneTriangles, self.gravityDirection = self.planeInfo.getPlaneTriangles( ) # add pool balls self.ballRoots = [] self.balls = [] self.ballSpheres = [] self.ballGroundRays = [] for ballIndex in xrange(3): ballRoot = render.attachNewNode("ballRoot_" + str(ballIndex)) ball = loader.loadModel("models/ball_" + str(ballIndex) + "_center.egg") ball.setScale(self.ballSize, self.ballSize, self.ballSize) cs = CollisionSphere(0, 0, 0, 1) ballSphere = ball.attachNewNode( CollisionNode('ball_' + str(ballIndex))) ballSphere.node().addSolid(cs) ballSphere.node().setFromCollideMask( BitMask32.bit(0) | BitMask32.bit(1) | BitMask32.bit(3) | BitMask32.bit(4)) ballSphere.node().setIntoCollideMask(BitMask32.bit(1)) ball.reparentTo(ballRoot) self.ballRoots.append(ballRoot) self.balls.append(ball) self.ballSpheres.append(ballSphere) ballGroundRay = CollisionRay() # Create the ray ballGroundRay.setOrigin(0, 0, 0) # Set its origin ballGroundRay.setDirection( self.gravityDirection[0], self.gravityDirection[1], self.gravityDirection[2]) # And its direction # Collision solids go in CollisionNode # Create and name the node ballGroundCol = CollisionNode('ball_ray_' + str(ballIndex)) ballGroundCol.addSolid(ballGroundRay) # Add the ray ballGroundCol.setFromCollideMask( BitMask32.bit(2)) # Set its bitmasks ballGroundCol.setIntoCollideMask(BitMask32.allOff()) # Attach the node to the ballRoot so that the ray is relative to the ball # (it will always be 10 feet over the ball and point down) ballGroundColNp = ballRoot.attachNewNode(ballGroundCol) self.ballGroundRays.append(ballGroundColNp) ballRoot.hide() continue # Finally, we create a CollisionTraverser. CollisionTraversers are what # do the job of walking the scene graph and calculating collisions. # For a traverser to actually do collisions, you need to call # traverser.traverse() on a part of the scene. Fortunately, ShowBase # has a task that does this for the entire scene once a frame. By # assigning it to self.cTrav, we designate that this is the one that # it should call traverse() on each frame. self.cTrav = CollisionTraverser() # Collision traversers tell collision handlers about collisions, and then # the handler decides what to do with the information. We are using a # CollisionHandlerQueue, which simply creates a list of all of the # collisions in a given pass. There are more sophisticated handlers like # one that sends events and another that tries to keep collided objects # apart, but the results are often better with a simple queue self.cHandler = CollisionHandlerQueue() # Now we add the collision nodes that can create a collision to the # traverser. The traverser will compare these to all others nodes in the # scene. There is a limit of 32 CollisionNodes per traverser # We add the collider, and the handler to use as a pair #self.cTrav.addCollider(self.ballSphere, self.cHandler) for ballSphere in self.ballSpheres: self.cTrav.addCollider(ballSphere, self.cHandler) continue for ballGroundRay in self.ballGroundRays: self.cTrav.addCollider(ballGroundRay, self.cHandler) continue #self.cTrav.addCollider(self.ballGroundColNp, self.cHandler) # Collision traversers have a built in tool to help visualize collisions. # Uncomment the next line to see it. #self.cTrav.showCollisions(render) # This section deals with lighting for the ball. Only the ball was lit # because the maze has static lighting pregenerated by the modeler ambientLight = AmbientLight("ambientLight") ambientLight.setColor((.55, .55, .55, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(LVector3(0, 0, -1)) directionalLight.setColor((0.375, 0.375, 0.375, 1)) directionalLight.setSpecularColor((1, 1, 1, 1)) for ballRoot in self.ballRoots: ballRoot.setLight(render.attachNewNode(ambientLight)) ballRoot.setLight(render.attachNewNode(directionalLight)) continue # This section deals with adding a specular highlight to the ball to make # it look shiny. Normally, this is specified in the .egg file. m = Material() m.setSpecular((1, 1, 1, 1)) m.setShininess(96) for ball in self.balls: ball.setMaterial(m, 1) continue # self.original = False # if self.original: # camera.setPosHpr(0, 0, 25, 0, -90, 0) # self.maze = loader.loadModel("models/maze") # self.maze.reparentTo(render) # self.walls = self.maze.find("**/wall_collide") # self.walls.node().setIntoCollideMask(BitMask32.bit(0)) # self.walls.show() # pass # create collision entities from plane predictions self.triNPs = [] for triangleIndex, triangle in enumerate(planeTriangles): #print(triangleIndex) #for triangle in triangles: #print(triangle) tri = CollisionPolygon( Point3(triangle[0][0], triangle[0][1], triangle[0][2]), Point3(triangle[1][0], triangle[1][1], triangle[1][2]), Point3(triangle[2][0], triangle[2][1], triangle[2][2])) triNP = render.attachNewNode( CollisionNode('tri_' + str(triangleIndex))) triNP.node().setIntoCollideMask(BitMask32.bit(0)) triNP.node().addSolid(tri) self.triNPs.append(triNP) #triNP.show() continue # create special collision entities for horizontal planes so that balls can fall on one horizontal plane and bounce on it for triangleIndex, triangle in enumerate(horizontalPlaneTriangles): #print(triangleIndex) #for triangle in triangles: #print(triangle) tri = CollisionPolygon( Point3(triangle[0][0], triangle[0][1], triangle[0][2]), Point3(triangle[1][0], triangle[1][1], triangle[1][2]), Point3(triangle[2][0], triangle[2][1], triangle[2][2])) triNP = render.attachNewNode( CollisionNode('ground_' + str(triangleIndex))) triNP.node().setIntoCollideMask(BitMask32.bit(2)) triNP.node().addSolid(tri) self.triNPs.append(triNP) #triNP.show() continue # tri = CollisionPolygon(Point3(-1, 4, -1), Point3(2, 4, -1), Point3(2, 4, 2)) # triNP = render.attachNewNode(CollisionNode('tri')) # triNP.node().setIntoCollideMask(BitMask32.bit(0)) # triNP.node().addSolid(tri) # triNP.show() #self.planeScene.node().setIntoCollideMask(BitMask32.bit(0)) # roomRootNP = self.planeScene # roomRootNP.flattenLight() # mesh = BulletTriangleMesh() # polygons = roomRootNP.findAllMatches("**/+GeomNode") # # p0 = Point3(-10, 4, -10) # # p1 = Point3(-10, 4, 10) # # p2 = Point3(10, 4, 10) # # p3 = Point3(10, 4, -10) # # mesh.addTriangle(p0, p1, p2) # # mesh.addTriangle(p1, p2, p3) # print(polygons) # for polygon in polygons: # geom_node = polygon.node() # #geom_node.reparentTo(self.render) # #print(geom_node.getNumGeoms()) # ts = geom_node.getTransform() # #print(ts) # for geom in geom_node.getGeoms(): # mesh.addGeom(geom, ts) # continue # continue # #self.scene = roomRootNP # shape = BulletTriangleMeshShape(mesh, dynamic=False) # #shape = BulletPlaneShape(Vec3(0, 0, 1), 1) # room = BulletRigidBodyNode('scene') # room.addShape(shape) # #room.setLinearDamping(0.0) # #room.setFriction(0.0) # print(shape) # room.setDeactivationEnabled(False) # roomNP = render.attachNewNode(room) # roomNP.setPos(0, 0, 0) # roomNP.node().setIntoCollideMask(BitMask32.bit(0)) # self.world = BulletWorld() # self.world.setGravity(Vec3(0, 0, 0)) # self.world.attachRigidBody(roomNP.node()) #room.setRestitution(1) #self.roomNP = self.scene # create the cue self.cueRoot = render.attachNewNode("cueRoot") self.cue = loader.loadModel("models/cue_center.egg") self.cue.setScale(self.cueLength * 3, self.cueLength * 3, self.cueLength) self.cue.reparentTo(self.cueRoot) self.cuePos = (10, 0, 0) self.pickerNode = CollisionNode('mouseRay') # Attach that node to the camera since the ray will need to be positioned # relative to it self.pickerNP = camera.attachNewNode(self.pickerNode) # Everything to be picked will use bit 1. This way if we were doing other # collision we could separate it self.pickerNode.setFromCollideMask(BitMask32.bit(2)) self.pickerNode.setIntoCollideMask(BitMask32.allOff()) self.pickerRay = CollisionRay() # Make our ray # Add it to the collision node self.pickerNode.addSolid(self.pickerRay) # Register the ray as something that can cause collisions self.cTrav.addCollider(self.pickerNP, self.cHandler) self.accept("mouse1", self.hit) # left-click grabs a piece # create holes self.holeLength = 0.06 holePos, holeHpr = self.planeInfo.getHolePos() self.holeRoot = render.attachNewNode("holeRoot") #self.hole = loader.loadModel("models/hole_horizontal_center.egg") self.hole = loader.loadModel("models/hole_color.egg") #self.hole = loader.loadModel("models/billiards_hole_center.egg") self.hole.setScale(self.holeLength, self.holeLength, self.holeLength) self.hole.reparentTo(self.holeRoot) self.hole.setTwoSided(True) self.holeRoot.setPos(holePos[0], holePos[1], holePos[2]) self.holeRoot.setHpr(holeHpr[0], holeHpr[1], holeHpr[2]) #tex = loader.loadTexture('models/Black_Hole.jpg') #self.hole.setTexture(tex, 1) self.holeRoot.hide() ct = CollisionTube(0, 0, 0, 0, 0.001, 0, 0.5) self.holeTube = self.hole.attachNewNode(CollisionNode('hole')) self.holeTube.node().addSolid(ct) self.holeTube.node().setFromCollideMask(BitMask32.allOff()) self.holeTube.node().setIntoCollideMask(BitMask32.bit(4)) #self.holeTube.show() # create portals inPortalPos, inPortalHpr, outPortalPos, outPortalHpr, self.portalNormal = self.planeInfo.getPortalPos( ) self.portalLength = 0.06 self.inPortalRoot = render.attachNewNode("inPortalRoot") self.inPortal = loader.loadModel("models/portal_2_center.egg") self.inPortal.setScale(self.portalLength, self.portalLength, self.portalLength) self.inPortal.reparentTo(self.inPortalRoot) self.inPortalRoot.setPos(inPortalPos[0], inPortalPos[1], inPortalPos[2]) self.inPortalRoot.setHpr(inPortalHpr[0], inPortalHpr[1], inPortalHpr[2]) self.inPortalRoot.hide() ct = CollisionTube(0, 0, 0, 0, 0.001, 0, 1) self.inPortalTube = self.inPortal.attachNewNode( CollisionNode('portal_in')) self.inPortalTube.node().addSolid(ct) self.inPortalTube.node().setFromCollideMask(BitMask32.allOff()) self.inPortalTube.node().setIntoCollideMask(BitMask32.bit(3)) #self.inPortalTube.hide() self.outPortalRoot = render.attachNewNode("outPortalRoot") self.outPortal = loader.loadModel("models/portal_2_center.egg") self.outPortal.setScale(self.portalLength, self.portalLength, self.portalLength) self.outPortal.reparentTo(self.outPortalRoot) self.outPortalRoot.setPos(outPortalPos[0], outPortalPos[1], outPortalPos[2]) self.outPortalRoot.setHpr(outPortalHpr[0], outPortalHpr[1], outPortalHpr[2]) self.outPortalRoot.hide() ct = CollisionTube(0, 0, 0, 0, 0.001, 0, 1) self.outPortalTube = self.outPortal.attachNewNode( CollisionNode('portal_out')) self.outPortalTube.node().addSolid(ct) self.outPortalTube.node().setFromCollideMask(BitMask32.allOff()) self.outPortalTube.node().setIntoCollideMask(BitMask32.bit(3)) #self.outPortalTube.hide() #self.inPortalTube.show() #self.outPortalTube.show() #self.holeTube.show() #self.cTrav.addCollider(self.holeTube, self.cHandler) # create background image background_image = loader.loadTexture('dump/' + str(self.sceneIndex) + '_image.png') cm = CardMaker('background') cm.setHas3dUvs(True) info = np.load('dump/' + str(self.sceneIndex) + '_info.npy') #self.camera = getCameraFromInfo(self.info) depth = 10.0 sizeU = info[2] / info[0] * depth sizeV = info[6] / info[5] * depth cm.setFrame(Point3(-sizeU, depth, -sizeV), Point3(sizeU, depth, -sizeV), Point3(sizeU, depth, sizeV), Point3(-sizeU, depth, sizeV)) self.card = self.render.attachNewNode(cm.generate()) self.card.setTransparency(True) self.card.setTexture(background_image) self.card.hide() self.ballGroundMap = {} self.ballBouncing = np.full(len(self.balls), 3) self.started = False self.start() #self.hitIndex = -1 self.showing = 'parts' self.showingProgress = 0 partsScene = PartsScene(self.sceneIndex) self.planeNPs, self.planeCenters = partsScene.generateEggModel() return
def __init__(self): base.setBackgroundColor(0.1, 0.1, 0.8, 1) base.setFrameRateMeter(True) # road geometry generation #road=trail(100,50,40,0.2) # generating a circular lane track self.precision = 1 # length of a piece of centerLine self.texLength = 10 self.laneNum = 4 self.radiu = 500 road = basicFreeWay(200, self.radiu, 3, self.precision, 2) # generating a piece of freeway #road=straightCenter(np.array([0,0]),math.pi/2,2000,2) # generating a straight way self.segLine = road.getLine() # the centerLine self.road = roadGenerator(np.array([0, -1]), 8, 2, road.getFollowing(), self.segLine, -1, self.texLength, self.precision) # generate road polygon self.rightBound = self.road.rightPoints self.leftBound = self.road.leftPoints segLength = len(self.segLine) self.lines = [] for j in range(0, self.laneNum): line = [] for i in range(0, segLength): line.append( np.array([ self.rightBound[i][0] * (1 / 8 + j * 1 / 4) * 1 + self.leftBound[i][0] * (7 / 8 - j * 1 / 4) * 1, self.rightBound[i][1] * (1 / 8 + j * 1 / 4) + self.leftBound[i][1] * (7 / 8 - j * 1 / 4) ])) self.lines = self.lines + [line] #self.rightLine.append(self.segLine[i]/2+self.rightBound[i]/2) #self.leftLine.append(self.segLine[i]/2+self.leftBound[i]/2) node = self.road.getNode() # road texture floorTex = loader.loadTexture('maps/street4.jpg') floor = render.attachNewNode(node) floor.setTexture(floorTex) #floor.flattenStrong() # grass background generation '''floorTex1 = loader.loadTexture('maps/envir-ground.jpg') cm1 = CardMaker('') cm1.setFrame(-2, 2, -2, 2) floor1 = render.attachNewNode(PandaNode("floor1")) for y in range(400): for x in range(22): nn1 = floor1.attachNewNode(cm1.generate()) nn1.setP(-90) nn1.setPos((x - 10) * 4, (y - 20) * 4, -1.1) floor1.setTexture(floorTex1) floor1.flattenStrong()''' # central planner settings self.scenario = 0 # specify a scenario self.replayFile = "traj_log_2.npz" # specify a filename to replay self.replanFlag = True self.changeFlag = False self.MAX_ITER = 20 self.min_dist = 3.9 self.num_steps = 20 self.replayTrajectories = None self.replayIndex = 0 self.changeIdx = [] if self.replayFile is not None: loadData = np.load(self.replayFile) self.replayTrajectories = loadData["log"] self.changeIdx = loadData["c"] if self.replayTrajectories is not None: print("File loaded") else: print("Fail to load file") if self.replayFile is "traj_log_2.npz": self.scenario = 0 elif self.replayFile is "traj_log_9.npz": self.scenario = 1 self.traj_log = [] # initial automated vehicle self.initAV = [] self.agents = [] if self.scenario is 0: # 2 cars take over with different desired velocity scenario ----- desiredV = 6 self.num_steps = 40 # car 0 ** self.initAV.append([0, -2, desiredV]) self.agents.append( mccfsAgent(vGain=50, thetaGain=1000, desiredV=desiredV, laneId=1)) # car 1 ** self.initAV.append([10, -2, desiredV]) self.agents.append( mccfsAgent(vGain=50, thetaGain=1000, desiredV=desiredV, laneId=1)) # ----- 2 cars take over''' elif self.scenario is 1: # 9 cars scenario ----- desiredV = 20 self.num_steps = 20 # car 0 ** self.initAV.append([0, -6, 10]) self.agents.append( mccfsAgent(vGain=20, thetaGain=1000, desiredV=desiredV, laneId=0)) # car 1 ** self.initAV.append([10, -6, 10]) self.agents.append( mccfsAgent(vGain=20, thetaGain=1000, desiredV=desiredV, laneId=0)) # car 2 self.initAV.append([14, -6, 10]) self.agents.append( mccfsAgent(vGain=20, thetaGain=1000, desiredV=desiredV, laneId=0)) # car 3 ** self.initAV.append([2, -2, 10]) self.agents.append( mccfsAgent(vGain=20, thetaGain=1000, desiredV=desiredV, laneId=1)) # car 4 self.initAV.append([15, -2, 10]) self.agents.append( mccfsAgent(vGain=20, thetaGain=1000, desiredV=desiredV, laneId=1)) # car 5 self.initAV.append([25, -2, 10]) self.agents.append( mccfsAgent(vGain=20, thetaGain=1000, desiredV=desiredV, laneId=1)) # car 6 self.initAV.append([5, 2, 10]) self.agents.append( mccfsAgent(vGain=20, thetaGain=1000, desiredV=desiredV, laneId=2)) # car 7 self.initAV.append([10, 2, 10]) self.agents.append( mccfsAgent(vGain=20, thetaGain=1000, desiredV=desiredV, laneId=2)) # car 8 self.initAV.append([20, 2, 10]) self.agents.append( mccfsAgent(vGain=20, thetaGain=1000, desiredV=desiredV, laneId=2)) # ----- 9 cars scenario''' # initialize traj in replay mode if self.replayFile is not None: for i in range(len(self.initAV)): self.agents[i].traj = self.replayTrajectories[ i, self.replayIndex:self.replayIndex + 2, :] # initial camera base.cam.setPos(0, -20, 4) base.cam.lookAt(0, 0, 0) # Light alight = AmbientLight('ambientLight') alight.setColor(Vec4(0.5, 0.5, 0.5, 1)) alightNP = render.attachNewNode(alight) dlight = DirectionalLight('directionalLight') dlight.setDirection(Vec3(1, 1, -1)) dlight.setColor(Vec4(0.7, 0.7, 0.7, 1)) dlightNP = render.attachNewNode(dlight) render.clearLight() render.setLight(alightNP) render.setLight(dlightNP) # Input setup 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('u', self.doLaneChangeLeft) self.accept('o', self.doLaneChangeRight) self.accept('c', self.doLaneChangeDesigned) # inputState.watchWithModifiers('forward', 'w') # inputState.watchWithModifiers('reverse', 's') # inputState.watchWithModifiers('turnLeft', 'a') # inputState.watchWithModifiers('turnRight', 'd') # inputState.watchWithModifiers('brake1', 'x') # inputState.watchWithModifiers('For', 'i') # inputState.watchWithModifiers('Back', 'k') # inputState.watchWithModifiers('Lef', 'j') # inputState.watchWithModifiers('Righ', 'l') # inputState.watchWithModifiers('brake2', 'space') # Task manager taskMgr.add(self.update, 'updateWorld') # Physics self.setup()
def __init__(self): # Set up the window, camera, etc. ShowBase.__init__(self) # Set the background color to black self.win.setClearColor((0, 0, 0, 1)) # This is used to store which keys are currently pressed. self.keyMap = { "left": 0, "right": 0, "forward": 0, "cam-left": 0, "cam-right": 0 } # Post the instructions self.title = addTitle( "Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)") self.inst1 = addInstructions(0.06, "[ESC]: Quit") self.inst2 = addInstructions(0.12, "[Left Arrow]: Rotate Ralph Left") self.inst3 = addInstructions(0.18, "[Right Arrow]: Rotate Ralph Right") self.inst4 = addInstructions(0.24, "[Up Arrow]: Run Ralph Forward") self.inst6 = addInstructions(0.30, "[A]: Rotate Camera Left") self.inst7 = addInstructions(0.36, "[S]: Rotate Camera Right") # Set up the environment # # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) # Create the main character, Ralph ralphStartPos = self.environ.find("**/start_point").getPos() self.ralph = Actor("models/ralph", { "run": "models/ralph-run", "walk": "models/ralph-walk" }) self.ralph.reparentTo(render) self.ralph.setScale(.2) self.ralph.setPos(ralphStartPos + (0, 0, 0.5)) # Create a floater object, which floats 2 units above ralph. We # use this as a target for the camera to look at. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(self.ralph) self.floater.setZ(2.0) # Accept the control keys for movement and rotation self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", True]) self.accept("arrow_right", self.setKey, ["right", True]) self.accept("arrow_up", self.setKey, ["forward", True]) self.accept("a", self.setKey, ["cam-left", True]) self.accept("s", self.setKey, ["cam-right", True]) self.accept("arrow_left-up", self.setKey, ["left", False]) self.accept("arrow_right-up", self.setKey, ["right", False]) self.accept("arrow_up-up", self.setKey, ["forward", False]) self.accept("a-up", self.setKey, ["cam-left", False]) self.accept("s-up", self.setKey, ["cam-right", False]) taskMgr.add(self.move, "moveTask") # Game state variables self.isMoving = False # Set up the camera self.disableMouse() self.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2) # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. One ray will # start above ralph's head, and the other will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal. self.cTrav = CollisionTraverser() self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0, 0, 9) self.ralphGroundRay.setDirection(0, 0, -1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(CollideMask.bit(0)) self.ralphGroundCol.setIntoCollideMask(CollideMask.allOff()) self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol) self.ralphGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler) self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0, 0, 9) self.camGroundRay.setDirection(0, 0, -1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(CollideMask.bit(0)) self.camGroundCol.setIntoCollideMask(CollideMask.allOff()) self.camGroundColNp = self.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Uncomment this line to see the collision rays #self.ralphGroundColNp.show() #self.camGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring #self.cTrav.showCollisions(render) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor((.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection((-5, -5, -5)) directionalLight.setColor((1, 1, 1, 1)) directionalLight.setSpecularColor((1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight))
def __init__(self): #try: #if(co == 0): ShowBase.__init__(self) # co += 1 self.disableMouse() base.setBackgroundColor(0, 0, 1) #camera.setPosHpr(45, -45, 45, 45, -45, 45) self.accept("escape", sys.exit) # Escape quits # Disable default mouse-based camera control. This is a method on the # ShowBase class from which we inherit. #self.disableMouse() camera.setPosHpr(-10, -50, 10, -10, -7, 0) #camera.setPosHpr(-50, 40, 0, 270, 0, 0) #base.setBackgroundColor(0,1,0) #base net = loader.loadModel("models/drawnNet") net.setColor(1, 1, 0) net.setScale(2.5, 2.5, 1.5) net.setPosHpr(0, 53, -2, 0, -10, 0) net.reparentTo(render) global targetY targetY = 40 postR = loader.loadModel("models/box") postR.setColor(0.75, 0, 0.25) postR.setScale(0.03, 0.03, 1) LidR = postR.find('**/lid') PandaR = postR.find('**/turningthing') HingeNodeR = postR.find('**/box').attachNewNode('nHingeNode') HingeNodeR.setPos(.8659, 6.5, 5.4) LidR.wrtReparentTo(HingeNodeR) HingeNodeR.setHpr(0, 90, 0) lidCloseR = Parallel( LerpHprInterval(HingeNodeR, 2.0, (0, 90, 0), blendType='easeInOut')) postR.setPosHpr(18, 55.5, -2, 0, 0, 0) postR.reparentTo(render) postGR = loader.loadModel("models/box") postGR.setColor(0.75, 0, 0.25) postGR.setScale(0.03, 0.03, 1) lidGR = postGR.find('**/lid') PandaGR = postGR.find('**/turningthing') HingeNodeGR = postGR.find('**/box').attachNewNode('nHingeNode') HingeNodeGR.setPos(.8659, 6.5, 5.4) #lidGR.wrtReparentTo(HingeNodeR) HingeNodeGR.setHpr(0, 90, 0) lidCloseGR = Parallel( LerpHprInterval(HingeNodeGR, 2.0, (0, 90, 0), blendType='easeInOut')) postGR.setPosHpr(18, 58.5, -4, 90, 0, 90) postGR.reparentTo(render) postL = loader.loadModel("models/box") postL.setColor(0.75, 0, 0.25) postL.setScale(0.03, 0.03, 2) LidL = postL.find('**/lid') PandaL = postL.find('**/turningthing') HingeNodeL = postL.find('**/box').attachNewNode('nHingeNode') HingeNodeL.setPos(.8659, 6.5, 5.4) LidL.wrtReparentTo(HingeNodeL) HingeNodeL.setHpr(0, 90, 0) lidCloseL = Parallel( LerpHprInterval(HingeNodeL, 2.0, (90, 0, 0), blendType='easeInOut')) postL.setPosHpr(-18, 55.5, -1, 0, 0, 0) postL.reparentTo(render) postGL = loader.loadModel("models/box") postGL.setColor(0.75, 0, 0.25) postGL.setScale(0.03, 0.03, 1) lidGL = postGL.find('**/lid') PandaGL = postGL.find('**/turningthing') HingeNodeGL = postGL.find('**/box').attachNewNode('nHingeNode') HingeNodeGL.setPos(.8659, 6.5, 5.4) #lidGR.wrtReparentTo(HingeNodeR) HingeNodeGL.setHpr(0, 90, 0) lidCloseGL = Parallel( LerpHprInterval(HingeNodeGL, 2.0, (0, 90, 0), blendType='easeInOut')) postGL.setPosHpr(-18, 58.5, -4.5, 90, 0, 90) postGL.reparentTo(render) #camera.setPosHpr(20, 45, 0, 90, 0, 0) postT = loader.loadModel("models/box") postT.setColor(0.75, 0, 0.25) postT.setScale(1.70, 0.03, 0.03) LidT = postL.find('**/lid') PandaT = postT.find('**/turningthing') HingeNodeT = postT.find('**/box').attachNewNode('nHingeNode') HingeNodeT.setPos(.8659, 6.5, 5.4) LidT.wrtReparentTo(HingeNodeT) HingeNodeT.setHpr(0, 90, 0) lidCloseT = Parallel( LerpHprInterval(HingeNodeT, 2.0, (0, 90, 0), blendType='easeInOut')) postT.setPosHpr(0, 55.5, 9.8, 0, 0, 0) postT.reparentTo(render) global ball ballRoot = render.attachNewNode("ballRoot") ball = loader.loadModel("models/ball") ball.reparentTo(ballRoot) #ball.setColor(0.5, 0, 1) ball.setScale(6, 6, 6) ball.setPosHpr(0, -12, -3, 0, -20, 0) #self.kick.setPos(0, 40, 0) ballTex = loader.loadTexture("pictures/ball.jpg") ball.setTexture(ballTex) ball.reparentTo(render) ballSphere = ball.find("**/ball") ballSphere.node().setFromCollideMask(BitMask32.bit(0)) ballSphere.node().setIntoCollideMask(BitMask32.allOff()) ambientLight = AmbientLight("ambientLight") ambientLight.setColor((.55, .55, .55, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(LVector3(0, 0, -1)) directionalLight.setColor((0.375, 0.375, 0.375, 1)) directionalLight.setSpecularColor((1, 1, 1, 1)) ballRoot.setLight(render.attachNewNode(ambientLight)) ballRoot.setLight(render.attachNewNode(directionalLight)) m = Material() m.setSpecular((1, 1, 1, 1)) m.setShininess(96) ball.setMaterial(m, 1) cs = CollisionSphere(0, 0, 0, 0.41) cNodePath = ball.attachNewNode(CollisionNode('cnode')) cNodePath.node().addSolid(cs) #cNodePath.show() #0, 53, -2 cW = CollisionPolygon(Point3(-1, 40, -4), Point3(-1, 40, 8), Point3(1, 40, 8), Point3(1, 40, -4)) cwNodePath = net.attachNewNode(CollisionNode('cwnode')) cwNodePath.node().addSolid(cW) #cwNodePath.show() #queue = CollisionHandlerQueue() #traverser.addCollider(cs, queue) #traverser.traverse(render) ground = loader.loadModel("models/square") ground.setPosHpr(0, 35, -5, 0, 0, 0) ground.setScale(120, 120, 120) #ground.setColor(0.2, 1, 0) grass = loader.loadTexture("pictures/grass_1.jpg") ground.setTexture(grass) ground.reparentTo(render) wall = loader.loadModel("models/square") wall.setPosHpr(5, 100, 18, 0, 90, 0) wall.setScale(90, 50, 75) #camera.setPos(0, -150, 0) #wall.setColor(0.5, 0.5, 0.5) crowd = loader.loadTexture("pictures/crowd.png") wall.setTexture(crowd) wall.reparentTo(render) rightWall = loader.loadModel("models/square") rightWall.setPosHpr(48, 45, 0, -90, 90, 0) rightWall.setScale(100, 100, 100) rightWall.setColor(0.75, 0.75, 0.75) rightWall.reparentTo(render) global angle angle = loader.loadModel("models/box") angle.setColor(0.25, 0.25, 0.25) angle.setScale(1.0, 0.25, 0.03) LidA = angle.find('**/lid') PandaA = angle.find('**/turningthing') HingeNodeA = angle.find('**/box').attachNewNode('nHingeNode') HingeNodeA.setPos(.8659, 6.5, 5.4) LidA.wrtReparentTo(HingeNodeA) HingeNodeA.setHpr(0, 90, 0) lidCloseA = Parallel( LerpHprInterval(HingeNodeA, 2.0, (0, 90, 0), blendType='easeInOut')) angle.setPosHpr(0, 10.5, -3, 0, 90, 0) #bar = loader.loadTexture("pictures/bar.png") #angle.setTexture(bar) angle.reparentTo(render) global angleD angleD = loader.loadModel("models/box") angleD.setColor(0, 0, 1) angleD.setScale(0.1, 0.25, 0.03) LidD = angleD.find('**/lid') PandaD = angleD.find('**/turningthing') HingeNodeD = angleD.find('**/box').attachNewNode('nHingeNode') HingeNodeD.setPos(.8659, 6.5, 5.4) LidD.wrtReparentTo(HingeNodeD) HingeNodeD.setHpr(0, 90, 0) lidCloseD = Parallel( LerpHprInterval(HingeNodeD, 2.0, (0, 90, 0), blendType='easeInOut')) angleD.setPosHpr(0, 10.4, -3, 0, 90, 0) angleD.reparentTo(render) global power power = loader.loadModel("models/box") power.setColor(0.25, 0.25, 0.25) power.setScale(0.12, 2.2, 0.03) LidP = power.find('**/lid') PandaP = power.find('**/turningthing') HingeNodeP = power.find('**/box').attachNewNode('nHingeNode') HingeNodeP.setPos(.8659, 6.5, 5.4) LidP.wrtReparentTo(HingeNodeP) HingeNodeP.setHpr(0, 90, 0) lidCloseP = Parallel( LerpHprInterval(HingeNodeP, 2.0, (0, 90, 0), blendType='easeInOut')) power.setPosHpr(-18, 10.5, -3, 0, 90, 0) global powerD powerD = loader.loadModel("models/box") powerD.setColor(1, 0, 0) powerD.setScale(0.12, 0.05, 0.03) LidD = power.find('**/lid') PandaD = power.find('**/turningthing') HingeNodeD = power.find('**/box').attachNewNode('nHingeNode') HingeNodeD.setPos(.8659, 6.5, 5.4) LidD.wrtReparentTo(HingeNodeD) HingeNodeD.setHpr(0, 90, 0) lidCloseD = Parallel( LerpHprInterval(HingeNodeD, 2.0, (0, 90, 0), blendType='easeInOut')) powerD.setPosHpr(-18, 10, -4.5, 0, 50, 0) global bishop bishop = loader.loadModel("models/bishop") bs = loader.loadTexture("pictures/bishop.png") bishop.setTexture(bs) bishop.setScale(10, 10, 10) #bishop.setColor(0, 0.4, 1) bishop.setPosHpr(0, 42, -5, 90, 0, 0) bishop.reparentTo(render) global bArmL bArmL = loader.loadModel("models/bishop") bArmL.setScale(2, 2, 4) bishop.setTexture(bs) #bArmL.setColor(0, 0.4, 1) bArmL.setPos(-1, 55, 6) #bArmL.reparentTo(render) global bArmR bArmR = loader.loadModel("models/bishop") bArmR.setScale(2, 2, 4) bishop.setTexture(bs) #bArmR.setColor(0, 0.4, 1) bArmR.setPos(1, 55, 6) #bArmR.reparentTo(render) global start start = loader.loadModel("models/square") start.setPosHpr(5, -25, 18, 0, 90, 0) start.setScale(90, 50, 75) #camera.setPos(0, -150, 0) start.setColor(0.5, 0.5, 0.5) #crowd = loader.loadTexture("pictures/crowd.png") #start.setTexture(crowd) start.reparentTo(render) title = TextNode('title') title.setText("Welcome to Penalty Kick!") global textNodePath textNodePath = aspect2d.attachNewNode(title) textNodePath.setScale(0.25) title.setWordwrap(8) title.setCardColor(0, 0, 0, 0) title.setCardAsMargin(0, 0, 0, 0) title.setCardDecal(True) textNodePath.setPos(-0.75, 0, 0.5) self.instructions = \ OnscreenText(text="Press any key to begin", parent=base.a2dBottomRight, align=TextNode.ARight, pos=(-1, +0.08), fg=(1, 1, 1, 1), scale=.06, shadow=(0, 0, 0, 0.5)) #self.accept('ball-into-net', ballCollideHandler) base.buttonThrowers[0].node().setKeystrokeEvent('keystroke') self.accept('keystroke', self.next)
def __init__(self): #create Queue to hold the incoming chat #request the heartbeat so that the caht interface is being refreshed in order to get the message from other player self.keyMap = { "left": 0, "right": 0, "forward": 0, "cam-left": 0, "cam-right": 0, "charge": 0 } base.win.setClearColor(Vec4(0, 0, 0, 1)) self.cManager = ConnectionManager() self.cManager.startConnection() #------------------------------ #Chat Chat(self.cManager) #send dummy login info of the particular client #send first chat info #--------------------------------------- self.userName = username dummy_login = { 'user_id': self.userName, 'factionId': faction, 'password': '******' } self.cManager.sendRequest(Constants.RAND_STRING, dummy_login) chat = { 'userName': self.userName, #username 'message': '-------Login------' } self.cManager.sendRequest(Constants.CMSG_CHAT, chat) #-------------------------------------- #self.minimap = OnscreenImage(image="images/minimap.png", scale=(0.2,1,0.2), pos=(-1.1,0,0.8)) #frame = DirectFrame(text="Resource Bar", scale=0.001) resource_bar = DirectWaitBar(text="", value=35, range=100, pos=(0, 0, 0.9), barColor=(255, 255, 0, 1), frameSize=(-0.3, 0.3, 0, 0.03)) cp_bar = DirectWaitBar(text="", value=70, range=100, pos=(1.0, 0, 0.9), barColor=(0, 0, 255, 1), frameSize=(-0.3, 0.3, 0, 0.03), frameColor=(255, 0, 0, 1)) # Set up the environment # # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) self.environ.setPos(0, 0, 0) # Create the main character, Ralph ralphStartPos = self.environ.find("**/start_point").getPos() self.ralph = Actor("models/ralph", { "run": "models/ralph-run", "walk": "models/ralph-walk" }) self.ralph.reparentTo(render) self.ralph.setScale(.2) self.ralph.setPos(ralphStartPos) nameplate = TextNode('textNode username_' + str(self.userName)) nameplate.setText(self.userName) npNodePath = self.ralph.attachNewNode(nameplate) npNodePath.setScale(0.8) npNodePath.setBillboardPointEye() #npNodePath.setPos(1.0,0,6.0) npNodePath.setZ(6.5) bar = DirectWaitBar(value=100, scale=1.0) bar.setColor(255, 0, 0) #bar.setBarRelief() bar.setZ(6.0) bar.setBillboardPointEye() bar.reparentTo(self.ralph) # Create a floater object. We use the "floater" as a temporary # variable in a variety of calculations. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # Accept the control keys for movement and rotation self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", 1]) self.accept("arrow_right", self.setKey, ["right", 1]) self.accept("arrow_up", self.setKey, ["forward", 1]) self.accept("a", self.setKey, ["cam-left", 1]) self.accept("s", self.setKey, ["cam-right", 1]) self.accept("arrow_left-up", self.setKey, ["left", 0]) self.accept("arrow_right-up", self.setKey, ["right", 0]) self.accept("arrow_up-up", self.setKey, ["forward", 0]) self.accept("a-up", self.setKey, ["cam-left", 0]) self.accept("s-up", self.setKey, ["cam-right", 0]) self.accept("c", self.setKey, ["charge", 1]) self.accept("c-up", self.setKey, ["charge", 0]) taskMgr.add(self.move, "moveTask") # Game state variables self.isMoving = False # Set up the camera base.disableMouse() base.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2) # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. One ray will # start above ralph's head, and the other will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal. self.cTrav = CollisionTraverser() self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0, 0, 1000) self.ralphGroundRay.setDirection(0, 0, -1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0)) self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff()) self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol) self.ralphGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler) self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0, 0, 1000) self.camGroundRay.setDirection(0, 0, -1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(BitMask32.bit(0)) self.camGroundCol.setIntoCollideMask(BitMask32.allOff()) self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Uncomment this line to see the collision rays #self.ralphGroundColNp.show() #self.camGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring #self.cTrav.showCollisions(render) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight))
def __init__(self): # Set up the window, camera, etc. ShowBase.__init__(self) # Set the background color to black self.win.setClearColor((0, 0, 0, 1)) # Post the instructions self.title = addTitle( "Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)") self.inst1 = addInstructions(0.06, "[ESC]: Quit") self.inst2 = addInstructions(0.12, "[Left trackpad]: Rotate Left") self.inst3 = addInstructions(0.18, "[Right trackpad]: Rotate Right") self.inst4 = addInstructions(0.24, "[Up trackpad]: Walk Forward") self.inst4 = addInstructions(0.30, "[Down trackpad]: Walk Backward") # Set up the environment # # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) # Create the main character, Ralph self.vr = RoamingRalphVR() self.vr.init(msaa=4) self.ralph = render.attachNewNode('ralph') self.ralphStartPos = self.environ.find("**/start_point").getPos() self.vr.tracking_space.setPos(self.ralphStartPos) self.ralph.setPos(self.vr.hmd_anchor.getPos(render)) self.accept("escape", sys.exit) taskMgr.add(self.collision, "collisionTask") # Set up the camera self.disableMouse() # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. One ray will # start above ralph's head, and the other will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal. self.cTrav = CollisionTraverser() self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0, 0, 9) self.ralphGroundRay.setDirection(0, 0, -1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(CollideMask.bit(0)) self.ralphGroundCol.setIntoCollideMask(CollideMask.allOff()) self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol) self.ralphGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler) # Uncomment this line to see the collision rays #self.ralphGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring #self.cTrav.showCollisions(render) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor((.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection((-5, -5, -5)) directionalLight.setColor((1, 1, 1, 1)) directionalLight.setSpecularColor((1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight))