def render(self): GL.glClearColor(0, 0, 0, 1) GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) # active shader program GL.glUseProgram(self.shaderProgram) ''' # Update the uniform color tval = time.time() green = (numpy.sin(tval)/2) + 0.5 vertexColorLocation = GL.glGetUniformLocation(shaderProgram, 'ourColor') GL.glUniform4f(vertexColorLocation, 0.0, green, 0.0, 1.0) ''' try: GL.glBindVertexArray(self.VAO) # Draw a triangle # GL.glDrawArrays(GL.GL_TRIANGLES, 0, 3) # draw triangle, starting index of the vertex array, # of vertices (6 = indexData.size), # EBO indexes remain the same (accounts for stride of extra data GL.glDrawElements(GL.GL_TRIANGLES, self.index_size, GL.GL_UNSIGNED_INT, None) finally: # Unbind when we finish GL.glBindVertexArray(0) GL.glUseProgram(0)
def init(): initialize_program() initialize_vertex_buffer() n = 1 vao_array = GL.arrays.GLuintArray.zeros((n,)) GL.glBindVertexArray( vao_array )
def render(shader, vao, tex, tex2): gl.glClearColor(0.2, 0.3, 0.3, 0.4) gl.glClear(gl.GL_COLOR_BUFFER_BIT|gl.GL_DEPTH_BUFFER_BIT) gl.glBindTexture(gl.GL_TEXTURE_2D, tex) gl.glUseProgram(shader) gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(gl.GL_TEXTURE_2D, tex) gl.glUniform1i(gl.glGetUniformLocation(shader, "ourTexture1"), 0) gl.glActiveTexture(gl.GL_TEXTURE1) gl.glBindTexture(gl.GL_TEXTURE_2D, tex2) gl.glUniform1i(gl.glGetUniformLocation(shader, "ourTexture2"), 1) view = gl.glGetUniformLocation(shader, "view") view_matrix = array([ [0.8, 0, 0, 0], [0, 0.8, 0, 0], [0, 0, 0.8, -4], [0, 0, 0, 1], ]) gl.glUniformMatrix4fv(view, 1, gl.GL_TRUE, view_matrix) projection = gl.glGetUniformLocation(shader, "projection") projection_matrix = get_projection_matrix(45, WINDOW_WIDTH/WINDOW_HEIGHT, 0.1, 100) gl.glUniformMatrix4fv(projection, 1, gl.GL_FALSE, projection_matrix) gl.glBindVertexArray(vao) for idx in range(0, len(CUBEPOSITIONS)): model = gl.glGetUniformLocation(shader, "model") angel = glfw.get_time()%360 model_matrix = get_model_matrix(idx, angel) gl.glUniformMatrix4fv(model, 1, gl.GL_TRUE, model_matrix) gl.glDrawArrays(gl.GL_TRIANGLES, 0, VERTEXS.size) gl.glBindVertexArray(0) gl.glUseProgram(0)
def init(self): self.vao = GL.glGenVertexArrays(1) GL.glBindVertexArray(self.vao) self.initializeProgram() self.initializeVertexBuffer() colorDataOffset = 3*self.float_size*self.numberOfVertices GL.glBindBuffer(GL.GL_ARRAY_BUFFER,self.vertexBufferObject) GL.glEnableVertexAttribArray(0) GL.glEnableVertexAttribArray(1) GL.glVertexAttribPointer(0, 3, GL.GL_FLOAT, GL.GL_FALSE, 0, None) GL.glVertexAttribPointer(1, 4, GL.GL_FLOAT, GL.GL_FALSE, 0, GL.GLvoidp(colorDataOffset)) GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER,self.indexBufferObject) GL.glBindVertexArray(0) GL.glEnable(GL.GL_CULL_FACE) GL.glCullFace(GL.GL_BACK) GL.glFrontFace(GL.GL_CW) GL.glEnable(GL.GL_DEPTH_TEST) GL.glDepthMask(GL.GL_TRUE) GL.glDepthFunc(GL.GL_LESS) GL.glDepthRange(0.0, 1.0)
def render(self): gl.glClearColor(0, 0, 0, 1) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) with self.shader_prog: # Activate array gl.glBindVertexArray(self.vao_id) # FIXME: Why does the following work? tex_uniform is 1, # palette_uniform is 0, but I have to set the uniform for # tex_uniform to 0 and the uniform for palette_uniform to 1. # Obviously I'm not understanding something. # # See: http://stackoverflow.com/questions/26622204 # https://www.opengl.org/discussion_boards/showthread.php/174926-when-to-use-glActiveTexture # Activate texture print(self.tex_uniform, self.palette_uniform, self.sample_texture, self.palette_id) gl.glActiveTexture(gl.GL_TEXTURE0 + self.tex_uniform) gl.glBindTexture(gl.GL_TEXTURE_2D, self.sample_texture) gl.glUniform1i(self.tex_uniform, 0) # Activate palette texture gl.glActiveTexture(gl.GL_TEXTURE0 + self.palette_uniform) gl.glBindTexture(gl.GL_TEXTURE_BUFFER, self.palette_texture) gl.glTexBuffer(gl.GL_TEXTURE_BUFFER, gl.GL_RGBA8, self.palette_id) gl.glUniform1i(self.palette_uniform, 1) # # Activate array # gl.glBindVertexArray(self.vao_id) # draw triangle gl.glDrawArrays(gl.GL_TRIANGLE_STRIP, 0, 4)
def init(self): super(BasicWindow, self).init() vert_shader = compileShader(vert_shader_source, GL.GL_VERTEX_SHADER) frag_shader = compileShader(frag_shader_source, GL.GL_FRAGMENT_SHADER) self.shader = game_core.ShaderProgram(vert_shader, frag_shader) self.ndc_vao = GL.glGenVertexArrays(1) GL.glBindVertexArray(self.ndc_vao) vertex_buffer = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, vertex_buffer) data = [ -1.0, -1.0, 0.0, 0.0, 1.0, 0.0, 1.0, -1.0, 0.0, ] array_type = (GL.GLfloat*len(data)) GL.glBufferData( GL.GL_ARRAY_BUFFER, len(data)*game_core.FLOAT_SIZE, array_type(*data), GL.GL_STATIC_DRAW ) GL.glEnableVertexAttribArray(0) GL.glVertexAttribPointer(0, 3, GL.GL_FLOAT, GL.GL_FALSE, 0, None) GL.glBindVertexArray(0)
def render(): global shaderProgram global VAO global EBO global indexData GL.glClearColor(0, 0, 0, 1) GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) # active shader program GL.glUseProgram(shaderProgram) try: GL.glBindVertexArray(VAO) # Draw a triangle # GL.glDrawArrays(GL.GL_TRIANGLES, 0, 3) # draw triangle, starting index of the vertex array, # of vertices (6 = indexData.size), GL.glDrawElements(GL.GL_TRIANGLES, indexData.size, GL.GL_UNSIGNED_INT, None) finally: # Unbind when we finish GL.glBindVertexArray(0) GL.glUseProgram(0)
def __init__(self, name, vertices, indices): self.name = name assert len(indices) % 3 == 0 self.numTriangles = len(indices) / 3 vertex_data = vertices if isinstance(vertices, numpy.ndarray) else numpy.concatenate(vertices) index_data = numpy.array(indices, dtype=numpy.uint32) self.vao = GL.glGenVertexArrays(1) GL.glBindVertexArray(self.vao) self.vbo, self.ibo = GL.glGenBuffers(2) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.vbo) GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, self.ibo) self.program = BlinnWithoutNormalsProgram.get() GL.glEnableVertexAttribArray(self.program.attrib_position) GL.glVertexAttribPointer(self.program.attrib_position, 3, GL.GL_FLOAT, False, 3*SIZE_OF_FLOAT32, ctypes.c_void_p(0)) # Send the data over to the buffer GL.glBufferData(GL.GL_ARRAY_BUFFER, len(vertex_data) * SIZE_OF_FLOAT32, vertex_data.astype(numpy.float32, copy=False), GL.GL_STATIC_DRAW) GL.glBufferData(GL.GL_ELEMENT_ARRAY_BUFFER, len(index_data) * SIZE_OF_UNSIGNED32, index_data, GL.GL_STATIC_DRAW) # Unbind the VAO first (Important) GL.glBindVertexArray(0) # Unbind other stuff GL.glDisableVertexAttribArray(self.program.attrib_position) GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, 0) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0)
def trial(self): # glfw.make_context_current(self.window) # self.gui_lock.acquire() vertexData = np.array([0.0, 0.5, 0.0, 1.0, 0.5, -0.366, 0.0, 1.0, -0.5, -0.366, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, ], dtype=np.float32) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self._VBO) # gl.glBufferData(gl.GL_ARRAY_BUFFER, vertexData.nbytes, vertexData, gl.GL_STATIC_DRAW) # enable array and set up data gl.glEnableVertexAttribArray(0) gl.glEnableVertexAttribArray(1) gl.glVertexAttribPointer(0, 4, gl.GL_FLOAT, gl.GL_FALSE, 0, None) # the last parameter is a pointer # python donot have pointer, have to using ctypes gl.glVertexAttribPointer(1, 4, gl.GL_FLOAT, gl.GL_FALSE, 0, ctypes.c_void_p(48)) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0) gl.glBindVertexArray(0)
def quad(self, g, quad): # Enable alpha blending/transparency self.vbuffer.sync() gl.glUseProgram(self.program.id) gl.glEnable(gl.GL_BLEND) gl.glEnable(gl.GL_DEPTH_TEST) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) # Bind texture gl.glUniform1i(self.program.tex, 0) gl.glBindTexture(gl.GL_TEXTURE_2D, quad.texture.id) # Set up geometry transforms worldMatrix = Matrix.scale(quad.width, quad.height, 1) worldMatrix = Matrix.translate(quad.x, quad.y, 0) * worldMatrix worldViewProjectionMatrix = g.viewProjectionMatrix * worldMatrix #worldViewProjectionMatrix = g.viewProjectionMatrix gl.glUniformMatrix4fv(self.program.worldViewProjectionMatrix, 1, 0, worldViewProjectionMatrix.data) # Draw geometry gl.glBindVertexArray(self.vao) gl.glDrawArrays(gl.GL_TRIANGLE_STRIP, 0, 4) gl.glBindVertexArray(0)
def draw(): """Put the main drawing code in here.""" def inc(x, amount=1): return (x + amount) % 4 def wlc(x): return (x >> 4) | x if chaem.stat == chaem.states.stop: x, z = int((chaem.pos.z + 1) / 2), int((chaem.pos.x + 1) / 2) spot = room[x][z] dire = inc(int(round(chaem.heading * 2 / pi)), 1) # Get this into room coordinates (0-3) for x in [3, 0, 1, 2]: # Check each side, starting with the right. if not wlc(spot) & (2 ** (inc(dire, x))): dire = inc(dire, x) break chaem.movdir = quaternion.from_y_rotation((dire - 1) * pi / 2) * vector([0., 0., -1.]) chaem.mochae(timedelta) GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) GL.glUniformMatrix4fv(GL.glGetUniformLocation(shaderp, 'modelmatrix'), 1, False, modelmtx) GL.glUniformMatrix4fv(GL.glGetUniformLocation(shaderp, 'viewmatrix'), 1, False, chaem.lookat()) GL.glBindVertexArray(architincture) GL.glEnable(GL.GL_TEXTURE_2D) GL.glBindTexture(GL.GL_TEXTURE_2D, terrain) GL.glDrawArrays(GL.GL_QUADS, 0, len(vs)) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) GL.glBindVertexArray(0)
def create_object(shader): # Create a new VAO (Vertex Array Object) and bind it vertex_array_object = GL.glGenVertexArrays(1) GL.glBindVertexArray( vertex_array_object ) # Generate buffers to hold our vertices vertex_buffer = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, vertex_buffer) # Get the position of the 'position' in parameter of our shader and bind it. position = GL.glGetAttribLocation(shader, 'position') GL.glEnableVertexAttribArray(position) coord = GL.glGetAttribLocation(shader, 'coord') GL.glEnableVertexAttribArray(coord) # Describe the 'position' data layout in the buffer GL.glVertexAttribPointer(position, 2, GL.GL_FLOAT, False, 16, GL.GLvoidp(0)) GL.glVertexAttribPointer(coord, 2, GL.GL_FLOAT, False, 16, GL.GLvoidp(8)) # Send the data over to the buffer GL.glBufferData(GL.GL_ARRAY_BUFFER, 96, vertices, GL.GL_STATIC_DRAW) # Unbind the VAO first (Important) GL.glBindVertexArray(0) # Unbind other stuff GL.glDisableVertexAttribArray(position) GL.glDisableVertexAttribArray(coord) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0) return vertex_array_object
def bind_attrib(self, attrib_id, size, data, storagetype=gl.GL_STATIC_DRAW, instance_divisor=0, datatype=gl.GL_FLOAT, stride=0, offset=None, normalize=False): if RenderObject.bound_vao is not self.vao_id: gl.glBindVertexArray(self.vao_id) RenderObject.bound_vao = self.vao_id # Keep track of max instance divisor self.max_instance_divisor = max(instance_divisor, self.max_instance_divisor) # If the input is an array create a new GL buffer, otherwise assume the buffer already exists and a buffer ID is passed if type(data) is np.ndarray: # Get an index to one new buffer in GPU mem, bind it, and copy the array data to it buf_id = gl.glGenBuffers(1) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, buf_id) gl.glBufferData(gl.GL_ARRAY_BUFFER, data.nbytes, data, storagetype) else: # Assume that a GLuint is passed which means that the buffer is already in GPU memory buf_id = data gl.glBindBuffer(gl.GL_ARRAY_BUFFER, buf_id) # Assign this buffer to one of the attributes in the shader gl.glEnableVertexAttribArray(attrib_id) gl.glVertexAttribPointer(attrib_id, size, datatype, normalize, stride, offset) # For instanced data, indicate per how many instances we move a step in the buffer (1=per instance) if instance_divisor > 0: gl.glVertexAttribDivisor(attrib_id, instance_divisor) # Clean up gl.glDisableVertexAttribArray(attrib_id) self.enabled_attributes[attrib_id] = [size, buf_id, instance_divisor, datatype] return buf_id
def draw_grid(self,): gl.glUseProgram(self.simple_object_shader) gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) gl.glEnable(gl.GL_DEPTH_TEST) gl.glDepthFunc(gl.GL_LESS) gl.glBindVertexArray(self.grid_vao) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.grid_vbo) vProjection = gl.glGetUniformLocation(self.simple_object_shader, 'vProjection') vPosisition = gl.glGetAttribLocation(self.simple_object_shader, "vPosisition") vColor = gl.glGetAttribLocation(self.simple_object_shader, "vColor") vCamera = gl.glGetUniformLocation(self.simple_object_shader, 'vCamera') gl.glUniformMatrix4fv(vProjection, 1, gl.GL_FALSE, self.projection_matrix_function()) gl.glUniformMatrix4fv(vCamera, 1, gl.GL_FALSE, self.camera_matrix_function()) gl.glEnableVertexAttribArray(vPosisition) gl.glEnableVertexAttribArray(vColor) gl.glVertexAttribPointer(vPosisition, 4, gl.GL_FLOAT, gl.GL_FALSE, 0, None) gl.glVertexAttribPointer(vColor, 4, gl.GL_FLOAT, gl.GL_FALSE, 0, ctypes.c_void_p(self.grid_size * 4)) gl.glDrawArrays(gl.GL_TRIANGLES, 0, self.grid_size / 4)
def draw(self, tutorial_object): modelToCameraStack = MatrixStack() GL.glUseProgram(tutorial_object.theProgram) GL.glBindVertexArray(tutorial_object.vao) modelToCameraStack.translate(self.posBase) modelToCameraStack.rotateY(self.angBase) # Draw left base # modelToCameraStack.push() modelToCameraStack.translate(self.posBaseLeft) modelToCameraStack.scale([1.0, 1.0, self.scaleBaseZ]) GL.glUniformMatrix4fv(tutorial_object.modelToCameraMatrixUnif, 1, GL.GL_FALSE, modelToCameraStack.top().tolist()) GL.glDrawElements(GL.GL_TRIANGLES, len(tutorial_object.indexData), GL.GL_UNSIGNED_SHORT, None) modelToCameraStack.pop() # Draw right base # modelToCameraStack.push() modelToCameraStack.translate(self.posBaseRight) modelToCameraStack.scale([1.0, 1.0, self.scaleBaseZ]) GL.glUniformMatrix4fv(tutorial_object.modelToCameraMatrixUnif, 1, GL.GL_FALSE, modelToCameraStack.top().tolist()) GL.glDrawElements(GL.GL_TRIANGLES, len(tutorial_object.indexData), GL.GL_UNSIGNED_SHORT, None) modelToCameraStack.pop() # Draw main arm self.drawUpperArm(modelToCameraStack, tutorial_object) GL.glBindVertexArray(0) GL.glUseProgram(0)
def render(): global sampleTexture global shaderProgram global texUnitUniform global VAO GL.glClearColor(0, 0, 0, 1) GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) # active shader program GL.glUseProgram(shaderProgram) try: # Activate texture GL.glActiveTexture(GL.GL_TEXTURE0) GL.glBindTexture(GL.GL_TEXTURE_2D, sampleTexture) GL.glUniform1i(texUnitUniform, 0) # Activate array GL.glBindVertexArray(VAO) # draw triangle GL.glDrawArrays(GL.GL_TRIANGLES, 0, 3) finally: GL.glBindVertexArray(0) GL.glUseProgram(0)
def initializeGL(self): """ Create the graphic buffers and compile the shaders. """ # Create and bind a new VAO (Vertex Array Object). self.vertex_array_object = gl.glGenVertexArrays(1) gl.glBindVertexArray(self.vertex_array_object) # Upload color values (one for each triangle vertex) in RGB format. colBuf = gl.glGenBuffers(1) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, colBuf) col = np.array([1,0,0,0,1,0,0,0,1], dtype=np.float32) gl.glBufferData(gl.GL_ARRAY_BUFFER, col, gl.GL_STATIC_DRAW) gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 0, None) gl.glEnableVertexAttribArray(0) # Create and bind GPU buffer for vertex data. self.vertexBuffer = gl.glGenBuffers(1) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vertexBuffer) # Associate the vertex buffer with the "Layout 0" shader variable (look # for "v_N" variable in vertex shader program). gl.glVertexAttribPointer(1, 4, gl.GL_FLOAT, gl.GL_FALSE, 0, None) gl.glEnableVertexAttribArray(1) # Enable depth-sorting. gl.glEnable(gl.GL_DEPTH_TEST) gl.glDepthFunc(gl.GL_LESS) # Background color. gl.glClearColor(0, 0, 0, 0) # Compile- and install shader programs. self.shaders = self.linkShaders('blog4.vs', 'blog4.fs') gl.glUseProgram(self.shaders)
def _make_gl_selection_box(self): """ Creates the Vertex Array Object, Vertex Buffer Objects and fill the shaders with the data of the corresponding points. Since we will use two kind of drawing methods, lines and triangles, the index buffer will set to GL_DYNAMIC_DRAW, so as the coordinates, but not the colors, which will be set as GL_STATIC_DRAW. """ self.vao = GL.glGenVertexArrays(1) GL.glBindVertexArray(self.vao) ind_vbo = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, ind_vbo) GL.glBufferData(GL.GL_ELEMENT_ARRAY_BUFFER, self.indexes.itemsize*int(len(self.indexes)), self.indexes, GL.GL_DYNAMIC_DRAW) coord_vbo = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, coord_vbo) GL.glBufferData(GL.GL_ARRAY_BUFFER, self.points.itemsize*int(len(self.points)), self.points, GL.GL_DYNAMIC_DRAW) att_position = GL.glGetAttribLocation(self.selection_box_program, 'vert_coord') GL.glEnableVertexAttribArray(att_position) GL.glVertexAttribPointer(att_position, 2, GL.GL_FLOAT, GL.GL_FALSE, 2*self.points.itemsize, ctypes.c_void_p(0)) col_vbo = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, col_vbo) GL.glBufferData(GL.GL_ARRAY_BUFFER, self.color.itemsize*int(len(self.color)), self.color, GL.GL_STATIC_DRAW) att_colors = GL.glGetAttribLocation(self.selection_box_program, 'vert_color') GL.glEnableVertexAttribArray(att_colors) GL.glVertexAttribPointer(att_colors, 3, GL.GL_FLOAT, GL.GL_FALSE, 3*self.color.itemsize, ctypes.c_void_p(0)) GL.glBindVertexArray(0) GL.glDisableVertexAttribArray(att_position) GL.glDisableVertexAttribArray(att_colors) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0) GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, 0) self.buffers = (ind_vbo, coord_vbo, col_vbo)
def draw(self, **frame_data): view = frame_data.get('view_matrix', None) projection = frame_data.get('projection_matrix', None) if self._before_draw: self._before_draw(self, frame_data) if view is not None: self.world_matrix.dot(view, out=self._modelview) self._normal[:] = np.linalg.inv(self._modelview[:3,:3].T) for material, prims in self.primitives.items(): material.use(u_view=view, u_projection=projection, u_modelview=self._modelview, u_modelview_inverse_transpose=self._normal, u_model=self.world_matrix, frame_data=frame_data) technique = material.technique for prim in prims: gl.glBindVertexArray(prim.vaos[technique]) gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, prim.index_buffer) gl.glDrawElements(prim.mode, prim.indices.size, DTYPE_COMPONENT_TYPE[prim.indices.dtype], c_void_p(0)) if CHECK_GL_ERRORS: err = gl.glGetError() if err != gl.GL_NO_ERROR: raise Exception('error drawing primitive elements: %d' % err) gl.glBindVertexArray(0) # for location in technique.attribute_locations.values(): # gl.glDisableVertexAttribArray(location) material.release() material.technique.release() if self._after_draw: self._after_draw(self, frame_data) super().draw(**frame_data)
def _draw_selection_box(self): """ The drawing method for the selection box. Initially we will draw the box boundaries with lines, and then fill the interior with two triangles. IMPORTANT!!! THIS FUNCTION MUST BE CALLED ONLY WHEN AN OPENGL CONTEXT WINDOW HAS BEEN CREATED AND INITIALIZED, OTHERWISE WILL RAISE AN ERROR IN THE OPENGL WRAPPER!!! YOU HAVE BEEN WARNED """ GL.glUseProgram(self.selection_box_program) GL.glLineWidth(1) GL.glBindVertexArray(self.vao) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.buffers[1]) GL.glBufferData(GL.GL_ARRAY_BUFFER, self.points.itemsize*int(len(self.points)), self.points, GL.GL_DYNAMIC_DRAW) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.buffers[0]) GL.glBufferData(GL.GL_ARRAY_BUFFER, self.indexes.itemsize*int(len(self.indexes)), self.indexes, GL.GL_DYNAMIC_DRAW) GL.glDrawElements(GL.GL_LINE_STRIP, int(len(self.indexes)), GL.GL_UNSIGNED_INT, None) GL.glEnable(GL.GL_DEPTH_TEST) GL.glEnable(GL.GL_BLEND) GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_SRC_ALPHA) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.buffers[0]) GL.glBufferData(GL.GL_ARRAY_BUFFER, self.triangles.itemsize*int(len(self.triangles)), self.triangles, GL.GL_DYNAMIC_DRAW) GL.glDrawElements(GL.GL_TRIANGLE_STRIP, int(len(self.triangles)), GL.GL_UNSIGNED_INT, None) GL.glDisable(GL.GL_BLEND) GL.glDisable(GL.GL_DEPTH_TEST) GL.glBindVertexArray(0) GL.glUseProgram(0) return True
def __init__(self, vertices, normals, indices, draw_method): self.draw_method = draw_method self.indices = indices self.vao = GL.glGenVertexArrays(1) GL.glBindVertexArray(self.vao) vertexBufferObject = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, vertexBufferObject) data = vertices + normals array_type = (GL.GLfloat*len(data)) GL.glBufferData( GL.GL_ARRAY_BUFFER, len(data)*FLOAT_SIZE, array_type(*data), GL.GL_STATIC_DRAW) GL.glEnableVertexAttribArray(0) GL.glEnableVertexAttribArray(1) GL.glVertexAttribPointer(0, 3, GL.GL_FLOAT, GL.GL_FALSE, 0, None) GL.glVertexAttribPointer(1, 3, GL.GL_FLOAT, GL.GL_FALSE, 0, GL.GLvoidp(len(vertices)*FLOAT_SIZE)) indexBufferObject = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, indexBufferObject) array_type = (GL.GLuint*len(self.indices)) GL.glBufferData( GL.GL_ELEMENT_ARRAY_BUFFER, len(self.indices)*FLOAT_SIZE, array_type(*self.indices), GL.GL_STATIC_DRAW) GL.glBindVertexArray(0)
def init_gl(self, force=False): if self._initialized and not force: return self._initialized = False for material, prims in self.primitives.items(): material.init_gl(force=force) technique = material.technique for prim in prims: prim.init_gl(force=force) if technique in prim.vaos: continue vao = gl.glGenVertexArrays(1) prim.vaos[technique] = vao gl.glBindVertexArray(vao) for attribute_name, location in technique.attribute_locations.items(): attribute = prim.attributes[attribute_name] gl.glEnableVertexAttribArray(location) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, prim.buffers[attribute_name]) gl.glVertexAttribPointer(location, attribute.shape[-1], DTYPE_COMPONENT_TYPE[attribute.dtype], False, attribute.dtype.itemsize * attribute.shape[-1], NULL_PTR) if attribute_name in technique.attribute_divisors: gl.glVertexAttribDivisor(location, technique.attribute_divisors[attribute_name]) gl.glBindVertexArray(0) for location in technique.attribute_locations.values(): gl.glDisableVertexAttribArray(location) err = gl.glGetError() if err != gl.GL_NO_ERROR: raise Exception('failed to init primitive: %s' % err) _logger.info('%s.init_gl: OK' % self.__class__.__name__) self._initialized = True
def draw(self): assert threading.current_thread() is threading.main_thread() if self.dirty or not self.vao: self.bind() assert opengl_current_context() == self.context, "Cannot invoke Renderer from a different OpenGL context" gl.glBindVertexArray(self.vao) indexed = (self.indices is not None) if self.command == "points": mode = gl.GL_POINTS elif self.command == "lines": mode = gl.GL_LINES elif self.command == "triangles": mode = gl.GL_TRIANGLES elif self.command == "triangle_strip": mode = gl.GL_TRIANGLE_STRIP elif self.command == "triangle_fan": mode = gl.GL_TRIANGLE_FAN else: raise ValueError(self.command) if not indexed: if not self.instanced: gl.glDrawArrays(mode, 0, self.length) else: gl.glDrawArraysInstanced(mode, 0, self.length, self.instances) else: if not self.instanced: gl.glDrawElements(mode, self.indices.length, self.indices.gl_dtype, ctypes.c_void_p(self.indices.offset)) else: gl.glDrawElementsInstanced(mode, self.indices.length, self.indices.gl_dtype, ctypes.c_void_p(self.indices.offset), self.instances)
def __init__(self, vertices, indices, draw_method): from . import SHORT_SIZE, FLOAT_SIZE self.draw_method = draw_method self.indices = indices self.vao = GL.glGenVertexArrays(1) GL.glBindVertexArray(self.vao) vertexBufferObject = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, vertexBufferObject) array_type = (GL.GLfloat*len(vertices)) GL.glBufferData( GL.GL_ARRAY_BUFFER, len(vertices)*FLOAT_SIZE, array_type(*vertices), GL.GL_STATIC_DRAW) GL.glEnableVertexAttribArray(0) GL.glVertexAttribPointer(0, 3, GL.GL_FLOAT, GL.GL_FALSE, 0, None) indexBufferObject = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, indexBufferObject) array_type = (GL.GLushort*len(self.indices)) GL.glBufferData( GL.GL_ELEMENT_ARRAY_BUFFER, len(self.indices)*SHORT_SIZE, array_type(*self.indices), GL.GL_STATIC_DRAW) GL.glBindVertexArray(0)
def setAttributes(self, data): self.data = data self.dataLen = data.shape[0] # Make this buffer the default one gl.glBindVertexArray(self.VAO) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.buffer) # Upload data gl.glBufferData(gl.GL_ARRAY_BUFFER, data.nbytes, data, gl.GL_DYNAMIC_DRAW) offset = 0 for i, name in enumerate(data.dtype.names): # import ipdb; ipdb.set_trace() stride = data[name].strides[0] if data[name].ndim == 1: size = 1 else: size = data[name].shape[1] loc = gl.glGetAttribLocation(self.program, name) # remember these properties for later updating of buffer self.attribute_layout[name] = {'offset':offset} gl.glVertexAttribPointer(loc, size, gl.GL_FLOAT, False, stride, ctypes.c_void_p(offset)) gl.glEnableVertexAttribArray(loc) offset += data.dtype[name].itemsize gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0) gl.glBindVertexArray(0) # ensure correct mask is rendered: self.setMask()
def bind(self): assert threading.current_thread() is threading.main_thread() length = None first_atname = None if self.instanced: instances = None instanced_first_atname = None vao = gl.glGenVertexArrays(1) gl.glBindVertexArray(vao) if self.indices: self.indices.bind() for atname, at in self.attributes.items(): at.bind() if at.instanced: if instances is None: instances = at.length instanced_first_atname = atname if instances != at.length: raise ValueError((instanced_first_atname, instances), (atname, at.length)) else: if length is None: length = at.length first_atname = atname if length != at.length: raise ValueError((first_atname, length), (atname, at.length)) if length is None: length = 0 if self.instanced: self.instances = instances self.length = length self.vao = vao self.dirty = False
def init(): initialize_program() initialize_vertex_buffer() n = 1 vao_array = N.zeros(n, dtype=N.uint) vao_array = GL.glGenVertexArrays(n) GL.glBindVertexArray( vao_array )
def _make_sel_gl_dots(program, vismol_object = None, bckgrnd_color= [1.0,1.0,1.0,1.0]): """ Function doc """ colors = vismol_object.color_indexes dot_sizes = vismol_object.vdw_dot_sizes coords = vismol_object.frames[0] dot_qtty = int(len(coords)/3) bckgrnd_color = [bckgrnd_color[0],bckgrnd_color[1], bckgrnd_color[2],bckgrnd_color[3]]*dot_qtty bckgrnd_color = np.array(bckgrnd_color, dtype=np.float32) indexes = np.array(vismol_object.dot_indexes,dtype=np.uint32) vao = GL.glGenVertexArrays(1) GL.glBindVertexArray(vao) ind_vbo = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, ind_vbo) GL.glBufferData(GL.GL_ELEMENT_ARRAY_BUFFER, indexes.itemsize*int(len(indexes)), indexes, GL.GL_DYNAMIC_DRAW) coord_vbo = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, coord_vbo) GL.glBufferData(GL.GL_ARRAY_BUFFER, coords.itemsize*int(len(coords)), coords, GL.GL_STATIC_DRAW) att_position = GL.glGetAttribLocation(program, 'vert_coord') GL.glEnableVertexAttribArray(att_position) GL.glVertexAttribPointer(att_position, 3, GL.GL_FLOAT, GL.GL_FALSE, 3*coords.itemsize, ctypes.c_void_p(0)) col_vbo = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, col_vbo) GL.glBufferData(GL.GL_ARRAY_BUFFER, colors.itemsize*int(len(colors)), colors, GL.GL_STATIC_DRAW) att_colors = GL.glGetAttribLocation(program, 'vert_color') GL.glEnableVertexAttribArray(att_colors) GL.glVertexAttribPointer(att_colors, 3, GL.GL_FLOAT, GL.GL_FALSE, 3*colors.itemsize, ctypes.c_void_p(0)) dot_vbo = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, dot_vbo) GL.glBufferData(GL.GL_ARRAY_BUFFER, dot_sizes.itemsize*len(dot_sizes), dot_sizes, GL.GL_STATIC_DRAW) att_size = GL.glGetAttribLocation(program, 'vert_dot_size') GL.glEnableVertexAttribArray(att_size) GL.glVertexAttribPointer(att_size, 1, GL.GL_FLOAT, GL.GL_FALSE, dot_sizes.itemsize, ctypes.c_void_p(0)) bckgrnd_vbo = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, bckgrnd_vbo) GL.glBufferData(GL.GL_ARRAY_BUFFER, bckgrnd_color.itemsize*len(bckgrnd_color), bckgrnd_color, GL.GL_STATIC_DRAW) att_bck_color = GL.glGetAttribLocation(program, 'bckgrnd_color') GL.glEnableVertexAttribArray(att_bck_color) GL.glVertexAttribPointer(att_bck_color, 4, GL.GL_FLOAT, GL.GL_FALSE, 4*bckgrnd_color.itemsize, ctypes.c_void_p(0)) GL.glBindVertexArray(0) GL.glDisableVertexAttribArray(att_position) GL.glDisableVertexAttribArray(att_colors) GL.glDisableVertexAttribArray(att_size) GL.glDisableVertexAttribArray(att_bck_color) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0) GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, 0) vismol_object.sel_dots_vao = vao vismol_object.sel_dot_buffers = (ind_vbo, coord_vbo, col_vbo) return True
def drawCube(self, pos, ori, size, col=None): #this function expects center of the cube, orientation, and size as (length(x), breadh(y), height(z)) # glfw.make_context_current(self.window) # Draw Cube (multiple quads) # self.gui_lock.acquire() # gl.glBindVertexArray(self._VAO) gl.glLoadIdentity() gl.glTranslatef(pos[0],pos[1],pos[2]) gl.glScalef(size[0],size[1],size[0]) gl.glRotatef(ori[0],1.0,0.0,0.0) gl.glRotatef(ori[1],0.0,1.0,0.0) gl.glRotatef(ori[2],0.0,0.0,1.0) # Draw Cube (multiple quads) gl.glBegin(gl.GL_QUADS) gl.glColor3f(0.0,1.0,0.0) gl.glVertex3f( 1.0, 1.0,-1.0) gl.glVertex3f(-1.0, 1.0,-1.0) gl.glVertex3f(-1.0, 1.0, 1.0) gl.glVertex3f( 1.0, 1.0, 1.0) gl.glColor3f(1.0,0.0,0.0) gl.glVertex3f( 1.0,-1.0, 1.0) gl.glVertex3f(-1.0,-1.0, 1.0) gl.glVertex3f(-1.0,-1.0,-1.0) gl.glVertex3f( 1.0,-1.0,-1.0) gl.glColor3f(0.0,1.0,0.0) gl.glVertex3f( 1.0, 1.0, 1.0) gl.glVertex3f(-1.0, 1.0, 1.0) gl.glVertex3f(-1.0,-1.0, 1.0) gl.glVertex3f( 1.0,-1.0, 1.0) gl.glColor3f(1.0,1.0,0.0) gl.glVertex3f( 1.0,-1.0,-1.0) gl.glVertex3f(-1.0,-1.0,-1.0) gl.glVertex3f(-1.0, 1.0,-1.0) gl.glVertex3f( 1.0, 1.0,-1.0) gl.glColor3f(0.0,0.0,1.0) gl.glVertex3f(-1.0, 1.0, 1.0) gl.glVertex3f(-1.0, 1.0,-1.0) gl.glVertex3f(-1.0,-1.0,-1.0) gl.glVertex3f(-1.0,-1.0, 1.0) gl.glColor3f(1.0,0.0,1.0) gl.glVertex3f( 1.0, 1.0,-1.0) gl.glVertex3f( 1.0, 1.0, 1.0) gl.glVertex3f( 1.0,-1.0, 1.0) gl.glVertex3f( 1.0,-1.0,-1.0) gl.glEnd() gl.glBindVertexArray(0)
def initialize(self): # Load Shader self.window = Window('009.vs', '009.frag', 'window.png') # Enable Transparency GL.glEnable(GL.GL_BLEND); GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); # Same Data as EBO w/ Indices for buffers vertexData = numpy.array([ # Positions # Color # Texture 0.5, 0.5, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, # Top Right 0.5, -0.5, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, # Bottom Right -0.5, -0.5, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, # Bottom Left -0.5, 0.5, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, # Top Left ], dtype=numpy.float32) indexData = numpy.array([ 0, 1, 2, # First Triangle 0, 2, 3, # Second Triangle ], dtype=numpy.uint32) self.index_size = indexData.size # Core OpenGL requires that at least one OpenGL vertex array be bound self.VAO = GL.glGenVertexArrays(1) GL.glBindVertexArray(self.VAO) # Need VBO for triangle vertices VBO = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, VBO) GL.glBufferData(GL.GL_ARRAY_BUFFER, vertexData.nbytes, vertexData, GL.GL_STATIC_DRAW) # We make an EBO now EBO = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, EBO) GL.glBufferData(GL.GL_ELEMENT_ARRAY_BUFFER, indexData.nbytes, indexData, GL.GL_STATIC_DRAW) # Define Stride stride = 8 * ctypes.sizeof(_types.GLfloat) # enable array and set up data - calculating stride length, wow; not documented GL.glVertexAttribPointer(0, 3, GL.GL_FLOAT, GL.GL_FALSE, stride, None) GL.glEnableVertexAttribArray(0) # I like how offsets aren't documented either; http://pyopengl.sourceforge.net/documentation/manual-3.0/glVertexAttribPointer.html # offsets https://twistedpairdevelopment.wordpress.com/2013/02/16/using-array_buffers-in-pyopengl/ # http://stackoverflow.com/questions/11132716/how-to-specify-buffer-offset-with-pyopengl GL.glVertexAttribPointer(1, 3, GL.GL_FLOAT, GL.GL_FALSE, stride, ctypes.c_void_p((3 * ctypes.sizeof(_types.GLfloat)))) GL.glEnableVertexAttribArray(1) GL.glVertexAttribPointer(2, 2, GL.GL_FLOAT, GL.GL_FALSE, stride, ctypes.c_void_p((6 * ctypes.sizeof(_types.GLfloat)))) GL.glEnableVertexAttribArray(2) # Unbind so we don't mess w/ them GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0) GL.glBindVertexArray(0)
def draw_planes(): # Enable shader program gl.glUseProgram(program) # Set view matrix view = ut.matLookAt(camPosition[0], camPosition[1], camPosition[2], camTarget[0], camTarget[1], camTarget[2], camUp[0], camUp[1], camUp[2]) loc = gl.glGetUniformLocation(program, "view") gl.glUniformMatrix4fv(loc, 1, gl.GL_FALSE, view.transpose()) # Set projection matrix projection = ut.matPerspective(np.radians(fov), win_width/win_height, 0.1, 100.0) loc = gl.glGetUniformLocation(program, "projection") gl.glUniformMatrix4fv(loc, 1, gl.GL_FALSE, projection.transpose()) # Set current model matrix (global) loc = gl.glGetUniformLocation(program, "model") gl.glUniformMatrix4fv(loc, 1, gl.GL_FALSE, model.transpose()) # Set light attributes loc = gl.glGetUniformLocation(program, "lightColor") gl.glUniform3f(loc, lightColor[0], lightColor[1], lightColor[2]) loc = gl.glGetUniformLocation(program, "lightPosition") gl.glUniform3f(loc, lightPosition[0], lightPosition[1], lightPosition[2]) # Set color attributes for mesh loc = gl.glGetUniformLocation(program, "objectColor") gl.glUniform4f(loc, planeColor[0], planeColor[1], planeColor[2], planeColor[3]) # Set current model matrix (global) S = ut.matScale(1.5,1.5,1.0) loc = gl.glGetUniformLocation(program, "model") gl.glUniformMatrix4fv(loc, 1, gl.GL_FALSE, np.matmul(model,S).transpose()) # Draw planes gl.glBindVertexArray(VAO_planes) gl.glDrawArrays(gl.GL_TRIANGLES, 0, num_vertices_planes) gl.glBindVertexArray(0)
def make_circles(program): """ Function doc """ vertex_array_object = GL.glGenVertexArrays(1) GL.glBindVertexArray(vertex_array_object) coords = np.array([ 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 1.0, 0.0, -1.0, -1.0, 0.0, 0.0, -1.0, 0.0, 1.0, -1.0, 0.0, 0.0, 0.0, 0.0 ], dtype=np.float32) colors = np.array([ 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0 ], dtype=np.float32) coord_vbo = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, coord_vbo) GL.glBufferData(GL.GL_ARRAY_BUFFER, coords.itemsize * len(coords), coords, GL.GL_STATIC_DRAW) position = GL.glGetAttribLocation(program, 'vert_coord') GL.glEnableVertexAttribArray(position) GL.glVertexAttribPointer(position, 3, GL.GL_FLOAT, GL.GL_FALSE, 3 * coords.itemsize, ctypes.c_void_p(0)) col_vbo = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, col_vbo) GL.glBufferData(GL.GL_ARRAY_BUFFER, colors.itemsize * len(colors), colors, GL.GL_STATIC_DRAW) gl_colors = GL.glGetAttribLocation(program, 'vert_color') GL.glEnableVertexAttribArray(gl_colors) GL.glVertexAttribPointer(gl_colors, 3, GL.GL_FLOAT, GL.GL_FALSE, 3 * colors.itemsize, ctypes.c_void_p(0)) GL.glBindVertexArray(0) GL.glDisableVertexAttribArray(position) GL.glDisableVertexAttribArray(gl_colors) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0) return vertex_array_object, (coord_vbo, col_vbo), int(len(coords))
def init_gl(self, force=False): if self._initialized and not force: return self._initialized = False for material, prims in self.primitives.items(): material.init_gl(force=force) technique = material.technique for prim in prims: prim.init_gl(force=force) if technique in prim.vaos: continue vao = gl.glGenVertexArrays(1) prim.vaos[technique] = vao gl.glBindVertexArray(vao) for attribute_name, location in technique.attribute_locations.items( ): attribute = prim.attributes[attribute_name] gl.glEnableVertexAttribArray(location) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, prim.buffers[attribute_name]) gl.glVertexAttribPointer( location, attribute.shape[-1], DTYPE_COMPONENT_TYPE[attribute.dtype], False, attribute.dtype.itemsize * attribute.shape[-1], NULL_PTR) if attribute_name in technique.attribute_divisors: gl.glVertexAttribDivisor( location, technique.attribute_divisors[attribute_name]) gl.glBindVertexArray(0) for location in technique.attribute_locations.values(): gl.glDisableVertexAttribArray(location) err = gl.glGetError() if err != gl.GL_NO_ERROR: raise Exception('failed to init primitive: %s' % err) _logger.info('%s.init_gl: OK' % self.__class__.__name__) self._initialized = True
def process(self): gl.glEnable(gl.GL_CULL_FACE) gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) shader: WaterShader = self.world.water_shader shader.start() shader.load_view_matrix(self.world.view_matrix) shader.load_projection_matrix(self.world.projection_matrix) shader.load_light_setup(self.world.light_setup) shader.add_delta(self.world.delta) for _id, (mesh, transformation) in self.world.get_components( TerrainMesh, TransformationMatrix): # Bind buffers gl.glBindVertexArray(mesh.vba_id) mesh.index_buffer.bind() gl.glEnableVertexAttribArray(TerrainMesh.TEX_COORDS_ATTR) gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture( gl.GL_TEXTURE_2D, mesh.height_maps[self.world.height_map_index].texture) gl.glUniform1i(shader.u_tex_map, 0) # Draw the beautiful shader.load_transformation_matrix(transformation.value) gl.glDrawElements(gl.GL_TRIANGLES, mesh.vertex_count, gl.GL_UNSIGNED_INT, None) # Unbind the thingies gl.glDisableVertexAttribArray(TerrainMesh.TEX_COORDS_ATTR) gl.glBindVertexArray(0) shader.stop() gl.glDisable(gl.GL_BLEND) gl.glDisable(gl.GL_CULL_FACE)
def set_up_scene(self): self.vertex_data = [] v = self.scene_volume_init s = self.scale_spacing scale = 0.3 mat_scale = numpy.diag( numpy.array([scale, scale, scale, 1], dtype=numpy.float32)) t = -0.5 * v * s mat_translate = translate(t, t, t) mat = mat_translate @ mat_scale for z in range(v): for y in range(v): for x in range(v): self.add_cube_to_scene(mat) mat = translate(s, 0, 0) @ mat mat = translate(-v * s, s, 0) @ mat mat = translate(0, -v * s, s) @ mat vertex_data = numpy.array(self.vertex_data, dtype=numpy.float32).flatten() self.vert_count = len(vertex_data) / 5 self.scene_vao = GL.glGenVertexArrays(1) GL.glBindVertexArray(self.scene_vao) self.scene_vert_buffer = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.scene_vert_buffer) GL.glBufferData(GL.GL_ARRAY_BUFFER, vertex_data, GL.GL_STATIC_DRAW) f_size = sizeof(c_float) stride = 5 * f_size GL.glEnableVertexAttribArray(0) GL.glVertexAttribPointer(0, 3, GL.GL_FLOAT, False, stride, cast(0 * f_size, c_void_p)) GL.glEnableVertexAttribArray(1) GL.glVertexAttribPointer(1, 2, GL.GL_FLOAT, False, stride, cast(3 * f_size, c_void_p)) GL.glBindVertexArray(0) GL.glDisableVertexAttribArray(0) GL.glDisableVertexAttribArray(1)
def initialize(self): vertices_a = np.array([ -0.6, -0.5, 0.0, 0.4, -0.5, 0.0, -0.1, 0.5, 0.0], dtype=np.float32) vertices_b = np.array([ 0.1, 0.5, 0.0, 0.6, -0.5, 0.0, 1.0, 0.5, 0.0 ], dtype=np.float32) self._vao_a = GL.glGenVertexArrays(1) GL.glBindVertexArray(self._vao_a) vbo = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, vbo) GL.glBufferData(GL.GL_ARRAY_BUFFER, vertices_a, GL.GL_STATIC_DRAW) GL.glVertexAttribPointer(0, 3, GL.GL_FLOAT, GL.GL_FALSE, 3 * ctypes.sizeof(ctypes.c_float), None) GL.glEnableVertexAttribArray(0) GL.glBindVertexArray(0) self._vao_b = GL.glGenVertexArrays(1) GL.glBindVertexArray(self._vao_b) vbo = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, vbo) GL.glBufferData(GL.GL_ARRAY_BUFFER, vertices_b, GL.GL_STATIC_DRAW) GL.glVertexAttribPointer(0, 3, GL.GL_FLOAT, GL.GL_FALSE, 3 * ctypes.sizeof(ctypes.c_float), None) GL.glEnableVertexAttribArray(0) GL.glBindVertexArray(0) vertex_shader = Shader(GL.GL_VERTEX_SHADER, "shaders_src/hello_triangle_vertex.glsl") fragment_shader_orange = Shader(GL.GL_FRAGMENT_SHADER, "shaders_src/hello_triangle_ex3_frag.glsl.template", color="1.0, 0.6, 0.2, 1.0") fragment_shader_pink = Shader(GL.GL_FRAGMENT_SHADER, "shaders_src/hello_triangle_ex3_frag.glsl.template", color="1.0, 0.75, 0.8, 1.0") self._shader_program_orange = ShaderProgram(vertex_shader, fragment_shader_orange) self._shader_program_pink = ShaderProgram(vertex_shader, fragment_shader_pink) vertex_shader.delete() fragment_shader_orange.delete() fragment_shader_pink.delete()
def __init__(self, shader): self.shader = shader self.color = (1, 0, 1) # triangle position buffer position = np.array(((0, 0.5, 0), (0.5, -.5, 0), (-.5, -.5, 0)), 'f') color = np.array(((1, 0, 0), (0, 1, 0), (0, 0, 1)), 'f') self.glid = GL.glGenVertexArrays(1) # create OpenGL vertex array id GL.glBindVertexArray(self.glid) # activate to receive state below # self.buffers = [GL.glGenBuffers(1)] # create buffer for position attrib # GL.glGenBuffers(n) with n > 1 directly returns a list and not an index self.buffers = GL.glGenBuffers(2) # if n > 1, use this instead # bind the vbo, upload position data to GPU, declare its size and type GL.glEnableVertexAttribArray(0) # assign to layout = 0 attribute GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.buffers[0]) GL.glBufferData(GL.GL_ARRAY_BUFFER, position, GL.GL_STATIC_DRAW) GL.glVertexAttribPointer(0, 3, GL.GL_FLOAT, False, 0, None) GL.glEnableVertexAttribArray(1) # assign to layout = 0 attribute GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.buffers[1]) GL.glBufferData(GL.GL_ARRAY_BUFFER, color, GL.GL_STATIC_DRAW) GL.glVertexAttribPointer(1, 3, GL.GL_FLOAT, False, 0, None)
def draw_segments(): # Enable shader program for segments gl.glUseProgram(program2) # Set view matrix view = ut.matLookAt(camPosition[0], camPosition[1], camPosition[2], camTarget[0], camTarget[1], camTarget[2], camUp[0], camUp[1], camUp[2]) loc = gl.glGetUniformLocation(program2, "view") gl.glUniformMatrix4fv(loc, 1, gl.GL_FALSE, view.transpose()) # Set projection matrix projection = ut.matPerspective(np.radians(fov), win_width/win_height, 0.1, 100.0) loc = gl.glGetUniformLocation(program2, "projection") gl.glUniformMatrix4fv(loc, 1, gl.GL_FALSE, projection.transpose()) # Set current model matrix (global) loc = gl.glGetUniformLocation(program2, "model") gl.glUniformMatrix4fv(loc, 1, gl.GL_FALSE, model.transpose()) # Draw segments gl.glLineWidth(1.5) gl.glBindVertexArray(VAO_segments) gl.glDrawArrays(gl.GL_LINES, 0, num_vertices_segments) gl.glBindVertexArray(0) gl.glLineWidth(1.0)
def __createBuffer(self): self.__VAO = gl.glGenVertexArrays(1) self.__positionVBO = gl.glGenBuffers(1) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.__positionVBO) gl.glBufferData(gl.GL_ARRAY_BUFFER, self.__vertexPosition.nbytes, self.__vertexPosition, gl.GL_STATIC_DRAW) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0) if (len(self.__vertexIndices) > 0): gl.glBindVertexArray(self.__VAO) self.__EBO = gl.glGenBuffers(1) gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, self.__EBO) gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER, self.__vertexIndices.nbytes, self.__vertexIndices, gl.GL_STATIC_DRAW) gl.glBindVertexArray(0) if (len(self.__vertexColor) > 0): self.__colorVBO = gl.glGenBuffers(1) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.__colorVBO) gl.glBufferData(gl.GL_ARRAY_BUFFER, self.__vertexColor.nbytes, self.__vertexColor, gl.GL_STATIC_DRAW) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0)
def initialise_gl(self): state = OpenGLContextState() state.shader_program.addShaderFromSourceCode(QOpenGLShader.Vertex, VERTEX) state.shader_program.addShaderFromSourceCode(QOpenGLShader.Fragment, FRAGMENT) if not state.shader_program.link(): raise Exception("Could not link shaders - {}".format( state.shader_program.log())) state.vertex_attribute_object = GL.glGenVertexArrays(1) GL.glBindVertexArray(state.vertex_attribute_object) vertex_buffer_object = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, vertex_buffer_object) GL.glBufferData(GL.GL_ARRAY_BUFFER, self.vertex_data.nbytes, self.vertex_data, GL.GL_STATIC_DRAW) state.invert = state.shader_program.uniformLocation("invert") state.projection = state.shader_program.uniformLocation("projection") state.view = state.shader_program.uniformLocation("view") state.model = state.shader_program.uniformLocation("model") state.vertex_position = state.shader_program.attributeLocation( "vertexPosition") GL.glVertexAttribPointer(state.vertex_position, 3, GL.GL_FLOAT, GL.GL_FALSE, 0, None) GL.glEnableVertexAttribArray(0) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0) GL.glBindVertexArray(0) return state
def update(self): if not self.loaded: return None if not self.renderFlag_b: return None for key_s in self.vertices_d: obj_d = self.vertices_d[key_s] gl.glBindVertexArray(obj_d["vao"]) gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(gl.GL_TEXTURE_2D, obj_d["txid"]) #### To vertex shader #### gl.glUniformMatrix4fv(3, 1, gl.GL_FALSE, self.getModelMatrix()) #### To fragment shader #### gl.glUniform1f(11, self.shininess_f) gl.glUniform1f(53, self.specularStrength_f) #### #### gl.glDrawArrays(gl.GL_TRIANGLES, 0, obj_d["ver_num"])
def render(self, offset, window_dimensions): font_height = self.img_dimensions[1] / 16 font_width = self.img_dimensions[0] / 16 gl.glBindVertexArray(self.vao) gl.glViewport(0, 0, window_dimensions[0], window_dimensions[1]) gl.glUseProgram(self.shader) gl.glBindTexture(gl.GL_TEXTURE_2D, self.texture_ids['font']) view_matrix = get_view_matrix(1.0, 1.0) proj_matrix = get_projection_matrix(0, window_dimensions[0], 0, window_dimensions[1]) gl.glUniformMatrix4fv(self.uniform_locs['view_matrix'], 1, gl.GL_TRUE, view_matrix) gl.glUniformMatrix4fv(self.uniform_locs['proj_matrix'], 1, gl.GL_TRUE, proj_matrix) model_matrix = get_4x4_transform(font_width, font_height, offset[0], offset[1], 1.0) gl.glUniformMatrix4fv(self.uniform_locs['model_matrix'], 1, gl.GL_TRUE, model_matrix) gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, self.index_buffers['vert_indexes']) gl.glDrawElements(gl.GL_TRIANGLES, len(self.indexes), gl.GL_UNSIGNED_INT, ctypes.c_void_p(0))
def process(self): # Ugly hacks, because hacker man!! # You should delete this command before you hand in the assignment # nawww ~xFrednet shader: StandardShaderProgram = self.world.standard_shader for _id, (vba, translation, material) in self.world.get_components( StandardShaderVertexArray, com.TransformationMatrix, com.ObjectMaterial): # Bind buffers gl.glBindVertexArray(vba.vertex_array_id) gl.glEnableVertexAttribArray(shader.POSITION_ATTR) gl.glEnableVertexAttribArray(shader.NORMAL_ATTR) # Draw the beautiful shader.set_transformation_matrix(translation.value) shader.set_object_material(material) gl.glDrawArrays(gl.GL_TRIANGLES, 0, vba.vertex_count) # Unbind the thingies gl.glDisableVertexAttribArray(shader.POSITION_ATTR) gl.glDisableVertexAttribArray(shader.NORMAL_ATTR) gl.glBindVertexArray(0)
def initialize(self): vertices = np.array([-0.5, -0.5, 0.0, 0.5, -0.5, 0.0, 0.0, 0.5, 0.0], dtype=np.float32) self._vao = GL.glGenVertexArrays(1) GL.glBindVertexArray(self._vao) vbo = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, vbo) GL.glBufferData(GL.GL_ARRAY_BUFFER, vertices, GL.GL_STATIC_DRAW) GL.glVertexAttribPointer(0, 3, GL.GL_FLOAT, GL.GL_FALSE, 3 * ctypes.sizeof(ctypes.c_float), None) GL.glEnableVertexAttribArray(0) GL.glBindVertexArray(0) vertex_shader = Shader(GL.GL_VERTEX_SHADER, "shaders_src/hello_triangle_vertex.glsl") fragment_shader = Shader(GL.GL_FRAGMENT_SHADER, "shaders_src/hello_triangle_frag.glsl") self._shader_program = ShaderProgram(vertex_shader, fragment_shader) vertex_shader.delete() fragment_shader.delete()
def render(self): if self.crt and not self.disable_crt: GL.glUseProgram(self.crt_shader.program) GL.glUniform1i(self.crt_tex_uniform, 0) GL.glUniform2f(self.crt_res_uniform, self.width, self.height) GL.glUniform1f(self.crt_time_uniform, self.app.get_elapsed_time()) else: GL.glUseProgram(self.plain_shader.program) GL.glUniform1i(self.plain_tex_uniform, 0) GL.glBindTexture(GL.GL_TEXTURE_2D, self.texture) GL.glClearColor(*self.clear_color) GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) # VAO vs non-VAO paths if self.app.use_vao: GL.glBindVertexArray(self.vao) else: GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.vbo) GL.glVertexAttribPointer(self.plain_attrib, 2, GL.GL_FLOAT, GL.GL_FALSE, 0, None) GL.glEnableVertexAttribArray(self.plain_attrib) GL.glDrawArrays(GL.GL_TRIANGLE_STRIP, 0, 4) if self.app.use_vao: GL.glBindVertexArray(0) GL.glUseProgram(0)
def initgl(self): vert = resources.read_text("plots.shaders", "text_vert.glsl") frag = resources.read_text("plots.shaders", "text_frag.glsl") vert = shaders.compileShader(vert, gl.GL_VERTEX_SHADER) frag = shaders.compileShader(frag, gl.GL_FRAGMENT_SHADER) self.shaderProgram = shaders.compileProgram(vert, frag) self.vbo = vbo.VBO(np.array([ # x y u v 0, -1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, -1, 0, 0, 1, 0, 1, 1, 1, -1, 1, 0 ], 'f'), usage="GL_STATIC_DRAW") self.vao = gl.glGenVertexArrays(1) gl.glBindVertexArray(self.vao) self.vbo.bind() self.vbo.copy_data() gl.glVertexAttribPointer(0, 4, gl.GL_FLOAT, False, 4*self.vbo.data.itemsize, self.vbo) gl.glEnableVertexAttribArray(0) self.vbo.unbind() gl.glBindVertexArray(0)
def draw(self, projection, view, model, color_shader): GL.glUseProgram(color_shader.glid) matrix_location = GL.glGetUniformLocation(color_shader.glid, 'matrix') # matrix = frustum(-20, 20, -20, 20, -20, 20) # print(matrix) matrix = perspective(45, 480 / 640, -20, 100) # print(matrix) # matrix_S = scale(0.5) # matrix[0][0] = matrix_S[0][0] # matrix[1][1] = matrix_S[1][1] # matrix[2][1] = matrix_S[2][2] # matrix[3][3] = matrix_S[3][3] # matrix = matrix @ matrix_S matrix = matrix @ projection #rotate(vec(0, 0, 1), 45) GL.glUniformMatrix4fv(matrix_location, 1, True, matrix) # draw triangle as GL_TRIANGLE vertex array, draw array call GL.glBindVertexArray(self.glid) GL.glDrawArrays(GL.GL_TRIANGLES, 0, 3) GL.glBindVertexArray(0)
def drawTexture(self, texture, opacity): """ Draw `texture` on the screen. Args: texture (:class:Texture): texture instance opacity (float): opacity (alpha) of the texture 0 --> transparent 1 --> opaque """ self.screenProgram.bind() gl.glBindVertexArray(self._vaoQuad) gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, self.IBO) texture.bind(2) self.screenProgram.setUniforms(( ('u_screen', 2), ('u_opacity', opacity), )) gl.glDrawElements(gl.GL_TRIANGLES, 6, gl.GL_UNSIGNED_INT, ctypes.c_void_p(0)) self.screenProgram.unbind() gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, 0) gl.glBindVertexArray(0) texture.unbind()
def main(): glfw.init() glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) window = glfw.create_window(WIN_WIDTH, WIN_HEIGHT, "learning openGL", None, None) if window == 0: print("failed to create window") glfw.terminate() glfw.make_context_current(window) glfw.set_framebuffer_size_callback(window, framebuffer_size_callback) vertexShader = gl.glCreateShader(gl.GL_VERTEX_SHADER) gl.glShaderSource(vertexShader, vertexShaderSource) gl.glCompileShader(vertexShader) fragmentShader = gl.glCreateShader(gl.GL_FRAGMENT_SHADER) gl.glShaderSource(fragmentShader, fragmentShaderSource) gl.glCompileShader(fragmentShader) shaderProgram = gl.glCreateProgram() gl.glAttachShader(shaderProgram, vertexShader) gl.glAttachShader(shaderProgram, fragmentShader) gl.glLinkProgram(shaderProgram) gl.glDeleteShader(vertexShader) gl.glDeleteShader(fragmentShader) VAO = gl.glGenVertexArrays(1) VBO, EBO = gl.glGenBuffers(2) gl.glBindVertexArray(VAO) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, VBO) gl.glBufferData(gl.GL_ARRAY_BUFFER, sys.getsizeof(vertices), vertices, gl.GL_STATIC_DRAW) gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 24, c_void_p(0)) gl.glEnableVertexAttribArray(0) gl.glVertexAttribPointer(1, 3, gl.GL_FLOAT, gl.GL_FALSE, 24, c_void_p(12)) gl.glEnableVertexAttribArray(1) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0) gl.glBindVertexArray(0) while not glfw.window_should_close(window): process_input(window) gl.glClearColor(0.2, 0.3, 0.3, 1.0) gl.glClear(gl.GL_COLOR_BUFFER_BIT) gl.glUseProgram(shaderProgram) gl.glBindVertexArray(VAO) gl.glDrawArrays(gl.GL_TRIANGLES, 0, 3) glfw.swap_buffers(window) glfw.poll_events() glfw.terminate()
def __render_lines(self): GL.glPolygonMode(GL.GL_FRONT_AND_BACK, GL.GL_LINE) GL.glBindVertexArray(self.__vao_pointer) self.__line_data.bind() self.__handle_vertex_attrib() GL.glUseProgram(self.__shader_program) GL.glBindVertexArray(self.__vao_pointer) GL.glDrawArrays(GL.GL_LINES, 0, len(self.__line_data.data)) GL.glBindVertexArray(0)
def __render_voxels(self): GL.glPolygonMode(GL.GL_FRONT_AND_BACK, GL.GL_FILL) GL.glBindVertexArray(self.__vao_pointer) self.__voxel_indicies_data.bind() self.__voxel_data.bind() self.__handle_vertex_attrib() GL.glUseProgram(self.__shader_program) GL.glBindVertexArray(self.__vao_pointer) GL.glDrawElements(GL.GL_TRIANGLES, len(self.__voxel_data.data), GL.GL_UNSIGNED_INT, None) GL.glBindVertexArray(0)
def display(shader, vertex_array_object): global transform GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) GL.glUseProgram(shader[0]) transLoc = GL.glGetUniformLocation(shader[0], "transform") GL.glUniform1f(transLoc, transform) transform += 0.0001 GL.glBindVertexArray(vertex_array_object[0]) GL.glDrawArrays(GL.GL_TRIANGLES, 0, 3) GL.glBindVertexArray(0) GL.glUseProgram(0) GL.glUseProgram(shader[1]) GL.glBindVertexArray(vertex_array_object[1]) GL.glDrawArrays(GL.GL_TRIANGLES, 0, 3) GL.glBindVertexArray(0) GL.glUseProgram(0)
def draw(): gl.glClearColor(0.2, 0.3, 0.3, 1.0) gl.glClear(gl.GL_COLOR_BUFFER_BIT) gl.glUseProgram(shaderProgram) gl.glBindVertexArray(VAO) gl.glDrawElements(gl.GL_TRIANGLES, 3 * indices.shape[0], gl.GL_UNSIGNED_INT, None) gl.glBindVertexArray(VAO2) gl.glDrawElements(gl.GL_TRIANGLES, 3 * indices2.shape[0], gl.GL_UNSIGNED_INT, None) gl.glBindVertexArray(0) glfw.swap_buffers(window)
def display(self): GL.glClearColor(0, 0, 0, 0) GL.glClear(GL.GL_COLOR_BUFFER_BIT) GL.glUseProgram(self.shader) GL.glBindVertexArray(self.vao1) GL.glUniform3f(self.offset_location, 0.0, 0.0, 0.0) GL.glDrawElements(GL.GL_TRIANGLES, len(self.indices), GL.GL_UNSIGNED_SHORT, None) GL.glBindVertexArray(self.vao2) GL.glUniform3f(self.offset_location, 0.0, 0.0, -1.0) GL.glDrawElements(GL.GL_TRIANGLES, len(self.indices), GL.GL_UNSIGNED_SHORT, None) GL.glBindVertexArray(0) GL.glUseProgram(0)
def unbind_vao(self): GL.glBindVertexArray(0)
def bind_vao(self): if self.vaoID is None: self.vaoID = GL.glGenVertexArrays(1) GL.glBindVertexArray(self.vaoID)
def __init__(self): # set up the shader i_vert = gl.glCreateShader(gl.GL_VERTEX_SHADER) gl.glShaderSource(i_vert, vert_shader) i_frag = gl.glCreateShader(gl.GL_FRAGMENT_SHADER) gl.glShaderSource(i_frag, frag_shader) self.program = gl.glCreateProgram() gl.glAttachShader(self.program, i_vert) gl.glAttachShader(self.program, i_frag) gl.glCompileShader(i_vert) gl.glCompileShader(i_frag) gl.glLinkProgram(self.program) gl.glValidateProgram(self.program) gl.glUseProgram(self.program) # set up the geometry i_pos = gl.glGetAttribLocation(self.program, "pos") i_normal = gl.glGetAttribLocation(self.program, "normal") self.i_vao = gl.glGenVertexArrays(1) i_vbo = gl.glGenBuffers(1) gl.glBindVertexArray(self.i_vao) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, i_vbo) gl.glBufferData( gl.GL_ARRAY_BUFFER, # target vertex_data.nbytes, # size vertex_data, # data gl.GL_STATIC_DRAW, # usage ) gl.glEnableVertexAttribArray(i_pos) gl.glVertexAttribPointer( i_pos, # index 3, # size gl.GL_FLOAT, # type gl.GL_FALSE, # normalisation 0, # stride ctypes.c_void_p(0), # pointer ) gl.glEnableVertexAttribArray(i_normal) gl.glVertexAttribPointer( i_normal, # index 3, # size gl.GL_FLOAT, # type gl.GL_FALSE, # normalisation 0, # stride ctypes.c_void_p(len(points) * 4), # pointer ) self.i_proj = gl.glGetUniformLocation(self.program, "projection") self.i_view = gl.glGetUniformLocation(self.program, "view") self.i_model = gl.glGetUniformLocation(self.program, "model") self.i_colour = gl.glGetUniformLocation(self.program, "colour") self.i_lightsource_dir = gl.glGetUniformLocation( self.program, "lightsource_dir" ) self.i_ambient = gl.glGetUniformLocation(self.program, "ambient") # set the rotation matrix to null self.set_model(model=np.eye(4).T) gl.glUseProgram(0)
def initializeGL(self): openGL_format = self.format() self.is_core = openGL_format.profile() == QtGui.QSurfaceFormat.CoreProfile self.logOpenGLFormat(openGL_format) self.clearErrors() legacy_vertex_shader_source = """ #version 110 // input attribute vec3 in_color; uniform mat4 mvp; // output varying vec3 out_color; void main() { gl_Position = mvp * gl_Vertex; out_color = in_color; }""" core_vertex_shader_source = """ #version 150 core // input in vec3 in_position; in vec3 in_color; uniform mat4 mvp; // output out vec3 out_color; void main() { gl_Position = mvp * vec4(in_position, 1.0); out_color = in_color; }""" vertex_shader_source = core_vertex_shader_source if self.is_core else legacy_vertex_shader_source quad_vertex_shader = shaders.compileShader(vertex_shader_source, GL.GL_VERTEX_SHADER) legacy_fragment_shader_source = """ #version 110 // input varying vec3 out_color; void main() { gl_FragColor = vec4(out_color, 1.0); }""" core_fragment_shader_source = """ #version 150 core // input in vec3 out_color; // output out vec4 frag_color; void main() { frag_color = vec4(out_color, 1.0); }""" fragment_shader_source = core_fragment_shader_source if self.is_core else legacy_fragment_shader_source quad_fragment_shader = shaders.compileShader(fragment_shader_source, GL.GL_FRAGMENT_SHADER) if self.is_core: # on OpenGL 3 core, create a vertex array object (on non-core, there is one default VAO) self.vao = GL.glGenVertexArrays(1) # VAO needs to be bound before the program can be compiled GL.glBindVertexArray(self.vao) self.quad_shader = shaders.compileProgram(quad_vertex_shader, quad_fragment_shader) vertices = np.array( [[ 0, 100, 0 ], [ 100, 100, 0], [ 100, 0, 0 ], [200, 200, 0], [200, 400, 0], [400, 400, 0], [400, 400, 0], [200, 200, 0], [400, 200, 0]], 'f') self.background_vbo = vbo.VBO(vertices) self.border_vbo = vbo.VBO(vertices) self.ruler_vbo = vbo.VBO(vertices) self.grid_vbo = vbo.VBO(vertices) self.data_vbo = vbo.VBO(vertices)
def unbind_all(): gl.glBindVertexArray(0) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0) VertexAttributeObject.bound_vao = -1
def bind(self): if VertexAttributeObject.bound_vao != self.vao_id: gl.glBindVertexArray(self.vao_id) VertexAttributeObject.bound_vao = self.vao_id for attrib in self.enabled_attributes: attrib.enable()