def __init__(self, **kwargs): self.type = 'ambient' # ambient or directional for now self.color = color.rgb(0.3, 0.3, 0.3, 1) # a modest amount of full-spectrum light self.direction = Vec3( -1, -1, -1) # shining down from top-right corner, behind camera self.node = None for key, value in kwargs.items(): if key == 'type': if value == 'ambient' or value == 'directional': self.type = value else: print("ERR Light type is not 'ambient' or 'directional'") elif key == 'color': self.color = value elif key == 'direction': self.direction = value else: print("Err ", key, " is not a valid keyword") scene.lights.append( self) # light added for all subsequent entities if self.type == 'ambient': ambientLight = AmbientLight('ambientLight') ambientLight.setColor(self.color) self.node = scene.attachNewNode(ambientLight) if self.type == 'directional': directionalLight = DirectionalLight('directionalLight') directionalLight.setColor(self.color) self.node = scene.attachNewNode(directionalLight) # This light should be facing straight down, but clearly it isn't. self.node.setHpr( self.direction ) # convert vector to Hpr (in degrees!?) first
def __init__(self): ShowBase.__init__(self) self.key = {"left":0, "right": 0, "forward":0, "backward":0, "cam_left": 0,"cam_right": 0, "cam_down": 0, "cam_up": 0, "up":0, "down": 0} ##################### # # Simply testing procedural cave generation # ##################### self.start = PlatformSeg(LVector3(0,0,0)) self.start.generateAllParts(render) #################### # # 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.3, 0.3, 0.5, .1)) render.setLight(self.alight) base.disableMouse() base.camera.setPos(0, -20, 500) base.camera.setP(-50) self.bindKeys()
def __init__(self): ShowBase.__init__(self) base.set_background_color(0.1, 0.1, 0.8, 1) base.set_frame_rate_meter(True) base.cam.set_pos(0, -40, 10) base.cam.look_at(0, 0, 5) # Light alight = AmbientLight('ambientLight') alight.set_color(LVector4(0.5, 0.5, 0.5, 1)) alightNP = render.attach_new_node(alight) dlight = DirectionalLight('directionalLight') dlight.set_direction(LVector3(1, 1, -1)) dlight.set_color(LVector4(0.7, 0.7, 0.7, 1)) dlightNP = render.attach_new_node(dlight) render.clear_light() render.set_light(alightNP) render.set_light(dlightNP) # Input self.accept('escape', self.do_exit) self.accept('r', self.do_reset) self.accept('f1', base.toggle_wireframe) self.accept('f2', base.toggle_texture) self.accept('f3', self.toggle_debug) self.accept('f5', self.do_screenshot) self.accept('1', self.do_shoot, [True]) self.accept('2', self.do_shoot, [False]) # Task taskMgr.add(self.update, 'updateWorld') # Physics self.setup()
def __init__(self, left_barrel, right_barrel, world): self.render = world.render self.physics = world.physics self.world = world self.left_plasma = load_model('plasma_sight.egg') self.right_plasma = load_model('plasma_sight.egg') self.left_plasma.reparent_to(left_barrel) self.right_plasma.reparent_to(right_barrel) self.left_plasma.set_r(180) self.left_plasma.find("**/sight").setColor(*SIGHTS_FRIENDLY_COLOR) self.right_plasma.find("**/sight").setColor(*SIGHTS_FRIENDLY_COLOR) # inverted colors based on colors behind sights self.left_plasma.setTransparency(TransparencyAttrib.MAlpha) self.left_plasma.setAttrib( ColorBlendAttrib.make(ColorBlendAttrib.MInvSubtract, ColorBlendAttrib.OIncomingAlpha, ColorBlendAttrib.OOne)) self.right_plasma.setTransparency(TransparencyAttrib.MAlpha) self.right_plasma.setAttrib( ColorBlendAttrib.make(ColorBlendAttrib.MInvSubtract, ColorBlendAttrib.OIncomingAlpha, ColorBlendAttrib.OOne)) # ambient light source for lighting sight shapes sight_light = AmbientLight('sight_light') sight_light.set_color(VBase4(1, 1, 1, 1)) sight_lightnp = render.attach_new_node(sight_light) # the following excludes the sights from z-culling (always visible) self.left_plasma.set_bin("fixed", 40) self.left_plasma.set_depth_test(False) self.left_plasma.set_depth_write(False) self.left_plasma.set_light(sight_lightnp) self.right_plasma.set_bin("fixed", 40) self.right_plasma.set_depth_test(False) self.right_plasma.set_depth_write(False) self.right_plasma.set_light(sight_lightnp)
def __init__(self): ShowBase.__init__(self) # Override defaults self.disableMouse() self.setBackgroundColor(0.7, 0.7, 0.7) self.setFrameRateMeter(True) # Lights dlight = DirectionalLight("dlight") dlnp = self.render.attachNewNode(dlight) dlnp.setHpr(180.0, -70.0, 0) self.render.setLight(dlnp) alight = AmbientLight("alight") alnp = self.render.attachNewNode(alight) alight.setColor(VBase4(0.4, 0.4, 0.4, 1)) self.render.setLight(alnp) # Collisions self.cTrav = CollisionTraverser("collisionTraverser") #self.cTrav.showCollisions(self.render) # Camera controls self.cameraController = CameraController(self, 250, math.pi / 4.0, math.pi / 4.0) #self.cameraController = CameraController(self, 300, -math.pi, math.pi / 4.0) # Load the track self.track = self.loader.loadModel("models/trackMotegi") self.numCheckpoints = self.track.find( "checkpoints").node().getNumSolids() self.track.reparentTo(self.render) # Load the car self.car = KeyboardController(self) #self.cameraController.setTarget(self.car.getNodePath()) self.cameraController.follow(self.car.getNodePath())
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 createLights(self, r, g, b, startColor=1, fade=0): self.deleteLights() self.amblight = AmbientLight("amblight") self.amblight.setColor(VBase4(r, g, b, 1)) self.ambNode = render.attachNewNode(self.amblight) render.setLight(self.ambNode) if fade: self.lightTrack = LerpFunc(self.setLightColor, fromData=startColor, toData=r, duration=2.5, blendType="easeInOut") self.lightTrack.start() self.skyTrack = LerpColorInterval(self.sky, color=VBase4(r + 0.4, g + 0.4, b + 0.4, 1.0), startColor=VBase4(startColor, startColor, startColor, 1.0), duration=1.5) self.skyTrack.start() sky = "tt" if r < 0.6: sky = "br" self.skySeq = Sequence(Wait(1.5), Func(self.createSky, sky)) self.skySeq.start()
def setup_lights(self): pl = PointLight('pl') pl.setColor((1, 1, 1, 1)) plNP = render.attachNewNode(pl) plNP.setPos(0, 0, 0) render.setLight(plNP) # make shadows less black al = AmbientLight('al') al.setColor((0.1, 0.1, 0.1, 1)) alNP = render.attachNewNode(al) render.setLight(alNP) positions = [[[0, 0, 3], [0, 0, -1]], [[0, -3, 0], [0, 1, 0]], [[-3, 0, 0], [1, 0, 0]]] # set up directional lights (shadow casting) for i in positions: dl = Spotlight('dl') dl.setColor((1, 1, 1, 1)) dlNP = render.attachNewNode(dl) dlNP.setPos(*i[0]) # unpack the args dlNP.lookAt(*i[1]) dlNP.node().setShadowCaster(True) render.setLight(dlNP)
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): ShowBase.__init__(self) self.gameTask = taskMgr.add(self.flyCircles, "circles") base.disableMouse() base.camera.setPos(50, 100, 800) base.camera.lookAt(0, 0, 0) dl = DirectionalLight('dLight') dl.setColor(Vec4(0.1, 0.1, 0.1, 1)) dlNP = render.attachNewNode(dl) dlNP.setPos(1000, 1000, 0) al = AmbientLight('alight') al.setColor(Vec4(0.3, 0.3, 0.3, 1)) alNP = render.attachNewNode(al) pl = PointLight('plight') pl.setColor(VBase4(0.2, 0.2, 0.2, 1)) plNP = render.attachNewNode(pl) plNP.setPos(100, 100, 100) render.setLight(plNP) self.shipList = [Bwing("xwing1"), TieInterceptor("tie1")] for i, ship in enumerate(self.shipList): ship.reparentTo(render) ship.setScale(2) ship.setPos(Point3(i * 10, i * 0, i * 0)) # ship.setLight(dlNP) ship.setLight(alNP) self.count = 0 self.iter = 0
def __init__(self): ShowBase.__init__(self) self.win.setClearColor(Vec4(0.2, 0.2, 0.2, 1)) self.disableMouse() self.render.setShaderAuto() dlight = DirectionalLight('dlight') alight = AmbientLight('alight') dlnp = self.render.attachNewNode(dlight) alnp = self.render.attachNewNode(alight) dlight.setColor((0.8, 0.8, 0.5, 1)) alight.setColor((0.2, 0.2, 0.2, 1)) dlnp.setHpr(0, -60, 0) self.render.setLight(dlnp) self.render.setLight(alnp) # Put lighting on the main scene plight = PointLight('plight') plnp = self.render.attachNewNode(plight) plnp.setPos(0, 0, 10) self.render.setLight(plnp) self.render.setLight(alnp) self.loadRocketFonts() self.loadingTask = None #self.startModelLoadingAsync() self.startModelLoading() self.inputHandler = RocketInputHandler() self.mouseWatcher.attachNewNode(self.inputHandler) self.openLoadingDialog()
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 background(self): scene = loader.loadModel('maps/menu/terrain') scene.reparentTo(self.root_node) self.actor = Actor('actors/char', {'walk': 'actors/char-walk', 'hands': 'actors/char-hands'}) self.actor.reparentTo(scene) self.actor.setPos(0, 1, 0) moon = DirectionalLight('moon') moon.setColor(hex_to_rgb('4d5acc', brightness=.2)) moon.setShadowCaster(True, 2048, 2048) moon_np = scene.attachNewNode(moon) moon_np.setPos(-5, -5, 10) moon_np.lookAt(0, 0, 0) scene.setLight(moon_np) self.bonfire = prefab.Bonfire(scene) self.bonfire.holder.setPos(0, -.08, .1) ambient = AmbientLight('alight') ambient.setColor(hex_to_rgb('141414')) ambient_np = scene.attachNewNode(ambient) scene.setLight(ambient_np) def spin_camera_task(task): angle_degrees = task.time * 2.0 if angle_degrees > 360: angle_degrees -= 360 angle_radians = angle_degrees * (pi / 180) base.camera.setPos(3 * sin(angle_radians), -3 * cos(angle_radians), 1) base.camera.setHpr(angle_degrees, 4, 0) return task.cont base.taskMgr.add(spin_camera_task, 'spin_camera')
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 _addDefaultLighting(self): alight = AmbientLight('alight') alight.setColor(VBase4(0.2, 0.2, 0.2, 1)) alnp = self.scene.scene.attachNewNode(alight) self.scene.scene.setLight(alnp) for camera in self.cameras: #NOTE: Point light following the camera plight = PointLight('plight') plight.setColor(VBase4(1.0, 1.0, 1.0, 1)) plnp = camera.attachNewNode(plight) self.scene.scene.setLight(plnp) if self.shadowing: # Use a 512x512 resolution shadow map plight.setShadowCaster(True, 512, 512) # Enable the shader generator for the receiving nodes self.scene.scene.setShaderAuto() self.scene.scene.setAntialias(AntialiasAttrib.MAuto) if self.modelLightsInfo is not None: # Add model-related lights (e.g. lamps) for model in self.scene.scene.findAllMatches('**/+ModelNode'): modelId = model.getNetTag('model-id') for lightNp in self.modelLightsInfo.getLightsForModel(modelId): if self.shadowing: # Use a 512x512 resolution shadow map lightNp.node().setShadowCaster(True, 512, 512) lightNp.reparentTo(model) self.scene.scene.setLight(lightNp)
def __init__(self, cr): DistributedObject.__init__(self, cr) self.accept("checkBoardAnimationDone", self.checkBoardAnimationDone) base.messenger.send("registerLoadEvent", ["loadBoardDone"]) base.messenger.send("registerLoadEvent", ["loadTableDone"]) self.modelLoadList = {"board": False, "table": False} self.boardAnimation = None self.boardAnimationStarted = False self.lightSun = DirectionalLight('light_sun') self.lightSun.setColorTemperature(5300) self.lightSun.setShadowCaster(True, 2048, 2048) self.lightSunNP = render.attachNewNode(self.lightSun) self.lightSunNP.setPos(-2, 2, 2) self.lightSunNP.lookAt(2, -2, -0.5) self.lightAmb = AmbientLight('light_ambient') #self.lightAmb.setColor((0.1, 0.1, 0.1, 1)) self.lightAmb.setColorTemperature(4500) c = self.lightAmb.getColor() self.lightAmb.setColor((c.x / 2, c.y / 2, c.z / 2, 1)) self.lightAmbNP = render.attachNewNode(self.lightAmb) self.accept("loadDone", self.loadDone) self.boardSceneLoadTask = loader.loadModel( "assets/models/board/BoardScene.bam", callback=self.boardLoaded) self.tableLoadTask = loader.loadModel("assets/models/table/Table.bam", callback=self.tableLoaded) # render lights render.setLight(self.lightSunNP) render.setLight(self.lightAmbNP)
def __init__(self, config): super(Light, self).__init__(random_seed=0) self.global_light = config["global_light"] self.direction_np = NodePath(DirectionalLight("direction light")) # self.light.node().setScene(self.render) # Too large will cause the graphics card out of memory. # self.direction_np.node().setShadowCaster(True, 8192, 8192) # self.direction_np.node().setShadowCaster(True, 4096, 4096) if self.global_light: self.direction_np.node().setShadowCaster(True, 16384, 16384) self.direction_np.setPos(0, 0, 50) self.direction_np.lookAt(100, -30, 0) else: self.direction_np.node().setShadowCaster(True, 128, 128) # self.direction_np.node().showFrustum() # self.light.node().getLens().setNearFar(10, 100) self.direction_np.node().setColor(LVector4(1, 1, 0.8, 1)) self.direction_np.node().setCameraMask(CamMask.Shadow) dlens = self.direction_np.node().getLens() if self.global_light: dlens.setFilmSize(256, 256) else: dlens.setFilmSize(8, 8) # dlens.setFocalLength(1) # dlens.setNear(3) self.direction_np.node().setColorTemperature(4000) self.direction_np.reparentTo(self.origin) self.ambient_np = NodePath(AmbientLight("Ambient")) self.ambient_np.node().setColor(LVector4(0.8, 0.8, 0.8, 1)) self.ambient_np.reparentTo(self.origin)
def begin(self): base.setBackgroundColor( self.environment['colourBackground'] ) alight = AmbientLight('AmbientLight') alight.setColor(self.environment['colourAmbient'] ) alnp = self.node.attachNewNode(alight) self.node.setLight(alnp) if self.environment['fog']: fog = Fog( 'sceneName' ) fog.setColor( self.environment['fog']['color'] ) if self.environment['fog']['mode'] == "linear": fog.setLinearRange(self.environment['fog']['linearStart']*1000,self.environment['fog']['linearEnd']*1000) else: fog.setExpDensity( self.environment['fog']['expDensity'] ) self.node.setFog(fog) [self.createNode(props) for props in self.nodes] [self.createLight(props) for props in self.lights] [self.createCamera(props) for props in self.cameras] [self.createEntity(props) for props in self.entities] [self.createStaticGeoms(props) for props in self.staticGeoms]
def __init__(self, heightfield_fn="heightfield.png"): # Store the heightfield's filename. self.heightfield_fn = heightfield_fn """ Load some configuration variables, it's important for this to happen before ShowBase is initialized """ load_prc_file_data("", """ sync-video #t textures-power-2 none ###gl-coordinate-system default notify-level-gobj warning notify-level-grutil debug notify-level-shader_terrain debug notify-level-bullet debug ### model paths model-path /usr/share/panda3d model-path /home/juzzuj/code/prereq/bullet-samples/bullet-samples """) ShowBase.__init__(self) base.set_background_color(0.1, 0.1, 0.8, 1) base.set_frame_rate_meter(True) # Increase camera Field Of View and set near and far planes base.camLens.set_fov(90) base.camLens.set_near_far(0.1, 50000) # Lights alight = AmbientLight('ambientLight') alight.set_color(LVector4(0.5, 0.5, 0.5, 1)) alightNP = render.attach_new_node(alight) dlight = DirectionalLight('directionalLight') dlight.set_direction(LVector3(1, 1, -1)) dlight.set_color(LVector4(0.7, 0.7, 0.7, 1)) dlightNP = render.attach_new_node(dlight) render.clear_light() render.set_light(alightNP) render.set_light(dlightNP) # Basic game controls self.accept('escape', self.do_exit) self.accept('f1', base.toggle_wireframe) self.accept('f2', base.toggle_texture) self.accept('f3', self.toggle_debug) self.accept('f5', self.do_screenshot) self.accept('r', self.do_reset) # Vehicle controls inputState.watchWithModifiers('forward', 'w') inputState.watchWithModifiers('turnLeft', 'a') inputState.watchWithModifiers('reverse', 's') inputState.watchWithModifiers('turnRight', 'd') inputState.watchWithModifiers('forward', 'arrow_up') inputState.watchWithModifiers('turnLeft', 'arrow_left') inputState.watchWithModifiers('reverse', 'arrow_down') inputState.watchWithModifiers('turnRight', 'arrow_right') self.accept('space', self.reset_vehicle) # Controls to do with the terrain #self.accept('t', self.rise_in_front) self.accept('t', self.deform_terrain, ["raise"]) self.accept('g', self.deform_terrain, ["depress"]) self.accept('b', self.drop_boxes) # Some debugging and miscellaneous controls self.accept('e', self.query_elevation) self.accept('c', self.convert_coordinates) self.accept('p', self.save) self.accept('h', self.hide_terrain) # Task taskMgr.add(self.update, 'updateWorld') self.setup()
def __init__(self): ShowBase.__init__(self) self.calibrated = False self.disableMouse() self.time_total_img = [] self.time_total_sens = [] # ENV SETUP self.env = quad(time_int_step, max_timesteps, direct_control=1, T=T) self.sensor = sensor(self.env) self.aux_dl = dl_in_gen(T, self.env.state_size, self.env.action_size) self.error = [] state_dim = self.aux_dl.deep_learning_in_size self.policy = ActorCritic(state_dim, action_dim=4, action_std=0).to(device) #CONTROLLER SETUP try: self.policy.load_state_dict(torch.load('./controller/PPO_continuous_solved_drone.pth',map_location=device)) print('Saved policy loaded') except: print('Could not load policy') sys.exit(1) n_parameters = sum(p.numel() for p in self.policy.parameters()) print('Neural Network Number of Parameters: %i' %n_parameters) # Load the environment model. self.scene = self.loader.loadModel(mydir + "/models/city.egg") self.scene.reparentTo(self.render) self.scene.setScale(1, 1, 1) self.scene.setPos(0, 0, 0) # Load the skybox self.skybox = self.loader.loadModel(mydir + "/models/skybox.egg") self.skybox.setScale(100,100,100) self.skybox.setPos(0,0,-500) self.skybox.reparentTo(self.render) # Also add an ambient light and set sky color. skycol = panda3d.core.VBase3(135 / 255.0, 206 / 255.0, 235 / 255.0) self.set_background_color(skycol) alight = AmbientLight("sky") alight.set_color(panda3d.core.VBase4(skycol * 0.04, 1)) alight_path = render.attachNewNode(alight) render.set_light(alight_path) # 4 perpendicular lights (flood light) dlight1 = DirectionalLight('directionalLight') dlight1.setColor(panda3d.core.Vec4(0.3,0.3,0.3,0.3)) dlight1NP = render.attachNewNode(dlight1) dlight1NP.setHpr(0,0,0) dlight2 = DirectionalLight('directionalLight') dlight2.setColor(panda3d.core.Vec4(0.3,0.3,0.3,0.3)) dlight2NP = render.attachNewNode(dlight2) dlight2NP.setHpr(-90,0,0) dlight3 = DirectionalLight('directionalLight') dlight3.setColor(panda3d.core.Vec4(0.3,0.3,0.3,0.3)) dlight3NP = render.attachNewNode(dlight3) dlight3NP.setHpr(-180,0,0) dlight4 = DirectionalLight('directionalLight') dlight4.setColor(panda3d.core.Vec4(0.3,0.3,0.3,0.3)) dlight4NP = render.attachNewNode(dlight4) dlight4NP.setHpr(-270,0,0) render.setLight(dlight1NP) render.setLight(dlight2NP) render.setLight(dlight3NP) render.setLight(dlight4NP) # 1 directional light (Sun) dlight = DirectionalLight('directionalLight') dlight.setColor(panda3d.core.Vec4(1, 1, 1, 1)) # directional light is dim green dlight.getLens().setFilmSize(panda3d.core.Vec2(50, 50)) dlight.getLens().setNearFar(-100, 100) dlight.setShadowCaster(True, 4096*2, 4096*2) # dlight.show_frustum() dlightNP = render.attachNewNode(dlight) dlightNP.setHpr(0,-65,0) #Turning shader and lights on render.setShaderAuto() render.setLight(dlightNP) # Add the spinCameraTask procedure to the task manager. self.taskMgr.add(self.calibrate, 'Camera Calibration') self.taskMgr.add(self.drone_position_task, 'Drone Position') # Load and transform the quadrotor actor. self.quad = self.loader.loadModel(mydir + '/models/quad.egg') self.quad.reparentTo(self.render) self.prop_1 = self.loader.loadModel(mydir + '/models/prop.egg') self.prop_1.setPos(-0.26,0,0) self.prop_1.reparentTo(self.quad) self.prop_2 = self.loader.loadModel(mydir + '/models/prop.egg') self.prop_2.setPos(0,0.26,0) self.prop_2.reparentTo(self.quad) self.prop_3 = self.loader.loadModel(mydir + '/models/prop.egg') self.prop_3.setPos(0.26,0,0) self.prop_3.reparentTo(self.quad) self.prop_4 = self.loader.loadModel(mydir + '/models/prop.egg') self.prop_4.setPos(0,-0.26,0) self.prop_4.reparentTo(self.quad) # Load the checkerboard actor self.checker = self.loader.loadModel(mydir+ '/models/checkerboard.egg') self.checker.reparentTo(self.render) self.checker_scale = 0.5 self.checker_sqr_size = 0.2046 self.checker.setScale(self.checker_scale, self.checker_scale, 1) self.checker.setPos(3*self.checker_scale*self.checker_sqr_size, 2.5*self.checker_scale*self.checker_sqr_size, 0.001) #env cam self.cam.node().getLens().setFilmSize(36, 24) self.cam.node().getLens().setFocalLength(45) self.cam.setPos(5,5,7) self.cam.reparentTo(self.render) self.cam.lookAt(self.quad) if IMG_POS_DETER: self.taskMgr.add(self.pos_deter, 'Position Determination') window_size = (self.win.getXSize(), self.win.getYSize()) self.buffer = self.win.makeTextureBuffer('Buffer', *window_size, None, True) self.tex = self.buffer.getTexture() self.cam_1 = self.makeCamera(self.buffer) self.cam_1.setName('cam_1') self.cam_1.node().getLens().setFilmSize(36, 24) self.cam_1.node().getLens().setFocalLength(45) self.cam_1.reparentTo(self.quad) self.cam_1.setPos(0,0,0.01) self.cam_1.lookAt(self.quad) self.pipe = panda3d.core.GraphicsPipeSelection.get_global_ptr().make_module_pipe('pandagl') input('Start?')
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()
def __init__(self): ShowBase.__init__(self) self.disableMouse() properties = WindowProperties() properties.setSize(1000, 750) self.win.requestProperties(properties) self.exitFunc = self.cleanup mainLight = DirectionalLight("main light") self.mainLightNodePath = render.attachNewNode(mainLight) self.mainLightNodePath.setHpr(45, -45, 0) render.setLight(self.mainLightNodePath) ambientLight = AmbientLight("ambient light") ambientLight.setColor(Vec4(0.2, 0.2, 0.2, 1)) self.ambientLightNodePath = render.attachNewNode(ambientLight) render.setLight(self.ambientLightNodePath) render.setShaderAuto() self.environment = loader.loadModel("Models/Misc/environment") self.environment.reparentTo(render) self.camera.setPos(0, 0, 32) self.camera.setP(-90) self.keyMap = { "up" : False, "down" : False, "left" : False, "right" : False, "shoot" : False } self.accept("w", self.updateKeyMap, ["up", True]) self.accept("w-up", self.updateKeyMap, ["up", False]) self.accept("s", self.updateKeyMap, ["down", True]) self.accept("s-up", self.updateKeyMap, ["down", False]) self.accept("a", self.updateKeyMap, ["left", True]) self.accept("a-up", self.updateKeyMap, ["left", False]) self.accept("d", self.updateKeyMap, ["right", True]) self.accept("d-up", self.updateKeyMap, ["right", False]) self.accept("mouse1", self.updateKeyMap, ["shoot", True]) self.accept("mouse1-up", self.updateKeyMap, ["shoot", False]) self.pusher = CollisionHandlerPusher() self.cTrav = CollisionTraverser() self.pusher.setHorizontal(True) self.pusher.add_in_pattern("%fn-into-%in") self.accept("trapEnemy-into-wall", self.stopTrap) self.accept("trapEnemy-into-trapEnemy", self.stopTrap) self.accept("trapEnemy-into-player", self.trapHitsSomething) self.accept("trapEnemy-into-walkingEnemy", self.trapHitsSomething) wallSolid = CollisionTube(-8.0, 0, 0, 8.0, 0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(8.0) wallSolid = CollisionTube(-8.0, 0, 0, 8.0, 0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(-8.0) wallSolid = CollisionTube(0, -8.0, 0, 0, 8.0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setX(8.0) wallSolid = CollisionTube(0, -8.0, 0, 0, 8.0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setX(-8.0) self.updateTask = taskMgr.add(self.update, "update") self.player = None self.enemies = [] self.trapEnemies = [] self.deadEnemies = [] self.spawnPoints = [] numPointsPerWall = 5 for i in range(numPointsPerWall): coord = 7.0/numPointsPerWall + 0.5 self.spawnPoints.append(Vec3(-7.0, coord, 0)) self.spawnPoints.append(Vec3(7.0, coord, 0)) self.spawnPoints.append(Vec3(coord, -7.0, 0)) self.spawnPoints.append(Vec3(coord, 7.0, 0)) self.initialSpawnInterval = 1.0 self.minimumSpawnInterval = 0.2 self.spawnInterval = self.initialSpawnInterval self.spawnTimer = self.spawnInterval self.maxEnemies = 2 self.maximumMaxEnemies = 20 self.numTrapsPerSide = 2 self.difficultyInterval = 5.0 self.difficultyTimer = self.difficultyInterval self.enemySpawnSound = loader.loadSfx("Sounds/enemySpawn.ogg") self.gameOverScreen = DirectDialog(frameSize = (-0.7, 0.7, -0.7, 0.7), fadeScreen = 0.4, relief = DGG.FLAT, frameTexture = "UI/stoneFrame.png") self.gameOverScreen.hide() self.font = loader.loadFont("Fonts/Wbxkomik.ttf") buttonImages = ( loader.loadTexture("UI/UIButton.png"), loader.loadTexture("UI/UIButtonPressed.png"), loader.loadTexture("UI/UIButtonHighlighted.png"), loader.loadTexture("UI/UIButtonDisabled.png") ) label = DirectLabel(text = "Game Over!", parent = self.gameOverScreen, scale = 0.1, pos = (0, 0, 0.2), text_font = self.font, relief = None) self.finalScoreLabel = DirectLabel(text = "", parent = self.gameOverScreen, scale = 0.07, pos = (0, 0, 0), text_font = self.font, relief = None) btn = DirectButton(text = "Restart", command = self.startGame, pos = (-0.3, 0, -0.2), parent = self.gameOverScreen, scale = 0.07, text_font = self.font, clickSound = loader.loadSfx("Sounds/UIClick.ogg"), frameTexture = buttonImages, frameSize = (-4, 4, -1, 1), text_scale = 0.75, relief = DGG.FLAT, text_pos = (0, -0.2)) btn.setTransparency(True) btn = DirectButton(text = "Quit", command = self.quit, pos = (0.3, 0, -0.2), parent = self.gameOverScreen, scale = 0.07, text_font = self.font, clickSound = loader.loadSfx("Sounds/UIClick.ogg"), frameTexture = buttonImages, frameSize = (-4, 4, -1, 1), text_scale = 0.75, relief = DGG.FLAT, text_pos = (0, -0.2)) btn.setTransparency(True) self.titleMenuBackdrop = DirectFrame(frameColor = (0, 0, 0, 1), frameSize = (-1, 1, -1, 1), parent = render2d) self.titleMenu = DirectFrame(frameColor = (1, 1, 1, 0)) title = DirectLabel(text = "Panda-chan", scale = 0.1, pos = (0, 0, 0.9), parent = self.titleMenu, relief = None, text_font = self.font, text_fg = (1, 1, 1, 1)) title2 = DirectLabel(text = "and the", scale = 0.07, pos = (0, 0, 0.79), parent = self.titleMenu, text_font = self.font, frameColor = (0.5, 0.5, 0.5, 1)) title3 = DirectLabel(text = "Endless Horde", scale = 0.125, pos = (0, 0, 0.65), parent = self.titleMenu, relief = None, text_font = self.font, text_fg = (1, 1, 1, 1)) btn = DirectButton(text = "Start Game", command = self.startGame, pos = (0, 0, 0.2), parent = self.titleMenu, scale = 0.1, text_font = self.font, clickSound = loader.loadSfx("Sounds/UIClick.ogg"), frameTexture = buttonImages, frameSize = (-4, 4, -1, 1), text_scale = 0.75, relief = DGG.FLAT, text_pos = (0, -0.2)) btn.setTransparency(True) btn = DirectButton(text = "Quit", command = self.quit, pos = (0, 0, -0.2), parent = self.titleMenu, scale = 0.1, text_font = self.font, clickSound = loader.loadSfx("Sounds/UIClick.ogg"), frameTexture = buttonImages, frameSize = (-4, 4, -1, 1), text_scale = 0.75, relief = DGG.FLAT, text_pos = (0, -0.2)) btn.setTransparency(True) music = loader.loadMusic("Music/Defending-the-Princess-Haunted.ogg") music.setLoop(True) music.setVolume(0.075) music.play()
def __init__(self): self.lights = l = render.attachNewNode("equilibra7d_lights") self.ambient = l.attachNewNode(AmbientLight('ambient_light')) self.point = l.attachNewNode(PointLight('point_light')) self.directional = l.attachNewNode( DirectionalLight('directional_light'))
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))
makeFractalTree(bodydata, nodePath, length, newPos, numIterations - 1, numCopies, randomAxis(vecList)) else: # just make another branch connected to this one with a small # variation in direction makeFractalTree(bodydata, nodePath, length, newPos, numIterations - 1, numCopies, smallRandomAxis(vecList)) else: drawBody(nodePath, bodydata, pos, vecList, length.getX(), False) drawLeaf(nodePath, bodydata, pos, vecList) alight = AmbientLight('alight') alight.setColor((0.5, 0.5, 0.5, 1)) alnp = render.attachNewNode(alight) render.setLight(alnp) slight = Spotlight('slight') slight.setColor((1, 1, 1, 1)) lens = PerspectiveLens() slight.setLens(lens) slnp = render.attachNewNode(slight) render.setLight(slnp) slnp.setPos(0, 0, 40) # rotating light to show that normals are calculated correctly
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)
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 _make_ambient(self): alight = AmbientLight('ambient') alight.set_color(VBase4(*DEFAULT_AMBIENT_COLOR)) node = self.scene.attach_new_node(alight) self.scene.set_light(node) return node
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, panda3d): # Inicialización de variables self.winsize = [0, 0] self.panda3d = panda3d self.panda3d.mouse_on_workspace = False # Desabilita el comportamiento por defecto de la camara self.panda3d.disable_mouse() # Llama a la función self.window_rezise_event cuando la ventana cambia de tamaño self.accept('window-event', self.window_rezise_event) # self.panda3d.accept('aspectRatioChanged', lambda: print("ss")) # Creamos el punto donde se centrará la cámara target_pos = Point3(0., 0., 0.) self.panda3d.cam_target = self.panda3d.render.attach_new_node("camera_target") self.panda3d.cam_target.set_pos(target_pos) self.panda3d.camera.reparent_to(self.panda3d.cam_target) self.panda3d.camera.set_y(-50.) # Definimos la cambinación de teclas para el control de la camara self.camera_active = False self.orbit_mouse_btn = "mouse2" self.orbit_keyboard_btn = "shift" self.orbit_mouse_reference = None self.orbit_camera_reference = None self.pan_mouse_btn = "mouse2" self.pan_keyboard_btn = "mouse2" self.pan_mouse_reference = None self.pan_camera_reference = None self.zoom_mouse_btn = "mouse2" self.zoom_keyboard_btn = "control" self.zoom_mouse_reference = None self.zoom_camera_reference = None # Establecemos los valores máximos y minimos para el zoom self.max_zoom = 10 self.min_zoom = 0.1 # Creamos la tarea de control de la camara self.panda3d.task_mgr.add(self.camera_control_task, "camera_control") # El movimiento de la rueda del mouse controla el zoom self.panda3d.accept("wheel_up", self.zoom_in) self.panda3d.accept("wheel_down", self.zoom_out) # Una fución de prueba para comprobar la posición del mouse en el modelo 3d # self.panda3d.accept("mouse1", self.entity_select) # Se establece la lente ortografica en lugar de la perspectiva self.lens_type = "OrthographicLens" self.set_lens(self.lens_type) # Agrega un indicador de ejes en la esquina inferior izquierda self.corner = self.panda3d.camera.attachNewNode("corner of screen") # self.axis = self.panda3d.loader.loadModel("data/geom/custom-axis") # self.axis = self.panda3d.loader.loadModel("data/geom/view_gizmo_F") self.view_gizmo = list() self.view_gizmo.append(self.panda3d.loader.loadModel("data/geom/view_gizmo_compass")) # self.view_gizmo.append(self.panda3d.loader.loadModel("data/geom/view_gizmo_L")) # self.view_cube = ViewGizmoZone() # self.view_cube.set_geom(self.axis) for gizmo_geom in self.view_gizmo: gizmo_geom.setLightOff(1) # gizmo_geom.setColorScale(1,1,1,1) gizmo_geom.setShaderInput("colorborders", LVecBase4(0, 0, 0, 0.25)) gizmo = ViewGizmoZone() gizmo.set_geom(gizmo_geom) gizmo_geom.node().setBounds(BoundingSphere(Point3(0, 0, 0), 10)) gizmo_geom.node().setFinal(True) #gizmo_geom.showTightBounds() # gizmo_geom.showBounds() self.show_view_gizmo() # Agregamos una luz puntual en la ubicación de la camara plight = DirectionalLight("camera_light") plight.setColor((1, 1, 1, 1)) #plight.setAttenuation((1, 0, 0)) #print("getMaxDistance {}".format(plight.getMaxDistance())) self.panda3d.plight_node = self.panda3d.render.attach_new_node(plight) self.panda3d.plight_node.setPos(0, -50, 0) self.panda3d.render.setLight(self.panda3d.plight_node) self.panda3d.plight_node.reparentTo(self.panda3d.camera) # Agregamos luz ambiental que disminuya las zonas oscuras alight = AmbientLight('alight') alight.setColor((0.3, 0.3, 0.3, 1)) alnp = self.panda3d.render.attachNewNode(alight) self.panda3d.render.setLight(alnp) #def init_select_detection(self): self.traverser = CollisionTraverser("") # self.traverser.show_collisions(self.panda3d.render) self.picker_ray = CollisionRay() self.handler = CollisionHandlerQueue() self.picker_node = CollisionNode('mouseRay') self.picker_np = self.panda3d.camera.attachNewNode(self.picker_node) self.picker_node.setFromCollideMask(GeomNode.getDefaultCollideMask()) self.picker_ray = CollisionRay() self.picker_node.addSolid(self.picker_ray) self.traverser.addCollider(self.picker_np, self.handler)