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()
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]
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))
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))
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
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
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
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
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()
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
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()
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()
def update(self, dt: float): """Call this repeatedly with the time in seconds since last frame""" rotations = self._rotations self._rotations = [] for i, rot in enumerate(rotations): # print(i, rot) amount = rot["amount"] * dt * .1 * glm.sin(rot["t"] * glm.pi()) self._matrix = glm.rotate(self._matrix, amount, rot["axis"]) rot["t"] += dt / (1. + abs(rot["amount"])) * 5. if rot["t"] < 0.99: self._rotations.append(rot) translations = self._translations self._translations = [] for i, rot in enumerate(translations): # print(i, rot) amount = rot["amount"] * dt * .1 * glm.sin(rot["t"] * glm.pi()) self._matrix = glm.translate(self._matrix, amount * rot["axis"]) rot["t"] += dt / (1. + abs(rot["amount"])) * 5. if rot["t"] < 0.99: self._translations.append(rot)
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
def direction(self): v = self.origin + 1 * glm.vec2(glm.cos(self.radians), glm.sin(self.radians)) return glm.normalize(v - self.origin)
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)
def main(): global lastFrame, deltaTime glfw.init() glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) window = glfw.create_window(screenWidth, screenHeight, "LearnOpenGL", None, None) glfw.make_context_current(window) glfw.set_framebuffer_size_callback(window, framebuffer_size_callback) glfw.set_cursor_pos_callback(window, mouse_callback) glfw.set_scroll_callback(window, scroll_callback) # tell glfw to capture our mouse glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED) glEnable(GL_DEPTH_TEST) lighting_shader_program = ShaderProgram("shaders/c05_materials.vs", "shaders/c05_materials.fs") lighting_shader = lighting_shader_program.program_id lightcube_shader_program = ShaderProgram("shaders/c05_lightcube.vs", "shaders/c05_lightcube.fs") lightcube_shader = lightcube_shader_program.program_id texture_floor_shader = ShaderProgram("shaders/c06_floor.vs", "shaders/c06_floor.fs") vertices = np.array([ -0.5, -0.5, -0.5, 0.0, 0.0, -1.0, 0.5, -0.5, -0.5, 0.0, 0.0, -1.0, 0.5, 0.5, -0.5, 0.0, 0.0, -1.0, 0.5, 0.5, -0.5, 0.0, 0.0, -1.0, -0.5, 0.5, -0.5, 0.0, 0.0, -1.0, -0.5, -0.5, -0.5, 0.0, 0.0, -1.0, -0.5, -0.5, 0.5, 0.0, 0.0, 1.0, 0.5, -0.5, 0.5, 0.0, 0.0, 1.0, 0.5, 0.5, 0.5, 0.0, 0.0, 1.0, 0.5, 0.5, 0.5, 0.0, 0.0, 1.0, -0.5, 0.5, 0.5, 0.0, 0.0, 1.0, -0.5, -0.5, 0.5, 0.0, 0.0, 1.0, -0.5, 0.5, 0.5, -1.0, 0.0, 0.0, -0.5, 0.5, -0.5, -1.0, 0.0, 0.0, -0.5, -0.5, -0.5, -1.0, 0.0, 0.0, -0.5, -0.5, -0.5, -1.0, 0.0, 0.0, -0.5, -0.5, 0.5, -1.0, 0.0, 0.0, -0.5, 0.5, 0.5, -1.0, 0.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0, 0.0, 0.5, 0.5, -0.5, 1.0, 0.0, 0.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.0, 0.5, -0.5, 0.5, 1.0, 0.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0, 0.0, -0.5, -0.5, -0.5, 0.0, -1.0, 0.0, 0.5, -0.5, -0.5, 0.0, -1.0, 0.0, 0.5, -0.5, 0.5, 0.0, -1.0, 0.0, 0.5, -0.5, 0.5, 0.0, -1.0, 0.0, -0.5, -0.5, 0.5, 0.0, -1.0, 0.0, -0.5, -0.5, -0.5, 0.0, -1.0, 0.0, -0.5, 0.5, -0.5, 0.0, 1.0, 0.0, 0.5, 0.5, -0.5, 0.0, 1.0, 0.0, 0.5, 0.5, 0.5, 0.0, 1.0, 0.0, 0.5, 0.5, 0.5, 0.0, 1.0, 0.0, -0.5, 0.5, 0.5, 0.0, 1.0, 0.0, -0.5, 0.5, -0.5, 0.0, 1.0, 0.0, ], dtype=np.float32) indices = np.array([0, 1, 3, 1, 2, 3], dtype=np.int32) bar_indices, bar_buffer = ObjLoader.load_model("models/bar.obj") floor_indices, floor_buffer = ObjLoader.load_model("models/floor.obj") ''' What is a VAO? when configuring vertex attribute, you only need to run those once. ''' cubeVAO = glGenVertexArrays(1) VBO = glGenBuffers(1) # EBO = glGenBuffers(1) glBindVertexArray(cubeVAO) # copy vertex info mation to buffer glBindBuffer(GL_ARRAY_BUFFER, VBO) glBufferData(GL_ARRAY_BUFFER, size_of(bar_buffer), bar_buffer, GL_STATIC_DRAW) # glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO) # glBufferData(GL_ELEMENT_ARRAY_BUFFER, size_of(indices), indices, GL_STATIC_DRAW) # set vertex attribute pointer # the fifth param is STRIDE: 3*size of float f_size = bar_buffer.itemsize glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * f_size, c_void_p(0)) glEnableVertexAttribArray(0) glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * f_size, c_void_p(3 * f_size)) glEnableVertexAttribArray(1) glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 8 * f_size, c_void_p(5 * f_size)) glEnableVertexAttribArray(2) # set cube vbo lightCubeVAO = glGenVertexArrays(1) lightCubeVBO = glGenBuffers(1) glBindVertexArray(lightCubeVAO) glBindBuffer(GL_ARRAY_BUFFER, lightCubeVBO) glBufferData(GL_ARRAY_BUFFER, size_of(vertices), vertices, GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * f_size, c_void_p(0)) glEnableVertexAttribArray(0) # set floor floorVAO = glGenVertexArrays(1) floorVBO = glGenBuffers(1) glBindVertexArray(floorVAO) glBindBuffer(GL_ARRAY_BUFFER, floorVBO) glBufferData(GL_ARRAY_BUFFER, size_of(floor_buffer), floor_buffer, GL_STATIC_DRAW) f_size = bar_buffer.itemsize glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * f_size, c_void_p(0)) glEnableVertexAttribArray(0) glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * f_size, c_void_p(3 * f_size)) glEnableVertexAttribArray(1) glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 8 * f_size, c_void_p(5 * f_size)) glEnableVertexAttribArray(2) floor_texture = load_texture("resources/textures/floor.jpg") #glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) # polygon mode while not glfw.window_should_close(window): # per-frame time logit current_frame = glfw.get_time() deltaTime = current_frame - lastFrame lastFrame = current_frame process_input(window) glClearColor(0.9, 0.9, 0.9, 1.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) lighting_shader_program.use() lighting_shader_program.setVec3("light.position", lightPos) lighting_shader_program.setVec3("viewPos", camera.Position) lightColor = glm.vec3() lightColor.x = glm.sin(glfw.get_time() * 2.0) lightColor.y = glm.sin(glfw.get_time() * 0.7) lightColor.z = glm.sin(glfw.get_time() * 1.3) lightColor = glm.vec3(0.9, 0.8, 0.1) diffuseColor = lightColor * glm.vec3(0.5) ambientColor = diffuseColor * glm.vec3(0.2) lighting_shader_program.setVec3("light.ambient", ambientColor) lighting_shader_program.setVec3("light.diffuse", diffuseColor) lighting_shader_program.setVec3("light.specular", glm.vec3(1.0, 1.0, 1.0)) lighting_shader_program.setVec3("material.ambient", glm.vec3(1.0, 0.5, 3.1)) lighting_shader_program.setVec3("material.diffuse", glm.vec3(1.0, 0.5, 3.1)) lighting_shader_program.setVec3("material.specular", glm.vec3(0.5, 0.5, 0.5)) lighting_shader_program.setFloat("material.shininess", 8.0) projection = glm.perspective(glm.radians(camera.Zoom), float(screenWidth / screenHeight), 0.1, 100) view = camera.getViewMatrix() lighting_shader_program.setMat4("projection", projection) lighting_shader_program.setMat4("view", view) model = glm.mat4(1.0) lighting_shader_program.setMat4("model", model) # render the cube glBindVertexArray(cubeVAO) glDrawArrays(GL_TRIANGLES, 0, len(bar_indices)) # glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, None) # glDrawArrays(GL_TRIANGLES, 0, 3) texture_floor_shader.use() texture_floor_shader.setMat4("projection", projection) texture_floor_shader.setMat4("view", view) texture_floor_shader.setMat4("model", model) glBindVertexArray(floorVAO) glBindTexture(GL_TEXTURE_2D, floor_texture) glDrawArrays(GL_TRIANGLES, 0, len(floor_indices)) # also draw the lamp object lightcube_shader_program.use() lightcube_shader_program.setMat4("projection", projection) lightcube_shader_program.setMat4("view", view) model = glm.mat4(1.0) model = glm.translate(model, lightPos) model = glm.scale(model, glm.vec3(0.2)) lightcube_shader_program.setMat4("model", model) glBindVertexArray(lightCubeVAO) glDrawArrays(GL_TRIANGLES, 0, 36) glfw.swap_buffers(window) glfw.poll_events() glfw.terminate() return
shadowTransforms.append( 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 *