def update_objects(self) -> None: """Update proxy objects when object list changes. Called from GLCanvas upon core_o_list_changed signal. """ self._meshes.clear() for index, object3d in enumerate(self.core.objects): vao = glGenVertexArrays(1) glBindVertexArray(vao) vertices: glm.array = None normals: glm.array = None indices: glm.array = None if object3d.__class__ == CylinderObject3D: vertices, normals, indices = get_cylinder_vertices( object3d, 24) elif object3d.__class__ == OBJObject3D: vertices = object3d.vertices normals = object3d.normals indices = object3d.indices elif object3d.__class__ == AABBObject3D: vertices, normals, indices = get_aabb_vertices(object3d) else: continue vbo = glGenBuffers(3) # vertices glBindBuffer(GL_ARRAY_BUFFER, vbo[0]) glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices.ptr, GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) # normals glBindBuffer(GL_ARRAY_BUFFER, vbo[1]) glBufferData(GL_ARRAY_BUFFER, normals.nbytes, normals.ptr, GL_STATIC_DRAW) glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0)) glEnableVertexAttribArray(1) # indices glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo[2]) glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.nbytes, indices.ptr, GL_STATIC_DRAW) self._meshes.append( Mesh(color=vec4(0.8, 0.8, 0.8, 0.85), count=indices.length * 3, vao=vao, object_id=index, selected=False)) glBindVertexArray(0)
def build(self) -> None: self._vao = glGenVertexArrays(1) vbos = glGenBuffers(2) glBindVertexArray(self._vao) self._material.build_shader() vertices = np.array(self._vertices, dtype=np.float32) indices = np.array(self._indices, dtype=np.int32) glBindBuffer(GL_ARRAY_BUFFER, vbos[0]) glEnableVertexAttribArray(0) # shader layout location glVertexAttribPointer(0, 3, GL_FLOAT, False, 0, ctypes.c_void_p(0)) glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbos[1]) glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.nbytes, indices, GL_STATIC_DRAW) self._vertex_count = len(indices) glBindVertexArray(0) # glDisableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, 0) glDeleteBuffers(2, vbos) if self.static: # we can clear this data to free some more memory self._vertices = [] self._indices = []
def __init__(self, data): self.cull_face = data["cull_face"] indicesData, buffer = ObjLoader.load_model( "resources/objects/obj/{}.obj".format(data["name"])) self.__indicesLen = len(indicesData) self.VAO = glGenVertexArrays(1) self.VBO = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.VBO) glBufferData(GL_ARRAY_BUFFER, buffer.nbytes, buffer, GL_STATIC_DRAW) glBindVertexArray(self.VAO) # vertices glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, buffer.itemsize * 8, ctypes.c_void_p(0)) # textures glEnableVertexAttribArray(2) glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, buffer.itemsize * 8, ctypes.c_void_p(12)) # normals glEnableVertexAttribArray(1) glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, buffer.itemsize * 8, ctypes.c_void_p(20)) glBindBuffer(GL_ARRAY_BUFFER, 0) glBindVertexArray(0) self.texture = LoadTexture('resources/objects/texture/{}'.format( data["texture_name"]))
def create_grad(rows, cols, size): # y = 5*x + z*z vertices_list = [] def der_x(x): return math.sin(x) def der_z(z): return math.cos(z) for z in range(0, 50): for x in range(0, 50): d_x = der_x(x) d_z = der_z(z) vertices_list.append([x, 0.0, z]) vertices_list.append([x + d_x, 0.0, z + d_z]) vertices_vec = np.array(vertices_list, dtype=np.float32) vao = glGenVertexArrays(1) vbo_vertices = glGenBuffers(1) glBindVertexArray(vao) glBindBuffer(GL_ARRAY_BUFFER, vbo_vertices) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(vertices_vec), vertices_vec.flatten(), GL_STATIC_DRAW) # glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(0) glBindVertexArray(0) return (vao, len(vertices_list))
def get_shader( context_identifier: str, shader_name: str ) -> OpenGL.GL.shaders.ShaderProgram: shader_key = (context_identifier, shader_name) if shader_key not in _shaders: def compile_shader(): return OpenGL.GL.shaders.compileProgram( _load_shader( os.path.join(shader_dir, f"{shader_name}.vert"), GL_VERTEX_SHADER ), _load_shader( os.path.join(shader_dir, f"{shader_name}.frag"), GL_FRAGMENT_SHADER ), ) try: shader = compile_shader() except OpenGL.GL.shaders.ShaderValidationError: # on Mac the above fails if there is no VBO bound glBindVertexArray(glGenVertexArrays(1)) shader = compile_shader() glBindVertexArray(0) _shaders[shader_key] = shader return _shaders[shader_key]
def getTriangleVAO1(program): # it is a container for buffers vao_id = glGenVertexArrays(1) glBindVertexArray(vao_id) vbo_id = glGenBuffers(2) # bind some GL_ARRAY_BUFFER to generated one id # it's a position buffer glBindBuffer(GL_ARRAY_BUFFER, vbo_id[0]) # fill it with values glBufferData(GL_ARRAY_BUFFER, vertex_data1, GL_STATIC_DRAW) # tell, how to interpret it glVertexAttribPointer(program.attribLocation('vin_position'), 3, GL_FLOAT, GL_FALSE, 0, None) # open the valve, let it to be used. glEnableVertexAttribArray(0) # repeat it for colors. glBindBuffer(GL_ARRAY_BUFFER, vbo_id[1]) glBufferData(GL_ARRAY_BUFFER, color_data1, GL_STATIC_DRAW) glVertexAttribPointer(program.attribLocation('vin_color'), 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(1) # there we unbind current buffer and vertex array object glBindBuffer(GL_ARRAY_BUFFER, 0) glBindVertexArray(0) # will bind VAO's at every draw action. return vao_id
def initGL(self): self.vertexData = [-1, -1, 0, 1, -1, 0, 0, 1, 0] self.vertexArrayID = glGenVertexArrays(1) glBindVertexArray(self.vertexArrayID) self.attrID = 0 self.vertexBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.vertexBuffer) arrayType = GLfloat * len(self.vertexData) #initialize data for the buffer target = GL_ARRAY_BUFFER size = len(self.vertexData) * ctypes.sizeof(ctypes.c_float) data = arrayType(*self.vertexData) usage = GL_STATIC_DRAW glBufferData(target, size, data, usage) glVertexAttribPointer(self.attrID, 3, GL_FLOAT, False, 0, None) glEnableVertexAttribArray(self.attrID) #access the code for the vertex and fragment shaders with open(self.vertPath, 'r') as vertProg: self.vertCode = vertProg.read() with open(self.fragPath, 'r') as fragProg: self.fragCode = fragProg.read() #compile those shaders self.vertShader = shaders.compileShader(self.vertCode, GL_VERTEX_SHADER) self.fragShader = shaders.compileShader(self.fragCode, GL_FRAGMENT_SHADER) self.shader = shaders.compileProgram(self.vertShader, self.fragShader) glUseProgram(self.shader)
def __initiate_buffers(self, number_of_buffers): """Generate VAO and VBO buffers.""" self.__vao_id = glGenVertexArrays(1) glBindVertexArray(self.__vao_id) if number_of_buffers == 1: self.__vbo_id = [glGenBuffers(number_of_buffers)] elif number_of_buffers > 1: self.__vbo_id = glGenBuffers(number_of_buffers)
def create_vaos(self) -> None: """Bind VAOs to define vertex data.""" vbo = glGenBuffers(1) # initialize camera box # TODO: update to obj file vertices = glm.array( vec3(-1.0, -0.5, -1.0), # bottom vec3(-1.0, -0.5, 1.0), vec3(-1.0, 0.5, 1.0), vec3(-1.0, 0.5, -1.0), vec3(1.0, -0.5, -1.0), # right vec3(-1.0, -0.5, -1.0), vec3(-1.0, 0.5, -1.0), vec3(1.0, 0.5, -1.0), vec3(1.0, -0.5, 1.0), # top vec3(1.0, -0.5, -1.0), vec3(1.0, 0.5, -1.0), vec3(1.0, 0.5, 1.0), vec3(-1.0, -0.5, 1.0), # left vec3(1.0, -0.5, 1.0), vec3(1.0, 0.5, 1.0), vec3(-1.0, 0.5, 1.0), vec3(1.0, 0.5, -1.0), # back vec3(-1.0, 0.5, -1.0), vec3(-1.0, 0.5, 1.0), vec3(1.0, 0.5, 1.0), vec3(-1.0, -0.5, -1.0), # front vec3(1.0, -0.5, -1.0), vec3(1.0, -0.5, 1.0), vec3(-1.0, -0.5, 1.0), ) glBindBuffer(GL_ARRAY_BUFFER, vbo) glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices.ptr, GL_STATIC_DRAW) self._vaos['box'] = glGenVertexArrays(1) glBindVertexArray(self._vaos['box']) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) self._vaos['camera'] = glGenVertexArrays(1) glBindVertexArray(self._vaos['camera']) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0)) glEnableVertexAttribArray(0)
def __create_vao(self) -> int: """ Creates a new Vertex Array Object, activates (bind) it and returns its ID. A VAO holds data (geometric coordinates, colors, etc) and it is stored in the GPU's memory, so that it can be accessed fast during rendering. Returns: (int): The new Vertex Array Object's ID """ vao_id: int = glGenVertexArrays(1) self.__vaos.append(vao_id) glBindVertexArray(vao_id) return vao_id
def create_vaos(self) -> None: """Bind VAOs to define vertex data.""" self._vao_gridlines, self._vao_bounding_box = glGenVertexArrays(2) vbo = glGenBuffers(5) vertices, colors = self._get_gridlines() self._count_gridlines = vertices.size // 3 glBindVertexArray(self._vao_gridlines) # gridlines glBindBuffer(GL_ARRAY_BUFFER, vbo[0]) glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, vbo[1]) glBufferData(GL_ARRAY_BUFFER, colors.nbytes, colors, GL_STATIC_DRAW) glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0)) glEnableVertexAttribArray(1) # --- points, indices = self._get_bounding_box() self._count_bounding_box = indices.length glBindVertexArray(self._vao_bounding_box) # bounding box glBindBuffer(GL_ARRAY_BUFFER, vbo[2]) glBufferData(GL_ARRAY_BUFFER, points.nbytes, points, GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, vbo[3]) glBufferData(GL_ARRAY_BUFFER, points.nbytes, points, GL_STATIC_DRAW) glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(12)) glEnableVertexAttribArray(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo[4]) glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.nbytes, indices.ptr, GL_STATIC_DRAW) self._axes.create_vaos() glBindVertexArray(0) glDeleteBuffers(5, vbo)
def read_ply(): plydata = PlyData.read('cloud.ply') vertices_list = [] normal_list = [] color_list = [] for data in plydata.elements[0].data: vertices_list.append([data[0],data[1],data[2]]) normal_list.append([data[3],data[4],data[5]]) color_list.append([data[6], data[7], data[8]]) vector_vertices = np.array(vertices_list, dtype=np.float32) vector_normal = np.array(normal_list, dtype=np.float32) vector_color = np.array(color_list, dtype=np.float32) vector_color /= 255.0 vao = glGenVertexArrays(1) vbo_vertices = glGenBuffers(1) vbo_normals = glGenBuffers(1) vbo_colors = glGenBuffers(1) glBindVertexArray(vao) glBindBuffer(GL_ARRAY_BUFFER, vbo_vertices) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(vector_vertices), vector_vertices.flatten(), GL_STATIC_DRAW) # glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, vbo_normals) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(vector_normal), vector_normal.flatten(), GL_STATIC_DRAW) # glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(1) glBindBuffer(GL_ARRAY_BUFFER, vbo_colors) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(vector_color), vector_color.flatten(), GL_STATIC_DRAW) # glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(2) glBindVertexArray(0) return vao, len(vertices_list)
def _setup(self): """Setup OpenGL attributes if required""" if self._vao is None: # if the opengl state has not been set self._shader = get_shader(self.context_identifier, self.shader_name) glUseProgram(self._shader) self._transform_location = glGetUniformLocation( self._shader, "transformation_matrix" ) self._texture_location = glGetUniformLocation(self._shader, "image") self._vao = glGenVertexArrays(1) # create the array glBindVertexArray(self._vao) self._vbo = glGenBuffers(1) # and the buffer glBindBuffer(GL_ARRAY_BUFFER, self._vbo) self._setup_opengl_attrs() self._change_verts() glBindVertexArray(0) glBindBuffer(GL_ARRAY_BUFFER, 0) glUseProgram(0)
def on_realize(self, area): # We need to make the context current if we want to # call GL API area.make_current() context = area.get_context() if (area.get_error() != None): return fragment_shader = shaders.compileShader(FRAGMENT_SOURCE, GL_FRAGMENT_SHADER) vertex_shader = shaders.compileShader(VERTEX_SOURCE, GL_VERTEX_SHADER) self.shaderContent.shader_prog = shaders.compileProgram( fragment_shader, vertex_shader) glLinkProgram(self.shaderContent.shader_prog) self.vertex_array_object = glGenVertexArrays(1) glBindVertexArray(self.vertex_array_object) # Generate buffers to hold our vertices self.vertex_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.vertex_buffer) self.position = glGetAttribLocation(self.shaderContent.shader_prog, 'position') self.time_l = glGetUniformLocation(self.shaderContent.shader_prog, 'time') print(self.time_l) # glBindAttribLocation(self.shaderContent.shader_prog, self.time, 'time') glEnableVertexAttribArray(self.position) glVertexAttribPointer(index=self.position, size=4, type=GL_FLOAT, normalized=False, stride=0, pointer=ctypes.c_void_p(0)) glBufferData(GL_ARRAY_BUFFER, 192, self.vertices, GL_STATIC_DRAW) glBindVertexArray(0) glDisableVertexAttribArray(self.position) glBindBuffer(GL_ARRAY_BUFFER, 0) self.on_render(self.shaderContent) return True
def get_shader(context_identifier: str, shader_name: str) -> OpenGL.GL.shaders.ShaderProgram: shader_key = (context_identifier, shader_name) if shader_key not in _shaders: gl_version_match = GL_VERSION_MATCH.match( glGetString(GL_SHADING_LANGUAGE_VERSION).decode("utf-8")) if gl_version_match: gl_version_tuple = tuple(int(v) for v in gl_version_match.groups()) if gl_version_tuple >= (3, 30): gl_version = "330" # opengl 3.3 else: gl_version = "120" # opengl 2.1 else: # in theory this shouldn't happen if the version is correctly formatted. gl_version = "330" def compile_shader(): return OpenGL.GL.shaders.compileProgram( _load_shader( os.path.join(shader_dir, f"{shader_name}_{gl_version}.vert"), GL_VERTEX_SHADER, ), _load_shader( os.path.join(shader_dir, f"{shader_name}_{gl_version}.frag"), GL_FRAGMENT_SHADER, ), ) try: shader = compile_shader() except OpenGL.GL.shaders.ShaderValidationError: # on Mac the above fails if there is no VBO bound glBindVertexArray(glGenVertexArrays(1)) shader = compile_shader() glBindVertexArray(0) _shaders[shader_key] = shader return _shaders[shader_key]
def __init__(self): self._vao = glGenVertexArrays(1) self._points = pxng.BufferObject(data_type=glm.vec3, array_type=GL_ARRAY_BUFFER) self._chars = pxng.BufferObject(data_type=glm.uvec1, array_type=GL_ARRAY_BUFFER) program = pxng.ShaderProgram('FontShader') program.add_shader(pxng.resource('shaders/font.vert'), pxng.ShaderType.Vertex) program.add_shader(pxng.resource('shaders/font.geom'), pxng.ShaderType.Geometry) program.add_shader(pxng.resource('shaders/font.frag'), pxng.ShaderType.Fragment) program.compile_and_link() program.add_uniform('projection_view', glm.mat4x4) program.add_uniform('model', glm.mat4x4) program.add_uniform('color', glm.vec4) program.add_uniform('size', glm.uvec1) program.add_uniform('sprite_texture', glm.ivec1) self._program = program
def setup_scene_geometry(self, vertex_data, index_data, faces): self.has_geometry = True from tremor.graphics.vbo import VertexBufferObject from OpenGL.GL import glGenVertexArrays, glBindVertexArray, glBindBuffer, GL_FALSE, GL_FLOAT, glGenBuffers, \ GL_STATIC_DRAW, \ GL_ELEMENT_ARRAY_BUFFER, glBufferData, glVertexAttribPointer, ctypes, glEnableVertexAttribArray self.faces = faces self.vao = glGenVertexArrays(1) glBindVertexArray(self.vao) self.faceVBO = VertexBufferObject() self.faceVBO.update_data(vertex_data, True) # vertex information: vec3f pos, vec3f norm, vec2f tex self.faceVBO.bind() self.faceIBO = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.faceIBO) glBufferData(GL_ELEMENT_ARRAY_BUFFER, index_data, GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, (3 + 3 + 2) * 4, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, (3 + 3 + 2) * 4, ctypes.c_void_p(3 * 4)) glEnableVertexAttribArray(1) glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, (3 + 3 + 2) * 4, ctypes.c_void_p(6 * 4)) glEnableVertexAttribArray(3) glBindVertexArray(0)
def __init__(self, vertex, fragment, number_of_buffers=0, number_of_textures=0): """Initialize program with shaders.""" self.__program = glCreateProgram() self.__current_shaders = {} self.__shaders = {GL_VERTEX_SHADER: [], GL_FRAGMENT_SHADER: []} self.__depth_map_fbo = None self.__attributes = [] if not isinstance(vertex, list): vertex = [vertex] for v in vertex: self.__load_shader(get_shader_path(v), GL_VERTEX_SHADER) if not isinstance(fragment, list): fragment = [fragment] for f in fragment: self.__load_shader(get_shader_path(f), GL_FRAGMENT_SHADER) self.change_shader(0, 0) glLinkProgram(self.__program) assert glGetProgramiv(self.__program, GL_LINK_STATUS) == GL_TRUE self.__vao_id = glGenVertexArrays(1) glBindVertexArray(self.__vao_id) if number_of_buffers == 1: self.__vbo_id = [glGenBuffers(number_of_buffers)] elif number_of_buffers > 1: self.__vbo_id = glGenBuffers(number_of_buffers) if number_of_textures == 1: self.__textures_ids = [glGenTextures(1)] elif number_of_textures > 1: self.__textures_ids = glGenTextures(number_of_textures) self.__textures = []
def render(self) -> None: """Render background of the scene""" if not self.visible: return if not self._vao: self._vao = glGenVertexArrays(1) glBindVertexArray(self._vao) self._shader.build() glBindVertexArray(0) glDisable(GL_DEPTH_TEST) self._shader.use() self._shader.set_vector4_np("top_color", np.array(self.top_color, dtype=np.float32)) self._shader.set_vector4_np( "bot_color", np.array(self.bottom_color, dtype=np.float32)) glBindVertexArray(self._vao) glDrawArrays(GL_TRIANGLES, 0, 3) glBindVertexArray(0) self._shader.end() glEnable(GL_DEPTH_TEST)
def buff_vertices(verts: list, indes: list=None) -> int: """Given a list of vertex-like objects, an optional list of indices, returns a VAO handle. Format (all should be floats): [[pX, pY, pZ, nX, nY, nZ, cR, cR, cB, tU, tV]] * len.""" vao = glGenVertexArrays(1) glBindVertexArray(vao) v = vbo.VBO(array(verts, 'f')) v.bind() glVertexAttribPointer(0, 3, GL_FLOAT, False, 44, v) glVertexAttribPointer(1, 3, GL_FLOAT, False, 44, v+12) glVertexAttribPointer(2, 3, GL_FLOAT, False, 44, v+24) glVertexAttribPointer(3, 2, GL_FLOAT, False, 44, v+36) glEnableVertexAttribArray(0) glEnableVertexAttribArray(1) glEnableVertexAttribArray(2) glEnableVertexAttribArray(3) # Maybe you want to include the vertices verbatim? Go for it. if indes is not None: ebo = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo) glBufferData(GL_ELEMENT_ARRAY_BUFFER, len(indes)*8, array(indes, 'i'), GL_STATIC_DRAW) glBindVertexArray(0) return vao
def update_action_vaos(self) -> None: """Update VAOs when action list changes.""" self._vaos['line'].clear() self._vaos['point'].clear() # --- bind data for lines --- for key, value in self._items['line'].items(): # ignore if 1 or fewer points if len(value) <= 1: continue points = glm.array([vec3(mat[1][3]) for mat in value]) vbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, vbo) glBufferData(GL_ARRAY_BUFFER, points.nbytes, points.ptr, GL_STATIC_DRAW) vao = glGenVertexArrays(1) glBindVertexArray(vao) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) self._vaos['line'][key] = vao glBindVertexArray(0) # --- bind data for points --- point_mats: glm.array = None point_cols: glm.array = None point_ids: glm.array = None scale = glm.scale(mat4(), vec3(3, 3, 3)) for key, value in self._items['point'].items(): new_mats = glm.array([p[1] * scale for p in value]) color = shade_color(vec4(self.colors[key % len(self.colors)]), -0.3) new_cols = glm.array([color] * len(value)) # if point is selected, darken its color for i, v in enumerate(value): # un-offset ids if (v[0] - self._num_devices) in self.core.selected_points: new_cols[i] = shade_color(vec4(new_cols[i]), 0.6) new_ids = glm.array.from_numbers(ctypes.c_int, *(p[0] for p in value)) point_mats = new_mats if point_mats is None else point_mats.concat( new_mats) point_cols = new_cols if point_cols is None else point_cols.concat( new_cols) point_ids = new_ids if point_ids is None else point_ids.concat( new_ids) # we're done if no points to set if not self._items['point']: return self._num_points = sum(len(i) for i in self._items['point'].values()) self._bind_vao_mat_col_id(self._vaos['box'], point_mats, point_cols, point_ids)
def main(): pg.init() display = (1680, 1050) pg.display.set_mode(display, DOUBLEBUF|OPENGL) # If everything went well the following calls # will display the version of opengl being used print('Vendor: %s' % (glGetString(GL_VENDOR))) print('Opengl version: %s' % (glGetString(GL_VERSION))) print('GLSL Version: %s' % (glGetString(GL_SHADING_LANGUAGE_VERSION))) print('Renderer: %s' % (glGetString(GL_RENDERER))) glClearColor(0.95, 1.0, 0.95, 0) # Lets compile our shaders since the use of shaders is now # mandatory. We need at least a vertex and fragment shader # begore we can draw anything program = ShaderProgram(fragment=fragment, vertex=vertex) # Lets create a VAO and bind it # Think of VAO's as object that encapsulate buffer state # Using a VAO enables you to cut down on calls in your draw # loop which generally makes things run faster vao_id = glGenVertexArrays(1) glBindVertexArray(vao_id) # Lets create our Vertex Buffer objects - these are the buffers # that will contain our per vertex data vbo_id = glGenBuffers(2) # Bind a buffer before we can use it glBindBuffer(GL_ARRAY_BUFFER, vbo_id[0]) # Now go ahead and fill this bound buffer with some data glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(vertex_data), vertex_data, GL_STATIC_DRAW) # Now specify how the shader program will be receiving this data # In this case the data from this buffer will be available in the shader as the vin_position vertex attribute glVertexAttribPointer(program.attribute_location('vin_position'), 3, GL_FLOAT, GL_FALSE, 0, None) # Turn on this vertex attribute in the shader glEnableVertexAttribArray(0) # Now do the same for the other vertex buffer glBindBuffer(GL_ARRAY_BUFFER, vbo_id[1]) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(color_data), color_data, GL_STATIC_DRAW) glVertexAttribPointer(program.attribute_location('vin_color'), 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(1) # Lets unbind our vbo and vao state # We will bind these again in the draw loop glBindBuffer(GL_ARRAY_BUFFER, 0) glBindVertexArray(0) while True: for event in pg.event.get(): if event.type == pg.QUIT: pg.quit() quit() glClear(GL_COLOR_BUFFER_BIT) # Specify shader to be used glUseProgram(program.program_id) # Bind VAO - this will automatically # bind all the vbo's saving us a bunch # of calls glBindVertexArray(vao_id) # Modern GL makes the draw call really simple # All the complexity has been pushed elsewhere glDrawArrays(GL_TRIANGLES, 0, 3) # Lets unbind the shader and vertex array state glUseProgram(0) glBindVertexArray(0) # Now lets show our master piece on the screen pg.display.flip() pg.time.wait(10)
def create_vaos(self) -> None: """Bind VAOs to define vertex data.""" self._vaos['box'], self._vaos['side'], \ self._vaos['top'] = glGenVertexArrays(3) vbo = glGenBuffers(4) vertices = np.array( [ -0.5, -1.0, -1.0, # bottom 0.5, -1.0, -1.0, 0.5, -1.0, 1.0, -0.5, -1.0, 1.0, -0.5, 1.0, -1.0, # right 0.5, 1.0, -1.0, 0.5, -1.0, -1.0, -0.5, -1.0, -1.0, -0.5, 1.0, 1.0, # top 0.5, 1.0, 1.0, 0.5, 1.0, -1.0, -0.5, 1.0, -1.0, -0.5, -1.0, 1.0, # left 0.5, -1.0, 1.0, 0.5, 1.0, 1.0, -0.5, 1.0, 1.0, 0.5, 1.0, -1.0, # back 0.5, 1.0, 1.0, 0.5, -1.0, 1.0, 0.5, -1.0, -1.0, -0.5, -1.0, -1.0, # front -0.5, -1.0, 1.0, -0.5, 1.0, 1.0, -0.5, 1.0, -1.0, ], dtype=np.float32) glBindVertexArray(self._vaos['box']) glBindBuffer(GL_ARRAY_BUFFER, vbo[0]) glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) # --- below are unused vaos for rendering a cylinder (for the camerae model) # keep them, but TODO implement general object class thetas = np.linspace(0, 2 * np.pi, 24, endpoint=True) y = np.cos(thetas) * 0.7 z = np.sin(thetas) * 0.7 vertices = np.zeros(6 * 24, dtype=np.float32) vertices[::3] = np.tile(np.array([1.0, 0.5], dtype=np.float32), 24) vertices[1::3] = np.repeat(y, 2) vertices[2::3] = np.repeat(z, 2) glBindVertexArray(self._vaos['side']) glBindBuffer(GL_ARRAY_BUFFER, vbo[1]) glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) # --- vertices = np.concatenate( (np.array([1.0, 0.0, 0.0]), vertices)).astype(np.float32) indices = np.insert(np.arange(24) * 2 + 1, 0, 0).astype(np.uint16) glBindVertexArray(self._vaos['top']) glBindBuffer(GL_ARRAY_BUFFER, vbo[2]) glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo[3]) glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.nbytes, indices, GL_STATIC_DRAW) # --- glBindVertexArray(0) glDeleteBuffers(4, vbo)
def create_vaos(self) -> None: """Bind VAOs to define vertex data.""" self._vao_axes, *self._vao_arrows = glGenVertexArrays(3) vbo = glGenBuffers(5) build_dimensions = self.parent.build_dimensions x = build_dimensions[0] - build_dimensions[3], build_dimensions[3] y = build_dimensions[1] - build_dimensions[4], build_dimensions[4] z = build_dimensions[2] - build_dimensions[5], build_dimensions[5] points = np.array([ x[0], 0.0, 0.0, 1.0, 0.0, 0.0, -x[1], 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, y[0], 0.0, 0.0, 1.0, 0.0, 0.0, -y[1], 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, z[0], 0.0, 0.0, 1.0, 0.0, 0.0, -z[1], 0.0, 0.0, 1.0, ], dtype=np.float32) glBindVertexArray(self._vao_axes) # colored axes lines glBindBuffer(GL_ARRAY_BUFFER, vbo[0]) glBufferData(GL_ARRAY_BUFFER, points.nbytes, points, GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, vbo[1]) glBufferData(GL_ARRAY_BUFFER, points.nbytes, points, GL_STATIC_DRAW) glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(12)) glEnableVertexAttribArray(1) # --- vertices, colors = self._get_cones() glBindVertexArray(self._vao_arrows[0]) # colored axes arrows, cone glBindBuffer(GL_ARRAY_BUFFER, vbo[2]) glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, vbo[3]) glBufferData(GL_ARRAY_BUFFER, colors.nbytes, colors, GL_STATIC_DRAW) glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0)) glEnableVertexAttribArray(1) # --- vertices[0] = x[0] vertices[17 * 3 + 1] = y[0] vertices[17 * 6 + 2] = z[0] glBindVertexArray(self._vao_arrows[1]) # colored axes arrows, base glBindBuffer(GL_ARRAY_BUFFER, vbo[4]) glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, vbo[3]) glBufferData(GL_ARRAY_BUFFER, colors.nbytes, colors, GL_STATIC_DRAW) glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0)) glEnableVertexAttribArray(1) # --- glBindVertexArray(0) glDeleteBuffers(5, vbo)
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 simple_cube(): vertices_list = [ [-1.0, -1.0, -1.0], [-1.0, -1.0, +1.0], [1.0, -1.0, +1.0], [+1.0, -1.0, -1.0], [-1.0, +1.0, -1.0], [-1.0, +1.0, +1.0], [+1.0, +1.0, +1.0], [+1.0, +1.0, -1.0], [-1.0, -1.0, -1.0], [-1.0, +1.0, -1.0], [+1.0, +1.0, -1.0], [+1.0, -1.0, -1.0], [-1.0, -1.0, +1.0], [-1.0, +1.0, +1.0], [+1.0, +1.0, +1.0], [+1.0, -1.0, +1.0], [-1.0, -1.0, -1.0], [-1.0, -1.0, +1.0], [-1.0, +1.0, +1.0], [-1.0, +1.0, -1.0], [+1.0, -1.0, -1.0], [1.0, -1.0, +1.0], [+1.0, +1.0, +1.0], [1.0, +1.0, -1.0] ] normal_list = [ [0.0, -1.0, 0.0], [0.0, -1.0, 0.0], [0.0, -1.0, 0.0], [0.0, -1.0, 0.0], [0.0, 1.0, 0.0], [0.0, 1.0, 0.0], [0.0, 1.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, -1.0], [0.0, 0.0, -1.0], [0.0, 0.0, -1.0], [0.0, 0.0, -1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [-1.0, 0.0, 0.0], [-1.0, 0.0, 0.0], [-1.0, 0.0, 0.0], [-1.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 0.0, 0.0], ] indices_list = [ 0, 2, 1, 0, 3, 2, 4, 5, 6, 4, 6, 7, # 8, 9, 10, # 8, 10, 11, 12, 15, 14, 12, 14, 13, 16, 17, 18, 16, 18, 19, 20, 23, 22, 20, 22, 21 ] vertices_vec = np.array(vertices_list, dtype=np.float32) indices_vec = np.array(indices_list, dtype=np.uint32) normals_vec = np.array(normal_list, dtype=np.float32) vao = glGenVertexArrays(1) vbo_vertices = glGenBuffers(1) vbo_indices = glGenBuffers(1) vbo_normals = glGenBuffers(1) glBindVertexArray(vao) bind_buffer(vbo_vertices, vertices_vec, vbo_normals, normals_vec, vbo_indices, indices_vec) glBindVertexArray(0) return vao, indices_vec.size
def uv_torus(inner_radius, outer_radius, num_sides, num_faces): vertices_list = [] tri_ind = [] normal_list = [] t = 0.0 s = 0 t_incr = 1.0 / float(num_faces) s_incr = 1.0 / float(num_sides) for side_count in range(0, num_sides + 1): s += s_incr cos2ps = float(math.cos(2.0 * math.pi * s )) sin2ps = float(math.sin(2.0 * math.pi * s)) for face_count in range(0, num_faces + 1): t += t_incr cos2pt = float(math.cos(2.0 * math.pi * t)) sin2pt = float(math.sin(2.0 * math.pi * t)) x = (outer_radius + inner_radius * cos2pt) * cos2ps y = (outer_radius + inner_radius * cos2pt) * sin2ps z = inner_radius * sin2pt vertices_list.append([x, y, z]) x_norm = cos2ps * cos2pt; y_norm = sin2ps * cos2pt; z_norm = sin2pt; normal_list.append([x_norm, y_norm, z_norm]) for side_count in range(0, num_sides): for face_count in range(0, num_faces): v0 = ((side_count * (num_faces + 1)) + face_count); v1 = (((side_count + 1) * (num_faces + 1)) + face_count); v2 = (((side_count + 1) * (num_faces + 1)) + (face_count + 1)); v3 = ((side_count * (num_faces + 1)) + (face_count + 1)); tri_ind.append(v0) tri_ind.append(v1) tri_ind.append(v2) tri_ind.append(v0) tri_ind.append(v2) tri_ind.append(v3) vertices_vec = np.array(vertices_list, dtype=np.float32) indices_vec = np.array(tri_ind, dtype=np.uint32) normals_vec = np.array(normal_list, dtype=np.float32) vao = glGenVertexArrays(1) vbo_vertices = glGenBuffers(1) vbo_indices = glGenBuffers(1) vbo_normals = glGenBuffers(1) glBindVertexArray(vao) bind_buffer(vbo_vertices, vertices_vec, vbo_normals, normals_vec, vbo_indices, indices_vec) glBindVertexArray(0) return (vao, indices_vec.size)
def uv_sphere( mers, pars ): vertices_list = [] vertices_list.append([0.0, 1.0, 0.0]) tri_ind = [] for i in range(pars): polar = math.pi * (i+1) / pars sp = math.sin(polar) cp = math.cos(polar) for j in range(mers): azimuth = 2.0 * math.pi * j / mers sa = math.sin(azimuth) ca = math.cos(azimuth) x = sp * ca y = cp z = sp * sa vertices_list.append([x, y, z]) vertices_list.append([0.0, -1.0, 0.0]) for i in range(mers): a = i+1 b = (i+1) % mers + 1 tri_ind.append( 0 ) tri_ind.append( b ) tri_ind.append( a ) for j in range(pars-2): aStart = j * mers + 1 bStart = (j + 1) * mers + 1 for i in range(mers): a = aStart + i a1 = aStart + (i+1) % mers b = bStart + i b1 = bStart + (i+1) % mers tri_ind.append(a) tri_ind.append(a1) tri_ind.append(b1) tri_ind.append(a) tri_ind.append(b1) tri_ind.append(b) for i in range(mers): a = i + mers * (pars-2) + 1 b = (i+1) % mers + mers * (pars-2) + 1 tri_ind.append( len(vertices_list) - 1 ) tri_ind.append(a) tri_ind.append(b) vertices_vec = np.array(vertices_list, dtype=np.float32) indices_vec = np.array(tri_ind, dtype=np.uint32) normals_vec = normals_for_triangles(indices_vec, vertices_vec, indices_vec.size//3) vao = glGenVertexArrays(1) vbo_vertices = glGenBuffers(1) vbo_indices = glGenBuffers(1) vbo_normals = glGenBuffers(1) glBindVertexArray(vao) bind_buffer(vbo_vertices, vertices_vec, vbo_normals, normals_vec, vbo_indices, indices_vec) glBindVertexArray(0) return (vao, indices_vec.size, normals_vec)
def __init__(self): self._gl_id = glGenVertexArrays(1)
def __init__(self, vertices, indices, normals=None, uvs=None): """Constructor. Creates and initializes corresponding OpenGL objects with given data. :param vertices: Vertex data, specified as a contiguous list of X,Y,Z floating point values. :type vertices: list :param indices: Indices which identify model faces. The only supported geometry primitive is the triangle, thus, the size of indices list must be a multiple of 3. :type indices: list :param normals: Normals data, specified as a contiguos list of Xn,Yn,Zn floating point values. List length must be a multiple of 3. :type normals: list :param uvs: List of texture coordinates, specified as a contigous array of U,V floating pont values.. List length must be a multiple of 2. :type uvs: list """ if len(vertices) < 3 or len(vertices) % 3: raise ValueError( 'Vertex data must be an array of floats, which length is a ' 'positive multiple of 3') if len(indices) < 3 or len(indices) % 3: raise ValueError('Indices count must be a positive multiple of 3') if normals and (len(normals) < 3 or len(normals) % 3): raise ValueError( 'Normals data must be an array of floats, which length is a ' 'positive multiple of 3') if uvs is not None and len(uvs) % 2: raise ValueError('UVs count must be a positive multiple of 2') self.num_elements = len(indices) # generate vertex array object and make it active self.vao = glGenVertexArrays(1) glBindVertexArray(self.vao) # generate buffers self.buffers = glGenBuffers(2) vbo, ibo = self.buffers # initialize vertex buffer vertex_data = np.array(vertices, np.float32) # append normals data, if provided normals_offset = 0 if normals: normals_offset = vertex_data.nbytes vertex_data = np.append(vertex_data, np.array(normals, np.float32)) # append UVs data, if provided uvs_offset = 0 if uvs: uvs_offset = vertex_data.nbytes vertex_data = np.append(vertex_data, np.array(uvs, np.float32)) glBindBuffer(GL_ARRAY_BUFFER, vbo) glBufferData(GL_ARRAY_BUFFER, vertex_data.nbytes, vertex_data, GL_STATIC_DRAW) # initialize index buffer index_data = np.array(indices, np.uint32) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo) glBufferData(GL_ELEMENT_ARRAY_BUFFER, index_data.nbytes, index_data, GL_STATIC_DRAW) # specify first attribute as vertex data glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None) # if provided, specify normals as second attribute if normals is not None: glEnableVertexAttribArray(1) glVertexAttribPointer( 1, 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(normals_offset)) # if provided, specify UVs as third attribute if uvs is not None: glEnableVertexAttribArray(2) glVertexAttribPointer( 2, 2, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(uvs_offset)) # unbind the vertex array object glBindVertexArray(0)
def __enter__(self): if self.gl_identifier is None: self.gl_identifier = glGenVertexArrays(1) glBindVertexArray(self.gl_identifier) return self
def _init_vao(self): self.vao = glGenVertexArrays(1) glBindVertexArray(self.vao) self._enable_domain_attrib_pointers() glBindVertexArray(0)
print 'Opengl version: %s' % (glGetString(GL_VERSION)) print 'GLSL Version: %s' % (glGetString(GL_SHADING_LANGUAGE_VERSION)) print 'Renderer: %s' % (glGetString(GL_RENDERER)) glClearColor(0.95, 1.0, 0.95, 0) # Lets compile our shaders since the use of shaders is now # mandatory. We need at least a vertex and fragment shader # begore we can draw anything program = ShaderProgram(fragment=fragment, vertex=vertex) # Lets create a VAO and bind it # Think of VAO's as object that encapsulate buffer state # Using a VAO enables you to cut down on calls in your draw # loop which generally makes things run faster vao_id = glGenVertexArrays(1) glBindVertexArray(vao_id) # Lets create our Vertex Buffer objects - these are the buffers # that will contain our per vertex data vbo_id = glGenBuffers(2) # Bind a buffer before we can use it glBindBuffer(GL_ARRAY_BUFFER, vbo_id[0]) # Now go ahead and fill this bound buffer with some data glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(vertex_data), vertex_data, GL_STATIC_DRAW) # Now specify how the shader program will be receiving this data
def initialize_vertex_array(): vertex_array = GLuint(0) glGenVertexArrays(1, vertex_array) return vertex_array