def draw(self, reset, modelview): """Binds the shaders and things to draw the lamp itself. Takes a reference to the 'matrix reset' function, and a modelview matrix to draw by.""" glUseProgram(shaderl) reset(shaderl) glUniformMatrix4fv(glGetUniformLocation(shaderl, 'modelmatrix'), 1, False, modelview) self.model.draw()
def level5_init(level, program): # 1.59 - approximate position of the eyes of a person who is 1.69 meters tall level.position = array([0, 0, 1.59, 1], dtype='float32') # looking forward in Y-axis positive direction level.orientation = array([0, 1, 0, 0], dtype='float32') level.time_start = time() level.time_checkpoint = level.time_start # get position for view matrix level.view_pos = glGetUniformLocation(program, 'view') # get position for rotating model matrix level.rotating_model_pos = glGetUniformLocation(program, 'rotating_model') # sun level.sun_color = array([1.0, 1.0, 1.0], dtype='float32') level.sun_color_pos = glGetUniformLocation(program, 'sunColor') glUniform3fv(level.sun_color_pos, 1, level.sun_color) level.sun_direction_pos = glGetUniformLocation(program, 'sunDirection') glUniform3fv(level.sun_direction_pos, 1, level.sun_direction) level.ambient_intensity = 0.2 level.ambient_intensity_pos = glGetUniformLocation(program, 'ambientIntensity') glUniform1f(level.ambient_intensity_pos, level.ambient_intensity) # initialize projection matrix once level.projection = perspective(pi / 3.5, level.screen_w / level.screen_h, 0.005, 1000000.0) level.projection_pos = glGetUniformLocation(program, 'projection') glUniformMatrix4fv(level.projection_pos, 1, GL_FALSE, level.projection)
def level4_render(level): left = glfwGetKey(level.window, GLFW_KEY_LEFT) == GLFW_PRESS or \ glfwGetKey(level.window, GLFW_KEY_A) == GLFW_PRESS right = glfwGetKey(level.window, GLFW_KEY_RIGHT) == GLFW_PRESS or \ glfwGetKey(level.window, GLFW_KEY_D) == GLFW_PRESS backward = glfwGetKey(level.window, GLFW_KEY_DOWN) == GLFW_PRESS or \ glfwGetKey(level.window, GLFW_KEY_S) == GLFW_PRESS forward = glfwGetKey(level.window, GLFW_KEY_UP) == GLFW_PRESS or \ glfwGetKey(level.window, GLFW_KEY_W) == GLFW_PRESS up = glfwGetKey(level.window, GLFW_KEY_PAGE_UP) == GLFW_PRESS down = glfwGetKey(level.window, GLFW_KEY_PAGE_DOWN) == GLFW_PRESS current_time = time() speed = (current_time - level.time_checkpoint)*3 if glfwGetKey(level.window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS: speed *= 2 if glfwGetKey(level.window, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS: speed /= 2 if (left or right) and (backward or forward) and (up or down): speed /= sqrt(3.0) elif ((left or right) and (backward or forward)) or \ ((left or right) and (up or down)) or \ ((backward or forward) and (up or down)): speed /= sqrt(2.0) if left: v = vector_norm(array([level.orientation[0], level.orientation[1], 0, 0], dtype='float32')) v = rotate(pi/2).dot(v) try_to_move(lvl, level, -v[0]*speed, -v[1]*speed, start_x, start_y) if right: v = vector_norm(array([level.orientation[0], level.orientation[1], 0, 0], dtype='float32')) v = rotate(-pi/2).dot(v) try_to_move(lvl, level, -v[0]*speed, -v[1]*speed, start_x, start_y) if backward: v = vector_norm(array([level.orientation[0], level.orientation[1], 0, 0], dtype='float32')) v = rotate(pi).dot(v) try_to_move(lvl, level, v[0]*speed, v[1]*speed, start_x, start_y) if forward: v = vector_norm(array([level.orientation[0], level.orientation[1], 0, 0], dtype='float32')) try_to_move(lvl, level, v[0]*speed, v[1]*speed, start_x, start_y) if up: level.position[2] += speed if down: level.position[2] -= speed level.time_checkpoint = current_time # update view matrix (according to position and orientation) level.view = look_at(level.position[:3], add(level.position, level.orientation)[:3]) glUniformMatrix4fv(level.view_pos, 1, GL_FALSE, level.view) # update rotating model level.angle = -(level.time_start - time()) / 3 level.rotating_model = array([cos(level.angle), -sin(level.angle), 0, 0, sin(level.angle), cos(level.angle), 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], dtype='float32').reshape(4, 4) glUniformMatrix4fv(level.rotating_model_pos, 1, GL_FALSE, level.rotating_model)
def render_with_context(context): glUseProgram(context["shader"]) # need true because our matrices are row-major and opengl wants column major by default. modelview = context["modelview"] projection = context["projection"] glUniformMatrix4fv(modelview["location"], 1, True, modelview["matrix"]) glUniformMatrix4fv(projection["location"], 1, True, projection["matrix"]) position_location = context["position_location"] normal_location = context["normal_location"] color_location = context["color_location"] stack = [modelview["matrix"]] try: render_thing(context["thing"], position_location, normal_location, color_location, modelview["location"], stack) finally: shaders.glUseProgram( 0 )
def uniform(self, name, value): with self: if type(value) == int or type(value) == long: glUniform1i(self.uniformLocation(name), value) elif type(value) == float or type(value) == numpy.float32: glUniform1f(self.uniformLocation(name), value) elif len(value) == 4: value = numpy.array(value, dtype=numpy.float32) glUniform4f(self.uniformLocation(name), *value) elif len(value) == 16: glUniformMatrix4fv(self.uniformLocation(name), 1, GL_FALSE, value) elif len(value) == 9: glUniformMatrix3fv(self.uniformLocation(name), 1, GL_FALSE, value) elif len(value) == 2: value = numpy.array(value, dtype=numpy.float32) glUniform2f(self.uniformLocation(name), *value) else: print(len(value)) raise Exception('not implemented')
def setup(self, actor): ''' Setup the shader uniforms / attributes. Assumes actor.vbo is already bound ''' # Bind the shader shaders.glUseProgram(self.program) # Enable vertex attribute arrays glEnableVertexAttribArray(self.attrib_position) # Set the Attribute pointers glVertexAttribPointer(self.attrib_position, 4, GL_FLOAT, False, 0, actor.vbo) # Apply uniforms glUniformMatrix4fv(self.uniform_modelCamera, 1, GL_TRUE, actor.modelCamera_matrix) glUniformMatrix4fv(self.uniform_projection, 1, GL_TRUE, actor.projection_matrix) glUniform1f(self.uniform_alpha, actor.alpha) # Bind to the correct texture glBindTexture(GL_TEXTURE_2D, actor.texid)
def render(self) -> None: """Render proxy objects to canvas with a diffuse shader.""" if not self.init(): return proj = self.parent.projection_matrix view = self.parent.modelview_matrix glUseProgram(self.parent.shaders['diffuse']) glUniformMatrix4fv(0, 1, GL_FALSE, glm.value_ptr(proj)) glUniformMatrix4fv(1, 1, GL_FALSE, glm.value_ptr(view)) for mesh in self._meshes: glBindVertexArray(mesh.vao) glUniform4fv(2, 1, glm.value_ptr(mesh.color)) glUniform1i(3, int(mesh.selected)) glDrawElements(GL_TRIANGLES, mesh.count, GL_UNSIGNED_INT, ctypes.c_void_p(0)) glBindVertexArray(0) glUseProgram(0)
def render(self, model, view_matrix, projection_matrix): glUseProgram(self.program) glEnableVertexAttribArray(self.vertices) glUniformMatrix4fv(self.model_view_matrix, 1, GL_TRUE, np.dot(view_matrix, model.matrix)) glUniformMatrix4fv(self.projection_matrix, 1, GL_TRUE, projection_matrix) glVertexAttribPointer(self.vertices, 3, GL_FLOAT, GL_FALSE, 0, model.vertex_buffer) glUniform1f(self.color_uniform, 0) glDrawElements(GL_LINES, model.line_buffer.size, GL_UNSIGNED_BYTE, model.line_buffer) glUniform1f(self.color_uniform, 0.5) glDrawElements(GL_TRIANGLES, model.index_buffer.size, GL_UNSIGNED_BYTE, model.index_buffer) glDisableVertexAttribArray(self.vertices)
def render_for_picking(self) -> None: """Render ViewCube for picking pass.""" if not self.init(): return glViewport(*self.viewport) proj = glm.ortho(-2.3, 2.3, -2.3, 2.3, -2.3, 2.3) mat = glm.lookAt( vec3(0.0, -1.0, 0.0), # position vec3(0.0, 0.0, 0.0), # target vec3(0.0, 0.0, 1.0)) # up modelview = mat * glm.mat4_cast(self.parent.rot_quat) glUseProgram(self.parent.shaders['default']) glUniformMatrix4fv(0, 1, GL_FALSE, glm.value_ptr(proj)) glUniformMatrix4fv(1, 1, GL_FALSE, glm.value_ptr(modelview)) glBindVertexArray(self._vao_picking) glDrawArrays(GL_QUADS, 0, 24) glBindVertexArray(0) glUseProgram(0)
def setup(self, actor): ''' Setup the shader uniforms / attributes. Assumes actor.vbo is already bound ''' # Bind the shader shaders.glUseProgram(self.program) # Enable vertex attribute arrays glEnableVertexAttribArray(self.attrib_position) glEnableVertexAttribArray(self.attrib_color) # colorOffset is sizeof float (4) * floats per point (4) * num of points (vbo/2) colorOffset = 4 * 4 * (len(actor.vbo) / 2) # Set the Attribute pointers glVertexAttribPointer(self.attrib_position, 4, GL_FLOAT, False, 0, actor.vbo) glVertexAttribPointer(self.attrib_color, 4, GL_FLOAT, False, 0, actor.vbo + colorOffset) # Apply uniforms glUniformMatrix4fv(self.uniform_modelCamera, 1, GL_TRUE, actor.modelCamera_matrix) glUniformMatrix4fv(self.uniform_projection, 1, GL_TRUE, actor.projection_matrix) glUniform1f(self.uniform_alpha, actor.alpha)
def render_for_picking(self) -> None: """Render action "pickables" for picking pass.""" if not self.init(): return proj = self.parent.projection_matrix view = self.parent.modelview_matrix glUseProgram(self.parent.shaders['instanced_picking']) glUniformMatrix4fv(0, 1, GL_FALSE, glm.value_ptr(proj)) glUniformMatrix4fv(1, 1, GL_FALSE, glm.value_ptr(view)) # render cameras for picking glBindVertexArray(self._vaos['camera']) glDrawArraysInstanced(GL_QUADS, 0, 24, self._num_devices) # render points for picking if self._num_points > 0: glBindVertexArray(self._vaos['box']) glDrawArraysInstanced(GL_QUADS, 0, 24, self._num_points) glBindVertexArray(0) glUseProgram(0)
def render_for_picking(self) -> None: """Render proxy objects for picking pass.""" if not self.init(): return proj = self.parent.projection_matrix view = self.parent.modelview_matrix glUseProgram(self.parent.shaders['solid']) glUniformMatrix4fv(0, 1, GL_FALSE, glm.value_ptr(proj)) glUniformMatrix4fv(1, 1, GL_FALSE, glm.value_ptr(view)) for mesh in self._meshes: glBindVertexArray(mesh.vao) glUniform1i(2, MAX_ID - mesh.object_id) glDrawElements(GL_TRIANGLES, mesh.count, GL_UNSIGNED_INT, ctypes.c_void_p(0)) glBindVertexArray(0) glUseProgram(0) glBindVertexArray(0) glUseProgram(0)
def render(self, model, view_matrix, projection_matrix): glUseProgram(self.program) glEnableVertexAttribArray(self.texcoords) glEnableVertexAttribArray(self.vertices) glEnableVertexAttribArray(self.bone_ids) glEnableVertexAttribArray(self.bone_weights) glUniformMatrix4fv( self.model_view_matrix, 1, GL_TRUE, np.dot(view_matrix, model.matrix) ) glUniformMatrix4fv( self.projection_matrix, 1, GL_TRUE, projection_matrix ) glUniformMatrix4fv( self.bone_matrices, len(model.bones), GL_TRUE, model.bone_matrices ) for group in model.groups: glBindTexture(GL_TEXTURE_2D, group.material.texture) glUniform1i(self.texture, 0) glVertexAttribPointer( self.bone_ids, 4, GL_SHORT, GL_FALSE, 0, group.bone_id_buffer ) glVertexAttribPointer( self.bone_weights, 4, GL_FLOAT, GL_FALSE, 0, group.bone_weight_buffer ) glVertexAttribPointer( self.vertices, 3, GL_FLOAT, GL_FALSE, 0, group.vertex_buffer ) glVertexAttribPointer( self.texcoords, 2, GL_FLOAT, GL_FALSE, 0, group.texcoord_buffer ) glDrawArrays(GL_TRIANGLES, 0, len(group.vertex_buffer)) glDisableVertexAttribArray(self.bone_weights) glDisableVertexAttribArray(self.bone_ids) glDisableVertexAttribArray(self.vertices) glDisableVertexAttribArray(self.texcoords)
def bind(self, uniform_location): count = 1 transpose = False glUniformMatrix4fv(uniform_location, count, transpose, self._data)
def render(self) -> None: """Render actions to canvas.""" if not self.init(): return proj = self.parent.projection_matrix view = self.parent.modelview_matrix model = mat4() # --- render cameras --- glUseProgram(self.parent.shaders['instanced_model_color']) glUniformMatrix4fv(0, 1, GL_FALSE, glm.value_ptr(proj)) glUniformMatrix4fv(1, 1, GL_FALSE, glm.value_ptr(view)) glBindVertexArray(self._vaos['camera']) glDrawArraysInstanced(GL_QUADS, 0, 24, self._num_devices) # --- render path lines --- glUseProgram(self.parent.shaders['single_color']) glUniformMatrix4fv(0, 1, GL_FALSE, glm.value_ptr(proj)) glUniformMatrix4fv(1, 1, GL_FALSE, glm.value_ptr(view)) glUniformMatrix4fv(2, 1, GL_FALSE, glm.value_ptr(model)) for key, value in self._vaos['line'].items(): color = self.colors[key % len(self.colors)] glUniform4fv(3, 1, glm.value_ptr(color)) glBindVertexArray(value) glDrawArrays(GL_LINE_STRIP, 0, len(self._items['line'][key])) # --- render points --- if self._num_points > 0: glUseProgram(self.parent.shaders['instanced_model_color']) glUniformMatrix4fv(0, 1, GL_FALSE, glm.value_ptr(proj)) glUniformMatrix4fv(1, 1, GL_FALSE, glm.value_ptr(view)) glBindVertexArray(self._vaos['box']) glDrawArraysInstanced(GL_QUADS, 0, 24, self._num_points) glBindVertexArray(0) glUseProgram(0)
def run(): #Start OpenGL and ask it for an OpenGL context pygame.init() clock = pygame.time.Clock() screen = pygame.display.set_mode( SCREEN_SIZE, pygame.HWSURFACE | pygame.OPENGL | pygame.DOUBLEBUF) #The first thing we do is print some OpenGL details and check that we have a good enough version print("OpenGL Implementation Details:") if glGetString(GL_VENDOR): print("\tGL_VENDOR: {}".format(glGetString(GL_VENDOR).decode())) if glGetString(GL_RENDERER): print("\tGL_RENDERER: {}".format(glGetString(GL_RENDERER).decode())) if glGetString(GL_VERSION): print("\tGL_VERSION: {}".format(glGetString(GL_VERSION).decode())) if glGetString(GL_SHADING_LANGUAGE_VERSION): print("\tGL_SHADING_LANGUAGE_VERSION: {}".format( glGetString(GL_SHADING_LANGUAGE_VERSION).decode())) major_version = int( glGetString(GL_VERSION).decode().split()[0].split('.')[0]) minor_version = int( glGetString(GL_VERSION).decode().split()[0].split('.')[1]) if major_version < 3 or (major_version < 3 and minor_version < 0): print("OpenGL version must be at least 3.0 (found {0})".format( glGetString(GL_VERSION).decode().split()[0])) #Now onto the OpenGL initialisation #Set up depth culling glEnable(GL_CULL_FACE) glEnable(GL_DEPTH_TEST) glDepthMask(GL_TRUE) glDepthFunc(GL_LEQUAL) glDepthRange(0.0, 1.0) #We create out shaders which do little more than set a flat colour for each face VERTEX_SHADER = shaders.compileShader( b""" #version 130 in vec4 position; in vec4 normal; uniform mat4 projectionMatrix; uniform mat4 viewMatrix; uniform mat4 modelMatrix; flat out float theColor; void main() { vec4 temp = modelMatrix * position; temp = viewMatrix * temp; gl_Position = projectionMatrix * temp; theColor = clamp(abs(dot(normalize(normal.xyz), normalize(vec3(0.9,0.1,0.5)))), 0, 1); } """, GL_VERTEX_SHADER) FRAGMENT_SHADER = shaders.compileShader( b""" #version 130 flat in float theColor; out vec4 outputColor; void main() { outputColor = vec4(1.0, 0.5, theColor, 1.0); } """, GL_FRAGMENT_SHADER) shader = shaders.compileProgram(VERTEX_SHADER, FRAGMENT_SHADER) #And then grab our attribute locations from it glBindAttribLocation(shader, 0, b"position") glBindAttribLocation(shader, 1, b"normal") #Create the Vertex Array Object to hold our volume mesh vertexArrayObject = GLuint(0) glGenVertexArrays(1, vertexArrayObject) glBindVertexArray(vertexArrayObject) #Create the index buffer object indexPositions = vbo.VBO(indices, target=GL_ELEMENT_ARRAY_BUFFER, usage=GL_STATIC_DRAW) #Create the VBO vertexPositions = vbo.VBO(vertices, usage=GL_STATIC_DRAW) #Bind our VBOs and set up our data layout specifications with indexPositions, vertexPositions: glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL_FLOAT, False, 6 * vertices.dtype.itemsize, vertexPositions + (0 * vertices.dtype.itemsize)) glEnableVertexAttribArray(1) glVertexAttribPointer(1, 3, GL_FLOAT, False, 6 * vertices.dtype.itemsize, vertexPositions + (3 * vertices.dtype.itemsize)) glBindVertexArray(0) glDisableVertexAttribArray(0) #Now grab out transformation martix locations modelMatrixUnif = glGetUniformLocation(shader, b"modelMatrix") viewMatrixUnif = glGetUniformLocation(shader, b"viewMatrix") projectionMatrixUnif = glGetUniformLocation(shader, b"projectionMatrix") modelMatrix = np.array([[1.0, 0.0, 0.0, -32.0], [0.0, 1.0, 0.0, -32.0], [0.0, 0.0, 1.0, -32.0], [0.0, 0.0, 0.0, 1.0]], dtype='f') viewMatrix = np.array([[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, -50.0], [0.0, 0.0, 0.0, 1.0]], dtype='f') projectionMatrix = np.array([[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]], dtype='f') #These next few lines just set up our camera frustum fovDeg = 45.0 frustumScale = 1.0 / tan(radians(fovDeg) / 2.0) zNear = 1.0 zFar = 1000.0 projectionMatrix[0][0] = frustumScale projectionMatrix[1][1] = frustumScale projectionMatrix[2][2] = (zFar + zNear) / (zNear - zFar) projectionMatrix[2][3] = -1.0 projectionMatrix[3][2] = (2 * zFar * zNear) / (zNear - zFar) #viewMatrix and projectionMatrix don't change ever so just set them once here with shader: glUniformMatrix4fv(projectionMatrixUnif, 1, GL_TRUE, projectionMatrix) glUniformMatrix4fv(viewMatrixUnif, 1, GL_TRUE, viewMatrix) #These are used to track the rotation of the volume LastFrameMousePos = (0, 0) CurrentMousePos = (0, 0) xRotation = 0 yRotation = 0 while True: clock.tick() for event in pygame.event.get(): if event.type == pygame.QUIT: return if event.type == pygame.KEYUP and event.key == pygame.K_ESCAPE: return if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: CurrentMousePos = event.pos LastFrameMousePos = CurrentMousePos if event.type == pygame.MOUSEMOTION and 1 in event.buttons: CurrentMousePos = event.pos diff = (CurrentMousePos[0] - LastFrameMousePos[0], CurrentMousePos[1] - LastFrameMousePos[1]) xRotation += event.rel[0] yRotation += event.rel[1] LastFrameMousePos = CurrentMousePos glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) #Perform the rotation of the mesh moveToOrigin = np.array( [[1.0, 0.0, 0.0, -32.0], [0.0, 1.0, 0.0, -32.0], [0.0, 0.0, 1.0, -32.0], [0.0, 0.0, 0.0, 1.0]], dtype='f') rotateAroundX = np.array( [[1.0, 0.0, 0.0, 0.0], [0.0, cos(radians(yRotation)), -sin(radians(yRotation)), 0.0], [0.0, sin(radians(yRotation)), cos(radians(yRotation)), 0.0], [0.0, 0.0, 0.0, 1.0]], dtype='f') rotateAroundY = np.array( [[cos(radians(xRotation)), 0.0, sin(radians(xRotation)), 0.0], [0.0, 1.0, 0.0, 0.0], [-sin(radians(xRotation)), 0.0, cos(radians(xRotation)), 0.0], [0.0, 0.0, 0.0, 1.0]], dtype='f') modelMatrix = rotateAroundY.dot(rotateAroundX.dot(moveToOrigin)) with shader: glUniformMatrix4fv(modelMatrixUnif, 1, GL_TRUE, modelMatrix) glBindVertexArray(vertexArrayObject) glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, None) glBindVertexArray(0) # Show the screen pygame.display.flip()
def setMat4(self, name, value): location = glGetUniformLocation(self.program, name) glUniformMatrix4fv(location, 1, GL_FALSE, value.data())
def main(): global width global height global camera width = 1024 height = 1024 delta_time = 0.0 last_frame = 0.0 if not glfw.init(): return 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) glfw.window_hint(glfw.RESIZABLE, GL_FALSE) window = glfw.create_window(width, height, "opengl_lab1", None, None) glfw.set_key_callback(window, key_callback) glfw.set_cursor_pos_callback(window, mousemove_callback) glfw.set_mouse_button_callback(window, mouseclick_callback) if not window: glfw.terminate() return glfw.make_context_current(window) fun1 = lambda x, z: math.sin(x+z) fun2 = lambda x, z: math.exp(-x*x - z*z) fun3 = lambda x, z: (x**2 + z**2) / (x*z) contour_plot = lambda x, z: 0.0 heightmap_dummy_fun = lambda x, z: 0.0 surface_size = 50 (fun_vao1, ind_fun1) = create_surface(100, 100, surface_size, fun1, False) (fun_vao2, ind_fun2) = create_surface(100, 100, surface_size, fun2, False) (fun_vao3, ind_fun3) = create_surface(100, 100, surface_size, fun3, False) (grad_vao, grad_point_count) = create_grad(100, 100, surface_size) (contour_plot_vao, ind_con, vec_lines, vector_line_indexes) = create_surface(100, 100, surface_size, 0, False, True) (heightmap_vao, ind_hm) = create_surface(100,100, surface_size, heightmap_dummy_fun, True) (sphere_vao, sphere_ind, normals_for_glyph) = uv_sphere(22, 11) (torus_vao, torus_ind) = uv_torus(5, 10, 100, 100) (cm_vao, ind_cm) = create_surface(100, 100, surface_size, heightmap_dummy_fun, True) (cloud_vao, points_count) = read_ply() (perlin_vao, ind_perlin) = create_surface(100, 100, surface_size, heightmap_dummy_fun, False) (div_vao, ind_div) = create_surface(100, 100, surface_size, heightmap_dummy_fun, False) (traj_vao, ind_traj) = simple_cube() fun_shader_sources = [(GL_VERTEX_SHADER, "shaders/functions.vert"), (GL_FRAGMENT_SHADER, "shaders/functions.frag")] fun_program = ShaderProgram(fun_shader_sources) hm_shader_sources = [(GL_VERTEX_SHADER, "shaders/heightmap.vert"), (GL_FRAGMENT_SHADER, "shaders/heightmap.frag")] hm_program = ShaderProgram(hm_shader_sources) hm_texture = read_texture("1.jpg") contour_plot_shader_sources = [(GL_VERTEX_SHADER, "shaders/contourplot.vert"), (GL_FRAGMENT_SHADER, "shaders/contourplot.frag")] contour_plot_program = ShaderProgram(contour_plot_shader_sources) sphere_shader_sources = [(GL_VERTEX_SHADER, "shaders/sphere.vert"), (GL_FRAGMENT_SHADER, "shaders/sphere.frag")] sphere_program = ShaderProgram(sphere_shader_sources) glyph_shader_sources = [(GL_VERTEX_SHADER, "shaders/glyph.vert"), (GL_GEOMETRY_SHADER, "shaders/glyph.geom"), (GL_FRAGMENT_SHADER, "shaders/glyph.frag")] glyph_program = ShaderProgram(glyph_shader_sources) grad_shader_sources = [(GL_VERTEX_SHADER, "shaders/grad.vert"), (GL_GEOMETRY_SHADER, "shaders/grad.geom"), (GL_FRAGMENT_SHADER, "shaders/grad.frag")] grad_program = ShaderProgram(grad_shader_sources) cm_shader_sources = [(GL_VERTEX_SHADER, "shaders/colormap.vert"), (GL_FRAGMENT_SHADER, "shaders/colormap.frag")] cm_program = ShaderProgram( cm_shader_sources ) perlin_shader_sources = [(GL_VERTEX_SHADER, "shaders/perlin.vert"), (GL_FRAGMENT_SHADER, "shaders/perlin.frag")] perlin_program = ShaderProgram(perlin_shader_sources) cloud_shader_sources = [(GL_VERTEX_SHADER, "shaders/ply.vert"), (GL_FRAGMENT_SHADER, "shaders/ply.frag")] cloud_program = ShaderProgram(cloud_shader_sources) vf_shader_sources = [(GL_VERTEX_SHADER, "shaders/vector_field.vert"), (GL_FRAGMENT_SHADER, "shaders/vector_field.frag")] vf_program = ShaderProgram(vf_shader_sources) traj_shader_sources = [(GL_VERTEX_SHADER, "shaders/trajectory.vert"), (GL_FRAGMENT_SHADER, "shaders/trajectory.frag")] traj_program = ShaderProgram(traj_shader_sources) check_gl_errors() projection = projectionMatrixTransposed(60.0, float(width) / float(height), 1, 1000.0) HDR_TEXTURES_AMOUNT = 33 cm_textures = read_cm_textures(HDR_TEXTURES_AMOUNT) cm_texture_num = 0 cm_change_counter = 0 hdr_textures_speed = 6 perlin_time = 0.0 perlin_time_step = 0.03 cube_multiplier = 1.0 cube_center = [0.0, 0.0, 0.0] traj_points_list = [ cube_center ] cube_edge_length = 2.0 * cube_multiplier offset = cube_edge_length / 10 left_cube_pos = -25 * cube_edge_length cube_steps = -left_cube_pos / offset - 10 traj_points_count = int(cube_steps) for i in range(traj_points_count): traj_points_list.append( [0.5*cube_edge_length * i, 0.0, 0.0] ) traj_part_index = 0 while not glfw.window_should_close(window): current_frame = glfw.get_time() delta_time = current_frame - last_frame last_frame = current_frame glfw.poll_events() doCameraMovement(camera, delta_time) model = translateM4x4(np.array([0.0, 0.0, 0.0])) view = camera.get_view_matrix() glClearColor(0.5, 0.5, 0.5, 1.0) glViewport(0, 0, width, height) glEnable(GL_DEPTH_TEST) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) fun_program.bindProgram() glUniform3fv(fun_program.uniformLocation("col"), 1 , [1.0, 0, 0] ) glUniformMatrix4fv(fun_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glUniformMatrix4fv(fun_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten()) glUniformMatrix4fv(fun_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten()) glBindVertexArray(fun_vao1) glDrawElements(GL_TRIANGLE_STRIP, ind_fun1, GL_UNSIGNED_INT, None) model = translateM4x4(np.array([-1.5*surface_size,0.0 ,0.0 ])) glUniform3fv(fun_program.uniformLocation("col"), 1, [0.0, 1.0, 0]) glUniformMatrix4fv(fun_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glBindVertexArray(fun_vao2) glDrawElements(GL_TRIANGLE_STRIP, ind_fun2, GL_UNSIGNED_INT, None) model = translateM4x4(np.array([1.5 * surface_size, 0.0, 0.0])) glUniform3fv(fun_program.uniformLocation("col"), 1, [0.0, 0.0, 1.0]) glUniformMatrix4fv(fun_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glBindVertexArray(fun_vao3) glDrawElements(GL_TRIANGLE_STRIP, ind_fun3, GL_UNSIGNED_INT, None) cloud_program.bindProgram() translate_cloud = translateM4x4(np.array([-2.5*surface_size,0.0 ,0.0 ])) # rotate_cloud = rotateYM4x4(math.radians(180)) model = translate_cloud # glUniform3fv(fun_program.uniformLocation("col"), 1, [0.0, 1.0, 0]) glUniformMatrix4fv(cloud_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glUniformMatrix4fv(cloud_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten()) glUniformMatrix4fv(cloud_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten()) glBindVertexArray(cloud_vao) glDrawArrays(GL_POINTS, 0, points_count) sphere_program.bindProgram() sph_scale = scaleM4x4(np.array([sphere_radius, sphere_radius, sphere_radius])) sph_translate = translateM4x4(np.array([0.0, 0.0, 2.0 * surface_size])) glUniformMatrix4fv(sphere_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(sph_translate + sph_scale).flatten()) glUniformMatrix4fv(sphere_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten()) glUniformMatrix4fv(sphere_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten()) glBindVertexArray(sphere_vao) glDrawElements(GL_TRIANGLES, sphere_ind, GL_UNSIGNED_INT, None) torus_translate = translateM4x4(np.array([0.0, 0.0, 3.0 * surface_size])) glUniformMatrix4fv(sphere_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(torus_translate + sph_scale).flatten()) glBindVertexArray(torus_vao) glDrawElements(GL_TRIANGLES, torus_ind, GL_UNSIGNED_INT, None) glyph_program.bindProgram() sph_scale = scaleM4x4(np.array([sphere_radius, sphere_radius, sphere_radius])) sph_translate = translateM4x4(np.array([0.0, 0.0, 2.0 * surface_size])) glUniformMatrix4fv(glyph_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(sph_translate + sph_scale).flatten()) glUniformMatrix4fv(glyph_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten()) glUniformMatrix4fv(glyph_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten()) vao = glGenVertexArrays(1) glBindVertexArray(vao) vbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, vbo) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(normals_for_glyph), normals_for_glyph.flatten(), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(0) glDrawArrays(GL_POINTS, 0, 10000) glBindVertexArray(0) contour_plot_program.bindProgram() model = translateM4x4(np.array([-1.5 * surface_size, 0.0, -1.5 * surface_size])) glUniformMatrix4fv(contour_plot_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glUniformMatrix4fv(contour_plot_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten()) glUniformMatrix4fv(contour_plot_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten()) glBindVertexArray(contour_plot_vao) glDrawElements(GL_TRIANGLE_STRIP, ind_con, GL_UNSIGNED_INT, None) fun_program.bindProgram() lines_vao = glGenVertexArrays(1) glBindVertexArray(lines_vao) vbo_lines = glGenBuffers(1) vbo_indices = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, vbo_lines) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(vec_lines), vec_lines.flatten(), GL_STATIC_DRAW) # glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(0) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_indices) glBufferData(GL_ELEMENT_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(vector_line_indexes), vector_line_indexes.flatten(), GL_STATIC_DRAW) glUniformMatrix4fv(fun_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glUniformMatrix4fv(fun_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten()) glUniformMatrix4fv(fun_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten()) glBindVertexArray(lines_vao) glDrawElements(GL_LINES, vector_line_indexes.size, GL_UNSIGNED_INT, None) hm_program.bindProgram() model = translateM4x4(np.array([0.0, 0.0, -1.5 * surface_size])) bindTexture(0, hm_texture) glUniform1i(hm_program.uniformLocation("tex"), 0) glUniformMatrix4fv(hm_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glUniformMatrix4fv(hm_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten()) glUniformMatrix4fv(hm_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten()) glBindVertexArray(heightmap_vao) glDrawElements(GL_TRIANGLE_STRIP, ind_hm, GL_UNSIGNED_INT, None) cm_program.bindProgram() model = translateM4x4(np.array([1.5 * surface_size, 0.0, -1.5 * surface_size])) cur_cm_texture = cm_textures[cm_texture_num % HDR_TEXTURES_AMOUNT] bindTexture(1, cur_cm_texture) if cm_change_counter % hdr_textures_speed == 0: cm_texture_num += 1 cm_change_counter += 1 glUniform1i(cm_program.uniformLocation("cm_switch"), False) glUniform1i(cm_program.uniformLocation("tex"), 1) glUniformMatrix4fv(cm_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glUniformMatrix4fv(cm_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten()) glUniformMatrix4fv(cm_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten()) glBindVertexArray(cm_vao) glDrawElements(GL_TRIANGLE_STRIP, ind_cm, GL_UNSIGNED_INT, None) # draw second animated hdr on the same shader model = translateM4x4(np.array([2.5 * surface_size, 0.0, -2.5 * surface_size])) glUniformMatrix4fv(cm_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glUniform1i(cm_program.uniformLocation("cm_switch"), True) glDrawElements(GL_TRIANGLE_STRIP, ind_cm, GL_UNSIGNED_INT, None) perlin_program.bindProgram() model = translateM4x4(np.array([0.0, 0.0, -3.5 * surface_size])) glUniformMatrix4fv(perlin_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glUniformMatrix4fv(perlin_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten()) glUniformMatrix4fv(perlin_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten()) glUniform1f(perlin_program.uniformLocation("time"), perlin_time) perlin_time += perlin_time_step glBindVertexArray(perlin_vao) glDrawElements(GL_TRIANGLE_STRIP, ind_perlin, GL_UNSIGNED_INT, None) grad_program.bindProgram() model = translateM4x4(np.array([-25.0, 0.0, -7.0 * surface_size])) glUniformMatrix4fv(grad_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glUniformMatrix4fv(grad_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten()) glUniformMatrix4fv(grad_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten()) glBindVertexArray(grad_vao) glDrawArrays(GL_LINES, 0, grad_point_count) vf_program.bindProgram() model = translateM4x4(np.array([0.0, 0.0, -5.5 * surface_size])) glUniformMatrix4fv(vf_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glUniformMatrix4fv(vf_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten()) glUniformMatrix4fv(vf_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten()) glUniform1i(vf_program.uniformLocation("cm_switch"), True) glBindVertexArray(div_vao) glDrawElements(GL_TRIANGLE_STRIP, ind_div, GL_UNSIGNED_INT, None) glUniform1i(vf_program.uniformLocation("cm_switch"), False) model = translateM4x4(np.array([1.0 * surface_size, 0.0, -6.5 * surface_size])) glUniformMatrix4fv(vf_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glDrawElements(GL_TRIANGLE_STRIP, ind_div, GL_UNSIGNED_INT, None) traj_program.bindProgram() l_traj_part =[] r_traj_part =[] if offset > 0: traj_part_index = int(traj_points_count - cm_change_counter % cube_steps) r_traj_part = traj_points_list[0:traj_part_index] for traj_coords in r_traj_part: l_traj_part.append( [-x for x in traj_coords] ) else: traj_part_index = int(traj_points_count - cm_change_counter % cube_steps) # traj_part_index = int(cm_change_counter % cube_steps) l_traj_part = traj_points_list[0:traj_part_index] for traj_coords in l_traj_part: r_traj_part.append([-x for x in traj_coords]) l_traj_vec = np.array(l_traj_part, dtype=np.float32) r_traj_vec = np.array(r_traj_part, dtype=np.float32) indices_list = [i for i in range(len(r_traj_part))] indices_vec = np.array(indices_list, dtype=np.uint32) left_traj_vao = glGenVertexArrays(1) right_traj_vao = glGenVertexArrays(1) left_traj_vertices = glGenBuffers(1) left_traj_indices = glGenBuffers(1) right_traj_vertices = glGenBuffers(1) right_traj_indices = glGenBuffers(1) glBindVertexArray(left_traj_vao) glPointSize( 3.0 ) glBindBuffer(GL_ARRAY_BUFFER, left_traj_vertices) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(l_traj_vec), l_traj_vec.flatten(), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(0) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, left_traj_indices) glBufferData(GL_ELEMENT_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(indices_vec), indices_vec.flatten(), GL_STATIC_DRAW) glBindVertexArray(right_traj_vao) glBindBuffer(GL_ARRAY_BUFFER, right_traj_vertices) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(r_traj_vec), r_traj_vec.flatten(), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(0) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, right_traj_indices) glBufferData(GL_ELEMENT_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(indices_vec), indices_vec.flatten(), GL_STATIC_DRAW) glBindVertexArray(0) cube_scale_ = scaleM4x4(np.array([1.0, 1.0, 1.0])) left_cube_pos += offset left_translation = translateM4x4(np.array([left_cube_pos, 0.0, -7.5 * surface_size])) glUniformMatrix4fv(traj_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(left_translation).flatten()) glUniformMatrix4fv(traj_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten()) glUniformMatrix4fv(traj_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten()) glBindVertexArray(left_traj_vao) glDrawElements(GL_LINE_STRIP, indices_vec.size, GL_UNSIGNED_INT, None) glBindVertexArray(traj_vao) glDrawElements(GL_TRIANGLE_STRIP, ind_traj, GL_UNSIGNED_INT, None) right_translation = translateM4x4(np.array([-left_cube_pos, 0.0, -8.5 * surface_size])) glUniformMatrix4fv(traj_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(right_translation).flatten()) glDrawElements(GL_TRIANGLE_STRIP, ind_traj, GL_UNSIGNED_INT, None) glBindVertexArray(right_traj_vao) glDrawElements(GL_LINE_STRIP, indices_vec.size, GL_UNSIGNED_INT, None) if not cm_change_counter % cube_steps: # left_cube_pos = left_cube_pos + offset * (cube_steps-1) offset *= -1 # r_traj_part, l_traj_part = l_traj_part, r_traj_part traj_program.unbindProgram() glfw.swap_buffers(window) glfw.terminate()
def SetUniformMat4f(self, name, value): glUniformMatrix4fv(self.GetUniformLocation(name), 1, GL_FALSE, value)
def update(self): for camera in self.__active_camera: self.__vertices = camera.vertices self.__indices = camera.indices self.__data_for_render = camera.get_data_for_render() glBindBuffer(GL_ARRAY_BUFFER, self.__VBO) glBufferData(GL_ARRAY_BUFFER, self.__vertices.nbytes, self.__vertices, GL_STATIC_DRAW) camera.bind_frame_buffer() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) for material, data in self.__data_for_render.items(): material.use_program() num_of_items = sum( TYPE_TO_LENGTH[type_] for attrib, type_ in material.attributes_types.items() if attrib not in material.instanced_attribs) pointer = 0 glBindBuffer(GL_ARRAY_BUFFER, self.__VBO) for attrib, index in sorted(material.attributes.items(), key=lambda x: x[1]): if attrib not in material.instanced_attribs: length = TYPE_TO_LENGTH[ material.attributes_types[attrib]] glEnableVertexAttribArray(index) glVertexAttribPointer( index, length, GL_FLOAT, GL_FALSE, self.__vertices.itemsize * num_of_items, ctypes.c_void_p(pointer * 4)) pointer += length if material.view_matrix_name in material.uniforms: glUniformMatrix4fv( material.uniforms[material.view_matrix_name], 1, GL_FALSE, camera.obj.inverse_matrix) if material.projection_matrix_name in material.uniforms: glUniformMatrix4fv( material.uniforms[material.projection_matrix_name], 1, GL_FALSE, camera.projection) for dat in data: sampler_id = 0 for uniform, index in material.uniforms.items(): if material.uniforms_types[uniform] == GL_SAMPLER_2D: if uniform in dat['object'].components[ 'Mesh'].uniform_data: unif_dat = dat['object'].components[ 'Mesh'].uniform_data[uniform] if callable(unif_dat): unif_dat = unif_dat() glUniform1i(index, sampler_id) glActiveTexture(GL_TEXTURE0 + sampler_id) unif_dat.bind_texture() unif_dat.load_settings() if unif_dat.default_texture == unif_dat.texture: unif_dat.send_texture() # if type(unif_dat) == int: # glUniform1i(index, sampler_id) # glActiveTexture(GL_TEXTURE0 + sampler_id) # glBindTexture(GL_TEXTURE_2D, unif_dat) else: glUniform1i(index, sampler_id) glActiveTexture(GL_TEXTURE0 + sampler_id) unif_dat.bind_texture() unif_dat.load_settings() if unif_dat.default_texture == unif_dat.texture: unif_dat.send_texture() # glUniform1i(index, sampler_id) # glActiveTexture(GL_TEXTURE0 + sampler_id) # glBindTexture(GL_TEXTURE_2D, unif_dat) elif 'Texture' in dat['object'].components: # location = material.uniforms[uniform] texture = dat['object'].components['Texture'] glUniform1i(index, sampler_id) glActiveTexture(GL_TEXTURE0 + sampler_id) texture.bind_texture() texture.load_settings() if texture.default_texture == texture.texture: texture.send_texture() # texture.bind_default_texture() sampler_id += 1 elif material.model_matrix_name == uniform: glUniformMatrix4fv( index, 1, GL_FALSE, dat['object'].transformation_matrix) elif material.view_matrix_name == uniform: pass elif material.projection_matrix_name == uniform: pass elif uniform in dat['object'].components[ 'Mesh'].uniform_data: uniform_data = dat['object'].components[ 'Mesh'].uniform_data[uniform] if callable(uniform_data): uniform_data = uniform_data() if type(uniform_data) == int or float: glUniform1f(index, float(uniform_data)) elif type(uniform_data) == int or float: glUniform1f(index, float(uniform_data)) # glDrawElements(GL_TRIANGLES, dat['length'], GL_UNSIGNED_INT, ctypes.c_void_p(dat['pointer'] * 0)) flatten_indices = dat['indices'] glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.__EBO) glBufferData(GL_ELEMENT_ARRAY_BUFFER, flatten_indices.nbytes, flatten_indices, GL_STATIC_DRAW) # glDrawElements(GL_TRIANGLES, len(flatten_indices), GL_UNSIGNED_INT, None) mesh = dat['object'].components['Mesh'] if len(mesh.instanced_point_data): instance_data = mesh.get_instanced_data_positioned_to_material( material, flattened=False) instance_cnt = len(instance_data) instance_data = instance_data.flatten() glBindBuffer(GL_ARRAY_BUFFER, self.__instanceVBO) glBufferData(GL_ARRAY_BUFFER, instance_data.nbytes, instance_data, GL_STATIC_DRAW) num_of_items = sum( TYPE_TO_LENGTH[material.attributes_types[attrib]] for attrib in material.instanced_attribs) ptr = 0 for attrib, index in sorted( material.attributes.items(), key=lambda x: x[1]): if attrib in material.instanced_attribs: length = TYPE_TO_LENGTH[ material.attributes_types[attrib]] glEnableVertexAttribArray(index) glVertexAttribPointer( index, length, GL_FLOAT, GL_FALSE, instance_data.itemsize * num_of_items, ctypes.c_void_p(ptr * 4)) glVertexAttribDivisor(index, 1) ptr += length glDrawElementsInstanced(GL_TRIANGLES, len(flatten_indices), GL_UNSIGNED_INT, None, instance_cnt) else: glDrawRangeElements(GL_TRIANGLES, dat['pointer'], dat['pointer'] + dat['length'], len(flatten_indices), GL_UNSIGNED_INT, None)
def bind_uniform_matrix(self, data, name): """Bind uniform matrix parameter.""" location = glGetUniformLocation(self.__program, name) assert location >= 0 glUniformMatrix4fv(location, 1, GL_FALSE, data.flatten())
shaders.glUseProgram(shaderProg) points = vbo.VBO(data=imgnp, usage="GL_DYNAMIC_DRAW", target='GL_ARRAY_BUFFER', size=None) points.bind() modelmat = glGetUniformLocation(shaderProg, 'model') viewmat = glGetUniformLocation(shaderProg, 'view') projectionmat = glGetUniformLocation(shaderProg, 'projection') glPushMatrix() glRotatef(-90, 0, 0, 1) scal = 0.01 glTranslatef(-0.5, -0.5, 0) glScalef(1 / imgnp.shape[0], 1 / imgnp.shape[1], 1) model2 = glGetDoublev(GL_MODELVIEW_MATRIX) glPopMatrix() # print(model2) glUniformMatrix4fv(modelmat, 1, GL_FALSE, model2) glutDisplayFunc(draw_points) # glutInitWindowPosition(600, 100) # wind2 = glutCreateWindow("OpenGL Window2") # glutMouseFunc(moveMouse) glutMainLoop()
def render_thing(thing, position_location, normal_location, color_location, modelview_location, context_matrix): try: translate = np.array(matrix_translate(thing["position"]), 'f') except: print "render_thing can't translate thing: ", thing exit() #print "render_thing type: ", thing["type"], thing["position"] context_matrix = np.dot(context_matrix, translate) rotates = thing["rotates"] if len(rotates) == 2: rotate0 = np.array(matrix_rotate_ortho(rotates[0]["angle"], rotates[0]["axis"]), 'f') tmp_matrix = np.dot(context_matrix, rotate0) rotate1 = np.array(matrix_rotate_ortho(rotates[1]["angle"], rotates[1]["axis"]), 'f') context_matrix = np.dot(tmp_matrix, rotate1) #print "render_thing:\n {}\n{}\n{}".format(translate, rotate0, rotate1) #print "context_matrix:\n", context_matrix glUniformMatrix4fv(modelview_location, 1, True, context_matrix) geometry = thing["geometry"] if geometry != None: if geometry["static"]: key = int(float(geometry["id"])) #print "thing type: {}, key: {}".format(thing["type"], key) if not key in vbos: vertices = geometry["vertices"] #print "adding geometry:\n{}".format(vertices[0]) #vbos[key] = (vbo.VBO(np.array(vertices, 'f')), len(vertices)) vbos[key] = (vbo.VBO(vertices), len(vertices)) buffer_object, buffer_size = vbos[key] else: vertices = geometry["vertices"] buffer_object = vbo.VBO(vertices) buffer_size = len(vertices) #print "rendering type: {}, size: {}".format(buffer_object, buffer_size) #pdb.set_trace() buffer_object.bind() try: glEnableVertexAttribArray( position_location ) glEnableVertexAttribArray( normal_location ) glEnableVertexAttribArray( color_location ) stride = 10*4 glVertexAttribPointer( position_location, 3, GL_FLOAT,False, stride, buffer_object ) glVertexAttribPointer( normal_location, 3, GL_FLOAT,False, stride, buffer_object+12 ) glVertexAttribPointer( color_location, 4, GL_FLOAT,False, stride, buffer_object+24 ) glDrawArrays(GL_TRIANGLES, 0, buffer_size) #print 'buffer size: ', buffer_size finally: buffer_object.unbind() glDisableVertexAttribArray( position_location ) glDisableVertexAttribArray( color_location ) else: for child in thing["children"]: render_thing(child, position_location, normal_location, color_location, modelview_location, context_matrix)
def run(): #Start OpenGL and ask it for an OpenGL context pygame.init() clock = pygame.time.Clock() screen = pygame.display.set_mode(SCREEN_SIZE, pygame.HWSURFACE|pygame.OPENGL|pygame.DOUBLEBUF) #The first thing we do is print some OpenGL details and check that we have a good enough version print("OpenGL Implementation Details:") if glGetString(GL_VENDOR): print("\tGL_VENDOR: {}".format(glGetString(GL_VENDOR).decode())) if glGetString(GL_RENDERER): print("\tGL_RENDERER: {}".format(glGetString(GL_RENDERER).decode())) if glGetString(GL_VERSION): print("\tGL_VERSION: {}".format(glGetString(GL_VERSION).decode())) if glGetString(GL_SHADING_LANGUAGE_VERSION): print("\tGL_SHADING_LANGUAGE_VERSION: {}".format(glGetString(GL_SHADING_LANGUAGE_VERSION).decode())) major_version = int(glGetString(GL_VERSION).decode().split()[0].split('.')[0]) minor_version = int(glGetString(GL_VERSION).decode().split()[0].split('.')[1]) if major_version < 3 or (major_version < 3 and minor_version < 0): print("OpenGL version must be at least 3.0 (found {0})".format(glGetString(GL_VERSION).decode().split()[0])) #Now onto the OpenGL initialisation #Set up depth culling glEnable(GL_CULL_FACE) glEnable(GL_DEPTH_TEST) glDepthMask(GL_TRUE) glDepthFunc(GL_LEQUAL) glDepthRange(0.0, 1.0) #We create out shaders which do little more than set a flat colour for each face VERTEX_SHADER = shaders.compileShader(b""" #version 130 in vec4 position; in vec4 normal; uniform mat4 projectionMatrix; uniform mat4 viewMatrix; uniform mat4 modelMatrix; flat out float theColor; void main() { vec4 temp = modelMatrix * position; temp = viewMatrix * temp; gl_Position = projectionMatrix * temp; theColor = clamp(abs(dot(normalize(normal.xyz), normalize(vec3(0.9,0.1,0.5)))), 0, 1); } """, GL_VERTEX_SHADER) FRAGMENT_SHADER = shaders.compileShader(b""" #version 130 flat in float theColor; out vec4 outputColor; void main() { outputColor = vec4(1.0, 0.5, theColor, 1.0); } """, GL_FRAGMENT_SHADER) shader = shaders.compileProgram(VERTEX_SHADER, FRAGMENT_SHADER) #And then grab our attribute locations from it glBindAttribLocation(shader, 0, b"position") glBindAttribLocation(shader, 1, b"normal") #Create the Vertex Array Object to hold our volume mesh vertexArrayObject = GLuint(0) glGenVertexArrays(1, vertexArrayObject) glBindVertexArray(vertexArrayObject) #Create the index buffer object indexPositions = vbo.VBO(indices, target=GL_ELEMENT_ARRAY_BUFFER, usage=GL_STATIC_DRAW) #Create the VBO vertexPositions = vbo.VBO(vertices, usage=GL_STATIC_DRAW) #Bind our VBOs and set up our data layout specifications with indexPositions, vertexPositions: glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL_FLOAT, False, 6*vertices.dtype.itemsize, vertexPositions+(0*vertices.dtype.itemsize)) glEnableVertexAttribArray(1) glVertexAttribPointer(1, 3, GL_FLOAT, False, 6*vertices.dtype.itemsize, vertexPositions+(3*vertices.dtype.itemsize)) glBindVertexArray(0) glDisableVertexAttribArray(0) #Now grab out transformation martix locations modelMatrixUnif = glGetUniformLocation(shader, b"modelMatrix") viewMatrixUnif = glGetUniformLocation(shader, b"viewMatrix") projectionMatrixUnif = glGetUniformLocation(shader, b"projectionMatrix") modelMatrix = np.array([[1.0,0.0,0.0,-32.0],[0.0,1.0,0.0,-32.0],[0.0,0.0,1.0,-32.0],[0.0,0.0,0.0,1.0]], dtype='f') viewMatrix = np.array([[1.0,0.0,0.0,0.0],[0.0,1.0,0.0,0.0],[0.0,0.0,1.0,-50.0],[0.0,0.0,0.0,1.0]], dtype='f') projectionMatrix = np.array([[0.0,0.0,0.0,0.0],[0.0,0.0,0.0,0.0],[0.0,0.0,0.0,0.0],[0.0,0.0,0.0,0.0]], dtype='f') #These next few lines just set up our camera frustum fovDeg = 45.0 frustumScale = 1.0 / tan(radians(fovDeg) / 2.0) zNear = 1.0 zFar = 1000.0 projectionMatrix[0][0] = frustumScale projectionMatrix[1][1] = frustumScale projectionMatrix[2][2] = (zFar + zNear) / (zNear - zFar) projectionMatrix[2][3] = -1.0 projectionMatrix[3][2] = (2 * zFar * zNear) / (zNear - zFar) #viewMatrix and projectionMatrix don't change ever so just set them once here with shader: glUniformMatrix4fv(projectionMatrixUnif, 1, GL_TRUE, projectionMatrix) glUniformMatrix4fv(viewMatrixUnif, 1, GL_TRUE, viewMatrix) #These are used to track the rotation of the volume LastFrameMousePos = (0,0) CurrentMousePos = (0,0) xRotation = 0 yRotation = 0 while True: clock.tick() for event in pygame.event.get(): if event.type == pygame.QUIT: return if event.type == pygame.KEYUP and event.key == pygame.K_ESCAPE: return if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: CurrentMousePos = event.pos LastFrameMousePos = CurrentMousePos if event.type == pygame.MOUSEMOTION and 1 in event.buttons: CurrentMousePos = event.pos diff = (CurrentMousePos[0] - LastFrameMousePos[0], CurrentMousePos[1] - LastFrameMousePos[1]) xRotation += event.rel[0] yRotation += event.rel[1] LastFrameMousePos = CurrentMousePos glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) #Perform the rotation of the mesh moveToOrigin = np.array([[1.0,0.0,0.0,-32.0],[0.0,1.0,0.0,-32.0],[0.0,0.0,1.0,-32.0],[0.0,0.0,0.0,1.0]], dtype='f') rotateAroundX = np.array([[1.0,0.0,0.0,0.0],[0.0,cos(radians(yRotation)),-sin(radians(yRotation)),0.0],[0.0,sin(radians(yRotation)),cos(radians(yRotation)),0.0],[0.0,0.0,0.0,1.0]], dtype='f') rotateAroundY = np.array([[cos(radians(xRotation)),0.0,sin(radians(xRotation)),0.0],[0.0,1.0,0.0,0.0],[-sin(radians(xRotation)),0.0,cos(radians(xRotation)),0.0],[0.0,0.0,0.0,1.0]], dtype='f') modelMatrix = rotateAroundY.dot(rotateAroundX.dot(moveToOrigin)) with shader: glUniformMatrix4fv(modelMatrixUnif, 1, GL_TRUE, modelMatrix) glBindVertexArray(vertexArrayObject) glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, None) glBindVertexArray(0) # Show the screen pygame.display.flip()
def _load_matrix(location: int, matrix: np.ndarray) -> None: glUniformMatrix4fv(location, 1, True, matrix)
def setMat4(self, name, mat): glUniformMatrix4fv(self.getUniformLocation(name), 1, GL_FALSE, glm.value_ptr(mat))
GL_FLOAT_VEC2: (GLfloat, 2, glUniform2fv), GL_FLOAT_VEC3: (GLfloat, 3, glUniform3fv), GL_FLOAT_VEC4: (GLfloat, 4, glUniform4fv), GL_INT: (GLint, 1, glUniform1iv), GL_INT_VEC2: (GLint, 2, glUniform2iv), GL_INT_VEC3: (GLint, 3, glUniform3iv), GL_INT_VEC4: (GLint, 4, glUniform4iv), GL_FLOAT_MAT2: (GLfloat, 4, lambda x, y, z: glUniformMatrix2fv(x, y, TRANSPOSE_MATRIX, z), (2, 2)), GL_FLOAT_MAT3: (GLfloat, 9, lambda x, y, z: glUniformMatrix3fv(x, y, TRANSPOSE_MATRIX, z), (3, 3)), GL_FLOAT_MAT4: (GLfloat, 16, lambda x, y, z: glUniformMatrix4fv(x, y, TRANSPOSE_MATRIX, z), (4, 4)), GL_FLOAT_MAT2x3: (GLfloat, 6, lambda x, y, z: glUniformMatrix2x3fv(x, y, TRANSPOSE_MATRIX, z), (2, 3)), GL_FLOAT_MAT2x4: (GLfloat, 8, lambda x, y, z: glUniformMatrix2x4fv(x, y, TRANSPOSE_MATRIX, z), (2, 4)), GL_FLOAT_MAT3x2: (GLfloat, 6, lambda x, y, z: glUniformMatrix3x2fv(x, y, TRANSPOSE_MATRIX, z), (3, 2)), GL_FLOAT_MAT3x4: (GLfloat, 12, lambda x, y, z: glUniformMatrix3x4fv(x, y, TRANSPOSE_MATRIX, z), (3, 4)), GL_FLOAT_MAT4x2: (GLfloat, 8, lambda x, y, z: glUniformMatrix4x2fv(x, y, TRANSPOSE_MATRIX, z), (4, 2)),