Пример #1
0
    def mouse_callback(self, parent, x, y):
        if self.first_mouse:
            self.last_x, self.last_y = x, y
            self.first_mouse = False

        x_offset, y_offset = x - self.last_x, y - self.last_y
        self.last_x, self.last_y = x, y

        x_offset *= self.sensitivity
        y_offset *= self.sensitivity

        self.yaw += x_offset
        self.pitch -= y_offset

        if self.pitch > 89.95:
            self.pitch = 89.95
        if self.pitch < -89.95:
            self.pitch = -89.95

        direction = glm.vec3(
            glm.cos(glm.radians(self.yaw)) * glm.cos(glm.radians(self.pitch)),
            glm.sin(glm.radians(self.pitch)),
            glm.sin(glm.radians(self.yaw)) * glm.cos(glm.radians(self.pitch)))
        self.front = glm.normalize(direction)
        self.move.x = direction.x / glm.cos(glm.radians(self.pitch))
        self.move.z = direction.z / glm.cos(glm.radians(self.pitch))
Пример #2
0
def keyboard_d_keys(key, dx, y):
    global angle, cameraFront, cameraUp, cameraPos

    if not isinstance(key, int):
        key = key.decode("utf-8")

    front = glm.vec3(0, 0, -1)

    cam_speed = 0.2

    if key == GLUT_KEY_LEFT:
        print("D_KEYS_L ", key)
        angle -= cam_speed
        front.x = glm.sin(angle)
        front.z = -glm.cos(angle)
    elif key == GLUT_KEY_RIGHT:
        print("D_KEYS_R ", key)
        angle += cam_speed
        front.x = glm.sin(angle)
        front.z = -glm.cos(angle)
    elif key == GLUT_KEY_UP:
        print("D_KEYS_U ", key)
        angle += cam_speed
        front.y = glm.sin(angle)
        # front.z = -glm.cos(angle)
    elif key == GLUT_KEY_DOWN:
        print("D_KEYS_D ", key)
        angle -= cam_speed
        front.y = glm.sin(angle)
        # front.z = -glm.cos(angle)

    # cameraFront = glm.normalize(front)
    cameraFront = front
    glutPostRedisplay()
Пример #3
0
	def update(self, delta_time):
		# process input

		self.view_ray = glm.vec3(glm.cos(self.rotation[0]) * glm.cos(self.rotation[1]), 
						glm.sin(self.rotation[1]),
						glm.sin(self.rotation[0]) * glm.cos(self.rotation[1]))

		if delta_time * 20 > 1:
			self.speed = self.target_speed

		else:
			self.speed += (self.target_speed - self.speed) * delta_time * 20

		multiplier = self.speed * (1, 2)[self.flying]

		if self.flying and self.input[1]:
			self.accel[1] = self.input[1] * multiplier

		if self.input[0] or self.input[2]:
			angle = self.rotation[0] - math.atan2(self.input[2], self.input[0]) + math.tau / 4

			self.accel[0] = math.cos(angle) * multiplier
			self.accel[2] = math.sin(angle) * multiplier

		if not self.flying and self.input[1] > 0:
			self.jump()

		# process physics & collisions &c

		super().update(delta_time)

		self.rounded_position = [round(i) for i in self.position]
Пример #4
0
    def _update_cam_unit_pos(self):
        self._pitch = max(-89., min(89., self._pitch))

        pitch = glm.radians(self._pitch)
        yaw = glm.radians(self._yaw)

        self._cam_unit_pos = glm.normalize(glm.vec3(glm.cos(yaw) * glm.cos(pitch),
                                                    glm.sin(pitch),
                                                    glm.sin(yaw) * glm.cos(pitch)))
    def updateCameraVectors(self):
        self.front.x = glm.cos(glm.radians(self.yaw)) * glm.cos(
            glm.radians(self.pitch))
        self.front.y = glm.sin(glm.radians(self.pitch))
        self.front.z = glm.sin(glm.radians(self.yaw)) * glm.cos(
            glm.radians(self.pitch))
        self.front = glm.normalize(self.front)

        self.right = glm.normalize(glm.cross(self.front, self.worldUp))
        self.up = glm.normalize(glm.cross(self.right, self.front))
Пример #6
0
 def _update(self):
     current_frame = time.time()
     self.delta = current_frame - self.last_time
     self.last_time = current_frame
     print(f'delta = {self.delta}')
     angle = glm.radians(self.angle)
     print(f'angle = {angle}')
     light_x = self.light.position.x * glm.cos(angle) - self.light.position.z * glm.sin(angle)
     light_z = self.light.position.z * glm.cos(angle) + self.light.position.x * glm.sin(angle)
     self.light.position = glm.vec3(light_x, self.light.position.y, light_z)
     self.angle += 0.5 * self.delta
Пример #7
0
def rotate_points(points_list, angle):
    # passed in mesh is a list of vec3 x,y,z positions
    # rotation happens around the 0,0,0 position
    sizeofList = len(points_list) 
    i=0
    # for every vec3 in mesh 
    while i < (sizeofList):
        # simple 2d rotation about the Z axis following sum angle rule
        x2=((points_list[i].x*glm.cos(angle)) - (points_list[i].y*glm.sin(angle)))
        y2=((points_list[i].x*glm.sin(angle)) + (points_list[i].y*glm.cos(angle)))
        points_list[i].x = int(x2)
        points_list[i].y = int(y2)
        i += 1
    return points_list
Пример #8
0
def rotate_vector(vector, angle):
    # takes a vector and returns a normalized vector adjusted by angle
    # angle delivered in degrees
    # simple 2d rotation about the Z axis following sum angle rule
    x2 = ((vector.x * glm.cos(angle)) - (vector.y * glm.sin(angle)))
    y2 = ((vector.x * glm.sin(angle)) + (vector.y * glm.cos(angle)))

    # don't hold this to an int
    vector.x = x2
    vector.y = y2

    vector = glm.normalize(vector)

    return vector
Пример #9
0
 def relative_move(self, right, up, forward):
     '''Moves the camera relative to its own current rotation.
     For instance, if the camera is facing straight down,
     relative_move()ing forward would be the same as move()ing down.'''
     cyaw = glm.cos(self._yaw)
     syaw = glm.sin(self._yaw)
     cpitch = glm.cos(self._pitch)
     spitch = glm.sin(self._pitch)
     croll = glm.cos(self._roll)
     sroll = glm.sin(self._roll)
     x = (-1 * cyaw * syaw * sroll - sroll * croll) * right
     y = (-1 * syaw * spitch * sroll + cyaw * croll) * up
     z = -1 * (cpitch * sroll) * forward
     self._position = self._position + glm.vec3(x, y, z)
     self._transm = None
     self._matrix = None
Пример #10
0
def eulerToRotationMatrix(roll, pitch, yaw):
    """
    ZXY顺规, Z-Roll, X-Pitch, Y-Yaw, 单位角度
    参考: https://zhuanlan.zhihu.com/p/45404840
    """
    c1 = glm.cos(glm.radians(yaw))
    s1 = glm.sin(glm.radians(yaw))
    c2 = glm.cos(glm.radians(pitch))
    s2 = glm.sin(glm.radians(pitch))
    c3 = glm.cos(glm.radians(roll))
    s3 = glm.sin(glm.radians(roll))
    matrix = glm.mat4(c1*c3+s1*s2*s3, c3*s1*s2-c1*s3, c2*s1, 0,
                      c2*s3, c2*c3, -s2, 0,
                      c1*s2*s3-s1*c3, s1*s3+c1*c3*s2, c1*c2, 0,
                      0, 0, 0, 1)
    return matrix
def main():
    # initializing glfw library
    if not glfw.init():
        raise Exception("glfw can not be initialized!")

    # Configure the OpenGL context.
    # If we are planning to use anything above 2.1 we must at least
    # request a 3.3 core context to make this work across platforms.
    if "Windows" in pltf.platform():
        glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4)
        glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 6)
        glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
        glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True)
    else:
        glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4)
        glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 1)
        glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
        glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True)

    # 4 MSAA is a good default with wide support
    glfw.window_hint(glfw.SAMPLES, 4)

    # creating the window
    window = glfw.create_window(1280, 720, "My OpenGL window", None, None)

    # check if window was created
    if not window:
        glfw.terminate()
        raise Exception("glfw window can not be created!")

    # Query the actual framebuffer size so we can set the right viewport later
    # -> glViewport(0, 0, framebuffer_size[0], framebuffer_size[1])
    framebuffer_size = glfw.get_framebuffer_size(window)

    # set window's position
    glfw.set_window_pos(window, 100, 100)

    # make the context current
    glfw.make_context_current(window)

    # glClearColor(0.5, 0.5, 0.5, 1.0)
    print("GL_RENDERER   = ", glGetString(GL_RENDERER).decode("utf8"))
    print("GL_VERSION    = ", glGetString(GL_VERSION).decode("utf8"))

    # the main application loop
    while not glfw.window_should_close(window):
        glfw.poll_events()
        # glClear(GL_COLOR_BUFFER_BIT)
        COLOR = glm.array(
            glm.vec4([
                glm.sin(glfw.get_time()) * 0.5 + 0.5,
                glm.cos(glfw.get_time()) * 0.5 + 0.5, 0.0, 1.0
            ]))
        glClearBufferfv(GL_COLOR, 0, COLOR.ptr)

        glfw.swap_buffers(window)

    # terminate glfw, free up allocated resources
    glfw.terminate()
Пример #12
0
    def calc_collide_rays(self, numViewDirections, length):
        directions=[]

        goldenRatio = (1 + glm.sqrt(5)) / 2;
        angleIncrement = glm.pi() * 2 * goldenRatio;

        i=0 
        while i < (numViewDirections):
            t =  i / numViewDirections;
            inclination = glm.acos(1 - 2 * t); 
            azimuth = angleIncrement * i;
            x = glm.sin(inclination) * glm.cos(azimuth);
            y = glm.sin (inclination) * glm.sin(azimuth);
            z = glm.cos (inclination); 
            directions.append(glm.vec3(x, y, z)*length)
            i+=1

        return directions 
Пример #13
0
def draw_cylinder(x, y, z, radius, height):
    px = 0
    pz = 0
    c_angle = 0
    angle_stepsize = 0.1

    glBegin(GL_QUAD_STRIP)
    c_angle = 0
    while c_angle < 2 * glm.pi() + 1:
        px = radius * glm.cos(c_angle)
        pz = radius * glm.sin(c_angle)
        glVertex3f(x + px, y + height, z + pz)
        glVertex3f(x + px, y, z + pz)
        c_angle += angle_stepsize
    glEnd()

    glBegin(GL_POLYGON)
    c_angle = 0
    while c_angle < 2 * glm.pi():
        px = radius * glm.cos(c_angle)
        pz = radius * glm.sin(c_angle)
        glVertex3f(x + px, y + height, z + pz)
        c_angle += angle_stepsize
    glEnd()

    glBegin(GL_POLYGON)
    c_angle = 0
    while c_angle < 2 * glm.pi():
        px = radius * glm.cos(c_angle)
        pz = radius * glm.sin(c_angle)
        glVertex3f(x + px, y + height, z + pz)
        c_angle += angle_stepsize
    glEnd()

    glBegin(GL_POLYGON)
    c_angle = 0
    while c_angle < 2 * glm.pi():
        px = radius * glm.cos(c_angle)
        pz = radius * glm.sin(c_angle)
        glVertex3f(x + px, y, z + pz)
        c_angle += angle_stepsize
    glEnd()
Пример #14
0
def mouse_camera(mouse_x, mouse_y):
    global mouse_sensitivity, mouse_speed, angle_x, angle_y, cameraFront, old_mouse_x, old_mouse_y

    angle_x -= (mouse_x - old_mouse_x) * mouse_sensitivity
    angle_y -= (mouse_y - old_mouse_y) * mouse_sensitivity

    if angle_y > 2:
        angle_y = 2
    if angle_y < 1:
        angle_y = 1

    front = glm.vec3()
    front.x = glm.cos(angle_x) * glm.sin(angle_y)
    front.z = glm.sin(angle_x) * glm.sin(angle_y)
    front.y = glm.cos(angle_y)
    cameraFront = front

    old_mouse_x = mouse_x
    old_mouse_y = mouse_y
    glutPostRedisplay()
Пример #15
0
 def draw_scene(self,
                draw: ImageDraw.ImageDraw,
                player_radians: float,
                projection_plane: float,
                wall_height: int,
                hits: List[Hit]):
     y = self.height / 2
     precomputed = wall_height * projection_plane
     for x, hit in enumerate(hits):
         correct_distance = hit.length * glm.cos(hit.radians - player_radians)
         column_height = precomputed / correct_distance
         draw.line((x, y - column_height, x, y + column_height), COLOR_GRAY)
Пример #16
0
 def __init__(self,
              game_object: GameObject,
              cut_off: Optional[float] = None,
              outer_cut_off: Optional[float] = None,
              light_range: Optional[float] = None,
              ambient: Optional[float] = None,
              diffuse: Optional[float] = None,
              specular: Optional[float] = None,
              color: Optional[Color] = None):
     super(SpotLight, self).__init__(game_object=game_object,
                                     light_range=light_range,
                                     ambient=ambient,
                                     diffuse=diffuse,
                                     specular=specular,
                                     color=color)
     self.direction: Vector3 = game_object.transform.forward
     self.cut_off: float = glm.cos(
         glm.radians(12.5)) if cut_off is None else glm.cos(
             glm.radians(cut_off))
     self.outer_cut_off: float = glm.cos(
         glm.radians(15.0)) if outer_cut_off is None else glm.cos(
             glm.radians(outer_cut_off))
Пример #17
0
    def ray_travers(self, ray: 'Ray') -> Hit:
        current = ray.origin
        while True:
            tile = self._to_tile_coords(*current)
            box_min = tile * self.cell_size
            box_max = box_min + self.cell_size
            t = self._box_ray_intersection(ray, box_min, box_max)

            if self._is_out_of_range(*tile) or self.get(*tile) == self.stop_when:
                length = abs(ray.origin.x - current.x) / glm.cos(ray.radians)
                if not length:
                    length = abs(ray.origin.y - current.y) / glm.sin(ray.radians)
                return Hit(abs(length), ray.radians, current)
            current = ray.origin + t * ray.direction
Пример #18
0
    def __init__(self, position, front, window_size):
        self.pos = glm.vec3(position[0], position[1], position[2])
        self.front = glm.vec3(front[0], front[1], front[2])
        self.up = glm.vec3(0, 1, 0)
        self.move = glm.vec3(front[0], 0, front[2])

        self.sprint = False
        self.sprint_press = 0
        self.coords_toggle = False

        self.last_x, self.last_y = window_size[0] / 2, window_size[1] / 2
        self.pitch = glm.asin(self.front.y)
        self.yaw = glm.acos(self.front.x / glm.cos(self.pitch))

        self.sensitivity = 0.2

        self.first_mouse = True
Пример #19
0
        shadowProj * glm.lookAt(lightPos, lightPos + glm.vec3(0.0, 0.0, 1.0),
                                glm.vec3(0.0, -1.0, 0.0)))
    shadowTransforms.append(
        shadowProj * glm.lookAt(lightPos, lightPos + glm.vec3(0.0, 0.0, -1.0),
                                glm.vec3(0.0, -1.0, 0.0)))

    shadowTransforms = np.array([np.array(m) for m in shadowTransforms])

import time
with window:
    while not window.should_close():
        # Animate
        # -------
        lightPos = glm.vec3(
            glm.sin(time.time() * 1.6) * 2, 3,
            glm.cos(time.time() * 1.6) * 2)

        # shadow depth cubemap pass
        # -------------------------
        shadowTransforms = []
        shadowTransforms.append(
            shadowProj *
            glm.lookAt(lightPos, lightPos + glm.vec3(1.0, 0.0, 0.0),
                       glm.vec3(0.0, -1.0, 0.0)))
        shadowTransforms.append(
            shadowProj *
            glm.lookAt(lightPos, lightPos + glm.vec3(-1.0, 0.0, 0.0),
                       glm.vec3(0.0, -1.0, 0.0)))
        shadowTransforms.append(
            shadowProj *
            glm.lookAt(lightPos, lightPos + glm.vec3(0.0, 1.0, 0.0),
Пример #20
0
 def direction(self):
     v = self.origin + 1 * glm.vec2(glm.cos(self.radians), glm.sin(self.radians))
     return glm.normalize(v - self.origin)
Пример #21
0
 def cut_off(self):
     return glm.cos(glm.radians(self.fov / 2))
    def on_draw(self, event):
        print("psize" + str(self.physical_size))
        print("size" + str(self.size))
        if self.physical_size != self.size:
            print("False")
            eixt()
        # Read about depth testing and changing stated in vispy here http://vispy.org/gloo.html?highlight=set_state
        gloo.clear(color=[0, 0, 0, 1.0], depth=True)

        # delta_time
        self.current_frame = time()
        self.delta_time = self.current_frame - self.last_frame
        self.last_frame = self.current_frame
        self.lightPos = [sin(time() - self.startTime), 1, 0]

        if self.camera.bool_a:
            self.camera.ProcessKeyboard(Camera_Movement.LEFT, self.delta_time)
        if self.camera.bool_w:
            self.camera.ProcessKeyboard(Camera_Movement.FORWARD,
                                        self.delta_time)
        if self.camera.bool_s:
            self.camera.ProcessKeyboard(Camera_Movement.BACKWARD,
                                        self.delta_time)
        if self.camera.bool_d:
            self.camera.ProcessKeyboard(Camera_Movement.RIGHT, self.delta_time)

        self.view = self.camera.GetViewMatrix()
        self.projection = glm.perspective(glm.radians(self.camera.Zoom),
                                          builtins.width / builtins.height,
                                          0.1, 100.0)

        # vispy takes numpy array in m * n matrix form
        self.view = (np.array(self.view.to_list()).astype(np.float32))
        self.projection = (np.array(self.projection.to_list()).astype(
            np.float32))

        # reshaping to (m, n) to (1, m*n) to support data input in vispy
        self.view = self.view.reshape(
            (1, self.view.shape[0] * self.view.shape[1]))
        self.projection = self.projection.reshape(
            (1, self.projection.shape[0] * self.projection.shape[1]))

        self.model = glm.mat4(1.0)
        # self.model = glm.rotate(self.model, glm.radians((time() - self.startTime) * 100), glm.vec3(1,0,0))
        self.model = glm.translate(self.model, self.lightPos)
        self.model = (np.array(self.model.to_list()).astype(np.float32))
        self.model = self.model.reshape(
            (1, self.model.shape[0] * self.model.shape[1]))

        # drawing light source
        self.programLightSource['model'] = self.model
        self.programLightSource['view'] = self.view
        self.programLightSource['projection'] = self.projection
        self.programLightSource['a_position'] = self.vertices / 3

        self.programLightSource.draw('triangles')

        # drawing normal cube
        self.program['view'] = self.view
        self.program['projection'] = self.projection
        self.program['a_position'] = self.vertices
        self.program['aNormal'] = self.aNormal
        self.program['viewPos'] = self.camera.Position
        self.program['texCoords'] = self.texCoord

        self.program['l_ambient[0]'] = [0.2, 0.2, 0.2]
        self.program['l_diffuse[0]'] = [1.0, 1.0, 1.0]
        self.program['l_specular[0]'] = [1.0, 1.0, 1.0]
        self.program['l_position[0]'] = self.camera.Position
        self.program['l_direction[0]'] = self.camera.Front
        self.program['l_constant'] = 1.0
        self.program['l_linear'] = 0.09
        self.program['l_quadratic'] = 0.032
        self.program['l_cut_off'] = glm.cos(glm.radians(12.5))
        self.program['l_outer_cut_off'] = glm.cos(glm.radians(17.5))

        self.program['m_diffuse[0]'] = self.diffuse_map
        self.program['m_specular[0]'] = self.specular_map
        self.program['m_shininess[0]'] = 32

        i = 0
        for pos in self.cubePositions:
            i += 1
            self.model = glm.mat4(1.0)
            # rotate the cube if you want
            self.model = glm.translate(self.model, pos)
            # self.model = glm.rotate(self.model, glm.radians(glm.radians(2000) * i / 2),
            #                       glm.vec3(1.0, 0.3, 0.5))
            self.model = (np.array(self.model.to_list()).astype(np.float32))
            self.model = self.model.reshape(
                (1, self.model.shape[0] * self.model.shape[1]))

            self.program['model'] = self.model
            self.program.draw('triangles')

        self.update()
Пример #23
0
 def look_at(self, point):
     'Rotates the camera to look at a specific point.'
     p = point - self._position
     up = (-1 * glm.sin(self._yaw) * glm.sin(self._pitch) *
           glm.sin(self._roll) + glm.cos(self._yaw) * glm.cos(self._roll))
     self._rotm = glm.lookAt(glm.vec3(0, 0, 0), p, up)