def pipeline(camera: Camera, meshes: Sequence[Mesh], light: Light, width: int, height: int) -> Image.Image: # TODO adding true backface culling and Z-buffer! bitmap = Image.new('RGBA', (width, height), color='black') for mesh in meshes: projection_matrix = glm.perspective(glm.radians(90.0), width / height, 0.1, 1000.0) view_matrix = glm.lookAt(camera.position, camera.target, camera.up) model_matrix = get_model_matrix(mesh) mvp = projection_matrix * view_matrix * model_matrix for face in mesh.faces: dot = glm.dot(face.p0 - camera.position, face.normal) if dot >= 0: continue diffuse = light.get_diffuse_color(face, model_matrix) ambient_strength = 0.1 ambient = ambient_strength * light.color result = glm.vec4((ambient + diffuse) * mesh.color, 1.0) draw_face(bitmap, face, mvp, width, height, fill=tuple(map(int, result * 255))) return bitmap
def __init__(self, scene, width=1280, height=720, title="Viewer", floating=False, background_color=(0, 0, 0, 1)): # window self.width = width self.height = height self.scene = scene self.title = title self._floating = floating self.background_color = background_color # threading self.thread = None self.lock = None # renderer from editor.render.graphics import PerspectiveCamera self.camera = PerspectiveCamera(glm.mat4(1), glm.radians(39.6), self.width / self.height, 0.1, 30) self.camera.transform = glm.inverse( glm.lookAt(glm.vec3(2, 3, 6), glm.vec3(0, 0, 0), glm.vec3(0, 1, 0))) self.renderer = DeferredPBRRenderer(self.width, self.height)
def render(self) -> None: """Render ViewCube to canvas.""" if not self.init(): return glViewport(*self._get_viewport()) proj = glm.ortho(-2.3, 2.3, -2.3, 2.3, -2.3, 2.3) mat = glm.lookAt( vec3(0.0, -1.0, 0.0), # position vec3(0.0, 0.0, 0.0), # target vec3(0.0, 0.0, 1.0)) # up modelview = mat * glm.mat4_cast(self.parent.rot_quat) glUseProgram(self.parent.shaders['default']) glUniformMatrix4fv(0, 1, GL_FALSE, glm.value_ptr(proj)) glUniformMatrix4fv(1, 1, GL_FALSE, glm.value_ptr(modelview)) glBindVertexArray(self._vao) glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, ctypes.c_void_p(0)) self._render_highlighted() glBindVertexArray(0) glUseProgram(0)
def main(): global EVENT_MNGR, EVENT_DISP, EVENT_LIST,\ PROJECTION_MTRX, LOOKAT_MTRX, ASPECT_RATIO atexit.register(on_exit) glut.glutInit(sys.argv) OpenGL.GLUT.freeglut.glutSetOption(OpenGL.GLUT.GLUT_ACTION_ON_WINDOW_CLOSE, OpenGL.GLUT.GLUT_ACTION_GLUTMAINLOOP_RETURNS) init_window() EVENT_DISP = GloveletSensorEventDispatcher('/dev/ttyACM0', 115200) EVENT_LIST = GloveletDemoController() EVENT_MNGR = EventDispatchManager(EVENT_DISP, EVENT_LIST) init_hand() glut.glutShowWindow() # Init shaders if not init_shaders(): print('Failed to compile and link shader program.') # init OpenGL settings gl.glEnable(gl.GL_TEXTURE_2D) gl.glEnable(gl.GL_DEPTH_TEST) # set render callback glut.glutDisplayFunc(draw) glut.glutKeyboardFunc(keyboard_handler) # glut.glutPassiveMotionFunc(mouse_motion) # init perspective matrices PROJECTION_MTRX = glm.perspective(glm.radians(45.0), ASPECT_RATIO, 0.1, 100.0) LOOKAT_MTRX = glm.lookAt(glm.vec3((0.0, 2.0, -4.0), dtype='f'), # eye glm.vec3((0.0, 1.0, 0.0), dtype='f'), # center glm.vec3((0.0, 1.0, 0.0), dtype='f')) # up # begin main loop EVENT_MNGR.deploy_dispatchers() glut.glutMainLoop() EVENT_MNGR.end_dispatchers() exit()
def mouse_event(buttom, state, x, y): #print(buttom,state) global window_id global Project global move_x, move_z, r, theata, distance if buttom == GLUT_RIGHT_BUTTON: glutDestroyWindow(window_id) elif buttom == GLUT_LEFT_BUTTON: theata += 1 / 40 move_x = r * np.cos(np.pi * theata) move_z = r * np.sin(np.pi * theata) ## print(u'旋转x = {}, z = {}'.format(move_x, move_z)) ## print(u'旋转 angle = {}pi'.format(theata * np.pi)) Project = glm.lookAt(glm.vec3(0, move_x, move_z), glm.vec3(0, 0.0, 0.0), glm.vec3(0, 1, 0)) glutPostRedisplay() elif buttom == 3: ## print('upping') distance += 1 / 40 ## Project = glm.ortho(-1, 1, -1, 1, distance + 2, distance - 5) Project = glm.frustum(-1, 1, -1, 1, 1 + distance, -1) glutPostRedisplay() elif buttom == 4: distance -= 1 / 40 ## print('down') ## Project = glm.ortho(-1, 1, -1, 1, distance + 2, distance - 5) Project = glm.frustum(-1, 1, -1, 1, 1 + distance, -1) glutPostRedisplay()
def __init__(self, width, height, clear_color=(0.3,0.1,0.1,1)): super().__init__(width, height, clear_color) self.view_matrix = glm.lookAt( glm.vec3(0, 1,4), glm.vec3(0,0.0,0), glm.vec3(0,1,0) ) self.projection_matrix = glm.perspective(math.radians(60), width/height, 0.1, 100) @self.addEventListener("mousemove") def mousemove(x, y, dx, dy): if self.get_mouse_button(0): self.view_matrix = orbit(self.view_matrix, dx*2,dy*2) @self.addEventListener("mousebutton") def mousebutton(button, action, modifiers): pass @self.addEventListener("scroll") def scroll(dx, dy): s = 1+dy/10 self.view_matrix = glm.scale(self.view_matrix, (s,s,s)) @self.addEventListener("resize") def resize(w, h): glViewport(0, 0, w, h) self.projection_matrix = glm.perspective(math.radians(60), w/h, 1, 100) self._callbacks['setup'] = [] self._callbacks['draw'] = []
def prepare(self, shader): width, height = get_context().fbo.size dirty = self._aspect != width / height self._aspect = width / height _trigger_dirty_flat = self.matrix if dirty or self._dirty: self._view0 = glm.lookAt(self.position, self.position - self.front, self.up) self._proj0 = glm.perspective( self.yfov, self._aspect, self.znear, self.zfar ) shader._members['view'].write(self._view0) shader._members['camera.position'].value = tuple(self.position) shader._members['projection'].write(self._proj0) shader._members['camera.zfar'].value = self.zfar self._dirty.clear()
def view_transform(self, event): if event: return event.camera.getViewMatrix() #return super(lightShader, self).view_transform(event) radius = 0.5 (xpos, ypos, zpos) = (0, 0, 0) xpos = radius * cos(glfw.get_time()) #ypos = radius * sin(glfw.get_time()) zpos = radius * sin(glfw.get_time()) # theta = glfw.get_time() # phi = glfw.get_time() / 2.0 # xpos = radius * sin(theta) * cos(phi) # ypos = radius * sin(theta) * sin(phi) # zpos = radius * cos(theta) eye = glm.vec3(xpos, ypos, zpos) center = glm.vec3(0) up = glm.vec3(0, 1, 0) # radius = 1 # xpos = radius * math.cos(glfw.get_time()) # # ypos = radius * math.sin(glfw.get_time()) # ypos = 0 # zpos = radius * math.sin(glfw.get_time()) # eye = glm.vec3(xpos, ypos, zpos) # center = glm.vec3() # up = glm.vec3(0, 1, 0) view = glm.lookAt(eye, center, up) #self.store_id('view', view, shader_id) return view
def modelview_matrix(self) -> mat4: """Returns a mat4 representing the current modelview matrix.""" mat = glm.lookAt( vec3(0.0, -self._dist * 2.0 / self._zoom, 0.0), # eye vec3(0.0, 0.0, 0.0), # center vec3(0.0, 0.0, 1.0)) # up return glm.translate(mat * glm.mat4_cast(self._rot_quat), self._center)
def render(time): glClearBufferfv(GL_COLOR, 0, [0.0, 0.0, 0.0, 1.0]) glClearBufferfi(GL_DEPTH_STENCIL, 0, 1.0, 0) M_matrix = glm.mat4(1.0) V_matrix = glm.lookAt(glm.vec3(0.0, 0.0, 12.0), glm.vec3(3.0, 3.0, 3.0), glm.vec3(0.0, 1.0, 0.0)) glUseProgram(rendering_program) M_location = glGetUniformLocation(rendering_program, "M_matrix") V_location = glGetUniformLocation(rendering_program, "V_matrix") P_location = glGetUniformLocation(rendering_program, "P_matrix") glUniformMatrix4fv(V_location, 1, GL_FALSE, glm.value_ptr(V_matrix)) glUniformMatrix4fv(P_location, 1, GL_FALSE, glm.value_ptr(P_matrix)) for i in range(10): for i in range(10): M_matrix = glm.translate(M_matrix, glm.vec3(1.0, 0.0, 0.0)) M_matrix = glm.rotate(M_matrix, time, glm.vec3(1.0, 1.0, 0.0)) glUniformMatrix4fv(M_location, 1, GL_FALSE, glm.value_ptr(M_matrix)) glDrawArrays(GL_TRIANGLES, 0, 36) M_matrix = glm.rotate(M_matrix, time, glm.vec3(-1.0, -1.0, 0.0)) M_matrix = glm.translate(M_matrix, glm.vec3(-10.0, 1.0, 0.0))
def render_scene(): global model, view global x_theta, y_theta, z_theta, r_time r_time += 0.02 if x_rotate: x_theta = 0.02 elif not x_rotate: x_theta = 0 if y_rotate: y_theta = 0.02 elif not y_rotate: y_theta = 0 if z_rotate: z_theta = 0.02 elif not z_rotate: z_theta = 0 model = glm.rotate(model, x_theta, np.array([1, 0, 0], 'f4')) model = glm.rotate(model, y_theta, np.array([0, 1, 0], 'f4')) model = glm.rotate(model, z_theta, np.array([0, 0, 1], 'f4')) prog['model'].write(model) cam_x = np.sin(r_time) * swivel_radius cam_z = np.cos(r_time) * swivel_radius view = glm.lookAt(np.array((cam_x, 0, cam_z), 'f4'), camtarget, camup) prog['view'].write(view) vao.render(moderngl.TRIANGLES)
def render(time): glClearBufferfv(GL_COLOR, 0, [0.0, 0.0, 0.0, 1.0]) glClearBufferfi(GL_DEPTH_STENCIL, 0, 1.0, 0) M_matrix = glm.rotate(glm.mat4(1.0), time, glm.vec3(1.0, 1.0, 0.0)) V_matrix = glm.lookAt(glm.vec3(0.0, 0.0, 15.0), glm.vec3(0.0, 0.0, 0.0), glm.vec3(0.0, 15.0, 0.0)) glUseProgram(rendering_program) M_location = glGetUniformLocation(rendering_program, "M_matrix") V_location = glGetUniformLocation(rendering_program, "V_matrix") P_location = glGetUniformLocation(rendering_program, "P_matrix") glUniformMatrix4fv(M_location, 1, GL_FALSE, glm.value_ptr(M_matrix)) glUniformMatrix4fv(V_location, 1, GL_FALSE, glm.value_ptr(V_matrix)) glUniformMatrix4fv(P_location, 1, GL_FALSE, glm.value_ptr(P_matrix)) #Zadanie na 3.5 #glDrawArrays(GL_TRIANGLES, 0, 36) #Zadanie na 4.0 #classic_copy_board(M_matrix, M_location) #Zadanie na 4.5 i na 5.0 (różnica w vertex_shader_source) glDrawArraysInstanced(GL_TRIANGLES, 0, 36, 100)
def mainloop(): vp_valid, vp_size, view, projection = glut_navigation.update() angle1 = elapsed_ms() * math.pi * 2 / 5000.0 angle2 = elapsed_ms() * math.pi * 2 / 7333.0 model_matrices = [] for i in range(no_of_meshes): if i == 0: model = glm.mat4(1) model = glm.translate(model, glm.vec3(0, 0, -1)) else: angleY = angle1 + math.pi*2 * (i-1) / (no_of_meshes-1) model = glm.mat4(1) model = glm.rotate(model, angleY, glm.vec3(0, 0, 0.5)) model = glm.translate(model, glm.vec3(diameter/2, 0, 0.5)) model = glm.rotate(model, angle2, glm.vec3(0, 1, 0)) model_matrices.append(model) light_pos = glm.vec3(0, 0, 3) light_dir = glm.vec3(0, 0, -1) light_cone_angle_degree = 60 light_cone_cos = math.cos(math.radians(light_cone_angle_degree) / 2) shadow_proj = glm.perspective(glm.radians(light_cone_angle_degree + 1), 1, 0.1, 100.0) shadow_view = glm.lookAt(light_pos, light_pos+light_dir, glm.vec3(0,1,0)) glBindBuffer(GL_SHADER_STORAGE_BUFFER, model_ssbo) for i, model in enumerate(model_matrices): glBufferSubData(GL_SHADER_STORAGE_BUFFER, i*4*16, glm.sizeof(glm.mat4), glm.value_ptr(model)) glBindFramebuffer(GL_FRAMEBUFFER, shadow_fbo) glViewport(0, 0, *shadow_buffer_size) glClear(GL_DEPTH_BUFFER_BIT) glUseProgram(shadow_program) glUniformMatrix4fv(0, 1, GL_FALSE, glm.value_ptr(shadow_proj)) glUniformMatrix4fv(1, 1, GL_FALSE, glm.value_ptr(shadow_view)) glEnable(GL_POLYGON_OFFSET_FILL) glPolygonOffset(1.0, 1.0) model_multimesh.draw() glDisable(GL_POLYGON_OFFSET_FILL) glBindFramebuffer(GL_FRAMEBUFFER, 0) glViewport(0, 0, *vp_size) glClearColor(0.2, 0.3, 0.3, 1.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glUseProgram(phong_program) glUniformMatrix4fv(0, 1, GL_FALSE, glm.value_ptr(projection)) glUniformMatrix4fv(1, 1, GL_FALSE, glm.value_ptr(view)) glUniformMatrix4fv(2, 1, GL_FALSE, glm.value_ptr(shadow_proj)) glUniformMatrix4fv(3, 1, GL_FALSE, glm.value_ptr(shadow_view)) glUniform4fv(4, 1, glm.value_ptr(glm.vec4(light_pos, 1))) glUniform4fv(5, 1, glm.value_ptr(glm.vec4(light_dir, light_cone_cos))) glBindTextureUnit(1, shadow_depth_to) model_multimesh.draw() glutSwapBuffers() glutPostRedisplay()
def drawObject(self): # Update camera model, view, proj = glm.mat4(1), glm.mat4(1), glm.perspective(45, self.width() / self.height(), 0.01, 100) center, up, eye = glm.vec3(0, -0.075, 0), glm.vec3(0, -1, 0), glm.vec3(0, 0, -0.4 * (self.zoomLevel / 10)) view = glm.lookAt(eye, center, up) model = glm.rotate(model, self.xRot / 160.0, glm.vec3(1, 0, 0)) model = glm.rotate(model, self.yRot / 160.0, glm.vec3(0, 1, 0)) model = glm.rotate(model, self.zRot / 160.0, glm.vec3(0, 0, 1)) mvp = proj * view * model GL.glUniformMatrix4fv(self.UNIFORM_LOCATIONS['mvp'], 1, False, glm.value_ptr(mvp)) # Update data self.pos_vbo.set_array(self.pos) self.col_vbo.set_array(self.col) # Point size GL.glPointSize(2) # Position self.pos_vbo.bind() GL.glEnableVertexAttribArray(0) GL.glVertexAttribPointer(0, 3, GL.GL_FLOAT, GL.GL_FALSE, 0, None) # Color self.col_vbo.bind() GL.glEnableVertexAttribArray(1) GL.glVertexAttribPointer(1, 3, GL.GL_FLOAT, GL.GL_FALSE, 0, None) # Draw GL.glDrawArrays(GL.GL_POINTS, 0, self.pos.shape[0])
def display(): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) elapsed_ms = glutGet(GLUT_ELAPSED_TIME) projection = glm.perspective(glm.radians(60), aspect, 0.1, 20.0) view = glm.lookAt(glm.vec3(-1, -8, 4), glm.vec3(-1, 0, -1), glm.vec3(0, 0, 1)) angle = 0#elapsed_ms * math.pi * 2 / 10000.0 model = glm.rotate(glm.mat4(1), glm.radians(-30), glm.vec3(0, 0, 1)) model = glm.rotate(model, angle, glm.vec3(0, 1, 0)) model = glm.scale(model, glm.vec3(1, 5, 0.2)) glUniformMatrix4fv(0, 1, GL_FALSE, glm.value_ptr(projection)) glUniformMatrix4fv(1, 1, GL_FALSE, glm.value_ptr(view)) glUniformMatrix4fv(2, 1, GL_FALSE, glm.value_ptr(model)) glUniform3f(10, 50/255, 40/255, 30/255) glUniform3f(11, 200/255, 150/255, 100/255) glUniform1f(12, 1.0) # frequency glUniform1f(13, 10.0) # noiseScale glUniform1f(14, 0.1) # ringScale glUniform1f(15, 1.0) # contrast glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, None) glutSwapBuffers() glutPostRedisplay()
def update_gl(): Camera.model = glm.scale( glm.mat4(), glm.vec3(Config.scale, Config.scale, Config.scale)) Camera.position = -glm.normalize( glm.vec3( math.cos(math.radians(Camera._yaw)) * math.cos(math.radians(Camera._pitch)), math.sin(math.radians(Camera._pitch)), math.sin(math.radians(Camera._yaw)) * math.cos(math.radians(Camera._pitch)))) Camera.projection = glm.perspective( math.radians(Camera._field_of_view), Config.width / Config.height, 0.1, 100) Camera.view = glm.lookAt(Camera.position, glm.vec3(), Camera.camera_up) Program.forward_mat4("model", Camera.model) Program.forward_mat4("projection", Camera.projection) Program.forward_mat4("view", Camera.view) Program.forward_vec3("camera_position", Camera.position) ShadowProgram.forward_mat4("model", Camera.model) ShadowProgram.forward_mat4("projection", Camera.projection) ShadowProgram.forward_mat4("view", Camera.view) ShadowProgram.forward_vec3("camera_position", Camera.position)
def testLookAt(self): lookNGL = pyngl.lookAt(pyngl.Vec3(2.0, 2.0, 2.0), pyngl.Vec3(0, 0, 0), pyngl.Vec3(0, 1.0, 0)) lookGLM = glm.lookAt(glm.vec3(2.0, 2.0, 2.0), glm.vec3(0.0, 0.0, 0.0), glm.vec3(0.0, 1.0, 0.0)) self.assertTrue(self.glmToNGL(lookGLM) == lookNGL)
def set_state_shadowmap(self, shader): view = glm.lookAt(self.position, self.position - self.front, self.up) if self.type == 'directional': projection = glm.ortho( -self.swidth / 2, self.swidth / 2, -self.swidth / 2, self.swidth / 2, self.snear, self.sfar ) elif self.type == 'point': projection = glm.perspective( math.pi / 2, 1., self.snear, self.sfar ) else: projection = glm.perspective( 2 * self.outer_cone, 1., self.snear, self.sfar ) prefix = self.get_uniform_name('') shader[prefix + 'shadowmap_projection'] = flatten(projection * view)
def cameraView(self): r = (self.camPosition.x**2 + self.camPosition.z**2)**0.5 self.camPosition.x = r * math.cos(self.angle * math.pi / 180) self.camPosition.z = r * math.sin(self.angle * math.pi / 180) self.viewMatrix = glm.lookAt( self.camPosition, self.modelList[self.activeModelIndex].position, glm.vec3(0, 1, 0))
def render(window): global program, vao, indices, cube_positions GLFW.glfwPollEvents() GL.glViewport(0, 0, window.width, window.height) cameraPos = GLM.vec3(0.0, 0.0, 3.0) cameraTarget = GLM.vec3(0.0, 0.0, 0.0) cameraDirection = GLM.normalize(cameraPos - cameraTarget) up = GLM.vec3(0.0, 1.0, 0.0) cameraRight = GLM.normalize(GLM.cross(up, cameraDirection)) cameraUp = GLM.cross(cameraDirection, cameraRight) view = GLM.lookAt(GLM.vec3(0.0, 0.0, 3.0), GLM.vec3(0.0, 0.0, 0.0), GLM.vec3(0.0, 1.0, 0.0)) GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) program.useProgram() view = GLM.mat4(1.0) view = GLM.translate(view, GLM.vec3(0.0, 0.0, -3.0)) projection = GLM.perspective(GLM.radians(45.0), window.width / window.height, 0.1, 100.0) program.setMat4("projection", projection) for w in range(10): radius = 10.0 camX = MATH.sin(GLFW.glfwGetTime()) * radius camZ = MATH.cos(GLFW.glfwGetTime()) * radius view = GLM.lookAt(GLM.vec3(camX, 0.0, camZ), GLM.vec3(0.0, 0.0, 0.0), GLM.vec3(0.0, 1.0, 0.0)) model = GLM.mat4(1.0) model = GLM.translate(model, cube_positions[w]) model = GLM.rotate(model, GLM.radians(20.0 * w), GLM.vec3(1.0, 0.3, 0.5)) program.setMat4("model", model) program.setMat4("view", view) vao.useVAO(program) GL.glDrawArrays(GL.GL_TRIANGLES, 0, 36) vao.unBind() GLFW.glfwSwapBuffers(window.getWindow())
def key_callback(window, key, scancode, action, mods): if key == glfw.KEY_UP and action == glfw.PRESS: myCamera.camPos = myCamera.camPos + (myCamera.camSpeed * myCamera.camFront) view = glm.lookAt(myCamera.camPos, myCamera.camPos + myCamera.camFront, myCamera.camUp) MVP_loc = glGetUniformLocation(myShader.ID, 'MVP') MVP = projection * view * model * translate glUniformMatrix4fv(MVP_loc, 1, GL_FALSE, glm.value_ptr(MVP)) print("UP KEY PRESSED") print(myCamera.camPos) if key == glfw.KEY_DOWN and action == glfw.PRESS: myCamera.camPos = myCamera.camPos - (myCamera.camSpeed * myCamera.camFront) view = glm.lookAt(myCamera.camPos, myCamera.camPos + myCamera.camFront, myCamera.camUp) MVP_loc = glGetUniformLocation(myShader.ID, 'MVP') MVP = projection * view * model * translate glUniformMatrix4fv(MVP_loc, 1, GL_FALSE, glm.value_ptr(MVP)) print("DOWN KEY PRESSED") if key == glfw.KEY_RIGHT and action == glfw.PRESS: myCamera.camPos = myCamera.camPos + glm.normalize( glm.cross(myCamera.camFront, myCamera.camUp) * myCamera.camSpeed) view = glm.lookAt(myCamera.camPos, myCamera.camPos + myCamera.camFront, myCamera.camUp) MVP_loc = glGetUniformLocation(myShader.ID, 'MVP') MVP = projection * view * model * translate glUniformMatrix4fv(MVP_loc, 1, GL_FALSE, glm.value_ptr(MVP)) print("RIGHT KEY PRESSED") if key == glfw.KEY_LEFT and action == glfw.PRESS: myCamera.camPos = myCamera.camPos - glm.normalize( glm.cross(myCamera.camFront, myCamera.camUp) * myCamera.camSpeed) view = glm.lookAt(myCamera.camPos, myCamera.camPos + myCamera.camFront, myCamera.camUp) MVP_loc = glGetUniformLocation(myShader.ID, 'MVP') MVP = projection * view * model * translate glUniformMatrix4fv(MVP_loc, 1, GL_FALSE, glm.value_ptr(MVP)) print("LEFT KEY PRESSED")
def init(self, opengl_frame): self.__glsl_vert = phong_vert self.__glsl_frag = phong_frag mesh_defs = [ triangulated_mesh.Tetrahedron(), triangulated_mesh.Cube(), triangulated_mesh.Octahedron(), triangulated_mesh.Dodecahedron(), triangulated_mesh.Icosahedron(), triangulated_mesh.Tube(), triangulated_mesh.Cone(), triangulated_mesh.SphereSlice(), triangulated_mesh.SphereTessellated(), triangulated_mesh.Torus(), triangulated_mesh.TrefoilKnot(), triangulated_mesh.TorusKnot(), triangulated_mesh.Arrow() ] self.__tkinter_navigation = TkinterNavigation( opengl_frame, glm.lookAt(glm.vec3(0, 0, 2), glm.vec3(0, 0, 0), glm.vec3(0, 1, 0)), 90, 0.1, 100, lambda x, y: glReadPixels( x, y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT)) self.__program = compileProgram( compileShader(self.__glsl_vert, GL_VERTEX_SHADER), compileShader(self.__glsl_frag, GL_FRAGMENT_SHADER), ) self.___attrib = { a: glGetAttribLocation(self.__program, a) for a in ['a_pos', 'a_nv', 'a_col'] } print(self.___attrib) self.___uniform = { u: glGetUniformLocation(self.__program, u) for u in ['u_model', 'u_view', 'u_proj'] } print(self.___uniform) self.__ssbo = glGenBuffers(1) glBindBuffer(GL_SHADER_STORAGE_BUFFER, self.__ssbo) glBufferData(GL_SHADER_STORAGE_BUFFER, 4 * 16 * len(mesh_defs), None, GL_STATIC_DRAW) glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, self.__ssbo) self.__meshes = [SingleMesh(definition) for definition in mesh_defs] self.__multimesh = MultiMesh(mesh_defs, *mesh_defs[0].format) glEnable(GL_DEPTH_TEST) glUseProgram(self.__program) glEnable(GL_CULL_FACE) glFrontFace(GL_CCW) glCullFace(GL_BACK)
def draw_scene(scene): global framecount glClearColor(0.0, 0.0, 0.0, 0.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) if scene is None: return glUseProgram(0) if scene.current_player_ent is None: transform = Transform(None) else: transform = scene.current_player_ent.transform cam_transform = transform.clone() cam_transform.translate_local(np.array([0, 30, 0])) perspective_mat = glm.perspective(glm.radians(90.0), screen_utils.aspect_ratio(), 0.1, 100000.0) tmat = cam_transform._get_translation_matrix() rmat = cam_transform._get_rotation_matrix( ) # fine as long as we never pitch a = tmat.dot(rmat.dot(matrix.create_translation_matrix([1, 0, 0]))) b = tmat.dot(rmat.dot(matrix.create_translation_matrix([0, 1, 0]))) cam_vec = glm.vec3((matrix.translation_from_matrix( cam_transform.to_model_view_matrix()))[:3]) point_at = glm.vec3(matrix.translation_from_matrix(a)[:3]) up_vec = glm.normalize( glm.vec3(matrix.translation_from_matrix(b)[:3]) - cam_vec) view_mat = glm.lookAt(cam_vec, point_at, up_vec) model_mat = np.identity( 4, dtype='float32') # by default, no transformations applied update_all_uniform('modelViewMatrix', [1, GL_FALSE, model_mat]) update_all_uniform('viewMatrix', [1, GL_FALSE, np.array(view_mat)]) update_all_uniform('projectionMatrix', [1, GL_FALSE, np.array(perspective_mat)]) update_all_uniform('time', [framecount / screen_utils.MAX_FPS]) # seconds light_pos = [ np.sin(framecount * 0.01) * 5, np.cos(framecount * 0.01) * 5, np.cos(framecount * 0.001) ] update_all_uniform('light_pos', light_pos) scene.bind_scene_vao() for element in scene.entities: if element is None: continue if element.is_renderable() and element.mesh.is_scene_mesh: element.mesh.render_scene_mesh(scene, element.transform) for element in scene.entities: if element is None: continue if element.is_renderable(): if not element.mesh.is_scene_mesh: element.mesh.render(element.transform) framecount += 1
def __init__(self, width=1280, height=720, title="puregl-viewer", floating=False): self.width, self.height = width, height self.title = title self.events = {'on_setup':[], 'on_draw':[]} # Handle window events # ------------- self.view = glm.lookAt(glm.vec3(2,2,4), glm.vec3(0,0,0), glm.vec3(0,1,0)) self.projection = glm.perspective(glm.radians(48.5), self.width/self.height,0.1,30)
def getMatrix(self, camera_pos, projection, camera_rot): i = glm.mat4(1) translate = glm.translate(i, glm.vec3(0, 0, 0)) pitch = glm.rotate(i, glm.radians(self.rotation.x), glm.vec3(1, 0, 0)) yaw = glm.rotate(i, glm.radians(self.rotation.y), glm.vec3(0, 1, 0)) roll = glm.rotate(i, glm.radians(self.rotation.z), glm.vec3(0, 0, 1)) rotate = pitch * yaw * roll scale = glm.scale(i, self.scale) view = glm.lookAt(camera_pos, self.position, glm.vec3(0, 1, 0)) return translate * rotate * scale
def __init__(self, ortho=True): self.ortho = ortho self.camera_loc = glm.vec3(0.0, 0.0, 1.0) self.camera_lookat = glm.vec3(0.0, 0.0, 0.0) self.camera_up = glm.vec3(0.0, 1.0, 0.0) self.view_mat = glm.lookAt(self.camera_loc, self.camera_lookat, self.camera_up) self.proj_mat = glm.ortho(-1.0, 1.0, -1.0, 1.0, 0.1, 100.0) gl.glEnable(gl.GL_DEPTH_TEST)
def createTheMatrix(counter): translate = glm.translate(i, glm.vec3(0, 0, 0)) rotate = glm.rotate(i, glm.radians(counter), glm.vec3(0, 1, 0)) scale = glm.scale(i, glm.vec3(1, 1, 1)) model = translate * rotate * scale view = glm.lookAt(glm.vec3(0, 0, 200), glm.vec3(0, 0, 0), glm.vec3(0, 1, 0)) projection = glm.perspective(glm.radians(45), 800/600, 0.1, 1000) return projection * view * model
def get_view_matrix(self): '''print('camera_pos',self.camera_pos) print('camera_front',self.camera_front) print('camera_up',self.camera_up) print('camera_right', self.camera_right)''' return np.array(glm.lookAt(self.camera_pos, self.camera_pos + self.camera_front, self.camera_up), dtype=np.float32)
def __update_shader_parameters(self): view_matrix_loc = GL.glGetUniformLocation(self.__shader_program, "view") view_matrix = glm.lookAt(self.__camera_coords, self.__camera_coords + self.__camera_front, self.__camera_up) GL.glUniformMatrix4fv(view_matrix_loc, 1, GL.GL_FALSE, np.ascontiguousarray(view_matrix, np.float32)) perspective_matrix = glm.perspective(glm.radians(self.__camera_fov/2), self.frame_width / self.frame_height, 0.1, 200) projection_matrix_loc = GL.glGetUniformLocation(self.__shader_program, "projection") GL.glUniformMatrix4fv(projection_matrix_loc, 1, GL.GL_FALSE, np.ascontiguousarray(perspective_matrix, np.float32))
def look_at(self, time): radius = 2.5e-4 time *= 0.5 camX = math.sin(3 * time) * radius camY = math.sin(2 * time) * radius camZ = math.cos(time) * radius view = glm.lookAt(glm.vec3(camX, camY, camZ), glm.vec3(0.0, 0.0, 0.0), glm.vec3(0.0, 1.0, 0.0)) return view
def paintGL(self): currentTime = self.__timer.elapsed() / 1000.0 self.__deltaTime = currentTime - self.__lastTime self.__lastTime = currentTime # change light position over time self.lightPos[2] = math.cos(currentTime) * 2.0 # 1. Render depth of scene to texture (from light's perspective) # Get light projection/view matrix. near_plane = 1.0 far_plane = 7.5 lightProjection = glm.ortho(-10.0, 10.0, -10.0, 10.0, near_plane, far_plane) #lightProjection = glm.perspective(45.0, float(self.width())/self.height(), near_plane, far_plane) lightView = glm.lookAt(self.lightPos, np.zeros(3, np.float32), np.ones(3, np.float32)) lightSpaceMatrix = lightProjection * lightView # now render scene from light's point of view glUseProgram(self.__simpleDepthShader) glUniformMatrix4fv(glGetUniformLocation(self.__simpleDepthShader, 'lightSpaceMatrix'), 1, GL_FALSE, lightSpaceMatrix) glViewport(0, 0, self.shadowWidth, self.shadowHeight) glBindFramebuffer(GL_FRAMEBUFFER, self.depthMapFBO) glClear(GL_DEPTH_BUFFER_BIT) self.renderScene(self.__simpleDepthShader) glBindFramebuffer(GL_FRAMEBUFFER, 0) # 2. render scene as normal glViewport(0, 0, self.width(), self.height()) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glUseProgram(self.__shader) projection = glm.perspective(self.camera.zoom, float(self.width())/self.height(), 0.1, 100.0) view = self.camera.viewMatrix glUniformMatrix4fv(glGetUniformLocation(self.__shader, 'projection'), 1, GL_FALSE, projection) glUniformMatrix4fv(glGetUniformLocation(self.__shader, 'view'), 1, GL_FALSE, view) # set light uniforms glUniform3fv(glGetUniformLocation(self.__shader, 'lightPos'), 1, self.lightPos) glUniform3fv(glGetUniformLocation(self.__shader, 'viewPos'), 1, self.camera.position) glUniformMatrix4fv(glGetUniformLocation(self.__shader, 'lightSpaceMatrix'), 1, GL_FALSE, lightSpaceMatrix) # Enable/Disable shadows by pressing 'SPACE' glUniform1i(glGetUniformLocation(self.__shader, 'shadows'), self.shadows) glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, self.woodTexture) glActiveTexture(GL_TEXTURE1) glBindTexture(GL_TEXTURE_2D, self.depthMap) self.renderScene(self.__shader) # 3. DEBUG: visualize depth map by rendering it to plane glUseProgram(self.__debugDepthQuad) glUniform1f(glGetUniformLocation(self.__debugDepthQuad, 'near_plane'), near_plane) glUniform1f(glGetUniformLocation(self.__debugDepthQuad, 'far_plane'), far_plane) glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, self.depthMap) #self.renderQuad() # uncomment this line to see depth map glUseProgram(0)
def paintGL(self): currentTime = self.__timer.elapsed() / 1000.0 self.__deltaTime = currentTime - self.__lastTime self.__lastTime = currentTime # change light position over time #self.lightPos[2] = math.cos(currentTime) * 2.0 # 0. Create depth cubemap transformation matrices aspect = float(self.shadowWidth) / self.shadowHeight near_plane = 1.0 far_plane = 25.0 shadowProj = glm.perspective(90.0, aspect, near_plane, far_plane) shadowTransforms = [] shadowTransforms.append(shadowProj * glm.lookAt(self.lightPos, self.lightPos + np.array([1.0, 0.0, 0.0], np.float32), np.array([0.0, -1.0, 0.0], np.float32))) shadowTransforms.append(shadowProj * glm.lookAt(self.lightPos, self.lightPos + np.array([-1.0, 0.0, 0.0], np.float32), np.array([0.0, -1.0, 0.0], np.float32))) shadowTransforms.append(shadowProj * glm.lookAt(self.lightPos, self.lightPos + np.array([0.0, 1.0, 0.0], np.float32), np.array([0.0, 0.0, 1.0], np.float32))) shadowTransforms.append(shadowProj * glm.lookAt(self.lightPos, self.lightPos + np.array([0.0, -1.0, 0.0], np.float32), np.array([0.0, 0.0, -1.0], np.float32))) shadowTransforms.append(shadowProj * glm.lookAt(self.lightPos, self.lightPos + np.array([0.0, 0.0, 1.0], np.float32), np.array([0.0, -1.0, 0.0], np.float32))) shadowTransforms.append(shadowProj * glm.lookAt(self.lightPos, self.lightPos + np.array([0.0, 0.0, -1.0], np.float32), np.array([0.0, -1.0, 0.0], np.float32))) # shadowTransforms = np.array(shadowTransforms, np.float32) # 1. Render scene to depth cubemap glViewport(0, 0, self.shadowWidth, self.shadowHeight) glBindFramebuffer(GL_FRAMEBUFFER, self.depthMapFBO) glClear(GL_DEPTH_BUFFER_BIT) glUseProgram(self.__simpleDepthShader) for i in range(6): glUniformMatrix4fv(glGetUniformLocation(self.__simpleDepthShader, 'shadowTransforms[{}]'.format(i)), 1, GL_FALSE, shadowTransforms[i]) glUniform1f(glGetUniformLocation(self.__simpleDepthShader, 'far_plane'), far_plane) glUniform3fv(glGetUniformLocation(self.__simpleDepthShader, 'lightPos'), 1, self.lightPos) self.renderScene(self.__simpleDepthShader) glBindFramebuffer(GL_FRAMEBUFFER, 0) # 2. render scene as normal glViewport(0, 0, self.width(), self.height()) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glUseProgram(self.__shader) projection = glm.perspective(self.camera.zoom, float(self.width())/self.height(), 0.1, 100.0) view = self.camera.viewMatrix glUniformMatrix4fv(glGetUniformLocation(self.__shader, 'projection'), 1, GL_FALSE, projection) glUniformMatrix4fv(glGetUniformLocation(self.__shader, 'view'), 1, GL_FALSE, view) # set light uniforms glUniform3fv(glGetUniformLocation(self.__shader, 'lightPos'), 1, self.lightPos) glUniform3fv(glGetUniformLocation(self.__shader, 'viewPos'), 1, self.camera.position) # Enable/Disable shadows by pressing 'SPACE' glUniform1i(glGetUniformLocation(self.__shader, 'shadows'), self.shadows) glUniform1f(glGetUniformLocation(self.__shader, 'far_plane'), far_plane) glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, self.woodTexture) glActiveTexture(GL_TEXTURE1) glBindTexture(GL_TEXTURE_CUBE_MAP, self.depthCubeMap) self.renderScene(self.__shader) glUseProgram(0)
def _update(self): eye = numpy.array((self.angle.sin(), self.elevation.sin(), self.angle.cos())) eye = eye * self.distance / numpy.linalg.norm(eye) target = (0, 0, 0) upv = (0, 1, 0) self._model_view = glm.lookAt(eye, target, upv) fovy = 70.0 * (math.pi / 180.0) aspect = self.aspect_ratio() near = 0.1 far = 100.0 self._proj = glm.perspective(fovy, aspect, near, far) self._mvp = self._proj * self._model_view
def viewMatrix(self): return glm.lookAt(self.position, self.position + self.front, self.up)
def testLookAt(self) : lookNGL=pyngl.lookAt(pyngl.Vec3(2.0,2.0,2.0),pyngl.Vec3(0,0,0),pyngl.Vec3(0,1.0,0)) lookGLM=glm.lookAt(glm.vec3(2.0,2.0,2.0),glm.vec3(0.0,0.0,0.0),glm.vec3(0.0,1.0,0.0)) self.assertTrue(self.glmToNGL(lookGLM)==lookNGL)