def updateUniformBuffers(self): self.uboVS['projection'] = glm.transpose( glm.perspectiveRH_ZO(glm.radians(60.0), self.width / self.height, 0.001, 256.0)) view = glm.transpose( glm.translate(glm.mat4(1.0), glm.vec3(0.0, 0.0, self.zoom))) self.uboVS['model'] = view * glm.translate(glm.mat4(1.0), self.cameraPos) self.uboVS['model'] = glm.rotate(self.uboVS['model'], glm.radians(self.rotation.x), glm.vec3(1.0, 0.0, 0.0)) self.uboVS['model'] = glm.rotate(self.uboVS['model'], glm.radians(self.rotation.y), glm.vec3(0.0, 1.0, 0.0)) self.uboVS['model'] = glm.rotate(self.uboVS['model'], glm.radians(self.rotation.z), glm.vec3(0.0, 0.0, 1.0)) self.uboVS['viewPos'] = glm.vec4(0.0, 0.0, -self.zoom, 0.0) uboVSSize = sum([glm.sizeof(ubo) for ubo in self.uboVS.values()]) uboVSBuffer = np.concatenate( (np.array(self.uboVS['projection']).flatten(order='C'), np.array(self.uboVS['model']).flatten(order='C'), np.array(self.uboVS['viewPos']).flatten(order='C'), np.array(self.uboVS['lodBias']).flatten(order='C'))) self.uniformBufferVS.map() self.uniformBufferVS.copyTo(uboVSBuffer, uboVSSize) self.uniformBufferVS.unmap()
def updateUniformBuffers(self): # see https://matthewwellings.com/blog/the-new-vulkan-coordinate-system/ #vulk=glm.mat4((1,0,0,0),(0,-1,0,0),(0,0,0.5,0),(0,0,0.5,1)) #self.uboVS['projectionMatrix'] = vulk*glm.perspective(glm.radians(60.0), self.width / self.height, 0.1, 256.0) #self.uboVS['projectionMatrix'] = glm.perspectiveRH_ZO(glm.radians(60.0), self.width / self.height, 0.1, 256.0) self.uboVS['projectionMatrix'] = glm.transpose( glm.perspectiveRH_ZO(glm.radians(60.0), self.width / self.height, 0.1, 256.0)) self.uboVS['viewMatrix'] = glm.transpose( glm.translate(glm.mat4(1.0), glm.vec3(0.0, 0.0, self.zoom))) self.uboVS['modelMatrix'] = glm.mat4(1.0) self.uboVS['modelMatrix'] = glm.rotate(self.uboVS['modelMatrix'], glm.radians(self.rotation.x), glm.vec3(1.0, 0.0, 0.0)) self.uboVS['modelMatrix'] = glm.rotate(self.uboVS['modelMatrix'], glm.radians(self.rotation.y), glm.vec3(0.0, 1.0, 0.0)) self.uboVS['modelMatrix'] = glm.rotate(self.uboVS['modelMatrix'], glm.radians(self.rotation.z), glm.vec3(0.0, 0.0, 1.0)) uboVSSize = sum([glm.sizeof(ubo) for ubo in self.uboVS.values()]) uboVSBuffer = np.concatenate( (np.array(self.uboVS['projectionMatrix']).flatten(order='C'), np.array(self.uboVS['modelMatrix']).flatten(order='C'), np.array(self.uboVS['viewMatrix']).flatten(order='C'))) data = vk.vkMapMemory(self.device, self.uniformBufferVS['memory'], 0, uboVSSize, 0) datawrapper = np.array(data, copy=False) np.copyto(datawrapper, uboVSBuffer.view(dtype=np.uint8), casting='no') vk.vkUnmapMemory(self.device, self.uniformBufferVS['memory'])
def draw(self, uProjection, uView, uModel): """ Set uniforms in the shader and render the object :param uProjection: :param uView: :param uModel: :return: """ self.material.bind() self.material.shader.set_uniform_mat4f("uProjection", glm.transpose(uProjection)) self.material.shader.set_uniform_mat4f("uView", glm.transpose(uView)) self.material.shader.set_uniform_mat4f("uModel", glm.transpose(uModel)) Renderer.draw(self.vao, self.ibo if self.ibo is not None else self.vbo, self.material.shader)
def link_matrices(self, model_matrix): self._shader.link_mat4("projectionMatrix", self._projection_matrix.to_list()) self._shader.link_mat4("viewMatrix", self._view_matrix.to_list()) self._normal_matrix = model_matrix self._normal_matrix = glm.transpose(self._normal_matrix) self._shader.link_mat4("normalMatrix", self._normal_matrix.to_list())
def update0(): global camera_matrix, move_matrix camera_matrix = glm.translate( mat4( make_camera_orientation_matrix(rotation_ypr.x, rotation_ypr.y, rotation_ypr.z)), -position) move_matrix = glm.transpose( make_camera_orientation_matrix(rotation_ypr.x, 0.0, 0.0))
def load_animations(self, file, correction): root = xml.parse(file).getroot() anim = root.find('library_animations').find('animation') root_ptr = self.get_child_with_attribute( root.find('library_visual_scenes').find('visual_scene'), 'node', 'id', 'Armature' ) if root_ptr != None: root_joint = root_ptr.find('node').attrib['id'] else: root_joint = root.find('library_visual_scenes').find('visual_scene').find('node').attrib['id'] times = [float(x) for x in ' '.join(anim.find('source').find('float_array').text.split('\n')).split(' ') if x != ''] duration = times[len(times) - 1] keyframes = [] for time in times: keyframes.append(KeyFrame(time)) for joint_node in root.find('library_animations').findall('animation'): joint_name_id = joint_node.find('channel').attrib['target'].split('/')[0] data_id = self.get_child_with_attribute( joint_node.find('sampler'), 'input', 'semantic', 'OUTPUT' ).attrib['source'][1:] transforms = [float(x) for x in ' '.join(self.get_child_with_attribute( joint_node, 'source', 'id', data_id ).find('float_array').text.split('\n')).split(' ') if x != ''] for i, time in enumerate(times): matrix = glm.mat4(transforms[i*16:(i+1)*16]) matrix = glm.transpose(matrix) if joint_name_id == root_joint: if correction: corr = glm.rotate(glm.mat4(1.0), glm.radians(90), glm.vec3(1, 0, 0)) else: corr = glm.mat4(1.0) matrix = corr * matrix position = glm.vec3(matrix[3].x, matrix[3].y, matrix[3].z) rotation = glm.quat_cast(matrix) keyframes[i].pose[joint_name_id] = JointTransform(position, rotation) return Animation(duration, keyframes)
def trbl(width, height, anchor_x=0, anchor_y=0, angle=0, scale=1): bb0 = glm.mat4x3(width, height, 1, width, 0, 1, 0, 0, 1, 0, height, 1) bb1 = affine0(angle, scale, anchor_x, anchor_y) @ glm.transpose(bb0) x = bb1[0] y = bb1[1] t, r, b, l = max(y), max(x), min(y), min(x) return t, r, b, l
def draw_scene(prog, projection_matrix, view_matrix): """Draw scen with a shader program""" program.set_uniform(prog, 'projectionMatrix', projection_matrix) program.set_uniform(prog, 'viewMatrix', view_matrix) camera_pos = glm.inverse(view_matrix)[3].xyz program.set_uniform(prog, 'cameraPos', camera_pos) model_matrix = glm.translate(glm.mat4(1), (-1, 0.5, 0)) normal_matrix = glm.mat3(glm.transpose(glm.inverse(model_matrix))) program.set_uniform(prog, 'modelMatrix', model_matrix) program.set_uniform(prog, 'normalMatrix', normal_matrix) imdraw.cube(prog) model_matrix = glm.translate(glm.mat4(1), (1, 0, 0)) normal_matrix = glm.mat3(glm.transpose(glm.inverse(model_matrix))) program.set_uniform(prog, 'modelMatrix', model_matrix) program.set_uniform(prog, 'normalMatrix', normal_matrix) imdraw.sphere(prog) model_matrix = glm.mat4(1) normal_matrix = glm.mat3(glm.transpose(glm.inverse(model_matrix))) program.set_uniform(prog, 'modelMatrix', model_matrix) program.set_uniform(prog, 'normalMatrix', normal_matrix) imdraw.plane(prog)
def update_frustum(self, mat): mat = glm.transpose(mat) for i in range(4): Frustum.left[i] = mat[3][i] + mat[0][i] Frustum.right[i] = mat[3][i] - mat[0][i] Frustum.bottom[i] = mat[3][i] + mat[1][i] Frustum.top[i] = mat[3][i] - mat[1][i] Frustum.near[i] = mat[3][i] + mat[2][i] Frustum.far[i] = mat[3][i] - mat[2][i] Frustum.left = normalize(Frustum.left) Frustum.right = normalize(Frustum.right) Frustum.bottom = normalize(Frustum.bottom) Frustum.top = normalize(Frustum.top) Frustum.near = normalize(Frustum.near) Frustum.far = normalize(Frustum.far)
def intersect(self, ray, hit, tmin): minverse = glm.inverse(self.matrix) tdir4 = minverse * glm.vec4(ray.direction, 0.0) tdir3 = tdir4.xyz if tdir4.w != 0.0: tdir3 = tdir3 / tdir4.w torig4 = minverse * glm.vec4(ray.origin, 1.0) torig3 = torig4.xyz / torig4.w hit = self.primitive.intersect(Ray(torig3, tdir3), hit, tmin) if hit: hit.normal = (glm.transpose(minverse) * glm.vec4(hit.normal, 1.0)).xyz return hit
def from_trimesh_scene(triscene): import uuid import logging from editor.render.graphics import Scene, Mesh, Geometry, Material # read scene scene = Scene() # convert gltf for name, data in triscene.graph.transforms.nodes(data=True): # extract transform import glm transform = glm.mat4(triscene.graph[name][0]) # extract mesh hasGeometry = 'geometry' in data if hasGeometry: trigeo = triscene.geometry[data['geometry']] print("!!!!!!!!!!", name) print(transform) # geometry geometry = Geometry( positions=trigeo.vertices.astype(np.float32), indices=trigeo.faces.astype(np.uint), normals=trigeo.vertex_normals.astype(np.float32), uvs=trigeo.visual.uv.astype(np.float32)) # material print("!!!!!!!!!!", trigeo.visual.material.baseColorFactor) material = Material( albedo=glm.vec3( *trigeo.visual.material.baseColorFactor[:3] / 255), emission=trigeo.visual.material.emissiveFactor[:3] / 255, roughness=float(trigeo.visual.material.roughnessFactor), metallic=float(trigeo.visual.material.metallicFactor)) scene.add_child( Mesh(name=name, transform=glm.transpose(transform), geometry=geometry, material=material)) else: logging.warning("currently only supports mesh") # extract light return scene
def load_joint(self, node, joints, correction, is_root, indent): name_id = node.attrib['id'] index = joints.index(name_id) matrix_data = [float(x) for x in node.find('matrix').text.split(' ')] matrix = glm.mat4(matrix_data) matrix = glm.transpose(matrix) if is_root: if correction: corr = glm.rotate(glm.mat4(1.0), glm.radians(90), glm.vec3(1, 0, 0)) else: corr = glm.mat4(1.0) matrix = corr * matrix j = Joint(index, name_id, matrix) self.joint_count += 1 for child in node.findall('node'): if child.attrib['id'] in joints: j.children.append(self.load_joint(child, joints, 0, False, ' '+indent)) return j
numpy_create_mat4 = lambda: numpy.identity(4, dtype=numpy.float32) glm_v3 = glm.vec3() numpy_v3 = numpy.array((0, 0, 0), dtype=numpy.float32) glm_v4 = glm.vec4() numpy_v4 = numpy.zeros( (4, ), dtype=numpy.float32) #numpy.array((0,0,0,0), dtype=numpy.float32) glm_m44 = glm.mat4() numpy_m44 = numpy.identity(4, dtype=numpy.float32) glm_dot = lambda: glm.dot(glm_v3, glm_v3) numpy_dot = lambda: numpy.vdot(numpy_v3, numpy_v3) glm_transpose = lambda: glm.transpose(glm_m44) numpy_transpose = lambda: numpy.transpose(numpy_m44) glm_mul_v4_v4 = lambda: glm_v4 * glm_v4 numpy_mul_v4_v4 = lambda: numpy_v4 * numpy_v4 glm_mul_m44_v4 = lambda: glm_m44 * glm_v4 numpy_mul_m44_v4 = lambda: numpy_m44 * numpy_v4 glm_mat4_getitem = lambda: glm_m44[0] numpy_mat4_getitem = lambda: numpy_m44[0] print("How PyGLM's performance roughly compares to NumPy's performance:") print("instruction\t | np speed (%)\t | glm speed (%)\t ")
model_matrix = np.identity(4) window = GLFWViewer(width, height, (0.6, 0.7, 0.7, 1.0)) with window: glEnable(GL_DEPTH_TEST) glEnable(GL_CULL_FACE) while not window.should_close(): glViewport(0, 0, window.width, window.height) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) with program.use(skybox_program): program.set_uniform(skybox_program, 'projection', window.projection_matrix) sky_view = glm.mat4(glm.mat3(window.view_matrix)) program.set_uniform(skybox_program, 'view', sky_view) camera_pos = glm.transpose( glm.transpose(glm.inverse(window.view_matrix)))[3].xyz program.set_uniform(skybox_program, 'cameraPos', camera_pos) program.set_uniform(skybox_program, 'skybox', 0) program.set_uniform(skybox_program, 'groundProjection', True) glActiveTexture(GL_TEXTURE0 + 0) glBindTexture(GL_TEXTURE_CUBE_MAP, env_cubemap) imdraw.cube(skybox_program, flip=True) glBindTexture(GL_TEXTURE_CUBE_MAP, 0) glDepthMask(GL_TRUE) # draw grid window.swap_buffers() GLFWViewer.poll_events()
def main(): window = create_window() shader_program, shaders, uniforms = setup_shaders() vao, vbo, ebo = setup_vertices() texture_index_diffuse = 0 texture_diffuse = load_texture('data/Gravel020_1K_Color.jpg', texture_index_diffuse) texture_index_normal = 1 texture_normal = load_texture('data/Gravel020_1K_Normal.jpg', texture_index_normal) # render setup proj_mat = glm.perspective(45.0, SCREEN_WIDTH / SCREEN_HEIGHT, 0.01, 100) view_mat = glm.lookAt(glm.vec3(0.8, 0.0, 0.8), glm.vec3(0, 0, 0), glm.vec3(0, 0, 1)) model_mat = glm.translate(glm.identity(glm.fmat4), glm.vec3(-1, 0, -1)) normal_mat = glm.inverse(model_mat * glm.transpose(view_mat)) render_parameters = {} # key callback def handle_key(window, key, scancode, action, mods): if action == glfw.PRESS: if key == glfw.KEY_ESCAPE: glfw.set_window_should_close(window, True) glfw.set_key_callback(window, handle_key) # loop until the user closes the window while not glfw.window_should_close(window): # render gl.glClearColor(0, 0, 0, 1) gl.glClear(gl.GL_COLOR_BUFFER_BIT) gl.glUseProgram(shader_program) gl.glUniform1i(uniforms[DIFFUSE_TEXTURE_UNIFORM], texture_index_diffuse) gl.glUniform1i(uniforms[NORMAL_MAP_UNIFORM], texture_index_normal) gl.glActiveTexture(gl.GL_TEXTURE0 + texture_index_diffuse) gl.glBindTexture(gl.GL_TEXTURE_2D, texture_diffuse) gl.glActiveTexture(gl.GL_TEXTURE0 + texture_index_normal) gl.glBindTexture(gl.GL_TEXTURE_2D, texture_normal) gl.glUniformMatrix4fv(uniforms[PROJ_MAT_UNIFORM], 1, gl.GL_FALSE, glm.value_ptr(proj_mat)) gl.glUniformMatrix4fv(uniforms[VIEW_MAT_UNIFORM], 1, gl.GL_FALSE, glm.value_ptr(view_mat)) gl.glUniformMatrix4fv(uniforms[MODEL_MAT_UNIFORM], 1, gl.GL_FALSE, glm.value_ptr(model_mat)) gl.glUniformMatrix4fv(uniforms[NORMAL_MAT_UNIFORM], 1, gl.GL_FALSE, glm.value_ptr(normal_mat)) gl.glBindVertexArray(vao) gl.glDrawElements(gl.GL_TRIANGLES, 6, gl.GL_UNSIGNED_INT, None) gl.glBindVertexArray(0) # shader logs for i, shader in enumerate(shaders): shader_log = gl.glGetShaderInfoLog(shader) if shader_log != '': print('vertex' if shader == 1 else 'fragment') print(shader_log) glfw.swap_buffers(window) glfw.poll_events() # gl.glReadBuffer(gl.GL_FRONT) # pixels = gl.glReadPixels(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, gl.GL_RGBA, gl.GL_FLOAT) # img = np.frombuffer(pixels, np.float32) # img = img.reshape((SCREEN_WIDTH, SCREEN_HEIGHT, -1)) # img = img[::-1, :] # img = Image.fromarray(np.uint8(img * 255)).convert('RGB') # cleanup gl.glDeleteVertexArrays(1, vao) gl.glDeleteBuffers(1, vbo) gl.glDeleteBuffers(1, ebo) gl.glDeleteTextures(texture_diffuse) gl.glDeleteTextures(texture_normal) gl.glDeleteProgram(shader_program) glfw.terminate()
def get_diffuse_color(self, face: Face, model: glm.mat4) -> glm.vec3: normal = glm.mat3(glm.transpose(glm.inverse(model))) * face.normal frag_pos = glm.vec3(model * glm.vec4(face.p0, 1.0)) light_dir = glm.normalize(self.position - frag_pos) diff = glm.clamp(glm.dot(normal, light_dir), 0.0, 1.0) return diff * self.color
{ outColor = vec4(0.0, 0.0, 0.0, 1.0); vec3 norm = normalize(vNorm); vec3 light_dir = normalize(vec3(0.2, 0.5, -1.0)); light_dir = reflect(light_dir, norm); if (light_dir.z>0.0) { float intensity = pow(light_dir.z, 5.0)*0.8; outColor += vec4(intensity, intensity, intensity, 0.0); } outColor = clamp(outColor, 0.0, 1.0); } ''')) proj = glm.perspective(glm.radians(45.0), width / height, 0.1, 2000.0) modelView = glm.lookAt(glm.vec3(-100.0, 200.0, 200.0), glm.vec3(0.0, 0.0, 0.0), glm.vec3(0.0, 1.0, 0.0)) mat_pos = vki.SVMat4x4(proj * modelView) mat_norm = vki.SVMat4x4(glm.transpose(glm.inverse(modelView))) rp.launch([len(vertex_inds)], [colorBuf], depthBuf, [0.5, 0.5, 0.5, 1.0], 1.0, [gpuPos, gpuNormals, gpuInd_pos, gpuInd_norm, mat_pos, mat_norm]) image_out = np.empty((height, width, 4), dtype=np.uint8) colorBuf.download(image_out) Image.fromarray(image_out, 'RGBA').save('output.png')
def render(): global stat time = glfw.get_time() sun_angle = 0.2 * time sun_dir = glm.normalize( vec3(-cos(sun_angle), 0.707 * sin(sun_angle), 0.707 * sin(sun_angle))) light_dir = sun_dir light_color = vec3(0.5 * max(0.0, sin(sun_angle))**0.5) ambi_color = vec3(0.6 + 0.4 * sin(sun_angle)) * vec3(0.7, 0.8, 1.0) + vec3( 0.3, 0.2, 0.0) * light_color glClearColor(*(vec3(0.2, 0.4, 0.9) * ambi_color), 0.0) models, textures = np.sum(stat, axis=0) lines = [] lines.append(((0.8, 0.8, 0.8) if vsync else ( 1.0, 0.0, 0.0 ), f'FPS: {fpsmeter.fps:.1f} (vsync {"on" if vsync else "off"}; переключение: V), время с запуска: {time:.0f} с' )) lines.append( ((0.8, 0.8, 0.8), f'Размер дерева: {tree_scale:.1f} (изменение: колёсико мыши)')) lines.append((( 1.0, 1.0, 1.0 ), f'Отрисовка текстурами с дальности {bill_threshold:.0f} (изменение: +/-). Отрисовано моделями: {models}, текстурами: {textures}, всего: {models + textures}' )) ctl_mode = 'полёт' if FLY_CONTROLS else 'обычный' if glfw.get_input_mode(window, glfw.CURSOR) == glfw.CURSOR_DISABLED: lines.append(((0.0, 1.0, 1.0) if FLY_CONTROLS else ( 1.0, 1.0, 1.0 ), f'Режим управления «{ctl_mode}» (мышь, {"стрелочки" if FLY_CONTROLS else "WASD"}, space/shift; переключение: R)' )) lines.append(((1.0, 0.7, 0.0), 'Мышь захвачена (освобождение по Tab)')) else: lines.append(((0.0, 1.0, 1.0) if FLY_CONTROLS else ( 1.0, 1.0, 1.0 ), f'Режим управления «{ctl_mode}» (WASD, space/shift, стрелочки; переключение: R)' )) lines.append(((0.0, 1.0, 0.0), 'Включение мышиного управления: Tab')) lines.append(((1.0, 0.7, 0.0) if FLY_FORWARD else ( 0.8, 0.8, 0.8 ), f'Автополёт {"включён" if FLY_FORWARD else "выключен"} (переключение: F)' )) lines.append( f'Прозрачность: {TRANSPARENCY} (переключение: O); порог: {transparency_threshold} (изменение: //*)' ) overlay.draw(lines) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glMatrixMode(GL_MODELVIEW) glLoadMatrixf(camera_matrix) r = h = 0.5 * tree_scale m = glm.transpose(projection_matrix * camera_matrix) cull_matrix = mat4(m[3] - m[0], m[3] + m[0], m[3] - m[1], m[3] + m[1]) # точно по пирамиде видимости for k in range(4): cull_matrix[k].w += r * glm.length( cull_matrix[k].xyz) # расширение на r cull_matrix = glm.translate(glm.transpose(cull_matrix), vec3( 0.0, 0.0, h)) # сдвиг на h («центр» дерева находится на высоте h) glUseProgram(programs.split) glUniform3fv(0, 1, position) glUniform2f(1, bill_threshold, 1.0) glUniformMatrix4fv(2, 1, False, cull_matrix) glBindBuffer(GL_DRAW_INDIRECT_BUFFER, indbuf) glBufferSubData(GL_DRAW_INDIRECT_BUFFER, 0, indirects) glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, obuf) glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, nbuf) glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, fbuf) glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 3, indbuf) glDispatchCompute(ocount, 1, 1) glMemoryBarrier(GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT | GL_COMMAND_BARRIER_BIT) stat = np.frombuffer(glGetBufferSubData(GL_DRAW_INDIRECT_BUFFER, 0, 36 * 3), dtype='uint32').reshape((-1, 9))[:, (1, 5)] glUseProgram(programs.mesh) glUniformMatrix4fv(0, 1, GL_FALSE, projection_matrix * camera_matrix) glUniformMatrix4fv(1, 1, GL_FALSE, mat4(1.0)) glUniform3fv(2, 1, light_dir) # Солнце =) glPointSize(16.0) glUniform3f(3, 1.0, 1.0, 1.0) glUniform3f(4, 0.0, 0.0, 0.0) glVertexAttrib3fv(0, 1000.0 * sun_dir) glVertexAttrib3f(1, 1.0, 1.0, 1.0) glVertexAttrib3f(2, 0.0, 0.0, 0.0) glVertexAttrib3f(3, 0.0, 0.0, 0.0) glDrawArrays(GL_POINTS, 0, 1) glUniformMatrix4fv(1, 1, GL_FALSE, glm.scale(model_matrix, vec3(tree_scale))) glUniform3fv(3, 1, ambi_color) glUniform3fv(4, 1, light_color) glEnableVertexAttribArray(0) glEnableVertexAttribArray(2) glEnableVertexAttribArray(3) glVertexAttribDivisor(2, 1) glBindBuffer(GL_ARRAY_BUFFER, nbuf) glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 16, ctypes.c_void_p(0)) for k in range(len(ocounts)): for vbuf, ibuf, count, color in meshes[k].bufs: glVertexAttrib3f(1, *color) glBindBuffer(GL_ARRAY_BUFFER, vbuf) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 32, ctypes.c_void_p(0)) glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 32, ctypes.c_void_p(20)) glBindBuffer(GL_ARRAY_BUFFER, 0) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibuf) glBufferSubData(GL_DRAW_INDIRECT_BUFFER, 36 * k, ctypes.c_uint32(count)) glDrawElementsIndirect(GL_TRIANGLES, GL_UNSIGNED_SHORT, ctypes.c_void_p(36 * k)) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) glVertexAttribDivisor(2, 0) glDisableVertexAttribArray(0) glDisableVertexAttribArray(2) glDisableVertexAttribArray(3) glUseProgram(0) glColor3fv( vec3(0.12, 0.10, 0.02) * (ambi_color + max(0.0, light_dir.z) * light_color)) glBegin(GL_QUADS) glVertex2f(-rad, -rad) glVertex2f(-rad, rad) glVertex2f(rad, rad) glVertex2f(rad, -rad) glEnd() glVertexAttrib2f(1, tree_scale, tree_scale) glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, fbuf) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 16, ctypes.c_void_p(0)) glBindBuffer(GL_ARRAY_BUFFER, 0) glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, hstb) glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, cmb) def render_bills(mode): glUniform1i(5, mode) for k in range(len(ocounts)): glBindTextureUnit(0, meshes[k].bill_color) glBindTextureUnit(1, meshes[k].bill_normal) glDrawArraysIndirect(GL_POINTS, ctypes.c_void_p(36 * k + 20)) glUseProgram(programs.bill) glUniformMatrix4fv(0, 1, GL_FALSE, projection_matrix) glUniformMatrix3fv(1, 1, GL_FALSE, mat3(camera_matrix)) glUniform3fv(2, 1, position) glUniform1i(3, v_halfcircle_steps) glUniform1f(4, transparency_threshold) glUniform3fv(6, 1, light_dir) glUniform3fv(7, 1, ambi_color) glUniform3fv(8, 1, light_color) if TRANSPARENCY == 'blend': render_bills(1) elif TRANSPARENCY in ['onepass', 'twopass_depth', 'twopass_color']: if TRANSPARENCY == 'twopass_color': glDisable(GL_BLEND) render_bills(0) glEnable(GL_BLEND) w, h = window_width, window_height glBindFramebuffer(GL_READ_FRAMEBUFFER, 0) glBindFramebuffer(GL_DRAW_FRAMEBUFFER, oit.framebuffer) glBlitFramebuffer(0, 0, w, h, 0, 0, w, h, GL_DEPTH_BUFFER_BIT, GL_NEAREST) glClearBufferfv(GL_COLOR, 0, (0.0, 0.0, 0.0, 0.0)) glClearBufferfv(GL_COLOR, 1, (1.0, 0.0, 0.0, 0.0)) glBlendFunci(0, GL_ONE, GL_ONE) glBlendFunci(1, GL_ZERO, GL_SRC_COLOR) if TRANSPARENCY == 'twopass_depth': glColorMask(False, False, False, False) render_bills(1) glColorMask(True, True, True, True) glDepthMask(False) if TRANSPARENCY == 'twopass_color': glDepthFunc(GL_LESS) glUniform1f(4, 0.0) render_bills(2) else: assert (False) glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0) glDisableVertexAttribArray(0) glBindBuffer(GL_DRAW_INDIRECT_BUFFER, 0) glDisable(GL_DEPTH_TEST) if TRANSPARENCY in ['onepass', 'twopass_depth', 'twopass_color']: glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0) glUseProgram(oit.merge) glBindTextureUnit(0, oit.colors) glBindTextureUnit(1, oit.transparencies) glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA) glDrawArrays(GL_POINTS, 0, 1) glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA) overlay.show() glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA) glUseProgram(0) glEnable(GL_DEPTH_TEST) glDepthFunc(GL_LEQUAL) glDepthMask(True)
def __init__(self, modelMat): self.m_modelMat = modelMat self.m_normMat = glm.transpose(glm.inverse(modelMat))