def display(): ''' Objekte rendern ''' global scale, center, points, vbo # Clear framebuffer glClear(GL_COLOR_BUFFER_BIT) # Render Color glColor(1.0, 1.0, 1.0) # Reset modelview matrix glLoadIdentity() # Rotate glRotate(rotateX, 1, 0, 0) glRotate(rotateY, 0, 1, 0) glRotate(rotateZ, 0, 0, 1) # Scale glScale(scale, scale, scale) # move to center glTranslatef(-center[0], -center[1], -center[2]) # load points vbo.bind() glVertexPointerf(vbo) glEnableClientState(GL_VERTEX_ARRAY) glDrawArrays(GL_POINTS, 0, len(points)) vbo.unbind() glDisableClientState(GL_VERTEX_ARRAY) #swap buffer glutSwapBuffers()
def Render( self, mode): """Render the geometry for the scene.""" if not mode.visible: return final_matrix = dot( self.perspective, self.matrix ) print('final_matrix:\n%s'%(final_matrix)) print('transformed:\n%s'%( dot( self.coord_mult, final_matrix ))) self.glslObject.getVariable( 'transform' ).value = final_matrix token = self.glslObject.render( mode ) tokens = [] vbo = self.indices.bind(mode) try: for attribute in self.attributes: token = attribute.render( self.glslObject, mode ) if token: tokens.append( (attribute, token) ) glDrawElements( GL_TRIANGLES, 3, GL_UNSIGNED_INT, vbo ) finally: for attribute,token in tokens: attribute.renderPost( self.glslObject, mode, token ) self.glslObject.renderPost( token, mode ) '''The index-array VBO also needs to be unbound.''' vbo.unbind()
def Render( self, mode = None): """Render the geometry for the scene.""" if not mode.visible: return for i,light in enumerate( self.lights ): self.LIGHTS[i] = self.lightAsArray( light ) self.glslObject.getVariable( 'lights' ).value = self.LIGHTS for key,value in self.materialFromAppearance( self.appearance, mode ).items(): self.glslObject.getVariable( key ).value = value token = self.glslObject.render( mode ) tokens = [ ] try: vbo = self.indices.bind(mode) for attribute in self.attributes: token = attribute.render( self.glslObject, mode ) if token: tokens.append( (attribute, token) ) '''The final parameter to glDrawElementsInstanced simply tells the GL how many instances to generate. gl_InstanceIDARB values will be generated for range( instance_count ) instances.''' glDrawElementsInstanced( GL_TRIANGLES, self.count, GL_UNSIGNED_INT, vbo, len(self.offset_array), # number of instances to draw... ) finally: for attribute,token in tokens: attribute.renderPost( self.glslObject, mode, token ) self.glslObject.renderPost( token, mode ) vbo.unbind()
def recursive_render(self, node, shader): for mesh in node.meshes: stride = 32 diffuse = mesh.material.properties["diffuse"] if len(diffuse) == 3: diffuse.append(1.0) ambient = mesh.material.properties["ambient"] if len(ambient) == 3: ambient.append(1.0) specular = mesh.material.properties["specular"] if len(specular) == 3: specular.append(1.0) shininess = mesh.material.properties["shininess"] Material_diffuse = glGetUniformLocation(shader,"Material_diffuse") Material_ambient = glGetUniformLocation(shader,"Material_ambient") Material_specular = glGetUniformLocation(shader,"Material_specular") Material_shininess = glGetUniformLocation(shader, "shininess") glUniform4f(Material_diffuse, *diffuse) glUniform4f(Material_ambient, *ambient) glUniform4f(Material_specular, *specular) glUniform1f(Material_shininess, shininess) vbo = mesh.gl["vbo"] vbo.bind() glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); glEnableVertexAttribArray(3); glVertexAttribPointer(1, 3, GL_FLOAT, False, stride, vbo ) glVertexAttribPointer(2, 3, GL_FLOAT, False, stride, vbo + 12 ) glVertexAttribPointer(3, 2, GL_FLOAT, False, stride, vbo + 24 ) if(('file', 1L) in mesh.material.properties): file_name = mesh.material.properties[('file', 1L)] texture_gl_id = (self.texture_files[file_name])[1] texture_slot = glGetUniformLocation(shader, "texture"); glBindTexture(GL_TEXTURE_2D, texture_gl_id) glUniform1i(texture_slot, texture_gl_id-1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.gl["faces"]) glDrawElements(GL_TRIANGLES, len(mesh.faces) * 3, GL_UNSIGNED_INT, None) vbo.unbind(); glDisableVertexAttribArray(1) glDisableVertexAttribArray(2) glDisableVertexAttribArray(3) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) glBindTexture(GL_TEXTURE_2D, 0) for child in node.children: self.recursive_render(child, shader)
def recursive_render(self, node, shader): """ Main recursive rendering method. """ # save model matrix and apply node transformation glPushMatrix() m = node.transformation.transpose() # OpenGL row major glMultMatrixf(m) for mesh in node.meshes: stride = 24 # 6 * 4 bytes diffuse = mesh.material.properties["diffuse"] if len(diffuse) == 3: diffuse.append(1.0) ambient = mesh.material.properties["ambient"] if len(ambient) == 3: ambient.append(1.0) glUniform4f( shader.Material_diffuse, *diffuse ) glUniform4f( shader.Material_ambient, *ambient ) vbo = mesh.gl["vbo"] vbo.bind() glEnableVertexAttribArray( shader.Vertex_position ) glEnableVertexAttribArray( shader.Vertex_normal ) glVertexAttribPointer( shader.Vertex_position, 3, GL_FLOAT,False, stride, vbo ) glVertexAttribPointer( shader.Vertex_normal, 3, GL_FLOAT,False, stride, vbo+12 ) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.gl["faces"]) glDrawElements(GL_TRIANGLES, len(mesh.faces) * 3, GL_UNSIGNED_INT, None) vbo.unbind() glDisableVertexAttribArray( shader.Vertex_position ) glDisableVertexAttribArray( shader.Vertex_normal ) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) for child in node.children: self.recursive_render(child, shader) glPopMatrix()
def recursive_render(self, node, shader): """ Main recursive rendering method. """ try: m = get_world_transform(self.scene, node) except AttributeError: #probably a new incoming node, that has not yet been converted to numpy self.glize(node) m = get_world_transform(self.scene, node) if node.type == MESH: # if the node has been recently turned into a mesh, we might not # have the mesh data yet. if not hasattr(node, "glmeshes"): self.glize(node) for id in node.glmeshes: stride = 12 # 3 * 4 bytes colorid = self.node2colorid[node] r,g,b= self.get_rgb_from_colorid(colorid) glUniform4f( shader.u_materialDiffuse, r/255.0,g/255.0,b/255.0,1.0 ) glUniformMatrix4fv( shader.u_modelMatrix, 1, GL_TRUE, m ) vbo = self.meshes[id]["vbo"] vbo.bind() glEnableVertexAttribArray( shader.a_vertex ) glVertexAttribPointer( shader.a_vertex, 3, GL_FLOAT,False, stride, vbo ) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.meshes[id]["faces"]) glDrawElements(GL_TRIANGLES, self.meshes[id]["nbfaces"] * 3, GL_UNSIGNED_INT, None) vbo.unbind() glDisableVertexAttribArray( shader.a_vertex ) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) for child in node.children: try: self.recursive_render(self.scene.nodes[child], shader) except KeyError as ke: logger.warning("Node ID %s listed as child of %s, but it" " does not exist! Skipping it" % (child, repr(node)))
def display(): global vbo glClear(GL_COLOR_BUFFER_BIT) glColor3f(0.75, 0.75, 0.75) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) vbo.bind() glVertexPointerf(vbo) glEnableClientState(GL_VERTEX_ARRAY) glDrawArrays(GL_TRIANGLE_STRIP, 0, 16) vbo.unbind() glDisableClientState(GL_VERTEX_ARRAY) glFlush()
def render( self, shader, mode, index ): """Bind the actual uniform value""" location = shader.getLocation( mode, self.name, uniform=True ) if location is not None and location != -1: value = self.currentValue( shader, mode ) if value: self.baseFunction( location, index ) glActiveTexture( GL_TEXTURE0 + index ) glBindTexture( GL_TEXTURE_BUFFER, self.texture( mode ) ) vbo = value.vbo(mode) vbo.bind() try: glTexBuffer( GL_TEXTURE_BUFFER, self.get_format(), int(vbo) ) finally: vbo.unbind() return True return False
def draw(): glDisable(GL_CULL_FACE) for mtl, (vbo, vbo_count) in vbos.iteritems(): mtl.apply() vbo.bind() glEnableClientState(GL_VERTEX_ARRAY) glEnableClientState(GL_NORMAL_ARRAY) glEnableClientState(GL_TEXTURE_COORD_ARRAY) glVertexPointer(3, GL_FLOAT, 36, vbo) glNormalPointer(GL_FLOAT, 36, vbo + 12) glTexCoordPointer(3, GL_FLOAT, 36, vbo + 24) glDrawArrays(GL_TRIANGLES, 0, vbo_count) glDisableClientState(GL_VERTEX_ARRAY) glDisableClientState(GL_NORMAL_ARRAY) glDisableClientState(GL_TEXTURE_COORD_ARRAY) vbo.unbind() glEnable(GL_CULL_FACE)
def display(): """ Render all objects""" glClear(GL_COLOR_BUFFER_BIT) # clear screen glColor(0.0, 0.0, 1.0) # render stuff glLoadIdentity() glRotate(angleX, 1, 0, 0) glRotate(angleY, 0, 1, 0) glRotate(angleZ, 0, 0, 1) glScale(scale, scale, scale) glTranslatef(-center[0], -center[1], -center[2]) glMultMatrixf(actOri * rotate(angle, axis)) vbo.bind() glVertexPointerf(vbo) glEnableClientState(GL_VERTEX_ARRAY) glDrawArrays(GL_POINTS, 0, len(points)) vbo.unbind() glDisableClientState(GL_VERTEX_ARRAY) glutSwapBuffers() # swap buffer
def display(): #print center """ Render all objects""" glClear(GL_COLOR_BUFFER_BIT) # clear screen glColor(color[0], color[1], color[2]) # render stuff glLoadIdentity() glTranslate(newX, newY, 0.0) glMultMatrixf(actOri * rotate(angle, axis)) glScale(scale, scale, scale) glTranslate(-center[0], -center[1], -center[2]) vbo.bind() glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) glVertexPointerf(vbo) glEnableClientState(GL_VERTEX_ARRAY) glDrawArrays(GL_TRIANGLES, 0, len(points)) vbo.unbind() glDisableClientState(GL_VERTEX_ARRAY) glutSwapBuffers() # swap buffer
def unbind(self, mode): """Unbind the vbo""" vbo = self.vbo(mode) vbo.unbind() return vbo
def renderPost(self, mode, shader, token=None): if token: vbo, location = token vbo.unbind() glDisableVertexAttribArray(location)
def recursive_render(self, node, kwargs): # Main recursive rendering method. # save model matrix and apply node transformation glPushMatrix() m = node.transformation.transpose() # OpenGL row major glMultMatrixf(m) for mesh in node.meshes: if mesh.gl["texture"]: stride = 36 # 9 * 4 bytes shader = GLModel.shaders["tex"] glUseProgram(shader) glBindTexture(GL_TEXTURE_2D, mesh.gl["texture"]) glEnableVertexAttribArray(shader.Vertex_position) glEnableVertexAttribArray(shader.Vertex_texcoords) vbo = mesh.gl["vbo"] vbo.bind() glVertexAttribPointer(shader.Vertex_position, 3, GL_FLOAT, False, stride, vbo) glVertexAttribPointer(shader.Vertex_texcoords, 3, GL_FLOAT, False, stride, vbo + 24) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.gl["faces"]) glDrawElements(GL_TRIANGLES, len(mesh.faces) * 3, GL_UNSIGNED_INT, None) vbo.unbind() glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) glDisableVertexAttribArray(shader.Vertex_position) glDisableVertexAttribArray(shader.Vertex_texcoords) glBindTexture(GL_TEXTURE_2D, 0) else: stride = 24 # 6 * 4 bytes shader = GLModel.shaders["color"] glUseProgram(shader) diffuse = mesh.material.properties["diffuse"] if len(diffuse) == 3: diffuse.append(1.0) glUniform4f(shader.Material_diffuse, *diffuse) ambient = mesh.material.properties["ambient"] if len(ambient) == 3: ambient.append(1.0) glUniform4f(shader.Material_ambient, *ambient) glEnableVertexAttribArray(shader.Vertex_position) glEnableVertexAttribArray(shader.Vertex_normal) vbo = mesh.gl["vbo"] vbo.bind() glVertexAttribPointer(shader.Vertex_position, 3, GL_FLOAT, False, stride, vbo) glVertexAttribPointer(shader.Vertex_normal, 3, GL_FLOAT, False, stride, vbo + 12) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.gl["faces"]) glDrawElements(GL_TRIANGLES, len(mesh.faces) * 3, GL_UNSIGNED_INT, None) vbo.unbind() glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) glDisableVertexAttribArray(shader.Vertex_position) glDisableVertexAttribArray(shader.Vertex_normal) glBindTexture(GL_TEXTURE_2D, 0) for child in node.children: self.recursive_render(child, kwargs) glPopMatrix()
def recursive_render(self, node, shader, mode=BASE, with_normals=True): """ Main recursive rendering method. """ normals = with_normals if mode == COLORS: normals = False if not hasattr(node, "selected"): node.selected = False m = get_world_transform(self.scene, node) # HELPERS mode ### if mode == HELPERS: # if node.type == ENTITY: self.render_axis(m, label=node.name if node != self.scene.rootnode else None, selected=node.selected if hasattr(node, "selected") else False) if node.type == CAMERA: self.render_camera(node, m) for child in node.children: self.recursive_render(child, shader, mode) return # Mesh rendering modes ### if node.type == MESH: for mesh in node.meshes: stride = 24 # 6 * 4 bytes if node.selected and mode == SILHOUETTE: glUniform4f(shader.u_materialDiffuse, 1.0, 0.0, 0.0, 1.0) glUniformMatrix4fv(shader.u_modelViewMatrix, 1, GL_TRUE, numpy.dot(self.view_matrix, m)) else: if mode == COLORS: colorid = self.node2colorid[node.name] r, g, b = self.get_rgb_from_colorid(colorid) glUniform4f(shader.u_materialDiffuse, r / 255.0, g / 255.0, b / 255.0, 1.0) elif mode == SILHOUETTE: glUniform4f(shader.u_materialDiffuse, .0, .0, .0, 1.0) else: if node.selected: diffuse = (1.0, 0.0, 0.0, 1.0) # selected nodes in red else: global part1ChangeIndex, part2ChangeIndex, part3ChangeIndex, part4ChangeIndex,\ part5ChangeIndex, tIndex, temperature, Tmin, Tmax, nt, diffuse1 # diffuse = mesh.material.properties["diffuse"] if tIndex < nt: if node.name == "Part1": part1ChangeIndex = 1 diffuse1[0] = (temperature[tIndex][0]-Tmin)/(Tmax - Tmin) diffuse1[1] = (temperature[tIndex][0]-Tmin)/(Tmax - Tmin) diffuse1[2] = (temperature[tIndex][0]-Tmin)/(Tmax - Tmin) # print("Part1:",temperature[tIndex][0]) elif node.name == "Part2": part2ChangeIndex = 1 diffuse2[0] = (temperature[tIndex][1]-Tmin) / (Tmax-Tmin) diffuse2[1] = (temperature[tIndex][1]-Tmin) / (Tmax-Tmin) diffuse2[2] = (temperature[tIndex][1]-Tmin) / (Tmax-Tmin) # print("Part2:",temperature[tIndex][1]) elif node.name == "Part3": part3ChangeIndex = 1 diffuse3[0] = (temperature[tIndex][2]-Tmin) / (Tmax-Tmin) diffuse3[1] = (temperature[tIndex][2]-Tmin) / (Tmax-Tmin) diffuse3[2] = (temperature[tIndex][2]-Tmin) / (Tmax-Tmin) # print("Part3:", temperature[tIndex][2]) elif node.name == "Part4": part4ChangeIndex = 1 diffuse4[0] = (temperature[tIndex][3]-Tmin) / (Tmax-Tmin) diffuse4[1] = (temperature[tIndex][3]-Tmin) / (Tmax-Tmin) diffuse4[2] = (temperature[tIndex][3]-Tmin) / (Tmax-Tmin) # print("Part4:", temperature[tIndex][3]) else: part5ChangeIndex = 1 diffuse5[0] = (temperature[tIndex][4]-Tmin) / (Tmax-Tmin) diffuse5[1] = (temperature[tIndex][4]-Tmin) / (Tmax-Tmin) diffuse5[2] = (temperature[tIndex][4]-Tmin) / (Tmax-Tmin) # print("Part5:", temperature[tIndex][1]) if part1ChangeIndex==1 and part2ChangeIndex==1 and part3ChangeIndex==1 and part4ChangeIndex==1 \ and part5ChangeIndex==1: part1ChangeIndex=0 part2ChangeIndex=0 part3ChangeIndex=0 part4ChangeIndex=0 part5ChangeIndex=0 print("Part1:", temperature[tIndex][0]," Part2:", temperature[tIndex][1]," Part3:", temperature[tIndex][2]," Part4:", temperature[tIndex][3]," Part5:", temperature[tIndex][4]) tIndex+=1 if node.name == "Part1": diffuse = diffuse1 elif node.name == "Part2": diffuse = diffuse2 elif node.name == "Part3": diffuse = diffuse3 elif node.name == "Part4": diffuse = diffuse4 else: diffuse = diffuse5 if len(diffuse) == 3: # RGB instead of expected RGBA diffuse.append(1.0) glUniform4f(shader.u_materialDiffuse, *diffuse) # if ambient: # glUniform4f( shader.Material_ambient, *mat["ambient"] ) if mode == BASE: # not in COLORS or SILHOUETTE normal_matrix = linalg.inv(numpy.dot(self.view_matrix, m)[0:3, 0:3]).transpose() # glUniformMatrix3fv(shader.u_normalMatrix, 1, GL_TRUE, normal_matrix) glUniformMatrix4fv(shader.u_modelMatrix, 1, GL_TRUE, m) vbo = mesh.gl["vbo"] vbo.bind() glEnableVertexAttribArray(shader.a_vertex) # if normals: # glEnableVertexAttribArray(shader.a_normal) glVertexAttribPointer( shader.a_vertex, 3, GL_FLOAT, False, stride, vbo ) # if normals: # glVertexAttribPointer( # shader.a_normal, # 3, GL_FLOAT, False, stride, vbo + 12 # ) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.gl["faces"]) glDrawElements(GL_TRIANGLES, mesh.gl["nbfaces"] * 3, GL_UNSIGNED_INT, None) vbo.unbind() glDisableVertexAttribArray(shader.a_vertex) # if normals: # glDisableVertexAttribArray(shader.a_normal) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) # self.DrawCircle(8, 100, False) for child in node.children: self.recursive_render(child, shader, mode)
def display(): ''' Display of object ''' global scaleFactor, center, vbo, actOri, angle, axis, data, newXPos, newYPos, zoomFactor, shadow, lightPos, wire, light # set color glColor(current_color) glMatrixMode(GL_MODELVIEW) # Clear framebuffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # Reset modelview matrix glLoadIdentity() # set to solid view glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) if light: glEnable(GL_LIGHTING) glEnable(GL_LIGHT0) glEnable(GL_DEPTH_TEST) glEnable(GL_COLOR_MATERIAL) glEnable(GL_DEPTH_TEST) glEnable(GL_NORMALIZE) glLightfv(GL_LIGHT0, GL_POSITION, [lightPos[0], lightPos[1], lightPos[2], 0.0]) else: glDisable(GL_LIGHTING) vbo.bind() glEnableClientState(GL_VERTEX_ARRAY) glEnableClientState(GL_NORMAL_ARRAY) glVertexPointer(3, GL_FLOAT, 24, vbo) glNormalPointer(GL_FLOAT, 24, vbo + 12) # Translate #print(newXPos, newYPos) glTranslate(newXPos, newYPos, 0.0) # Rotate glMultMatrixf(actOri * rotate(angle, axis)) # Scale glScale(scaleFactor, scaleFactor, scaleFactor) glDrawArrays(GL_TRIANGLES, 0, len(data)) if shadow: glDisable(GL_LIGHTING) glMatrixMode(GL_MODELVIEW) p = [ 1.0, 0, 0, 0, 0, 1.0, 0, -1.0 / lightPos[1], 0, 0, 1.0, 0, 0, 0, 0, 0 ] glTranslatef( 0.0, boundingBox[0][1] if boundingBox[0][1] < 0 else -boundingBox[0][1], 0.0) glPushMatrix() glTranslatef(lightPos[0], lightPos[1], lightPos[2]) glMultMatrixf(p) glTranslatef(-lightPos[0], -lightPos[1], -lightPos[2]) glColor(SHADOW) glTranslate( 0.0, -boundingBox[0][1] if boundingBox[0][1] < 0 else boundingBox[0][1], 0.0) glDrawArrays(GL_TRIANGLES, 0, len(data)) glColor(current_color) glPopMatrix() vbo.unbind() glDisableClientState(GL_VERTEX_ARRAY) glDisableClientState(GL_NORMAL_ARRAY) # swap buffer glutSwapBuffers()
def recursive_render(self, node, texture, shader, color): """ Main recursive rendering method. """ # save model matrix and apply node transformation glPushMatrix() m = node.transformation.transpose() # OpenGL row major glMultMatrixf(m) for mesh in node.meshes: stride = 32 # 8 * 4 bytes #diffuse = mesh.material.properties["diffuse"] #if len(diffuse) == 3: diffuse.append(1.0) #ambient = mesh.material.properties["ambient"] #if len(ambient) == 3: ambient.append(1.0) glUniform4f( shader.Material_diffuse, *color ) glUniform4f( shader.Material_ambient, *color ) # has been bound to texture #0 (i.e. texture #1... confusing) if texture: glBindTexture(GL_TEXTURE_2D, texture) glUniform1i(shader.thetexture,0) else: glBindTexture(GL_TEXTURE_2D, self.dummy_texture) glUniform1i(shader.thetexture,0) vbo = mesh.gl["vbo"] vbo.bind() glEnableVertexAttribArray( shader.Vertex_position ) glEnableVertexAttribArray( shader.Vertex_normal ) glEnableVertexAttribArray( shader.texcoords ) glVertexAttribPointer( shader.Vertex_position, 3, GL_FLOAT,False, stride, vbo ) glVertexAttribPointer( shader.Vertex_normal, 3, GL_FLOAT,False, stride, vbo+12 ) glVertexAttribPointer( shader.texcoords, 2, GL_FLOAT,False, stride, vbo+24 ) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.gl["faces"]) glDrawElements(GL_TRIANGLES, len(mesh.faces) * 3, GL_UNSIGNED_INT, None) vbo.unbind() glDisableVertexAttribArray( shader.Vertex_position ) glDisableVertexAttribArray( shader.Vertex_normal ) glDisableVertexAttribArray( shader.texcoords ) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) glBindTexture(GL_TEXTURE_2D, 0) for child in node.children: self.recursive_render(child, texture, shader, color) glPopMatrix()
def draw_fbo_cube(self, planetdescriptor, face, synth_pass, facex, facey, level, tex_in): #debug code self.timer.start() w = h = self.fbo_tex_size ds_exp = 0 bord = 0 if synth_pass == 'pass_1': #setup for heightmap rendering #1 pixel border h += 2 w += 2 ds_exp = 1.0 / float(w) material = MaterialManager.Materials[ planetdescriptor.height_material] else: material = MaterialManager.Materials[ planetdescriptor.normal_material] #define rendering target: the texture to create texture = glGenTextures(1) glActiveTexture(GL_TEXTURE5) glBindTexture(GL_TEXTURE_2D, texture) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, w, h, 0, GL_RGBA, GL_FLOAT, None) glBindTexture(GL_TEXTURE_2D, 0) #activate the rendering program glUseProgram(material) #standard dimensions for the scene cube ds = self.ds dz = np.cos(np.radians(45.0)) / np.sin(np.radians(45.0)) * ds #specific setup depending on pass (heightmap or normal) if synth_pass == 'pass_1': #setup for heightmap rendering #fov adapted to level glBindTexture(GL_TEXTURE_2D, 0) glDisable(GL_TEXTURE_2D) fov = 90.0 txindex = -1 #won't use texture coords matpass = '******' posattr = glGetAttribLocation(material, 'position') glEnableVertexAttribArray(posattr) glUniform1f(glGetUniformLocation(material, 'hmap_border_factor'), ds_exp / (2.0**level)) glUniform1f(glGetUniformLocation(material, 'hmap_dx'), facex * ds) glUniform1f(glGetUniformLocation(material, 'hmap_dy'), facey * ds) glUniform1f(glGetUniformLocation(material, 'patchscale'), 1.0 / (2.0**level)) glUniform1i(glGetUniformLocation(material, 'level'), level) fbo = self.hfbo vbo = self.p1vbo ibo = self.ibo stride = 4 * 3 if synth_pass == 'pass_2': glEnable(GL_TEXTURE_2D) glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, tex_in) fov = 90.0 txindex = 1 #will use texture coords #glGetAttribLocation(material,'texturecoord') faceindexlocation = glGetUniformLocation(material, 'cubefacedebug') glUniform1i(faceindexlocation, face) matpass = '******' posattr = glGetAttribLocation(material, 'position') texattr = glGetAttribLocation(material, 'texcoord') glEnableVertexAttribArray(posattr) glEnableVertexAttribArray(texattr) glUniform1f(glGetUniformLocation(material, 'planet_radius'), planetdescriptor.radius) glUniform1f(glGetUniformLocation(material, 'planet_height'), planetdescriptor.height) glUniform2f(glGetUniformLocation(material, 'patchcenter'), facex, facey) glUniform1f(glGetUniformLocation(material, 'patchscale'), 1.0 / (2.0**level)) glUniform1i(glGetUniformLocation(material, 'level'), level) fbo = self.nfbo vbo = self.p2vbo ibo = self.ibo stride = 4 * (2 + 3) #bind fbo and set render target glBindFramebuffer(GL_FRAMEBUFFER, fbo) glDrawBuffer(GL_COLOR_ATTACHMENT0) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0) #set up virtual camera fov (position will be set up just before draw) glClearColor(1.0, 0.0, 0.0, 1.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glDisable(GL_LIGHTING) glShadeModel(GL_SMOOTH) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(fov, float(w) / float(h), 0.001, 100.0) glMatrixMode(GL_MODELVIEW) glLoadIdentity() #set up rotation matrix for the cube face matrotlocation = glGetUniformLocation(material, 'rotcubev') glUniformMatrix3fv(matrotlocation, 1, False, self.matcube[matpass][face]) glViewport(0, 0, w, h) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) glClearColor(0.0, 1.0, 0.0, 1.0) vbo.bind() ibo.bind() glVertexAttribPointer(posattr, 3, GL_FLOAT, GL_FALSE, stride, vbo) if txindex <> -1: glVertexAttribPointer(texattr, 2, GL_FLOAT, GL_FALSE, stride, vbo + (3 * 4)) glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, ibo) vbo.unbind() ibo.unbind() glFinish() #disable FBO st = glCheckFramebufferStatus(GL_FRAMEBUFFER) #ALternative 1 (works) # glReadBuffer(GL_COLOR_ATTACHMENT0) # data = None # data = glReadPixels(0,0,w, h, GL_RGBA, GL_UNSIGNED_BYTE) glBindTexture(GL_TEXTURE_2D, 0) glBindFramebuffer(GL_FRAMEBUFFER, 0) glUseProgram(0) #glDeleteFramebuffers([fbo]) #Alternative 2 (works, and the output type is not necessary) # if level == 4: if level == 99: glBindTexture(GL_TEXTURE_2D, texture) OpenGL.UNSIGNED_BYTE_IMAGES_AS_STRING = False data = glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_FLOAT, outputType='str') min = 99999 max = -99999 for row in data: for el in row: if el[3] > max: max = el[3] if el[3] < min: min = el[3] print min print max glBindTexture(GL_TEXTURE_2D, texture) #debug code #print 'fbo '+synth_pass+str(face)+' '+str(self.timer.stop()*1000)+' ms' #self.timer.start() #debug code: save textures # from PIL import Image # image = Image.frombytes('RGBA', (w,h), data, 'raw') # image = image.transpose(Image.FLIP_TOP_BOTTOM) # image.save ('Media/Textures/f'+str(face)+' x'+str(facex)+' y'+str(facey)+' l'+str(level)+' m'+str(material)+' fv'+str(fov)+' fb'+str(fbo)+' '+synth_pass+'.png') # #debug code #print 'fbo save txt '+synth_pass+str(face)+' '+str(self.timer.stop()*1000)+' ms' if synth_pass == 'pass_1': return texture else: return texture
def OnDraw(self): '''Redraw the widget. ''' # clear color and depth buffers glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) self.setupScene() for obj in self.displayObjects: glMatrixMode(obj["matrix_mode"]) style = obj["style"] if style == "Red": glColor3f(1.0, 0.7, 0.7) elif style == "Blue": glColor3f(0.7, 0.7, 1.0) else: glColor3f(1.0, 1.0, 1.0) visible = obj["visible"] if not visible: continue if "list" in obj: glCallList(obj["list"]) #if self.controller.showgrid: # self.drawXAxisGrid() # self.drawYAxisGrid() # self.drawZAxisGrid() shaders.glUseProgram(self.shader) try: glUniform4f( self.Global_ambient_loc, .3,.3, .3, 0.5) glUniform4f(self.Light_diffuse_loc, 0.5, 0.5, 0.5, 0.5) glUniform3f(self.Light_location_loc, 0, 1, 10) for obj in self.displayObjects: visible = obj["visible"] if not visible: continue if not "vbo" in obj: continue vbo = obj["vbo"] #vao = obj["vao"] num_triangles = obj["vbo_len"] if not self.highlight: highlight = False else: highlight = True highlight_index = self.highlight_index vbo.bind() ### #glBindVertexArray(vao) try: style = obj["style"] if style == "Grey": glUniform4f(self.Base_colour_loc, 0.7, 0.7, 0.7, 0.5) elif style == "Red": glUniform4f(self.Base_colour_loc, 0.7, 0.3, 0.3, 0.5) elif style == "Blue": glUniform4f(self.Base_colour_loc, 0.3, 0.3, 0.7, 0.5) else: glUniform4f(self.Base_colour_loc, 0.7, 0.7, 0.7, 0.5) glEnableVertexAttribArray( self.Vertex_position_loc ) glEnableVertexAttribArray( self.Vertex_normal_loc ) stride = 24 glVertexAttribPointer(self.Vertex_position_loc, 3, GL_FLOAT, False, stride, vbo) glVertexAttribPointer(self.Vertex_normal_loc, 3, GL_FLOAT, False, stride, vbo+12) if not highlight: glDrawArrays(GL_TRIANGLES, 0, num_triangles) ### #glDrawElements(GL_TRIANGLES, num_triangles, GL_UNSIGNED_INT, None) else: if highlight_index == 0: glUniform4f(self.Base_colour_loc, 0.2, 0.2, 0.2, 0.5) glDrawArrays(GL_TRIANGLES, 0, 3) glUniform4f(self.Base_colour_loc, 0.7, 0.7, 0.7, 0.5) glDrawArrays(GL_TRIANGLES, 3, num_triangles-3) elif highlight_index == num_triangles-2: glUniform4f(self.Base_colour_loc, 0.2, 0.2, 0.2, 0.5) glDrawArrays(GL_TRIANGLES, 0, num_triangles-3) glUniform4f(self.Base_colour_loc, 0.7, 0.7, 0.7, 0.5) glDrawArrays(GL_TRIANGLES, num_triangles-3, 3) else: glUniform4f(self.Base_colour_loc, 0.7, 0.7, 0.7, 0.5) glDrawArrays(GL_TRIANGLES, 0, highlight_index) glDrawArrays(GL_TRIANGLES, highlight_index+3, num_triangles-highlight_index-3) glUniform4f(self.Base_colour_loc, 0.2, 0.2, 0.2, 0.5) glDrawArrays(GL_TRIANGLES, highlight_index, 3) finally: vbo.unbind() glDisableVertexAttribArray( self.Vertex_position_loc ) glDisableVertexAttribArray( self.Vertex_normal_loc ) finally: shaders.glUseProgram(0) self.SwapBuffers()
def Render( self, mode = None): """Render the geometry for the scene.""" if not mode.visible: return '''We are going to update the lights array on every frame, normally we'd cache the whole array and only update if there was a change. This is exactly what we did in our previous tutorial.''' for i,light in enumerate( self.lights ): self.LIGHTS[i] = self.lightAsArray( light ) '''With our newly-calculated light array, we configure the appropriate uniform with the data-array. The GLSLObject has a getVariable( name ) method which returns the attribute-or-uniform of the given name. Assigning to the variable's value attribute will cause the value to be passed in when the GLSLObject is rendered.''' self.glslObject.getVariable( 'lights' ).value = self.LIGHTS '''We do the same thing with our material configuration. We use our previous code to calculate the desired values and then configure the uniform variables with those values.''' for key,value in self.materialFromAppearance( self.appearance, mode ).items(): self.glslObject.getVariable( key ).value = value '''OpenGLContext rendering nodes will often return "tokens" which are to be passed back to the node after the rendering pass to disable the changes made. The GLSLObject produces one of these when rendered. The rendering will compile the shaders (reporting errors if they occur), bind the object, and iterate through the textures and uniforms configuring them for use with the shader. ''' token = self.glslObject.render( mode ) tokens = [ ] try: '''As mentioned above, our indices ShaderIndexBuffer would normally be rendered via a ShaderGeometry/ShaderSlice node. We're going to manually trigger it here.''' vbo = self.indices.bind(mode) '''Again, normally the ShaderGeometry/ShaderSlice would trigger the attribute nodes. We iterate over them passing in the shader object to which to attach themselves. The attributes will generally return tokens to disable the attribute configuration after rendering.''' for attribute in self.attributes: token = attribute.render( self.glslObject, mode ) if token: tokens.append( (attribute, token) ) '''And our actual drawing code. You will note that the *type* of the indices has changed. The ShaderIndexBuffer is intended to be generic, so it uses full 32-bit unsigned ints rather than 16-bit ints and has up-converted our array of 16-bit ints when we created it.''' glDrawElements( GL_TRIANGLES, self.count, GL_UNSIGNED_INT, vbo ) finally: '''We ask each thing which returned a rendering token to disable itself after the rendering pass.''' for attribute,token in tokens: attribute.renderPost( self.glslObject, mode, token ) self.glslObject.renderPost( token, mode ) '''The index-array VBO also needs to be unbound.''' vbo.unbind()
def recursive_render(self, node, shader, mode=BASE, with_normals=True): """ Main recursive rendering method. """ normals = with_normals if mode == COLORS: normals = False if not hasattr(node, "selected"): node.selected = False m = get_world_transform(self.scene, node) # HELPERS mode ### if mode == HELPERS: # if node.type == ENTITY: self.render_axis(m, label=node.name if node != self.scene.rootnode else None, selected=node.selected if hasattr(node, "selected") else False) if node.type == CAMERA: self.render_camera(node, m) for child in node.children: self.recursive_render(child, shader, mode) return # Mesh rendering modes ### if node.type == MESH: for mesh in node.meshes: stride = 24 # 6 * 4 bytes if node.selected and mode == SILHOUETTE: glUniform4f(shader.u_materialDiffuse, 1.0, 0.0, 0.0, 1.0) glUniformMatrix4fv(shader.u_modelViewMatrix, 1, GL_TRUE, numpy.dot(self.view_matrix, m)) else: if mode == COLORS: colorid = self.node2colorid[node.name] r, g, b = self.get_rgb_from_colorid(colorid) glUniform4f(shader.u_materialDiffuse, r / 255.0, g / 255.0, b / 255.0, 1.0) elif mode == SILHOUETTE: glUniform4f(shader.u_materialDiffuse, .0, .0, .0, 1.0) else: if node.selected: diffuse = (1.0, 0.0, 0.0, 1.0) # selected nodes in red else: diffuse = mesh.material.properties["diffuse"] if len(diffuse) == 3: # RGB instead of expected RGBA diffuse.append(1.0) glUniform4f(shader.u_materialDiffuse, *diffuse) # if ambient: # glUniform4f( shader.Material_ambient, *mat["ambient"] ) if mode == BASE: # not in COLORS or SILHOUETTE normal_matrix = linalg.inv(numpy.dot(self.view_matrix, m)[0:3, 0:3]).transpose() glUniformMatrix3fv(shader.u_normalMatrix, 1, GL_TRUE, normal_matrix) glUniformMatrix4fv(shader.u_modelMatrix, 1, GL_TRUE, m) vbo = mesh.gl["vbo"] vbo.bind() glEnableVertexAttribArray(shader.a_vertex) if normals: glEnableVertexAttribArray(shader.a_normal) glVertexAttribPointer( shader.a_vertex, 3, GL_FLOAT, False, stride, vbo ) if normals: glVertexAttribPointer( shader.a_normal, 3, GL_FLOAT, False, stride, vbo + 12 ) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.gl["faces"]) glDrawElements(GL_TRIANGLES, mesh.gl["nbfaces"] * 3, GL_UNSIGNED_INT, None) vbo.unbind() glDisableVertexAttribArray(shader.a_vertex) if normals: glDisableVertexAttribArray(shader.a_normal) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) for child in node.children: self.recursive_render(child, shader, mode)
def unbind( self, mode ): """Unbind the vbo""" vbo = self.vbo(mode) vbo.unbind() return vbo
def recursive_render(self, node, shader, mode=BASE, with_normals=True): """ Main recursive rendering method. """ normals = with_normals if mode == COLORS: normals = False if not hasattr(node, "selected"): node.selected = False m = get_world_transform(self.scene, node) # HELPERS mode ### if mode == HELPERS: # if node.type == ENTITY: self.render_axis( m, label=node.name if node != self.scene.rootnode else None, selected=node.selected if hasattr(node, "selected") else False) if node.type == CAMERA: self.render_camera(node, m) for child in node.children: self.recursive_render(child, shader, mode) return # Mesh rendering modes ### if node.type == MESH: for mesh in node.meshes: stride = 24 # 6 * 4 bytes if node.selected and mode == SILHOUETTE: glUniform4f(shader.u_materialDiffuse, 1.0, 0.0, 0.0, 1.0) glUniformMatrix4fv(shader.u_modelViewMatrix, 1, GL_TRUE, numpy.dot(self.view_matrix, m)) else: if mode == COLORS: colorid = self.node2colorid[node.name] r, g, b = self.get_rgb_from_colorid(colorid) glUniform4f(shader.u_materialDiffuse, r / 255.0, g / 255.0, b / 255.0, 1.0) elif mode == SILHOUETTE: glUniform4f(shader.u_materialDiffuse, .0, .0, .0, 1.0) else: if node.selected: diffuse = (1.0, 0.0, 0.0, 1.0 ) # selected nodes in red else: diffuse = mesh.material.properties["diffuse"] if len(diffuse) == 3: # RGB instead of expected RGBA diffuse.append(1.0) glUniform4f(shader.u_materialDiffuse, *diffuse) # if ambient: # glUniform4f( shader.Material_ambient, *mat["ambient"] ) if mode == BASE: # not in COLORS or SILHOUETTE normal_matrix = linalg.inv( numpy.dot(self.view_matrix, m)[0:3, 0:3]).transpose() glUniformMatrix3fv(shader.u_normalMatrix, 1, GL_TRUE, normal_matrix) glUniformMatrix4fv(shader.u_modelMatrix, 1, GL_TRUE, m) vbo = mesh.gl["vbo"] vbo.bind() glEnableVertexAttribArray(shader.a_vertex) if normals: glEnableVertexAttribArray(shader.a_normal) glVertexAttribPointer(shader.a_vertex, 3, GL_FLOAT, False, stride, vbo) if normals: glVertexAttribPointer(shader.a_normal, 3, GL_FLOAT, False, stride, vbo + 12) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.gl["faces"]) glDrawElements(GL_TRIANGLES, mesh.gl["nbfaces"] * 3, GL_UNSIGNED_INT, None) vbo.unbind() glDisableVertexAttribArray(shader.a_vertex) if normals: glDisableVertexAttribArray(shader.a_normal) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) for child in node.children: self.recursive_render(child, shader, mode)
def renderPost( self, mode, shader, token=None ): if token: vbo,location = token vbo.unbind() glDisableVertexAttribArray( location )