def move_and_rotate_camera_to(self, new_pos, new_rot, absolute=True, duration=0): if settings.debug_jump: duration = 0 if duration == 0: if absolute: self.camera.set_camera_pos(new_pos) self.camera.set_camera_rot(new_rot) else: self.camera.set_rel_camera_pos(new_pos) self.camera.set_rel_camera_rot(new_rot) else: if self.current_interval != None: self.current_interval.pause() self.fake = NodePath('fake') if absolute: self.start_pos = self.camera.get_rel_camera_pos() self.end_pos = self.camera.get_rel_position_of(new_pos) #TODO #new_rot = self.camera.get_rel_rotation_of(new_pos) nodepath_lerp = LerpQuatInterval(self.fake, duration=duration, blendType='easeInOut', quat = LQuaternion(*new_rot), startQuat = LQuaternion(*self.camera.get_camera_rot()) ) func_lerp = LerpFunc(self.do_camera_move_and_rot, fromData=0, toData=1, duration=duration, blendType='easeInOut', name=None) parallel = Parallel(nodepath_lerp, func_lerp) self.current_interval = parallel self.current_interval.start()
def create_quaternion(angle, axis): """Create a quaternion with the given characteristics""" radians = angle / 360 * math.pi cosine = math.cos(radians / 2) quaternion = LQuaternion(cosine, *axis) quaternion.normalize() return quaternion
def update_shader_shape(self, shape, appearance): planet = self.parameters.planet factor = 1.0 / shape.owner.scene_scale_factor inner_radius = self.parameters.planet_radius #TODO: We should get the oblateness correctly planet_scale = self.parameters.planet.surface.get_scale() descale = LMatrix4.scale_mat(inner_radius / planet_scale[0], inner_radius / planet_scale[1], inner_radius / planet_scale[2]) rotation_mat = LMatrix4() orientation = LQuaternion(*shape.owner.scene_orientation) orientation.extract_to_matrix(rotation_mat) rotation_mat_inv = LMatrix4() rotation_mat_inv.invert_from(rotation_mat) descale_mat = rotation_mat_inv * descale * rotation_mat pos = planet.rel_position scaled_pos = descale_mat.xform_point(LPoint3(*pos)) star_pos = planet.star._local_position - planet._local_position scaled_star_pos = descale_mat.xform_point(LPoint3(*star_pos)) scaled_star_pos.normalize() camera_height = scaled_pos.length() shape.instance.setShaderInput("v3OriginPos", pos) shape.instance.setShaderInput("v3CameraPos", -scaled_pos) shape.instance.setShaderInput("fCameraHeight", camera_height) shape.instance.setShaderInput("fCameraHeight2", camera_height * camera_height) shape.instance.setShaderInput("v3LightPos", scaled_star_pos) shape.instance.setShaderInput("model_scale", factor) shape.instance.setShaderInput("atm_descale", descale_mat)
def __init__(self): self.skybox = None self.sun_color = None self.skybox_color = None self.light_angle = None self.light_dir = LVector3d.up() self.light_quat = LQuaternion() self.light_color = (1.0, 1.0, 1.0, 1.0) self.fog = None
class RotationCorrector(): def __init__(self, init_rotation=None): if init_rotation is None: self.rotation = LQuaternion() else: self.rotation = LQuaternion(1, *init_rotation) self.last_t = time.time() def getHpr(self): return self.rotation.getHpr() def setHpr(self, *args, **kwargs): self.rotation.setHpr(*args, **kwargs) @staticmethod def rotationFromCompass(acceleration, magnetic_field): down = -acceleration east = down.cross(magnetic_field) north = east.cross(down) east.normalize() north.normalize() down.normalize() r = LMatrix4() r.setRow(0, north) r.setRow(1, east) r.setRow(2, down) return r @staticmethod def rotate(rotation, w, dt): rotation *= LQuaternion(1, w*dt/2) rotation.normalize() def rotationMagic(self, timestamp, angular_velocity, acceleration, magnetic_field): dt = timestamp - self.last_t self.last_t = timestamp angular_velocity = Vec3(*angular_velocity) acceleration = Vec3(*acceleration) magnetic_field = Vec3(*magnetic_field) correction = (0, 0, 0) if abs(acceleration.length() - 1) <= 0.3: correction_strength = 1 rotationCompass = self.rotationFromCompass(acceleration, magnetic_field) rotationMatrix = LMatrix4() self.rotation.extractToMatrix(rotationMatrix) correction = rotationCompass.getRow3(0).cross(rotationMatrix.getRow3(0)) correction += rotationCompass.getRow3(1).cross(rotationMatrix.getRow3(1)) correction += rotationCompass.getRow3(2).cross(rotationMatrix.getRow3(2)) correction *= correction_strength self.rotate(self.rotation, angular_velocity + correction, dt)
def npmat3_to_pdquat(npmat3): """ :param npmat3: 3x3 nparray :return: author: weiwei date: 20210109 """ quat = LQuaternion() quat.setFromMatrix(npmat3_to_pdmat3(npmat3)) return quat
def convert_quaternion(self, quaternion): """ Convert a OpenVR quaternion into a Panda3D quaternion. No coordinate system conversion is performed. """ return LQuaternion(quaternion.w, quaternion.x, quaternion.y, quaternion.z)
def update_instance(self, camera_pos, orientation): if self.instance: self.place_instance_params(self.instance, self.body.parent.scene_position, self.body.parent.scene_scale_factor, LQuaternion()) self.shader.update(self, self.appearance)
def create_instance(self): self.vertexData = GeomVertexData('vertexData', GeomVertexFormat.getV3c4(), Geom.UHStatic) self.vertexWriter = GeomVertexWriter(self.vertexData, 'vertex') self.colorwriter = GeomVertexWriter(self.vertexData, 'color') for r in range(1, self.nbOfRings + 1): for i in range(self.nbOfPoints): angle = 2 * pi / self.nbOfPoints * i x = cos(angle) * sin( pi * r / (self.nbOfRings + 1) ) y = sin(angle) * sin( pi * r / (self.nbOfRings + 1) ) z = sin( -pi / 2 + pi * r / (self.nbOfRings + 1) ) self.vertexWriter.addData3f((self.context.observer.infinity * x, self.context.observer.infinity * y, self.context.observer.infinity * z)) if r == self.nbOfRings / 2 + 1: self.colorwriter.addData4f(self.color.x * 1.5, 0, 0, 1) else: self.colorwriter.addData4f(*self.color) for s in range(self.nbOfSectors): for i in range(self.points_to_remove, self.nbOfPoints // 2 - self.points_to_remove + 1): angle = 2 * pi / self.nbOfPoints * i x = cos(2*pi * s / self.nbOfSectors) * sin(angle) y = sin(2*pi * s / self.nbOfSectors) * sin(angle) z = cos(angle) self.vertexWriter.addData3f((self.context.observer.infinity * x , self.context.observer.infinity * y, self.context.observer.infinity * z)) if s == 0: self.colorwriter.addData4f(self.color.x * 1.5, 0, 0, 1) else: self.colorwriter.addData4f(*self.color) self.lines = GeomLines(Geom.UHStatic) index = 0 for r in range(self.nbOfRings): for i in range(self.nbOfPoints-1): self.lines.addVertex(index) self.lines.addVertex(index+1) self.lines.closePrimitive() index += 1 self.lines.addVertex(index) self.lines.addVertex(index - self.nbOfPoints + 1) self.lines.closePrimitive() index += 1 for r in range(self.nbOfSectors): for i in range(self.nbOfPoints // 2 - self.points_to_remove * 2): self.lines.addVertex(index) self.lines.addVertex(index+1) self.lines.closePrimitive() index += 1 index += 1 self.geom = Geom(self.vertexData) self.geom.addPrimitive(self.lines) self.node = GeomNode("grid") self.node.addGeom(self.geom) self.instance = NodePath(self.node) self.instance.setRenderModeThickness(settings.grid_thickness) #myMaterial = Material() #myMaterial.setEmission((1.0, 1.0, 1.0, 1)) #self.instance.setMaterial(myMaterial) self.instance.reparentTo(self.context.annotation) self.instance.setQuat(LQuaternion(*self.orientation))
def update(self, observer): if self.instance is None: return False local_position = LPoint3d(*self.physics_instance.get_pos()) local_rotation = LQuaterniond(*self.physics_instance.get_quat()) if settings.camera_at_origin: scene_rel_position = local_position - observer._local_position else: scene_rel_position = local_position self.instance.set_pos(*scene_rel_position) self.instance.set_quat(LQuaternion(*local_rotation)) if (local_position - observer._local_position).length() > self.limit: print("Object is too far, removing it") self.remove_instance() return False else: return True
def __create2DConstraint__(self,obj): obj.setQuat(self,LQuaternion.identQuat()) obj.setY(self,0) constraint = BulletGenericConstraint(self.motion_plane_np_.node(),obj.node(), TransformState.makeIdentity(),TransformState.makeIdentity(),False) max_float = sys.float_info.max constraint.setLinearLimit(0,-max_float,max_float) constraint.setLinearLimit(1,0,0) constraint.setLinearLimit(2,-max_float,max_float) constraint.setDebugDrawSize(0) return constraint
def create_instance(self): if not self.instance: self.instance = self.shape.create_instance() if self.instance is None: return if self.appearance is not None: self.appearance.bake() self.appearance.apply(self) #Shader is applied once the textures are loaded # if self.shader is not None: # self.shader.apply(self.shape, self.appearance) self.instance.setQuat(LQuaternion(*self.orientation)) self.instance.set_two_sided(True) self.instance.setCollideMask(BitMask32.allOff()) self.instance.reparentTo(self.context.world) self.instance.setBin('background', settings.skysphere_depth) self.instance.set_depth_write(False)
def __init__( self, pos=[0, 0, 0], a0=[0, 0, 0], a1=[0, 0, 0], a2=[0, 0, 0], radius=[0, 0, 0], quat=[0, 0, 0, 0], #Scalar last format mode='quat', catid=-1): print("Got mode : ", mode) #Model Stuff self.modelPath = 'N/A' self.relModel = None #Geometry #Note: a0,a1,a2 only reflect the axis # initially given by data set, these wont change if we manually # change orientation(atleast not for now) self.pos = pos self.a0 = a0 self.a1 = a1 self.a2 = a2 self.radius = radius self.catid = catid #Quat Stuff self.quat = LQuaternion(r=quat[3], i=quat[0], j=quat[1], k=quat[2]) self.mode = mode #cur eurler angles(shouldnt interfere with nw podel) self.eAng = mymathnutils.getFullRot(self.a0, self.a1, self.a2) #Panda3D self.nodePath = None #Bounding Box self.ModelNodePath = None #Bounding Box
def get_bone_transform(self, bone_transform_array, bone_index): """ Returns the transform related to the given bone. The transform is returned as a translation vector and a quaternion rotation. bone_transform_array : Array containing all the bones transformations bone_index : Index of the bone transformation to retrieve. """ if bone_index < len(bone_transform_array): bone_transform = bone_transform_array[bone_index] if bone_transform is not None: position = bone_transform.position orientation = bone_transform.orientation return self.coord_mat.xform( self.convert_vector(position)), self.coord_mat.xform( self.convert_quaternion(orientation)) else: print( "ERROR: No transform data for bone {}".format(bone_index)) else: print("ERROR: Invalid bone index {}".format(bone_index)) return LVector4(), LQuaternion()
def set_camera_rot(self, rot): base.cam.set_quat(LQuaternion(*rot))
def update_camera(self): #Don't update camera position as everything is relative to camera self.camera_vector = self.get_camera_vector() self.cam.setQuat(LQuaternion(*self.get_camera_rot()))
def place_instance(self, instance, parent): instance.setPos(*self.parent.scene_position) instance.setScale(*(self.get_scale() * self.parent.scene_scale_factor)) instance.setQuat(LQuaternion(*self.parent.scene_orientation))
class RaphSkyBox(DirectObject): def __init__(self): self.skybox = None self.sun_color = None self.skybox_color = None self.light_angle = None self.light_dir = LVector3d.up() self.light_quat = LQuaternion() self.light_color = (1.0, 1.0, 1.0, 1.0) self.fog = None def init(self, config): skynode = base.camera.attachNewNode('skybox') base.camera.hide(BaseObject.AllCamerasMask) base.camera.show(BaseObject.DefaultCameraMask | BaseObject.WaterCameraMask) 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 * config.tile_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.sun_color = LColor(pow(1.0, 1 / 2.2), pow(0.9, 1 / 2.2), pow(0.7, 1 / 2.2), 1.0) self.skybox.setColor(self.skybox_color) def set_fog(self, fog): self.fog = fog self.set_light_angle(self.light_angle) 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()) if cosA >= 0: coef = sqrt(cosA) self.light_color = (1, coef, coef, 1) new_sky_color = self.skybox_color * cosA new_sky_color[3] = 1.0 self.skybox.setColor(new_sky_color) if self.fog is not None: self.fog.fog_color = self.skybox_color * cosA self.fog.sun_color = self.sun_color * cosA else: self.light_color = (0, 0, 0, 1) self.skybox.setColor(self.light_color) if self.fog is not None: self.fog.fog_color = self.skybox_color * 0 self.fog.sun_color = self.sun_color * 0
def update(self, time, dt): ActorShip.update(self, time, dt) if self.physics_instance is not None: offset = LPoint3d(0, 0, 0.8) self.physics_instance.set_pos(*(self._local_position + offset)) self.physics_instance.set_quat(LQuaternion(*self._orientation))
def __init__(self, init_rotation=None): if init_rotation is None: self.rotation = LQuaternion() else: self.rotation = LQuaternion(1, *init_rotation) self.last_t = time.time()
def __init__(self, args): self.app_config = RalphAppConfig() CosmoniumBase.__init__(self) settings.color_picking = False settings.scale = 1.0 settings.use_inv_scaling = False if args.config is not None: self.config_file = args.config else: self.config_file = 'ralph-data/ralph.yaml' self.splash = NoSplash() self.ralph_config = RalphConfigParser() if self.ralph_config.load_and_parse(self.config_file) is None: sys.exit(1) self.has_water = True self.water = self.ralph_config.water if self.ralph_config.physics.enable: self.physics = Physics(self.ralph_config.physics.debug) self.physics.enable() self.physics.set_gravity(self.ralph_config.physics.gravity) else: self.physics = None self.physic_objects = [] self.fullscreen = False self.shadow_caster = None self.set_ambient(0.3) self.cam.node().set_camera_mask(BaseObject.DefaultCameraMask | BaseObject.NearCameraMask) self.observer = CameraHolder(self.camera, self.camLens) self.observer.init() self.distance_to_obs = 2.0 #Can not be 0 ! self.height_under = 0.0 self.scene_position = LVector3d() self.scene_scale_factor = 1 self.scene_rel_position = LVector3d() self.scene_orientation = LQuaternion() self.model_body_center_offset = LVector3d() self.world_body_center_offset = LVector3d() self._local_position = LPoint3d() self.context = self self.oid_color = 0 self.oid_texture = None #Needed for create_light to work self.nearest_system = self self.star = self self.primary = None self.size = self.ralph_config.tile_size #TODO: Needed by populator self.skybox = RaphSkyBox() self.skybox.init(self.ralph_config) self.skybox.set_light_angle(45) self.vector_to_star = -self.skybox.light_dir self.vector_to_obs = base.camera.get_pos() self.vector_to_obs.normalize() if True: self.shadow_caster = ShadowMap(1024) self.shadow_caster.create() self.shadow_caster.set_lens( self.ralph_config.shadow_size, -self.ralph_config.shadow_box_length / 2.0, self.ralph_config.shadow_box_length / 2.0, -self.vector_to_star) self.shadow_caster.set_pos(self.vector_to_star * self.ralph_config.shadow_box_length / 2.0) self.shadow_caster.snap_cam = True else: self.shadow_caster = None self.ambientLight = AmbientLight("ambientLight") self.ambientLight.setColor( (settings.global_ambient, settings.global_ambient, settings.global_ambient, 1)) render.setLight(render.attachNewNode(self.ambientLight)) base.setFrameRateMeter(True) self.create_terrain() for component in self.ralph_config.layers: self.terrain.add_component(component) self.terrain_shape.add_linked_object(component) if self.ralph_config.fog_parameters is not None: self.fog = Fog(**self.ralph_config.fog_parameters) self.terrain.add_after_effect(self.fog) self.skybox.set_fog(self.fog) else: self.fog = None self.surface = self.terrain_object self.create_instance() self.create_tile(0, 0) # Create the main character, Ralph self.ralph_shape = ActorShape("ralph-data/models/ralph", { "run": "ralph-data/models/ralph-run", "walk": "ralph-data/models/ralph-walk" }, auto_scale_mesh=False, rotation=quaternion_from_euler( 180, 0, 0), scale=(0.2, 0.2, 0.2)) self.ralph_appearance = ModelAppearance(vertex_color=True, material=False) self.ralph_shader = BasicShader() self.ralph_shader.add_shadows( ShaderShadowMap('caster', None, self.shadow_caster, use_bias=True)) self.ralph_shape_object = ShapeObject('ralph', self.ralph_shape, self.ralph_appearance, self.ralph_shader, clickable=False) self.ralph = RalphShip('ralph', self.ralph_shape_object, 1.5, self.ralph_config.physics.enable) frame = CartesianSurfaceReferenceFrame(LPoint3d()) frame.set_parent_body(self) self.ralph.set_frame(frame) self.ralph.create_own_shadow_caster = False self.camera_controller = SurfaceFollowCameraController() #self.camera_controller = FixedCameraController() self.camera_controller.activate(self.observer, self.ralph) self.camera_controller.set_body(self) self.camera_controller.set_camera_hints(distance=5, max=1.5) self.controller = RalphControl(self.skybox, self) self.controller.register_events() self.mover = CartesianSurfaceBodyMover(self.ralph) self.mover.activate() self.nav = ControlNav(self.mover) self.nav.register_events(self) self.nav.speed = 25 self.nav.rot_step_per_sec = 2 #TEMPORARY self.ralph.update(0, 0) self.camera_controller.update(0, 0) self.mover.update() self.ralph.update_obs(self.observer) self.ralph.check_visibility(self.observer.pixel_size) self.ralph.check_and_update_instance(self.observer.get_camera_pos(), self.observer.get_camera_rot(), None) self.ralph.create_light() if self.ralph_config.physics.enable: for physic_object in self.physic_objects: physic_object.update(self.observer) taskMgr.add(self.move, "moveTask") # Set up the camera self.distance_to_obs = self.camera.get_z() - self.get_height( self.camera.getPos()) render.set_shader_input("camera", self.camera.get_pos()) self.terrain.update_instance(self.observer.get_camera_pos(), None)
def set_orientation(self, orientation): self.orientation = orientation if self.instance: self.instance.setQuat(LQuaternion(*self.orientation))
def rotate(rotation, w, dt): rotation *= LQuaternion(1, w * dt / 2) rotation.normalize()
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, args): CosmoniumBase.__init__(self) if args.config is not None: self.config_file = args.config else: self.config_file = 'ralph-data/ralph.yaml' self.splash = RalphSplash() self.ralph_config = RalphConfigParser() if self.ralph_config.load_and_parse(self.config_file) is None: sys.exit(1) self.water = self.ralph_config.water 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.observer = RalphCamera(self.cam, self.camLens) self.observer.init() self.distance_to_obs = 2.0 #Can not be 0 ! self.height_under = 0.0 self.scene_position = LVector3() self.scene_scale_factor = 1 self.scene_rel_position = LVector3() self.scene_orientation = LQuaternion() self.model_body_center_offset = LVector3() self.world_body_center_offset = LVector3() self.context = self self.size = self.ralph_config.tile_size #TODO: Needed by populator #Size of an edge seen from 4 units above self.edge_apparent_size = (1.0 * self.ralph_config.tile_size / self.ralph_config.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)) # 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 = ShadowMap(1024) self.shadow_caster.create() self.shadow_caster.set_lens( self.ralph_config.shadow_size, -self.ralph_config.shadow_box_length / 2.0, self.ralph_config.shadow_box_length / 2.0, -self.light_dir) self.shadow_caster.set_pos( self.light_dir * self.ralph_config.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() for component in self.ralph_config.layers: self.terrain.add_component(component) self.terrain_shape.add_linked_object(component) if self.ralph_config.fog_parameters is not None: self.fog = Fog(**self.ralph_config.fog_parameters) self.terrain.add_after_effect(self.fog) else: self.fog = None self.surface = self.terrain_object self.create_instance() 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_shader.add_shadows(ShaderShadowMap()) 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) self.ralph_body = NodePathHolder(self.ralph) self.ralph_floater = NodePathHolder(self.floater) self.follow_cam = FollowCam(self, self.cam, self.ralph, self.floater) self.nav = RalphNav(self.ralph, self.ralph_floater, self.cam, self.observer, self, self.follow_cam) self.nav.register_events(self) self.accept("escape", sys.exit) self.accept("control-q", sys.exit) 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.toggle_lod_freeze) self.accept("shift-f8", self.terrain_shape.dump_tree) self.accept('control-f8', self.toggle_split_merge_debug) self.accept('shift-f9', self.toggle_bb) self.accept('control-f9', self.toggle_frustum) self.accept("f10", self.save_screenshot) self.accept('alt-enter', self.toggle_fullscreen) self.accept('{', self.incr_ambient, [-0.05]) self.accept('}', self.incr_ambient, [+0.05]) taskMgr.add(self.move, "moveTask") # Set up the camera self.follow_cam.update() self.distance_to_obs = self.cam.get_z() - self.get_height( self.cam.getPos()) render.set_shader_input("camera", self.cam.get_pos()) self.terrain.update_instance(LPoint3d(*self.cam.getPos()), None)
def update_shape(self): self.mesh.set_pos(*self.offset) self.mesh.set_quat(LQuaternion(*self.rotation)) self.mesh.set_scale(*self.scale_factor)
class RotationCorrector(): def __init__(self, init_rotation=None): if init_rotation is None: self.rotation = LQuaternion() else: self.rotation = LQuaternion(1, *init_rotation) self.last_t = time.time() def getHpr(self): return self.rotation.getHpr() def setHpr(self, *args, **kwargs): self.rotation.setHpr(*args, **kwargs) @staticmethod def rotationFromCompass(acceleration, magnetic_field): down = -acceleration east = down.cross(magnetic_field) north = east.cross(down) east.normalize() north.normalize() down.normalize() r = LMatrix4() r.setRow(0, north) r.setRow(1, east) r.setRow(2, down) return r @staticmethod def rotate(rotation, w, dt): rotation *= LQuaternion(1, w * dt / 2) rotation.normalize() def rotationMagic(self, timestamp, angular_velocity, acceleration, magnetic_field): dt = timestamp - self.last_t self.last_t = timestamp angular_velocity = Vec3(*angular_velocity) acceleration = Vec3(*acceleration) magnetic_field = Vec3(*magnetic_field) correction = (0, 0, 0) if abs(acceleration.length() - 1) <= 0.3: correction_strength = 1 rotationCompass = self.rotationFromCompass(acceleration, magnetic_field) rotationMatrix = LMatrix4() self.rotation.extractToMatrix(rotationMatrix) correction = rotationCompass.getRow3(0).cross( rotationMatrix.getRow3(0)) correction += rotationCompass.getRow3(1).cross( rotationMatrix.getRow3(1)) correction += rotationCompass.getRow3(2).cross( rotationMatrix.getRow3(2)) correction *= correction_strength self.rotate(self.rotation, angular_velocity + correction, dt)
def place_instance_params(self, instance, scene_position, scene_scale_factor, scene_orientation): instance.setPos(*scene_position) instance.setScale(self.get_scale() * scene_scale_factor) instance.setQuat(LQuaternion(*scene_orientation))