def main(): if not opengl_init(): return load_gedung("itb_coordinate.txt") # Enable key events glfw.set_input_mode(window,glfw.STICKY_KEYS,GL_TRUE) glfw.set_cursor_pos(window, 1024/2, 768/2) # Set opengl clear color to something other than red (color used by the fragment shader) glClearColor(0.0,0.0,0.0,0.0) # Enable depth test glEnable(GL_DEPTH_TEST) # Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS); glEnable(GL_CULL_FACE) vertex_array_id = glGenVertexArrays(1) glBindVertexArray( vertex_array_id ) program_id = common.LoadShaders( ".\\shaders\\Tutorial6\\TransformVertexShader.vertexshader", ".\\shaders\\Tutorial6\\TextureFragmentShader.fragmentshader" ) # Get a handle for our "MVP" uniform matrix_id = glGetUniformLocation(program_id, "MVP"); texture = ["",""] glGenTextures(2, texture) texture = load_image(".\\content\\uvmap.bmp",texture[0]) texture2 = load_image(".\\content\\uvtemplate.bmp",texture[1])
def cursor_callback(win, x_pos, y_pos): if(x_pos != cartesian.x_pos_prev and y_pos != cartesian.y_pos_prev): glfw.set_cursor_pos(win, window_width/2, window_height/2); glfw.set_input_mode(win, glfw.CURSOR , glfw.CURSOR_NORMAL) horizontal_angle = matrixScene.horizontal_angle vertical_angle = matrixScene.vertical_angle mouse_speed = 4 horizontal_angle += mouse_speed * time.GetTimeDelta() * float(window_width / 2.0 - x_pos); vertical_angle += mouse_speed * time.GetTimeDelta() * float(window_height / 2.0 - y_pos); if (vertical_angle < -1.57): vertical_angle = -1.57; if (vertical_angle > 1.57): vertical_angle = 1.57; direction = np.array([np.cos(vertical_angle) * np.sin(horizontal_angle), np.sin(vertical_angle), np.cos(vertical_angle) * np.cos(horizontal_angle)]) right = np.array([-np.cos(horizontal_angle), 0, np.sin(horizontal_angle)]); up = np.cross(right, direction ) matrixScene.direction = direction matrixScene.right = right matrixScene.up = up matrixScene.horizontal_angle = horizontal_angle matrixScene.vertical_angle = vertical_angle matrixScene.calculate_view_matrix() cartesian.x_pos_prev = x_pos cartesian.y_pos_prev = y_pos
def _update_context(self, old_scene, new_scene): """ Update the GLFW and OpenGL context according to the Scene change. :param old_scene: :param new_scene: :return: """ # Set the cursor behavior glfw.set_input_mode(self.ctx.window, glfw.CURSOR, new_scene.cursor_mode) glfw.set_cursor_pos(self.ctx.window, *new_scene.cursor_origin) # Enable the OpenGL depth buffer if new_scene.enable_depth_test: gl.glEnable(gl.GL_DEPTH_TEST) gl.glDepthFunc(new_scene.depth_function) else: gl.glDisable(gl.GL_DEPTH_TEST) # Enable OpenGL face culling if new_scene.enable_face_culling: gl.glEnable(gl.GL_CULL_FACE) gl.glFrontFace(new_scene.front_face) gl.glCullFace(new_scene.cull_face) else: gl.glDisable(gl.GL_CULL_FACE)
def main(self): if not glfw.init(): # failed to init so leave return # get a list of monitors as we want the second one monitors = glfw.get_monitors() # make a new window that fills the second screen window = glfw.create_window(self.width, self.height, "LabyrinthMaker_GLFW", monitors[1], None) if not window: # if it failed the leave glfw.terminate() return # set focus on the window glfw.make_context_current(window) # until we say exit keep runnning this while not glfw.window_should_close(window): # set cursor position because of remote login # as this runs all the time mouse is essentially dead # so youll have to 'killall python' to get out if self.mode != "DEBUG": glfw.set_cursor_pos(window, 2000, 0) # run the draw loop self.draw() # update gl things in the window glfw.swap_buffers(window) glfw.poll_events() # kill gl glfw.terminate()
def main(self): glfw.set_error_callback(error_callback) if not glfw.init(): raise RuntimeError('glfw.init()') glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.SAMPLES, 4) glfw.window_hint(glfw.RESIZABLE, False) self.window = glfw.create_window(self.screen_x, self.screen_y, self.title, None, None) if not self.window: raise RuntimeError('glfw.CreateWindow())') glfw.make_context_current(self.window) glfw.set_input_mode(self.window, glfw.CURSOR, glfw.CURSOR_DISABLED) glfw.set_cursor_pos(self.window, 0, 0) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glEnable(GL_DEPTH_TEST) glDepthFunc(GL_LESS) glClearColor(0, 0, 0, 1) # print(b'OpenGL version: ' + glGetString(GL_VERSION)) # print(b'GLSL version: ' + glGetString(GL_SHADING_LANGUAGE_VERSION)) # print(b'Vendor: ' + glGetString(GL_VENDOR)) # print(b'Renderer: ' + glGetString(GL_RENDERER)) self.init() old_time = glfw.get_time() try: while not glfw.window_should_close(self.window): glfw.poll_events() if any(( ( glfw.get_key(self.window, glfw.KEY_LEFT_ALT) and \ glfw.get_key(self.window, glfw.KEY_F4) ), ( glfw.get_key(self.window, glfw.KEY_LEFT_CONTROL) and \ glfw.get_key(self.window, glfw.KEY_Q) ) )): glfw.set_window_should_close(self.window, True) now = glfw.get_time() self.update(float(now - old_time)) old_time = now self.render() glfw.swap_buffers(self.window) except KeyboardInterrupt: pass glfw.terminate()
def mouse_move_handler(display, x, y): print((x, y)) glfw.set_cursor_pos(display, WIDTH // 2, HEIGHT // 2) # glRotatef(0.1, 0.0, 1.0, 0.0) if WIDTH // 2 > x: glRotatef(1, 0, 1, 0) if WIDTH // 2 < x: glRotatef(1, 0, -1, 0)
def retrieve_mouse_data(self): window_size = glfw.get_framebuffer_size(self.window) window_center = [window_size[0] / 2, window_size[1] / 2] mouse_pos = [float(p - window_center[i]) / window_center[i] for i, p in enumerate(glfw.get_cursor_pos(self.window))] self.mouse_movement = (mouse_pos[0], mouse_pos[1]) glfw.set_cursor_pos(self.window, *window_center)
def look(self, window, xpos, ypos): """Look according to cursor position. Present as a callback for GLFW CursorPos event. """ center = numpy.array(glfw.get_window_size(window)) / 2 glfw.set_cursor_pos(window, *center) yaw, pitch = (center - [xpos, ypos]) * self.mouspeed * 2**self.zmlvl self.camera.rotate(*polar(complex(yaw, pitch)))
def setWindowHeight(self, h): ''' Set window height @param h: window height ''' self.gui.setWindowHeight(h) # If camera mode on then move cursor to center if self.cam_flag: glfw.set_cursor_pos(self.window, self.gui.window_width / 2, self.gui.window_height / 2)
def setWindowWidth(self, w): ''' Set window width @param w: window width ''' self.gui.setWindowWidth(w) # If camera mode on the move cursor to center if self.cam_flag: glfw.set_cursor_pos(self.window, self.gui.window_width / 2, self.gui.window_height / 2)
def camera_on(self): ''' Switch on camera mode (only for in game mode) ''' if self.mode == MODE_GAME: self.cam_flag = True # Hide cursor glfw.set_input_mode(self.window, glfw.CURSOR, glfw.CURSOR_HIDDEN) # Move cursor to center glfw.set_cursor_pos(self.window, self.gui.window_width / 2, self.gui.window_height / 2)
def setMousePos(self, pos): """Set/move the position of the mouse on the current window. Parameters ---------- pos : ArrayLike Position `(x, y)` in window coordinates. """ wcs = self._pixToWindowCoords(pos) glfw.set_cursor_pos(self.winHandle, int(wcs[0]), int(wcs[1]))
def show_window(window, program): glfw.show_window(window) glfw.set_cursor_pos(window, lastX, lastY) glEnable(GL_DEPTH_TEST) rotacao_inc = 0 while not glfw.window_should_close(window): glfw.poll_events() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glClearColor(1.0, 1.0, 1.0, 1.0) if polygonal_mode == True: glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) if polygonal_mode == False: glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) draw_ground(program) draw_house(program) draw_trees(program) draw_frog(program) draw_horse(program) draw_chair(program) draw_screen(program) draw_table(program) draw_cpu(program) draw_wind_mill_body(program) draw_wind_mill_circle(program, rotacao_inc) draw_sky(program) draw_street(program) draw_secondary_yard(program) draw_floor(program) draw_keyboard(program) rotacao_inc += 0.1 mat_view = view() loc_view = glGetUniformLocation(program, "view") glUniformMatrix4fv(loc_view, 1, GL_FALSE, mat_view) mat_projection = projection() loc_projection = glGetUniformLocation(program, "projection") glUniformMatrix4fv(loc_projection, 1, GL_FALSE, mat_projection) glfw.swap_buffers(window) glfw.terminate()
def __process_camera(self): ''' Calculate camera rotation caused by mouse moving ''' x, y = glfw.get_cursor_pos(self.window) dx = x - self.gui.window_width / 2.0 dy = y - self.gui.window_height / 2.0 cam_dir = v4_v3(mul_v(rotate(-dy * 0.5, cross(self.cam_dir, self.cam_up)), v3_v4(self.cam_dir))) cam_up = v4_v3(mul_v(rotate(-dy * 0.5, cross(self.cam_dir, self.cam_up)), v3_v4(self.cam_up))) cam_dir = v4_v3(mul_v(rotate(-dx * 0.5, cam_up), v3_v4(cam_dir))) self.cam_dir = normalize(cam_dir) self.cam_up = normalize(cam_up) glfw.set_cursor_pos(self.window, self.gui.window_width / 2, self.gui.window_height / 2)
def main(): if not glfw.init(): return glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 1) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) window = glfw.create_window(800, 600, "OpenGL Core Profile window", None, None) if not window: glfw.terminate() return # Enable key events glfw.set_input_mode(window, glfw.STICKY_KEYS, GL_TRUE) glfw.set_cursor_pos(window, 1024 / 2, 768 / 2) glfw.set_key_callback(window, key_event) glfw.make_context_current(window) while glfw.get_key( window, glfw.KEY_ESCAPE ) != glfw.PRESS and not glfw.window_should_close(window): shader = get_shader(scene.obj) glUseProgram(shader) glClearColor(0.2, 0.3, 0.2, 1.0) glEnable(GL_DEPTH_TEST) if scene.obj.wireOnShaded: glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) else: glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) glfw.poll_events() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) rot_x = pyrr.Matrix44.from_x_rotation(0.5 * glfw.get_time()) rot_y = pyrr.Matrix44.from_y_rotation(0.8 * glfw.get_time()) transformLoc = glGetUniformLocation(shader, "transform") glUniformMatrix4fv(transformLoc, 1, GL_FALSE, rot_x * rot_y) glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, None) glfw.swap_buffers(window) glfw.terminate()
def update(self): """Handle input, update GLSL programs and render the map.""" # Update instantaneous FPS next_time = glfw.get_time() self.fps = 1 / (next_time - self.last_time) self.last_time = next_time # Character movements right, upward, forward = 0, 0, 0 if self.is_pressed(glfw.KEY_UP): forward += 1 if self.is_pressed(glfw.KEY_DOWN): forward -= 1 if self.is_pressed(glfw.KEY_LEFT): right -= 1 if self.is_pressed(glfw.KEY_RIGHT): right += 1 self.camera.move(right, upward, forward) # Renderings width, height = glfw.get_window_size(self.window) self.context.viewport = 0, 0, width, height self.context.clear(*color('Background')) visibility = self.visibility projection = Matrix44.perspective_projection(self.fov, width / height, 3E-3, visibility) view = Matrix44.look_at(self.pos, self.pos + self.forward, self.upward) vp = (view @ projection).astype(np.float32).tobytes() self.maprog['visibility'].write(visibility.tobytes()) self.maprog['camera'].write(self.pos.tobytes()) self.maprog['mvp'].write(vp) self.mapva.render(moderngl.TRIANGLES) self.prog['visibility'].write(visibility.tobytes()) self.prog['camera'].write(self.pos.tobytes()) self.prog['vp'].write(vp) self.lock.acquire(blocking=False) for pico in self.picos.values(): shards = {} for index, shard in pico.shards.items(): if not shard.power: continue shard.update(self.fps) self.render_shard(shard) shards[index] = shard pico.shards = shards if pico is not self.camera: self.render_pico(pico) self.lock.release() glfw.swap_buffers(self.window) # Resetting cursor position and event queues glfw.set_cursor_pos(self.window, width / 2, height / 2) glfw.poll_events()
def update(self, elapsed): mouse_sensitivity = 0.1 speed = 3 # Mouse if glfw.get_key(self.window, glfw.KEY_ESCAPE): glfw.set_input_mode(self.window, glfw.CURSOR, glfw.CURSOR_NORMAL) if glfw.CURSOR_NORMAL == glfw.get_input_mode(self.window, glfw.CURSOR): if glfw.get_mouse_button(self.window, glfw.MOUSE_BUTTON_LEFT): glfw.set_input_mode(self.window, glfw.CURSOR, glfw.CURSOR_DISABLED) glfw.set_cursor_pos(self.window, 0, 0) else: x, y = glfw.get_cursor_pos(self.window) self.camera.offset_orientation(mouse_sensitivity * x, mouse_sensitivity * y) glfw.set_cursor_pos(self.window, 0, 0) # Keyboard if any((glfw.get_key(self.window, glfw.KEY_LEFT_SHIFT), glfw.get_key(self.window, glfw.KEY_RIGHT_SHIFT))): speed *= 5 # X & Z (wasd) if glfw.get_key(self.window, glfw.KEY_W): self.camera.position += elapsed * speed * self.camera.forward() elif glfw.get_key(self.window, glfw.KEY_S): self.camera.position += elapsed * speed * -self.camera.forward() if glfw.get_key(self.window, glfw.KEY_A): self.camera.position += elapsed * speed * -self.camera.right() elif glfw.get_key(self.window, glfw.KEY_D): self.camera.position += elapsed * speed * self.camera.right() # Y (space / ctrl) if glfw.get_key(self.window, glfw.KEY_SPACE): self.camera.position += elapsed * speed * glm.vec3(0, 1, 0) elif any((glfw.get_key(self.window, glfw.KEY_LEFT_CONTROL), glfw.get_key(self.window, glfw.KEY_RIGHT_CONTROL))): self.camera.position += elapsed * speed * -glm.vec3(0, 1, 0) # Center view if glfw.get_key(self.window, glfw.KEY_C): self.camera.look_at(glm.vec3(0, 0, 0)) # Reset camera if glfw.get_key(self.window, glfw.KEY_R): self.camera.position = glm.vec3(1.5, 1.5, 1.5) self.camera.look_at(glm.vec3(0, 0, 0))
def reshape(self, w, h): super(Game, self).reshape(w, h) window_center = [w / 2, h / 2] glfw.set_cursor_pos(self.window, *window_center) self.player.reshape(w, h) for shader in self.shaders.itervalues(): if 'cameraToClipMatrix' not in shader.uniforms: continue with shader: GL.glUniformMatrix4fv( shader.uniforms['cameraToClipMatrix'], 1, GL.GL_FALSE, self.player.projection_matrix.tolist(), )
def _wrap_around(window, width, height, x, y, dx, dy): wrapped = False if x <= 0.0: x = width - 1.0 wrapped = True elif x >= width: x = 0.0 wrapped = True if y <= 0.0: y = height - 1.0 wrapped = True elif y >= height: y = 0.0 wrapped = True if wrapped: glfw.set_cursor_pos(window, x, y) dx = 0.0 dy = 0.0 return x, y, dx, dy
glfw.set_mouse_button_callback(window, on_mouse) old_time = time.time() elapsed_time = 0.0 runtime = 0.0 # Create engine, gui and cube object engine = Engine(window) engine.setWindowHeight(height) engine.setWindowWidth(width) gui = GUI() gui.setWindowHeight(height) gui.setWindowWidth(width) cube = objectCube() glfw.set_cursor_pos(window, width / 2, height / 2) #Init texture gui.initTexture(0, "tests/data/mmp_gurov.png") gui.bindTexture(0) # Render function def render(): # Clear screen gl.glClearColor(0.25 * (1 - cos(0.5 * runtime)), 0.5 * (1 + sin(1 * runtime)), 0.5 * (1 + cos(0.33 * runtime)), 1.0) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT | gl.GL_STENCIL_BUFFER_BIT) gl.glViewport(0, 0, gui.window_width, gui.window_height) # Draw scene engine._Engine__process_camera() gui.enableLighting()
def main(): # Initialize GLFW and open a window if not opengl_init(): return # Enable key events glfw.set_input_mode(window, glfw.STICKY_KEYS, GL_TRUE) glfw.set_cursor_pos(window, 1024 / 2, 768 / 2) # Set opengl clear color to something other than red (color used by the fragment shader) glClearColor(0.0, 0.0, 0.4, 0.0) # Enable depth test glEnable(GL_DEPTH_TEST) # Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS) # Cull triangles which normal is not towards the camera glEnable(GL_CULL_FACE) vertex_array_id = glGenVertexArrays(1) glBindVertexArray(vertex_array_id) # Create and compile our GLSL program from the shaders program_id = common.LoadShaders( ".\\shaders\\Tutorial7\\TransformVertexShader.vertexshader", ".\\shaders\\Tutorial7\\TextureFragmentShader.fragmentshader") # Get a handle for our "MVP" uniform matrix_id = glGetUniformLocation(program_id, "MVP") # Load the texture texture = load_image(".\\content\\uvmap.bmp") # Get a handle for our "myTextureSampler" uniform texture_id = glGetUniformLocation(program_id, "myTextureSampler") # Read our OBJ file vertices, faces, uvs, normals, colors = objloader.load( ".\\content\\cube.obj") vertex_data, uv_data, normal_data = objloader.process_obj( vertices, faces, uvs, normals, colors) # Our OBJ loader uses Python lists, convert to ctype arrays before sending to OpenGL vertex_data = objloader.generate_2d_ctypes(vertex_data) uv_data = objloader.generate_2d_ctypes(uv_data) # Load OBJ in to a VBO vertex_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer) glBufferData(GL_ARRAY_BUFFER, len(vertex_data) * 4 * 3, vertex_data, GL_STATIC_DRAW) uv_buffer = glGenBuffers(1) array_type = GLfloat * len(uv_data) glBindBuffer(GL_ARRAY_BUFFER, uv_buffer) glBufferData(GL_ARRAY_BUFFER, len(uv_data) * 4 * 2, uv_data, GL_STATIC_DRAW) # vsync and glfw do not play nice. when vsync is enabled mouse movement is jittery. common.disable_vsyc() while glfw.get_key( window, glfw.KEY_ESCAPE ) != glfw.PRESS and not glfw.window_should_close(window): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glUseProgram(program_id) controls.computeMatricesFromInputs(window) ProjectionMatrix = controls.getProjectionMatrix() ViewMatrix = controls.getViewMatrix() ModelMatrix = mat4.identity() mvp = ProjectionMatrix * ViewMatrix * ModelMatrix # Send our transformation to the currently bound shader, # in the "MVP" uniform glUniformMatrix4fv(matrix_id, 1, GL_FALSE, mvp.data) # Bind our texture in Texture Unit 0 glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, texture) # Set our "myTextureSampler" sampler to user Texture Unit 0 glUniform1i(texture_id, 0) #1rst attribute buffer : vertices glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer) glVertexAttribPointer( 0, # attribute 0. No particular reason for 0, but must match the layout in the shader. 3, # len(vertex_data) GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) # 2nd attribute buffer : colors glEnableVertexAttribArray(1) glBindBuffer(GL_ARRAY_BUFFER, uv_buffer) glVertexAttribPointer( 1, # attribute 1. No particular reason for 1, but must match the layout in the shader. 2, # len(vertex_data) GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) # Draw the triangles, vertex data now contains individual vertices # so use array length glDrawArrays(GL_TRIANGLES, 0, len(vertex_data)) # Not strictly necessary because we only have glDisableVertexAttribArray(0) glDisableVertexAttribArray(1) # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() # !Note braces around vertex_buffer and uv_buffer. # glDeleteBuffers expects a list of buffers to delete glDeleteBuffers(1, [vertex_buffer]) glDeleteBuffers(1, [uv_buffer]) glDeleteProgram(program_id) glDeleteTextures([texture_id]) glDeleteVertexArrays(1, [vertex_array_id]) glfw.terminate()
def update(self): # glfwGetTime is called only once, the first time this function is called if self.lastTime is None: self.lastTime = glfw.get_time() # Compute time difference between current and last frame currentTime = glfw.get_time() deltaTime = float(currentTime - self.lastTime) # Get mouse position xpos, ypos = glfw.get_cursor_pos(self.window) # Reset mouse position for next frame glfw.set_cursor_pos(self.window, 1024/2, 768/2); # Compute new orientation self.horizontalAngle += self.mouseSpeed * float(1024/2 - xpos ) self.verticalAngle += self.mouseSpeed * float( 768/2 - ypos ) # Direction : Spherical coordinates to Cartesian coordinates conversion direction = np.array([ np.cos(self.verticalAngle) * np.sin(self.horizontalAngle), np.sin(self.verticalAngle), np.cos(self.verticalAngle) * np.cos(self.horizontalAngle) ]) # Right vector right = np.array([ np.sin(self.horizontalAngle - np.pi/2.0), 0, np.cos(self.horizontalAngle - np.pi/2.0) ]) # Up vector up = np.cross( right, direction ) # Move forward if glfw.get_key( self.window, glfw.KEY_UP ) == glfw.PRESS: self.position += direction * deltaTime * self.speed # Move backward if glfw.get_key( self.window, glfw.KEY_DOWN ) == glfw.PRESS: self.position -= direction * deltaTime * self.speed # Strafe right if glfw.get_key( self.window, glfw.KEY_RIGHT ) == glfw.PRESS: self.position += right * deltaTime * self.speed # Strafe left if glfw.get_key( self.window, glfw.KEY_LEFT ) == glfw.PRESS: self.position -= right * deltaTime * self.speed FoV = self.initialFoV #- 5 * glfwGetMouseWheel(); # Now GLFW 3 requires setting up a callback for this. # It's a bit too complicated for this beginner's tutorial, so it's disabled instead. # Projection matrix : 45 deg Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units self.ProjectionMatrix = glm_perspective(FoV*np.pi/180., 4.0 / 3.0, 0.1, 100.0) # Camera matrix self.ViewMatrix = glm_lookAt( self.position, # Camera is here self.position+direction, # and looks here : at the same position, plus "direction" up # Head is up (set to 0,-1,0 to look upside-down) ) # For the next frame, the "last time" will be "now" self.lastTime = currentTime self.ModelMatrix = np.eye(4) self.MVP = np.array( np.dot(np.dot(self.ModelMatrix, self.ViewMatrix), self.ProjectionMatrix), dtype=np.float32 )
def computeMatricesFromInputs(window): global lastTime global position global horizontalAngle global verticalAngle global initialFoV global ViewMatrix global ProjectionMatrix # glfwGetTime is called only once, the first time this function is called if lastTime == None: lastTime = glfw.get_time() # Compute time difference between current and last frame currentTime = glfw.get_time() deltaTime = currentTime - lastTime # Get mouse position xpos,ypos = glfw.get_cursor_pos(window) # Reset mouse position for next frame glfw.set_cursor_pos(window, 1024/2, 768/2); # Compute new orientation horizontalAngle += mouseSpeed * float(1024.0/2.0 - xpos ); verticalAngle += mouseSpeed * float( 768.0/2.0 - ypos ); # Direction : Spherical coordinates to Cartesian coordinates conversion direction = vec3( mathf.cos(verticalAngle) * mathf.sin(horizontalAngle), mathf.sin(verticalAngle), mathf.cos(verticalAngle) * mathf.cos(horizontalAngle) ) # Right vector right = vec3( mathf.sin(horizontalAngle - 3.14/2.0), 0.0, mathf.cos(horizontalAngle - 3.14/2.0) ) # Up vector up = vec3.cross( right, direction ) # Move forward if glfw.get_key( window, glfw.KEY_UP ) == glfw.PRESS or glfw.get_key( window, glfw.KEY_W ) == glfw.PRESS: position += direction * deltaTime * speed; # Move backward if glfw.get_key( window, glfw.KEY_DOWN ) == glfw.PRESS or glfw.get_key( window, glfw.KEY_S ) == glfw.PRESS: position -= direction * deltaTime * speed # Strafe right if glfw.get_key( window, glfw.KEY_RIGHT ) == glfw.PRESS or glfw.get_key( window, glfw.KEY_D ) == glfw.PRESS: position += right * deltaTime * speed # Strafe left if glfw.get_key( window, glfw.KEY_LEFT ) == glfw.PRESS or glfw.get_key( window, glfw.KEY_A ) == glfw.PRESS: position -= right * deltaTime * speed FoV = initialFoV# - 5 * glfwGetMouseWheel(); # Now GLFW 3 requires setting up a callback for this. It's a bit too complicated for this beginner's tutorial, so it's disabled instead. # Projection matrix : 45 Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units ProjectionMatrix = mat4.perspective(FoV, 4.0 / 3.0, 0.1, 100.0) # Camera matrix ViewMatrix = mat4.lookat( position, # Camera is here position+direction, # and looks here : at the same position, plus "direction" up # Head is up (set to 0,-1,0 to look upside-down) ) # For the next frame, the "last time" will be "now" lastTime = currentTime
def main(): if not opengl_init(): return OpenglInit() load_gedung("itb_coordinate.txt") # Enable key events glfw.set_input_mode(window,glfw.STICKY_KEYS,GL_TRUE) glfw.set_cursor_pos(window, 1024/2, 768/2) # Set opengl clear color to something other than red (color used by the fragment shader) glClearColor(0.0,0.0,0.0,0.0) # Enable depth test glEnable(GL_DEPTH_TEST) # Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS); glEnable(GL_CULL_FACE) vertex_array_id = glGenVertexArrays(1) glBindVertexArray( vertex_array_id ) program_id = common.LoadShaders( ".\\shaders\\Tutorial6\\TransformVertexShader.vertexshader", ".\\shaders\\Tutorial6\\TextureFragmentShader.fragmentshader" ) vertex_data = createAllBuilding() # Two UV coordinatesfor each vertex. They were created withe Blender. uv_data = createUVData() # Get a handle for our "MVP" uniform matrix_id = glGetUniformLocation(program_id, "MVP"); texture = [] texture_id = [] texture_id.append(glGetUniformLocation(program_id, "myTextureSampler")) texture_id.append(glGetUniformLocation(program_id, "myTextureSampler2")) tex1 = TextureLoader.load_texture("res/crate.jpg") tex2 = TextureLoader.load_texture("res/metal.jpg") # Our vertices. Tree consecutive floats give a 3D vertex; Three consecutive vertices give a triangle. # A cube has 6 faces with 2 triangles each, so this makes 6*2=12 triangles, and 12*3 vertices vertex_buffer = glGenBuffers(1); array_type = GLfloat * len(vertex_data) glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer) glBufferData(GL_ARRAY_BUFFER, len(vertex_data) * 4, array_type(*vertex_data), GL_STATIC_DRAW) uv_buffer = glGenBuffers(1); array_type = GLfloat * len(uv_data) glBindBuffer(GL_ARRAY_BUFFER, uv_buffer) glBufferData(GL_ARRAY_BUFFER, len(uv_data) * 4, array_type(*uv_data), GL_STATIC_DRAW) # vsync and glfw do not play nice. when vsync is enabled mouse movement is jittery. common.disable_vsyc() glUseProgram(program_id) #1rst attribute buffer : vertices glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer); glVertexAttribPointer( 0, # attribute 0. No particular reason for 0, but must match the layout in the shader. 3, # len(vertex_data) GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) # 2nd attribute buffer : colors glEnableVertexAttribArray(1) glBindBuffer(GL_ARRAY_BUFFER, uv_buffer); glVertexAttribPointer( 1, # attribute 1. No particular reason for 1, but must match the layout in the shader. 2, # len(vertex_data) GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) glActiveTexture(GL_TEXTURE0); currentTexture = [] for i in range(1, jumlah_tempat+1): currentTexture.append(TextureLoader.load_texture("img/building"+str(i)+".jpg")) while glfw.get_key(window,glfw.KEY_ESCAPE) != glfw.PRESS and not glfw.window_should_close(window): # Clear old render result glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT) controls.computeMatricesFromInputs(window) ProjectionMatrix = controls.getProjectionMatrix(); ViewMatrix = controls.getViewMatrix(); ModelMatrix = mat4.identity(); mvp = ProjectionMatrix * ViewMatrix * ModelMatrix; Display() ##################################################################### SET TEXTURE 1 # Send our transformation to the currently bound shader, # in the "MVP" uniform # draws Aula barat, timur ; CC barat, timur # glBindTexture(GL_TEXTURE_2D, tex1); # glUniformMatrix4fv(matrix_id, 1, GL_FALSE,mvp.data) # # Draw the shapes # glDrawArrays(GL_TRIANGLES, 0, 12*3*4) #3 indices starting at 0 -> 1 triangle # ####################################################################### SET TEXTURE 2 # #draws 4 labtek kembar + perpus, pau # glBindTexture(GL_TEXTURE_2D, tex2); # glUniformMatrix4fv(matrix_id, 1, GL_FALSE, mvp.data) # # Draw the shapes # glDrawArrays(GL_TRIANGLES, 12*3*4, 12*3*6) #3 indices starting at 0 -> 1 triangle # print (jumlah_tempat) for i in range(0, jumlah_tempat): # Send our transformation to the currently bound shader, # in the "MVP" uniform # draws Aula barat, timur ; CC barat, timur glBindTexture(GL_TEXTURE_2D, currentTexture[i]); glUniformMatrix4fv(matrix_id, 1, GL_FALSE,mvp.data) # # Draw the shapes glDrawArrays(GL_TRIANGLES, 12*3*i, 12*3) #3 indices starting at 0 -> 1 triangle ################################################### FINALIZE # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() # Not strictly necessary because we only have glDisableVertexAttribArray(0) glDisableVertexAttribArray(1) # !Note braces around vertex_buffer and uv_buffer. # glDeleteBuffers expects a list of buffers to delete glDeleteBuffers(1, [vertex_buffer]) glDeleteBuffers(1, [uv_buffer]) glDeleteProgram(program_id) glDeleteTextures([texture_id]) glDeleteVertexArrays(1, [vertex_array_id]) glfw.terminate()
def main(): init() window = glfw.create_window(800, 600, "Chapter5", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) glfw.set_input_mode(window, glfw.STICKY_KEYS, GL_TRUE) glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED) glfw.set_key_callback(window, key_callback) glfw.set_cursor_pos(window, 400, 300) glEnable(GL_DEPTH_TEST) glDepthFunc(GL_LESS) glClearColor(0.3, 0.3, 0.3, 1) vertex_array_id = glGenVertexArrays(1) glBindVertexArray(vertex_array_id) program_id = load_shaders('res/glsl/chapter8.vs', 'res/glsl/chapter8.fs') tex = texture.load('res/texture/eye.bmp') texture_id = glGetUniformLocation(program_id, 'TextureSampler') res_x, res_y = glfw.get_window_size(window) cam = camera.Camera(0, 0, 2, res_x, res_y) model = np.matrix(np.identity(4), dtype=np.float32) projection_id = glGetUniformLocation(program_id, 'projection') view_id = glGetUniformLocation(program_id, 'view') model_id = glGetUniformLocation(program_id, 'model') scene = load('res/model/sphere.obj') mesh = scene.meshes[0] vertex = mesh.vertices uv = mesh.texturecoords normal = mesh.normals index = mesh.faces vertex_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer) glBufferData(GL_ARRAY_BUFFER, vertex.nbytes, vertex, GL_STATIC_DRAW) uv_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, uv_buffer) glBufferData(GL_ARRAY_BUFFER, uv.nbytes, uv, GL_STATIC_DRAW) normal_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, normal_buffer) glBufferData(GL_ARRAY_BUFFER, normal.nbytes, normal, GL_STATIC_DRAW) element_buffer = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, element_buffer) glBufferData(GL_ELEMENT_ARRAY_BUFFER, index.nbytes, index, GL_STATIC_DRAW) while not glfw.window_should_close(window) and glfw.get_key( window, glfw.KEY_ESCAPE) != glfw.PRESS: glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) cam.controller(window) glUseProgram(program_id) glUniformMatrix4fv(projection_id, 1, GL_FALSE, cam.projection) glUniformMatrix4fv(view_id, 1, GL_FALSE, cam.view) glUniformMatrix4fv(model_id, 1, GL_FALSE, model) glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, tex) glUniform1i(texture_id, 0) glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(1) glBindBuffer(GL_ARRAY_BUFFER, uv_buffer) glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(2) glBindBuffer(GL_ARRAY_BUFFER, normal_buffer) glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, None) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, element_buffer) glDrawElements(GL_TRIANGLES, index.nbytes, GL_UNSIGNED_INT, None) glDisableVertexAttribArray(0) glDisableVertexAttribArray(1) glDisableVertexAttribArray(2) glfw.swap_buffers(window) glfw.poll_events() glfw.terminate()
def main(): if not opengl_init(): return load_gedung("itb_coordinate.txt") # Enable key events glfw.set_input_mode(window,glfw.STICKY_KEYS,GL_TRUE) glfw.set_cursor_pos(window, 1024/2, 768/2) # Set opengl clear color to something other than red (color used by the fragment shader) glClearColor(0.0,0.0,0.0,0.0) # Enable depth test glEnable(GL_DEPTH_TEST) # Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS); glEnable(GL_CULL_FACE) vertex_array_id = glGenVertexArrays(1) glBindVertexArray( vertex_array_id ) program_id = common.LoadShaders( ".\\shaders\\Tutorial6\\TransformVertexShader.vertexshader", ".\\shaders\\Tutorial6\\TextureFragmentShader.fragmentshader" ) vertex_data = createAllBuilding() # Two UV coordinatesfor each vertex. They were created withe Blender. uv_data = createUVData() # Get a handle for our "MVP" uniform matrix_id = glGetUniformLocation(program_id, "MVP"); texture = [] texture_id = [] texture_id.append(glGetUniformLocation(program_id, "myTextureSampler")) texture_id.append(glGetUniformLocation(program_id, "myTextureSampler2")) tex1 = TextureLoader.load_texture("res/crate.jpg") tex2 = TextureLoader.load_texture("res/metal.jpg") # Our vertices. Tree consecutive floats give a 3D vertex; Three consecutive vertices give a triangle. # A cube has 6 faces with 2 triangles each, so this makes 6*2=12 triangles, and 12*3 vertices vertex_buffer = glGenBuffers(1); array_type = GLfloat * len(vertex_data) glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer) glBufferData(GL_ARRAY_BUFFER, len(vertex_data) * 4, array_type(*vertex_data), GL_STATIC_DRAW) uv_buffer = glGenBuffers(1); array_type = GLfloat * len(uv_data) glBindBuffer(GL_ARRAY_BUFFER, uv_buffer) glBufferData(GL_ARRAY_BUFFER, len(uv_data) * 4, array_type(*uv_data), GL_STATIC_DRAW) # vsync and glfw do not play nice. when vsync is enabled mouse movement is jittery. common.disable_vsyc() glUseProgram(program_id) #1rst attribute buffer : vertices glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer); glVertexAttribPointer( 0, # attribute 0. No particular reason for 0, but must match the layout in the shader. 3, # len(vertex_data) GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) # 2nd attribute buffer : colors glEnableVertexAttribArray(1) glBindBuffer(GL_ARRAY_BUFFER, uv_buffer); glVertexAttribPointer( 1, # attribute 1. No particular reason for 1, but must match the layout in the shader. 2, # len(vertex_data) GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) glActiveTexture(GL_TEXTURE0); while glfw.get_key(window,glfw.KEY_ESCAPE) != glfw.PRESS and not glfw.window_should_close(window): # Clear old render result glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT) controls.computeMatricesFromInputs(window) ProjectionMatrix = controls.getProjectionMatrix(); ViewMatrix = controls.getViewMatrix(); ModelMatrix = mat4.identity(); mvp = ProjectionMatrix * ViewMatrix * ModelMatrix; ##################################################################### SET TEXTURE 1 # Send our transformation to the currently bound shader, # in the "MVP" uniform # draws Aula barat, timur ; CC barat, timur glBindTexture(GL_TEXTURE_2D, tex1); glUniformMatrix4fv(matrix_id, 1, GL_FALSE,mvp.data)
def main(): # Initialize GLFW and open a window if not opengl_init(): return # Enable key events glfw.set_input_mode(window,glfw.STICKY_KEYS,GL_TRUE) glfw.set_cursor_pos(window, 1024/2, 768/2) # Set opengl clear color to something other than red (color used by the fragment shader) glClearColor(0.0,0.0,0.4,0.0) # Enable depth test glEnable(GL_DEPTH_TEST) # Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS) # Cull triangles which normal is not towards the camera glEnable(GL_CULL_FACE) vertex_array_id = glGenVertexArrays(1) glBindVertexArray( vertex_array_id ) # Create and compile our GLSL program from the shaders program_id = common.LoadShaders( ".\\shaders\\Tutorial9\\StandardShading.vertexshader", ".\\shaders\\Tutorial9\\StandardShading.fragmentshader" ) # Get a handle for our "MVP" uniform matrix_id = glGetUniformLocation(program_id, "MVP") view_matrix_id = glGetUniformLocation(program_id, "V") model_matrix_id = glGetUniformLocation(program_id, "M") # Load the texture texture = textureutils.load_image(".\\content\\uvmap_suzanne.bmp") # Get a handle for our "myTextureSampler" uniform texture_id = glGetUniformLocation(program_id, "myTextureSampler") # Read our OBJ file vertices,faces,uvs,normals,colors = objloader.load(".\\content\\suzanne.obj") vertex_data,uv_data,normal_data = objloader.process_obj( vertices,faces,uvs,normals,colors) # Our OBJ loader uses Python lists, convert to ctype arrays before sending to OpenGL vertex_data = objloader.generate_2d_ctypes(vertex_data) uv_data = objloader.generate_2d_ctypes(uv_data) normal_data = objloader.generate_2d_ctypes(normal_data) indexed_vertices, indexed_uvs, indexed_normals, indices = vboindexer.indexVBO(vertex_data,uv_data,normal_data) indexed_vertices = c_type_fill(indexed_vertices,GLfloat) indexed_uvs = c_type_fill(indexed_uvs,GLfloat) indexed_normals = c_type_fill(indexed_normals,GLfloat) indices = c_type_fill_1D(indices,GLushort) # Load OBJ in to a VBO vertex_buffer = glGenBuffers(1); glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer) glBufferData(GL_ARRAY_BUFFER, len(indexed_vertices) * 4 * 3, indexed_vertices, GL_STATIC_DRAW) uv_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, uv_buffer) glBufferData(GL_ARRAY_BUFFER, len(indexed_uvs) * 4 * 2, indexed_uvs, GL_STATIC_DRAW) normal_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, normal_buffer) glBufferData(GL_ARRAY_BUFFER, len(indexed_normals) * 4 * 3, indexed_normals, GL_STATIC_DRAW) # Generate a buffer for the indices as well elementbuffer = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer) glBufferData(GL_ELEMENT_ARRAY_BUFFER, len(indices) * 2, indices , GL_STATIC_DRAW); # vsync and glfw do not play nice. when vsync is enabled mouse movement is jittery. common.disable_vsyc() # Get a handle for our "LightPosition" uniform glUseProgram(program_id); light_id = glGetUniformLocation(program_id, "LightPosition_worldspace"); last_time = glfw.get_time() frames = 0 while glfw.get_key(window,glfw.KEY_ESCAPE) != glfw.PRESS and not glfw.window_should_close(window): glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT) current_time = glfw.get_time() if current_time - last_time >= 1.0: glfw.set_window_title(window,"Tutorial 9. FPS: %d"%(frames)) frames = 0 last_time = current_time glUseProgram(program_id) controls.computeMatricesFromInputs(window) ProjectionMatrix = controls.getProjectionMatrix(); ViewMatrix = controls.getViewMatrix(); ModelMatrix = mat4.identity(); mvp = ProjectionMatrix * ViewMatrix * ModelMatrix; # Send our transformation to the currently bound shader, # in the "MVP" uniform glUniformMatrix4fv(matrix_id, 1, GL_FALSE,mvp.data) glUniformMatrix4fv(model_matrix_id, 1, GL_FALSE, ModelMatrix.data); glUniformMatrix4fv(view_matrix_id, 1, GL_FALSE, ViewMatrix.data); lightPos = vec3(4,4,4) glUniform3f(light_id, lightPos.x, lightPos.y, lightPos.z) # Bind our texture in Texture Unit 0 glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture); # Set our "myTextureSampler" sampler to user Texture Unit 0 glUniform1i(texture_id, 0); #1rst attribute buffer : vertices glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer); glVertexAttribPointer( 0, # attribute 0. No particular reason for 0, but must match the layout in the shader. 3, # len(vertex_data) GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) # 2nd attribute buffer : colors glEnableVertexAttribArray(1) glBindBuffer(GL_ARRAY_BUFFER, uv_buffer); glVertexAttribPointer( 1, # attribute 1. No particular reason for 1, but must match the layout in the shader. 2, # len(vertex_data) GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) # 3rd attribute buffer : normals glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, normal_buffer); glVertexAttribPointer( 2, # attribute 3, # size GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) # Draw the triangles, vertex data now contains individual vertices # so use array length # glDrawArrays(GL_TRIANGLES, 0, len(vertex_data)) # Index buffer glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer) # Draw the triangles ! glDrawElements( GL_TRIANGLES, # mode len(indices), # count GL_UNSIGNED_SHORT, # type null # element array buffer offset ) # Not strictly necessary because we only have glDisableVertexAttribArray(0) glDisableVertexAttribArray(1) glDisableVertexAttribArray(2) # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() frames += 1 # !Note braces around vertex_buffer and uv_buffer. # glDeleteBuffers expects a list of buffers to delete glDeleteBuffers(1, [vertex_buffer]) glDeleteBuffers(1, [uv_buffer]) glDeleteBuffers(1, [normal_buffer]) glDeleteProgram(program_id) glDeleteTextures([texture_id]) glDeleteVertexArrays(1, [vertex_array_id]) glfw.terminate()
def main(): # Initialize GLFW and open a window if not opengl_init(): return # Enable key events glfw.set_input_mode(window,glfw.STICKY_KEYS,GL_TRUE) glfw.set_cursor_pos(window, 1024/2, 768/2) # Set opengl clear color to something other than red (color used by the fragment shader) glClearColor(0.0,0.0,0.0,0.0) # Enable depth test glEnable(GL_DEPTH_TEST) # Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS) # Cull triangles which normal is not towards the camera glEnable(GL_CULL_FACE) vertex_array_id = glGenVertexArrays(1) glBindVertexArray( vertex_array_id ) # Create and compile our GLSL program from the shaders program_id = common.LoadShaders( ".\\shaders\\common\\StandardShading.vertexshader", ".\\shaders\\common\\StandardShading.fragmentshader" ) # Get a handle for our "MVP" uniform matrix_id = glGetUniformLocation(program_id, "MVP") view_matrix_id = glGetUniformLocation(program_id, "V") model_matrix_id = glGetUniformLocation(program_id, "M") # Read our OBJ file vertices,faces,uvs,normals,colors = objloader.load(".\\content\\male_apose_closed2.obj") vertex_data,uv_data,normal_data = objloader.process_obj( vertices,faces,uvs,normals,colors) # Our OBJ loader uses Python lists, convert to ctype arrays before sending to OpenGL vertex_data = objloader.generate_2d_ctypes(vertex_data) normal_data = objloader.generate_2d_ctypes(normal_data) # Load OBJ in to a VBO vertex_buffer = glGenBuffers(1); glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer) glBufferData(GL_ARRAY_BUFFER, len(vertex_data) * 4 * 3, vertex_data, GL_STATIC_DRAW) normal_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, normal_buffer) glBufferData(GL_ARRAY_BUFFER, len(normal_data) * 4 * 3, normal_data, GL_STATIC_DRAW) # vsync and glfw do not play nice. when vsync is enabled mouse movement is jittery. common.disable_vsyc() # Get a handle for our "LightPosition" uniform glUseProgram(program_id); light_id = glGetUniformLocation(program_id, "LightPosition_worldspace"); last_time = glfw.get_time() frames = 0 while glfw.get_key(window,glfw.KEY_ESCAPE) != glfw.PRESS and not glfw.window_should_close(window): glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT) current_time = glfw.get_time() glUseProgram(program_id) controls.computeMatricesFromInputs(window) ProjectionMatrix = controls.getProjectionMatrix(); ViewMatrix = controls.getViewMatrix(); ModelMatrix = mat4.identity(); mvp = ProjectionMatrix * ViewMatrix * ModelMatrix; # Send our transformation to the currently bound shader, # in the "MVP" uniform glUniformMatrix4fv(matrix_id, 1, GL_FALSE,mvp.data) glUniformMatrix4fv(model_matrix_id, 1, GL_FALSE, ModelMatrix.data); glUniformMatrix4fv(view_matrix_id, 1, GL_FALSE, ViewMatrix.data); lightPos = vec3(0,4,4) glUniform3f(light_id, lightPos.x, lightPos.y, lightPos.z) #1rst attribute buffer : vertices glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer); glVertexAttribPointer( 0, # attribute 0. No particular reason for 0, but must match the layout in the shader. 3, # len(vertex_data) GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) # 2nd attribute buffer : normals glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, normal_buffer); glVertexAttribPointer( 1, # attribute 3, # size GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) # Draw the triangles, vertex data now contains individual vertices # so use array length glDrawArrays(GL_TRIANGLES, 0, len(vertex_data)) # Not strictly necessary because we only have glDisableVertexAttribArray(0) glDisableVertexAttribArray(1) # Swap front and back buffers glfw.swap_buffers(window) # Take screenshot of active buffer if glfw.get_key( window, glfw.KEY_P ) == glfw.PRESS: print("Saving screenshot as 'test.bmp'") screenshot('test.bmp',1024,768) # Dump MVP matrix to the command line if glfw.get_key( window, glfw.KEY_M ) == glfw.PRESS: print(mvp) # Poll for and process events glfw.poll_events() frames += 1 # !Note braces around vertex_buffer and uv_buffer. # glDeleteBuffers expects a list of buffers to delete glDeleteBuffers(1, [vertex_buffer]) glDeleteBuffers(1, [normal_buffer]) glDeleteProgram(program_id) glDeleteVertexArrays(1, [vertex_array_id]) glfw.terminate()
def computeMatricesFromInputs(window): global lastTime global position global horizontalAngle global verticalAngle global initialFoV global ViewMatrix global ProjectionMatrix # glfwGetTime is called only once, the first time this function is called if lastTime == None: lastTime = glfw.get_time() # Compute time difference between current and last frame currentTime = glfw.get_time() deltaTime = currentTime - lastTime # Get mouse position xpos, ypos = glfw.get_cursor_pos(window) # Reset mouse position for next frame glfw.set_cursor_pos(window, 1024 / 2, 768 / 2) # Compute new orientation horizontalAngle += mouseSpeed * float(1024.0 / 2.0 - xpos) verticalAngle += mouseSpeed * float(768.0 / 2.0 - ypos) # Direction : Spherical coordinates to Cartesian coordinates conversion direction = vec3( mathf.cos(verticalAngle) * mathf.sin(horizontalAngle), mathf.sin(verticalAngle), mathf.cos(verticalAngle) * mathf.cos(horizontalAngle)) # Right vector right = vec3(mathf.sin(horizontalAngle - 3.14 / 2.0), 0.0, mathf.cos(horizontalAngle - 3.14 / 2.0)) # Up vector up = vec3.cross(right, direction) # Move forward if glfw.get_key(window, glfw.KEY_UP) == glfw.PRESS or glfw.get_key( window, glfw.KEY_W) == glfw.PRESS: position += direction * deltaTime * speed # Move backward if glfw.get_key(window, glfw.KEY_DOWN) == glfw.PRESS or glfw.get_key( window, glfw.KEY_S) == glfw.PRESS: position -= direction * deltaTime * speed # Strafe right if glfw.get_key(window, glfw.KEY_RIGHT) == glfw.PRESS or glfw.get_key( window, glfw.KEY_D) == glfw.PRESS: position += right * deltaTime * speed # Strafe left if glfw.get_key(window, glfw.KEY_LEFT) == glfw.PRESS or glfw.get_key( window, glfw.KEY_A) == glfw.PRESS: position -= right * deltaTime * speed FoV = initialFoV # - 5 * glfwGetMouseWheel(); # Now GLFW 3 requires setting up a callback for this. It's a bit too complicated for this beginner's tutorial, so it's disabled instead. # Projection matrix : 45 Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units ProjectionMatrix = mat4.perspective(FoV, 4.0 / 3.0, 0.1, 500.0) # Camera matrix ViewMatrix = mat4.lookat( position, # Camera is here position + direction, # and looks here : at the same position, plus "direction" up # Head is up (set to 0,-1,0 to look upside-down) ) # For the next frame, the "last time" will be "now" lastTime = currentTime
def cursor_position_callback(window, xpos, ypos): camera.mouth_update(xpos, ypos) if not glfw.init(): raise Exception('glfw con not be initialized') window = glfw.create_window(SCR_WIDTH, SCR_HEIGHT, 'My OpenGL window', None, None) if not window: glfw.terminate() raise Exception('glfw window can not be created') glfw.set_window_pos(window, 4000, 200) glfw.set_cursor_pos(window, SCR_WIDTH / 2, SCR_HEIGHT / 2) glfw.set_window_size_callback(window, window_resize) glfw.set_cursor_pos_callback(window, cursor_position_callback) glfw.make_context_current(window) # ============================================================ # # Loading shaders # # ============================================================ # shader = ShaderLoader('lightning_test/shaders/cube.vs', 'lightning_test/shaders/cube.fs') cube_shader = shader.get_compiled_shader() shader = ShaderLoader('lightning_test/shaders/screen_quad.vs', 'lightning_test/shaders/screen_quad.fs') screen_quad_shader = shader.get_compiled_shader() # ============================================================ #
def cursor_position_callback(window, xpos, ypos): camera.mouth_update(xpos, ypos) glfw.set_cursor_pos(window, WINDOW_RESOLUTION[0]/2, WINDOW_RESOLUTION[1]/2)
def main(): # Initialize GLFW and open a window if not opengl_init(): return # Enable key events glfw.set_input_mode(window, glfw.STICKY_KEYS, GL_TRUE) glfw.set_cursor_pos(window, 1024 / 2, 768 / 2) # Set opengl clear color to something other than red (color used by the fragment shader) glClearColor(0.0, 0.0, 0.4, 0.0) # Enable depth test glEnable(GL_DEPTH_TEST) # Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS) # Cull triangles which normal is not towards the camera glEnable(GL_CULL_FACE) vertex_array_id = glGenVertexArrays(1) glBindVertexArray(vertex_array_id) # Create and compile our GLSL program from the shaders program_id = common.LoadShaders( ".\\shaders\\Tutorial8\\StandardShading.vertexshader", ".\\shaders\\Tutorial8\\StandardShading.fragmentshader") # Get a handle for our "MVP" uniform matrix_id = glGetUniformLocation(program_id, "MVP") view_matrix_id = glGetUniformLocation(program_id, "V") model_matrix_id = glGetUniformLocation(program_id, "M") # Load the texture texture = load_image(".\\content\\oppo.bmp") #load image # Get a handle for our "myTextureSampler" uniform texture_id = glGetUniformLocation(program_id, "myTextureSampler") # Read our OBJ file # vertices,faces,uvs,normals,colors = objloader.load(".\\content\\suzanne.obj") # vertex_data,uv_data,normal_data = objloader.process_obj( vertices,faces,uvs,normals,colors) # Our OBJ loader uses Python lists, convert to ctype arrays before sending to OpenGL # vertex_data = objloader.generate_2d_ctypes(vertex_data) # uv_data = objloader.generate_2d_ctypes(uv_data) koordinat = 0.01 koordinat2 = 0.5 koordinat3 = 1.7 koordinat4 = 1.0 koordinat5 = 1.7 koordinat6 = 0.1 vertex_data = [ -koordinat2, -koordinat3, -koordinat, -koordinat2, -koordinat3, koordinat6, -koordinat2, koordinat5, koordinat6, koordinat4, koordinat5, -koordinat, -koordinat2, -koordinat3, -koordinat, -koordinat2, koordinat5, -koordinat, koordinat4, -koordinat3, koordinat6, -koordinat2, -koordinat3, -koordinat, koordinat4, -koordinat3, -koordinat, koordinat4, koordinat5, -koordinat, koordinat4, -koordinat3, -koordinat, -koordinat2, -koordinat3, -koordinat, -koordinat2, -koordinat3, -koordinat, -koordinat2, koordinat5, koordinat6, -koordinat2, koordinat5, -koordinat, koordinat4, -koordinat3, koordinat6, -koordinat2, -koordinat3, koordinat6, -koordinat2, -koordinat3, -koordinat, -koordinat2, koordinat5, koordinat6, -koordinat2, -koordinat3, koordinat6, koordinat4, -koordinat3, koordinat6, koordinat4, koordinat5, koordinat6, koordinat4, -koordinat3, -koordinat, koordinat4, koordinat5, -koordinat, koordinat4, -koordinat3, -koordinat, koordinat4, koordinat5, koordinat6, koordinat4, -koordinat3, koordinat6, koordinat4, koordinat5, koordinat6, koordinat4, koordinat5, -koordinat, -koordinat2, koordinat5, -koordinat, koordinat4, koordinat5, koordinat6, -koordinat2, koordinat5, -koordinat, -koordinat2, koordinat5, koordinat6, koordinat4, koordinat5, koordinat6, -koordinat2, koordinat5, koordinat6, koordinat4, -koordinat3, koordinat6 ] # Two UV coordinatesfor each vertex. They were created withe Blender. uv_data = [ 0.000059, 1.0 - 0.000004, 0.000103, 1.0 - 0.336048, 0.335973, 1.0 - 0.335903, 1.000023, 1.0 - 0.000013, 0.667979, 1.0 - 0.335851, 0.999958, 1.0 - 0.336064, 0.667979, 1.0 - 0.335851, 0.336024, 1.0 - 0.671877, 0.667969, 1.0 - 0.671889, 1.000023, 1.0 - 0.000013, 0.668104, 1.0 - 0.000013, 0.667979, 1.0 - 0.335851, 0.000059, 1.0 - 0.000004, 0.335973, 1.0 - 0.335903, 0.336098, 1.0 - 0.000071, 0.667979, 1.0 - 0.335851, 0.335973, 1.0 - 0.335903, 0.336024, 1.0 - 0.671877, 1.000004, 1.0 - 0.671847, 0.999958, 1.0 - 0.336064, 0.667979, 1.0 - 0.335851, 0.668104, 1.0 - 0.000013, 0.335973, 1.0 - 0.335903, 0.667979, 1.0 - 0.335851, 0.335973, 1.0 - 0.335903, 0.668104, 1.0 - 0.000013, 0.336098, 1.0 - 0.000071, 0.000103, 1.0 - 0.336048, 0.000004, 1.0 - 0.671870, 0.336024, 1.0 - 0.671877, 0.000103, 1.0 - 0.336048, 0.336024, 1.0 - 0.671877, 0.335973, 1.0 - 0.335903, 0.667969, 1.0 - 0.671889, 1.000004, 1.0 - 0.671847, 0.667979, 1.0 - 0.335851 ] normal_data = [ -0.5, 0, 0, -0.5, 0, 0, -0.5, 0, 0, 0, 0, -0.5, 0, 0, -0.5, 0, 0, -0.5, 0, -0.5, 0, 0, -0.5, 0, 0, -0.5, 0, 0, 0, -0.5, 0, 0, -0.5, 0, 0, -0.5, -0.5, 0, 0, -0.5, 0, 0, -0.5, 0, 0, 0, -0.5, 0, 0, -0.5, 0, 0, -0.5, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1 ] # Load OBJ in to a VBO vertex_buffer = glGenBuffers(1) array_type = GLfloat * len(vertex_data) glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer) glBufferData(GL_ARRAY_BUFFER, len(vertex_data) * 4, array_type(*vertex_data), GL_STATIC_DRAW) uv_buffer = glGenBuffers(1) array_type = GLfloat * len(uv_data) glBindBuffer(GL_ARRAY_BUFFER, uv_buffer) glBufferData(GL_ARRAY_BUFFER, len(uv_data) * 4, array_type(*uv_data), GL_STATIC_DRAW) normal_buffer = glGenBuffers(1) array_type = GLfloat * len(normal_data) glBindBuffer(GL_ARRAY_BUFFER, normal_buffer) glBufferData(GL_ARRAY_BUFFER, len(normal_data) * 4, array_type(*normal_data), GL_STATIC_DRAW) # vsync and glfw do not play nice. when vsync is enabled mouse movement is jittery. common.disable_vsyc() # Get a handle for our "LightPosition" uniform glUseProgram(program_id) light_id = glGetUniformLocation(program_id, "LightPosition_worldspace") last_time = glfw.get_time() frames = 0 while glfw.get_key( window, glfw.KEY_ESCAPE ) != glfw.PRESS and not glfw.window_should_close(window): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) current_time = glfw.get_time() if current_time - last_time >= 1.0: glfw.set_window_title(window, "Tutorial 8. FPS: %d" % (frames)) frames = 0 last_time = current_time glUseProgram(program_id) controls.computeMatricesFromInputs(window) ProjectionMatrix = controls.getProjectionMatrix() ViewMatrix = controls.getViewMatrix() ModelMatrix = mat4.identity() mvp = ProjectionMatrix * ViewMatrix * ModelMatrix # Send our transformation to the currently bound shader, # in the "MVP" uniform glUniformMatrix4fv(matrix_id, 1, GL_FALSE, mvp.data) glUniformMatrix4fv(model_matrix_id, 1, GL_FALSE, ModelMatrix.data) glUniformMatrix4fv(view_matrix_id, 1, GL_FALSE, ViewMatrix.data) lightPos = vec3(4, 4, 4) glUniform3f(light_id, lightPos.x, lightPos.y, lightPos.z) # Bind our texture in Texture Unit 0 glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, texture) # Set our "myTextureSampler" sampler to user Texture Unit 0 glUniform1i(texture_id, 0) #1rst attribute buffer : vertices glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer) glVertexAttribPointer( 0, # attribute 0. No particular reason for 0, but must match the layout in the shader. 3, # len(vertex_data) GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) # 2nd attribute buffer : colors glEnableVertexAttribArray(1) glBindBuffer(GL_ARRAY_BUFFER, uv_buffer) glVertexAttribPointer( 1, # attribute 1. No particular reason for 1, but must match the layout in the shader. 2, # len(vertex_data) GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) # 3rd attribute buffer : normals glEnableVertexAttribArray(2) glBindBuffer(GL_ARRAY_BUFFER, normal_buffer) glVertexAttribPointer( 2, # attribute 3, # size GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) # Draw the triangles, vertex data now contains individual vertices # so use array length glDrawArrays(GL_TRIANGLES, 0, len(vertex_data)) # Not strictly necessary because we only have glDisableVertexAttribArray(0) glDisableVertexAttribArray(1) glDisableVertexAttribArray(2) # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() frames += 1 # !Note braces around vertex_buffer and uv_buffer. # glDeleteBuffers expects a list of buffers to delete glDeleteBuffers(1, [vertex_buffer]) glDeleteBuffers(1, [uv_buffer]) glDeleteBuffers(1, [normal_buffer]) glDeleteProgram(program_id) glDeleteTextures([texture_id]) glDeleteVertexArrays(1, [vertex_array_id]) glfw.terminate()
def main(): # Initialize the library if not glfw.init(): raise RuntimeError("Failed to initialize GLFW") glfw.window_hint(glfw.SAMPLES, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True) # To make MacOS happy; should not be needed glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) # Create a windowed mode window and its OpenGL context window = glfw.create_window(1024, 768, "Tutorial 09 - VBO Indexing", None, None) if not window: glfw.terminate() raise RuntimeError("Failed to open GLFW window.") # Make the window's context current glfw.make_context_current(window) # Ensure we can capture the escape key being pressed below glfw.set_input_mode(window, glfw.STICKY_KEYS, True) # Hide the mouse and enable unlimited mouvement glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED) # Set the mouse at the center of the screen glfw.poll_events() glfw.set_cursor_pos(window, 1024/2, 768/2) # Dark blue background glClearColor(0.0, 0.0, 0.4, 0.0) # Enable depth test glEnable(GL_DEPTH_TEST) # Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS) vao = glGenVertexArrays(1) glBindVertexArray(vao) # Create and compile our GLSL program from the shaders shader = Shader("StandardShading.vertexshader", "StandardShading.fragmentshader") shader.compile() # Create Controls object controls = Controls(window) # Load the texture using any two methods Texture = loadDDS("uvmap2.DDS") # Read our .obj file vertices, uvs, normals = loadOBJ("suzanne.obj",invert_v=True) indices,indexed_vertices,indexed_uvs,indexed_normals = indexVBO(vertices,uvs,normals) # Create the vertex buffer object vbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, vbo) glBufferData(GL_ARRAY_BUFFER, indexed_vertices.nbytes, indexed_vertices, GL_STATIC_DRAW) # Create the uv buffer object uvbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, uvbo) glBufferData(GL_ARRAY_BUFFER, indexed_uvs.nbytes, indexed_uvs, GL_STATIC_DRAW) # Create normal buffer object nbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, nbo) glBufferData(GL_ARRAY_BUFFER, indexed_normals.nbytes, indexed_normals, GL_STATIC_DRAW) # Generate a buffer for the indices as well ibo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, ibo) glBufferData(GL_ARRAY_BUFFER, indices.nbytes, indices, GL_STATIC_DRAW) # For speed computation lastTime = glfw.get_time() nbFrames = 0 # Loop until the user closes the window while( glfw.get_key(window, glfw.KEY_ESCAPE ) != glfw.PRESS and glfw.window_should_close(window) == 0 ): # Measure speed currentTime = glfw.get_time() nbFrames += 1 if currentTime-lastTime >= 1.0: # If last prinf() was more than 1sec ago # printf and reset print("{:.5f} ms/frame".format(1000.0/float(nbFrames))) nbFrames = 0 lastTime += 1.0 # Clear the screen glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ) # Use our shader shader.enable() # Compute the MVP matrix from keyboard and mouse input controls.update() # Send our transformation to the currently bound shader, # in the "MVP" uniform shader.setUniform("V", "mat4", np.array(controls.ViewMatrix,dtype=np.float32)) shader.setUniform("M", "mat4", np.array(controls.ModelMatrix,dtype=np.float32)) shader.setUniform("MVP", "mat4", controls.MVP) shader.setUniform("LightPosition_worldspace", "vec3", np.array([4,4,4],dtype=np.float32)) # Bind our texture in Texture Unit 0 glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, Texture) # Set our "myTextureSampler" sampler to user Texture Unit 0 shader.setUniform("myTextureSampler","sampler2D",0) glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, vbo) glVertexAttribPointer( 0, # attribute 0. 3, # size GL_FLOAT, # type GL_FALSE, # normalized? 0, # stride None # array buffer offset ) # 2nd attribute buffer : UVs glEnableVertexAttribArray(1) glBindBuffer(GL_ARRAY_BUFFER, uvbo) glVertexAttribPointer( 1, # attribute. 2, # size GL_FLOAT, # type GL_FALSE, # normalized? 0, # stride None # array buffer offset ) # 3rd attribute buffer : UVs glEnableVertexAttribArray(2) glBindBuffer(GL_ARRAY_BUFFER, nbo) glVertexAttribPointer( 2, # attribute. 3, # size GL_FLOAT, # type GL_FALSE, # normalized? 0, # stride None # array buffer offset ) # Index buffer glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo) # Draw the triangles ! glDrawElements( GL_TRIANGLES, # mode len(indices), # count GL_UNSIGNED_SHORT, # type None # element array buffer offset ) glDisableVertexAttribArray(0) glDisableVertexAttribArray(1) glDisableVertexAttribArray(2) # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() glfw.terminate()
def show_window(window, program): glfw.show_window(window) glfw.set_cursor_pos(window, lastX, lastY) glEnable(GL_DEPTH_TEST) rotacao_inc = 0 moon_angle = 0.1 while not glfw.window_should_close(window): glfw.poll_events() # clear the screen color and set to black glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glClearColor(0, 0, 0, 1) # check if polygonal mode is on if polygonal_mode == True: glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) if polygonal_mode == False: glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) # draws objects draw_ground(program) draw_house(program) draw_trees(program) draw_frog(program) draw_horse(program) draw_chair(program) draw_screen(program) draw_table(program) draw_cpu(program) draw_wind_mill_body(program) draw_wind_mill_circle(program, rotacao_inc) draw_sky(program) draw_street(program) draw_secondary_yard(program) draw_floor(program) draw_keyboard(program) # increases rotacao_inc to rotate the windmill circle rotacao_inc += 0.1 # increases moon_angle to rotate the moon moon_angle += 0.3 draw_moon(70 * np.cos(np.deg2rad(moon_angle)), 70, 70 * np.sin(np.deg2rad(moon_angle)), program) mat_view = view() loc_view = glGetUniformLocation(program, "view") glUniformMatrix4fv(loc_view, 1, GL_FALSE, mat_view) mat_projection = projection() loc_projection = glGetUniformLocation(program, "projection") glUniformMatrix4fv(loc_projection, 1, GL_FALSE, mat_projection) # updates the camera position on GPU to calcula specular reflection # recover viesPos variable position on GPU loc_view_pos = glGetUniformLocation(program, "viewPos") # camera position (x, y, z) glUniform3f(loc_view_pos, cameraPos[0], cameraPos[1], cameraPos[2]) glfw.swap_buffers(window) glfw.terminate()
def main(): time_start = time.time() if not init_opengl(): return #key events glfw.set_input_mode(window, glfw.STICKY_KEYS, GL_TRUE) glfw.set_cursor_pos(window, 1024 / 2, 768 / 2) glfw.set_key_callback(window, key_event) glClearColor(0, 0, 0.4, 0) # Enable depth test glEnable(GL_DEPTH_TEST) # Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS) #Faces wont display if normal facing camera ie inside of mesh glEnable(GL_CULL_FACE) #Disable vsync glfw.swap_interval(0) shader_program = LoadShaders("VertexShader.vertexshader", "FragmentShader.fragmentshader") vao1 = glGenVertexArrays(1) glBindVertexArray(vao1) #Read obj vertices, faces, uvs, normals, colors = objloader.load("0000.obj") vertex_data, uv_data, normal_data = objloader.process_obj( vertices, faces, uvs, normals, colors) #convert to ctype #vertex_data = objloader.generate_2d_ctypes(vertex_data) #normal_data = objloader.generate_2d_ctypes(normal_data) #uv_data = objloader.generate_2d_ctypes(uv_data) vertex_data = np.array(vertex_data).astype(np.float32) normal_data = np.array(normal_data).astype(np.float32) uv_data = np.array(uv_data).astype(np.float32) # Load OBJ in to a VBO vertex_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer) glBufferData(GL_ARRAY_BUFFER, len(vertex_data) * 4 * 3, vertex_data, GL_STATIC_DRAW) #glBufferData(GL_ARRAY_BUFFER, len(vertex_data) * 4 * 3, vert_data, GL_STATIC_DRAW) normal_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, normal_buffer) glBufferData(GL_ARRAY_BUFFER, len(normal_data) * 4 * 3, normal_data, GL_STATIC_DRAW) uv_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, uv_buffer) glBufferData(GL_ARRAY_BUFFER, len(uv_data) * 4 * 2, uv_data, GL_STATIC_DRAW) #Unbind glBindVertexArray(0) #Radial VAO vao2 = glGenVertexArrays(1) #Radial curves data #radialcurve.create_vertex_face_dict(vertices, faces) time_end = time.time() print("Time passed until radial functions: ", time_end - time_start, " seconds") time_start = time.time() radialcurve.vertex_face_sort(vertices, faces) time_end = time.time() print("Array Time: ", time_end - time_start) segment = 20 time_start = time.time() radial_data_unfinished = radialcurve.get_radial_curves( segment, (5.163908, -21.303692), (0.601237, 58.022675), (-60, 0), (60, 0), (0, 60), (0, -60), (-40, -20), (20, -40)) time_end = time.time() print("Radial Curve Time: ", time_end - time_start) radial_data = radial_data_unfinished[3] #Increase z by 1 so easier to see for point in radial_data: point[2] = point[2] + 1 #point[2] = 25 #matplot #`x = [0, 1/6, 2/6, 3/6, 4/6, 5/6, 1] x = [i / (segment + 1) for i in range(segment + 2)] y = [] for lines in radial_data_unfinished: for data in lines: y.append(data[2]) plt.plot(x, y) y = [] #print(y) plt.xlabel("Distance") plt.ylabel("Depth") plt.show() #print(radial_data) #radial_data = [[5.163908, -21.303692, 25], [0.601237, 58.022675, 25]] radial_data = objloader.generate_2d_ctypes(radial_data) #Radial Curves radial_buffer = glGenBuffers(1) array_type = GLfloat * len(radial_data) glBindBuffer(GL_ARRAY_BUFFER, radial_buffer) #glBufferData(GL_ARRAY_BUFFER, len(radial_data) * 4, array_type(*radial_data), GL_STATIC_DRAW) rad_data = np.array(radial_data).astype(np.float32) glBufferData(GL_ARRAY_BUFFER, len(radial_data) * 4 * 3, rad_data, GL_STATIC_DRAW) #Unbind glBindVertexArray(0) ##### #Handles light_id = glGetUniformLocation(shader_program, "LightPosition_worldspace") matrix_id = glGetUniformLocation(shader_program, "MVP") view_matrix_id = glGetUniformLocation(shader_program, "V") model_matrix_id = glGetUniformLocation(shader_program, "M") # Enable key events glfw.set_input_mode(window, glfw.STICKY_KEYS, GL_TRUE) #Line Width glEnable(GL_LINE_SMOOTH) glLineWidth(3) while glfw.get_key( window, glfw.KEY_ESCAPE ) != glfw.PRESS and not glfw.window_should_close(window): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glUseProgram(shader_program) controls.computeMatricesFromInputs(window) pm = controls.getProjectionMatrix() vm = controls.getViewMatrix() #at origin mm = mat4.identity() mvp = pm * vm * mm glUniformMatrix4fv(matrix_id, 1, GL_FALSE, mvp.data) glUniformMatrix4fv(model_matrix_id, 1, GL_FALSE, mm.data) glUniformMatrix4fv(view_matrix_id, 1, GL_FALSE, vm.data) lightPos = vec3(0, 0, 50) glUniform3f(light_id, lightPos.x, lightPos.y, lightPos.z) ##VAO1################ glBindVertexArray(vao1) glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer) glVertexAttribPointer( 0, # attribute 3, # len(vertex_data) GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) glEnableVertexAttribArray(1) glBindBuffer(GL_ARRAY_BUFFER, normal_buffer) glVertexAttribPointer( 1, # attribute 3, # size GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) glEnableVertexAttribArray(2) glBindBuffer(GL_ARRAY_BUFFER, uv_buffer) glVertexAttribPointer( 2, # attribute 2, # size GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) # Draw glDrawArrays(GL_TRIANGLES, 0, len(vertex_data)) glDisableVertexAttribArray(0) glDisableVertexAttribArray(1) glDisableVertexAttribArray(2) glBindVertexArray(0) ###################################### #VAO2 glBindVertexArray(vao2) glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, radial_buffer) glVertexAttribPointer( 0, # attribute 3, # size GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) glDrawArrays(GL_LINE_STRIP, 0, len(radial_data)) #glDrawArrays(GL_TRIANGLES, 0, len(radial_data)) glBindVertexArray(0) glfw.swap_buffers(window) glfw.poll_events() glBindVertexArray(vao1) glDeleteBuffers(1, [vertex_buffer]) glDeleteBuffers(1, [normal_buffer]) glBindVertexArray(0) glDeleteVertexArrays(1, [vao1]) glBindVertexArray(vao2) glDeleteBuffers(1, [radial_buffer]) glDeleteVertexArrays(1, [vao2]) glDeleteProgram(shader_program) glfw.terminate()
def update_rotation_moused(): update_rotation_base() glfw.set_cursor_pos(window, rotation_ypr.x / -MOUSE_SPEED, rotation_ypr.y / -MOUSE_SPEED)
def cursor_position_callback(window, xpos, ypos): camera.mouth_update(xpos, ypos) glfw.set_cursor_pos(window, WINDOW_RESOLUTION[0]/2, WINDOW_RESOLUTION[1]/2) if not glfw.init(): raise Exception('glfw con not be initialized') window = glfw.create_window(1280, 720, 'My OpenGL window', None, None) if not window: glfw.terminate() raise Exception('glfw window can not be created') glfw.set_window_pos(window, 4000, 200) glfw.set_cursor_pos(window, WINDOW_RESOLUTION[0]/2, WINDOW_RESOLUTION[1]/2) glfw.set_window_size_callback(window, window_resize) glfw.set_cursor_pos_callback(window, cursor_position_callback) glfw.make_context_current(window) light_shader = compileProgram(compileShader(light_vs, GL_VERTEX_SHADER), compileShader(light_fs, GL_FRAGMENT_SHADER)) lamp_shader = compileProgram(compileShader(lamp_vs, GL_VERTEX_SHADER), compileShader(lamp_fs, GL_FRAGMENT_SHADER)) texture = glGenTextures(2) load_texture('lightning_test/textures/container.png', texture[0]) load_texture('lightning_test/textures/container_specular.png', texture[1]) ### BOX ############################### box_VAO = glGenVertexArrays(1) glBindVertexArray(box_VAO)
def main(): if not opengl_init(): return # Enable key events glfw.set_input_mode(window,glfw.STICKY_KEYS,GL_TRUE) glfw.set_cursor_pos(window, 1024/2, 768/2) # Set opengl clear color to something other than red (color used by the fragment shader) glClearColor(0.0,0.0,0.4,0.0) # Enable depth test glEnable(GL_DEPTH_TEST) # Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS); glEnable(GL_CULL_FACE) vertex_array_id = glGenVertexArrays(1) glBindVertexArray( vertex_array_id ) program_id = common.LoadShaders( ".\\shaders\\Tutorial6\\TransformVertexShader.vertexshader", ".\\shaders\\Tutorial6\\TextureFragmentShader.fragmentshader" ) # Get a handle for our "MVP" uniform matrix_id = glGetUniformLocation(program_id, "MVP"); texture = load_image(".\\content\\uvtemplate.bmp") texture_id = glGetUniformLocation(program_id, "myTextureSampler") # Our vertices. Tree consecutive floats give a 3D vertex; Three consecutive vertices give a triangle. # A cube has 6 faces with 2 triangles each, so this makes 6*2=12 triangles, and 12*3 vertices vertex_data = [ -1.0,-1.0,-1.0, -1.0,-1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0,-1.0, -1.0,-1.0,-1.0, -1.0, 1.0,-1.0, 1.0,-1.0, 1.0, -1.0,-1.0,-1.0, 1.0,-1.0,-1.0, 1.0, 1.0,-1.0, 1.0,-1.0,-1.0, -1.0,-1.0,-1.0, -1.0,-1.0,-1.0, -1.0, 1.0, 1.0, -1.0, 1.0,-1.0, 1.0,-1.0, 1.0, -1.0,-1.0, 1.0, -1.0,-1.0,-1.0, -1.0, 1.0, 1.0, -1.0,-1.0, 1.0, 1.0,-1.0, 1.0, 1.0, 1.0, 1.0, 1.0,-1.0,-1.0, 1.0, 1.0,-1.0, 1.0,-1.0,-1.0, 1.0, 1.0, 1.0, 1.0,-1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,-1.0, -1.0, 1.0,-1.0, 1.0, 1.0, 1.0, -1.0, 1.0,-1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0,-1.0, 1.0] # Two UV coordinatesfor each vertex. They were created withe Blender. uv_data = [ 0.000059, 1.0-0.000004, 0.000103, 1.0-0.336048, 0.335973, 1.0-0.335903, 1.000023, 1.0-0.000013, 0.667979, 1.0-0.335851, 0.999958, 1.0-0.336064, 0.667979, 1.0-0.335851, 0.336024, 1.0-0.671877, 0.667969, 1.0-0.671889, 1.000023, 1.0-0.000013, 0.668104, 1.0-0.000013, 0.667979, 1.0-0.335851, 0.000059, 1.0-0.000004, 0.335973, 1.0-0.335903, 0.336098, 1.0-0.000071, 0.667979, 1.0-0.335851, 0.335973, 1.0-0.335903, 0.336024, 1.0-0.671877, 1.000004, 1.0-0.671847, 0.999958, 1.0-0.336064, 0.667979, 1.0-0.335851, 0.668104, 1.0-0.000013, 0.335973, 1.0-0.335903, 0.667979, 1.0-0.335851, 0.335973, 1.0-0.335903, 0.668104, 1.0-0.000013, 0.336098, 1.0-0.000071, 0.000103, 1.0-0.336048, 0.000004, 1.0-0.671870, 0.336024, 1.0-0.671877, 0.000103, 1.0-0.336048, 0.336024, 1.0-0.671877, 0.335973, 1.0-0.335903, 0.667969, 1.0-0.671889, 1.000004, 1.0-0.671847, 0.667979, 1.0-0.335851] vertex_buffer = glGenBuffers(1); array_type = GLfloat * len(vertex_data) glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer) glBufferData(GL_ARRAY_BUFFER, len(vertex_data) * 4, array_type(*vertex_data), GL_STATIC_DRAW) uv_buffer = glGenBuffers(1); array_type = GLfloat * len(uv_data) glBindBuffer(GL_ARRAY_BUFFER, uv_buffer) glBufferData(GL_ARRAY_BUFFER, len(uv_data) * 4, array_type(*uv_data), GL_STATIC_DRAW) # vsync and glfw do not play nice. when vsync is enabled mouse movement is jittery. common.disable_vsyc() while glfw.get_key(window,glfw.KEY_ESCAPE) != glfw.PRESS and not glfw.window_should_close(window): glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT) glUseProgram(program_id) controls.computeMatricesFromInputs(window) ProjectionMatrix = controls.getProjectionMatrix(); ViewMatrix = controls.getViewMatrix(); ModelMatrix = mat4.identity(); mvp = ProjectionMatrix * ViewMatrix * ModelMatrix; # Send our transformation to the currently bound shader, # in the "MVP" uniform glUniformMatrix4fv(matrix_id, 1, GL_FALSE,mvp.data) # Bind our texture in Texture Unit 0 glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture); # Set our "myTextureSampler" sampler to user Texture Unit 0 glUniform1i(texture_id, 0); #1rst attribute buffer : vertices glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer); glVertexAttribPointer( 0, # attribute 0. No particular reason for 0, but must match the layout in the shader. 3, # len(vertex_data) GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) # 2nd attribute buffer : colors glEnableVertexAttribArray(1) glBindBuffer(GL_ARRAY_BUFFER, uv_buffer); glVertexAttribPointer( 1, # attribute 1. No particular reason for 1, but must match the layout in the shader. 2, # len(vertex_data) GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) # Draw the triangle ! glDrawArrays(GL_TRIANGLES, 0, 12*3) #3 indices starting at 0 -> 1 triangle # Not strictly necessary because we only have glDisableVertexAttribArray(0) glDisableVertexAttribArray(1) # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() # !Note braces around vertex_buffer and uv_buffer. # glDeleteBuffers expects a list of buffers to delete glDeleteBuffers(1, [vertex_buffer]) glDeleteBuffers(1, [uv_buffer]) glDeleteProgram(program_id) glDeleteTextures([texture_id]) glDeleteVertexArrays(1, [vertex_array_id]) glfw.terminate()
def main(): if not opengl_init(): return # Enable key events glfw.set_input_mode(window, glfw.STICKY_KEYS, GL_TRUE) glfw.set_cursor_pos(window, 1024 / 2, 768 / 2) # Set opengl clear color to something other than red (color used by the fragment shader) glClearColor(0.0, 0.0, 0.4, 0.0) # Enable depth test glEnable(GL_DEPTH_TEST) # Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS) glEnable(GL_CULL_FACE) vertex_array_id = glGenVertexArrays(1) glBindVertexArray(vertex_array_id) program_id = common.LoadShaders( ".\\shaders\\Tutorial6\\TransformVertexShader.vertexshader", ".\\shaders\\Tutorial6\\TextureFragmentShader.fragmentshader") # Get a handle for our "MVP" uniform matrix_id = glGetUniformLocation(program_id, "MVP") texture = load_image(".\\content\\uvtemplate.bmp") texture_id = glGetUniformLocation(program_id, "myTextureSampler") # Our vertices. Tree consecutive floats give a 3D vertex; Three consecutive vertices give a triangle. # A cube has 6 faces with 2 triangles each, so this makes 6*2=12 triangles, and 12*3 vertices vertex_data = [ -1.0, -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, -1.0, 1.0, -1.0, -1.0, -1.0, -1.0, 1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, 1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, -1.0, 1.0 ] # Two UV coordinatesfor each vertex. They were created withe Blender. uv_data = [ 0.000059, 1.0 - 0.000004, 0.000103, 1.0 - 0.336048, 0.335973, 1.0 - 0.335903, 1.000023, 1.0 - 0.000013, 0.667979, 1.0 - 0.335851, 0.999958, 1.0 - 0.336064, 0.667979, 1.0 - 0.335851, 0.336024, 1.0 - 0.671877, 0.667969, 1.0 - 0.671889, 1.000023, 1.0 - 0.000013, 0.668104, 1.0 - 0.000013, 0.667979, 1.0 - 0.335851, 0.000059, 1.0 - 0.000004, 0.335973, 1.0 - 0.335903, 0.336098, 1.0 - 0.000071, 0.667979, 1.0 - 0.335851, 0.335973, 1.0 - 0.335903, 0.336024, 1.0 - 0.671877, 1.000004, 1.0 - 0.671847, 0.999958, 1.0 - 0.336064, 0.667979, 1.0 - 0.335851, 0.668104, 1.0 - 0.000013, 0.335973, 1.0 - 0.335903, 0.667979, 1.0 - 0.335851, 0.335973, 1.0 - 0.335903, 0.668104, 1.0 - 0.000013, 0.336098, 1.0 - 0.000071, 0.000103, 1.0 - 0.336048, 0.000004, 1.0 - 0.671870, 0.336024, 1.0 - 0.671877, 0.000103, 1.0 - 0.336048, 0.336024, 1.0 - 0.671877, 0.335973, 1.0 - 0.335903, 0.667969, 1.0 - 0.671889, 1.000004, 1.0 - 0.671847, 0.667979, 1.0 - 0.335851 ] vertex_buffer = glGenBuffers(1) array_type = GLfloat * len(vertex_data) glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer) glBufferData(GL_ARRAY_BUFFER, len(vertex_data) * 4, array_type(*vertex_data), GL_STATIC_DRAW) uv_buffer = glGenBuffers(1) array_type = GLfloat * len(uv_data) glBindBuffer(GL_ARRAY_BUFFER, uv_buffer) glBufferData(GL_ARRAY_BUFFER, len(uv_data) * 4, array_type(*uv_data), GL_STATIC_DRAW) # vsync and glfw do not play nice. when vsync is enabled mouse movement is jittery. common.disable_vsyc() while glfw.get_key( window, glfw.KEY_ESCAPE ) != glfw.PRESS and not glfw.window_should_close(window): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glUseProgram(program_id) controls.computeMatricesFromInputs(window) ProjectionMatrix = controls.getProjectionMatrix() ViewMatrix = controls.getViewMatrix() ModelMatrix = mat4.identity() mvp = ProjectionMatrix * ViewMatrix * ModelMatrix # Send our transformation to the currently bound shader, # in the "MVP" uniform glUniformMatrix4fv(matrix_id, 1, GL_FALSE, mvp.data) # Bind our texture in Texture Unit 0 glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, texture) # Set our "myTextureSampler" sampler to user Texture Unit 0 glUniform1i(texture_id, 0) #1rst attribute buffer : vertices glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer) glVertexAttribPointer( 0, # attribute 0. No particular reason for 0, but must match the layout in the shader. 3, # len(vertex_data) GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) # 2nd attribute buffer : colors glEnableVertexAttribArray(1) glBindBuffer(GL_ARRAY_BUFFER, uv_buffer) glVertexAttribPointer( 1, # attribute 1. No particular reason for 1, but must match the layout in the shader. 2, # len(vertex_data) GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) # Draw the triangle ! glDrawArrays(GL_TRIANGLES, 0, 12 * 3) #3 indices starting at 0 -> 1 triangle # Not strictly necessary because we only have glDisableVertexAttribArray(0) glDisableVertexAttribArray(1) # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() # !Note braces around vertex_buffer and uv_buffer. # glDeleteBuffers expects a list of buffers to delete glDeleteBuffers(1, [vertex_buffer]) glDeleteBuffers(1, [uv_buffer]) glDeleteProgram(program_id) glDeleteTextures([texture_id]) glDeleteVertexArrays(1, [vertex_array_id]) glfw.terminate()
mat_view = glm.lookAt(cameraPos, cameraPos + cameraFront, cameraUp); mat_view = np.array(mat_view) return mat_view def projection(): global altura, largura # fov aspect ratio near far mat_projection = glm.perspective(glm.radians(90.0), largura/altura, 1, 5000.0) mat_projection = np.array(mat_projection) return mat_projection #}}} #{{{ LOOP glfw.show_window(window) glfw.set_cursor_pos(window, largura/2, altura/2) glEnable(GL_DEPTH_TEST) wave_obj = sa.WaveObject.from_wave_file("media/floral.wav") play_obj = wave_obj.play() last = glfw.get_time() nbframes = 0 bus_z_pos = -1300 while not glfw.window_should_close(window): glfw.poll_events() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glClearColor(0.0, 0.0, 0.0, 1.0)
mat_view = glm.lookAt(cameraPos, cameraPos + cameraFront, cameraUp) mat_view = np.array(mat_view) return mat_view def projection(): global altura, largura # perspective parameters: fovy, aspect, near, far mat_projection = glm.perspective(glm.radians(45.0), largura / altura, 0.1, 3000.0) mat_projection = np.array(mat_projection) return mat_projection glfw.show_window(window) glfw.set_cursor_pos(window, lastX, lastY) glEnable(GL_DEPTH_TEST) ### importante para 3D #fazer o gollum ficar pulando jump_speed = 0.35 while not glfw.window_should_close(window): glfw.poll_events() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glClearColor(1.0, 1.0, 1.0, 1.0) if polygonal_mode == True: glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
def main(): # Initialize GLFW and open a window if not opengl_init(): return # Enable key events glfw.set_input_mode(window,glfw.STICKY_KEYS,GL_TRUE) glfw.set_cursor_pos(window, 1024/2, 768/2) # Set opengl clear color to something other than red (color used by the fragment shader) glClearColor(0.0,0.0,0.4,0.0) # Enable depth test glEnable(GL_DEPTH_TEST) # Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS) # Cull triangles which normal is not towards the camera glEnable(GL_CULL_FACE) vertex_array_id = glGenVertexArrays(1) glBindVertexArray( vertex_array_id ) # Create and compile our GLSL program from the shaders program_id = common.LoadShaders( ".\\shaders\\Tutorial7\\TransformVertexShader.vertexshader", ".\\shaders\\Tutorial7\\TextureFragmentShader.fragmentshader" ) # Get a handle for our "MVP" uniform matrix_id = glGetUniformLocation(program_id, "MVP") # Load the texture texture = load_image(".\\content\\uvmap.bmp") # Get a handle for our "myTextureSampler" uniform texture_id = glGetUniformLocation(program_id, "myTextureSampler") # Read our OBJ file vertices,faces,uvs,normals,colors = objloader.load(".\\content\\cube.obj") vertex_data,uv_data,normal_data = objloader.process_obj( vertices,faces,uvs,normals,colors) # Our OBJ loader uses Python lists, convert to ctype arrays before sending to OpenGL vertex_data = objloader.generate_2d_ctypes(vertex_data) uv_data = objloader.generate_2d_ctypes(uv_data) # Load OBJ in to a VBO vertex_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer) glBufferData(GL_ARRAY_BUFFER, len(vertex_data) * 4 * 3, vertex_data, GL_STATIC_DRAW) uv_buffer = glGenBuffers(1) array_type = GLfloat * len(uv_data) glBindBuffer(GL_ARRAY_BUFFER, uv_buffer) glBufferData(GL_ARRAY_BUFFER, len(uv_data) * 4 * 2, uv_data, GL_STATIC_DRAW) # vsync and glfw do not play nice. when vsync is enabled mouse movement is jittery. common.disable_vsyc() while glfw.get_key(window,glfw.KEY_ESCAPE) != glfw.PRESS and not glfw.window_should_close(window): glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT) glUseProgram(program_id) controls.computeMatricesFromInputs(window) ProjectionMatrix = controls.getProjectionMatrix() ViewMatrix = controls.getViewMatrix() ModelMatrix = mat4.identity() mvp = ProjectionMatrix * ViewMatrix * ModelMatrix # Send our transformation to the currently bound shader, # in the "MVP" uniform glUniformMatrix4fv(matrix_id, 1, GL_FALSE,mvp.data) # Bind our texture in Texture Unit 0 glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, texture) # Set our "myTextureSampler" sampler to user Texture Unit 0 glUniform1i(texture_id, 0) #1rst attribute buffer : vertices glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer) glVertexAttribPointer( 0, # attribute 0. No particular reason for 0, but must match the layout in the shader. 3, # len(vertex_data) GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) # 2nd attribute buffer : colors glEnableVertexAttribArray(1) glBindBuffer(GL_ARRAY_BUFFER, uv_buffer) glVertexAttribPointer( 1, # attribute 1. No particular reason for 1, but must match the layout in the shader. 2, # len(vertex_data) GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) # Draw the triangles, vertex data now contains individual vertices # so use array length glDrawArrays(GL_TRIANGLES, 0, len(vertex_data)) # Not strictly necessary because we only have glDisableVertexAttribArray(0) glDisableVertexAttribArray(1) # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() # !Note braces around vertex_buffer and uv_buffer. # glDeleteBuffers expects a list of buffers to delete glDeleteBuffers(1, [vertex_buffer]) glDeleteBuffers(1, [uv_buffer]) glDeleteProgram(program_id) glDeleteTextures([texture_id]) glDeleteVertexArrays(1, [vertex_array_id]) glfw.terminate()