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 __init__(self, chunk_id): self.name = GLuint() glGenBuffers(1, self.name) self.chunk_id = chunk_id self.vertexes_count = 0 # render flag self.render = False
def SetDisplayingItems(self, data, dataLen, colors): self.data = data self.colors = colors self.xcount = len(unique(data[:, 0])) self.ycount = len(unique(data[:, 1])) workingData = self.data workingColors = self.colors self.dataNum = dataLen self.colorsNum = self.dataNum maxVals = amax(workingData, axis=0) self.xMax = maxVals[0] self.yMax = maxVals[1] self.zMax = maxVals[2] minVals = amin(workingData, axis=0) self.xMin = minVals[0] self.yMin = minVals[1] self.zMin = minVals[2] # print "Max before offset:", self.xMax, self.yMax, self.zMax # print "Min before offset:", self.xMin, self.yMin, self.zMin self.diffX = (self.xMax + self.xMin) / 2 self.diffY = (self.yMax + self.yMin) / 2 self.diffZ = (self.zMax + self.zMin) / 2 # print "Offset:", self.diffX, self.diffY, self.diffZ workingData = subtract(workingData, array([self.diffX, self.diffY, self.diffZ], float32)) # recollect limitations maxVals = amax(workingData, axis=0) self.xMax = maxVals[0] self.yMax = maxVals[1] self.zMax = maxVals[2] minVals = amin(workingData, axis=0) self.xMin = minVals[0] self.yMin = minVals[1] self.zMin = minVals[2] # print "Max:", self.xMax, self.yMax, self.zMax # print "Min:", self.xMin, self.yMin, self.zMin self.eyeDistance = 100 * max(abs(self.xMax), abs(self.xMin), abs(self.yMax), abs(self.yMin), abs(self.zMax), abs(self.zMin)) # print "eye distance:", self.eyeDistance self.vertices_vbo = glGenBuffers(1) glEnableClientState(GL_VERTEX_ARRAY) glBindBuffer(GL_ARRAY_BUFFER, self.vertices_vbo) glBufferData(GL_ARRAY_BUFFER, workingData.nbytes, workingData, GL_STATIC_DRAW) glVertexPointer(3, GL_FLOAT, 0, None) glBindBuffer(GL_ARRAY_BUFFER, 0) self.colors_vbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.colors_vbo) glBufferData(GL_ARRAY_BUFFER, workingColors.nbytes, workingColors, GL_STATIC_DRAW) glColorPointer(3, GL_FLOAT, 0, None) glBindBuffer(GL_ARRAY_BUFFER, 0) print "Points and color is ready"
def __init__(self, kind): self._kind = kind self._hnd = glGenBuffers(1) logging.info('glGenBuffers(1) -> %d', self._hnd) if self._hnd == 0: raise ValueError('glGenBuffers failed')
def init_vao_vbo(self,data=None): if data.size: self.vao_data=data # 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 self.vertexBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.vertexBuffer) glBufferData(GL_ARRAY_BUFFER, 4*len(self.vao_data), self.vao_data,GL_DYNAMIC_DRAW) #self.vbo_id = glGenBuffers(1) #glBindBuffer(GL_ARRAY_BUFFER, self.vbo_id) #vertexData = numpy.array(quadV, numpy.float32) #glBufferData(GL_ARRAY_BUFFER, 4*len(self.vao_data), self.vao_data,GL_DYNAMIC_DRAW) # self.vao_id = \ #vao_id=glGenVertexArrays(1,None) #self.vao_id=vao_id #print vao_id #glBindVertexArray(self.vao_id[0]) # Lets create our Vertex Buffer objects - these are the buffers # that will contain our per vertex data #self.vbo_id = glGenBuffers(1) # Bind a buffer before we can use it #glBindBuffer(GL_ARRAY_BUFFER, self.vbo_id[0]) # Now go ahead and fill this bound buffer with some data #glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(self.data), self.data, GL_DYNAMIC_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 # 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)
def __init__(self): self.vbo = GLuint() self.vertexes = ( 0, 0, 0, 1.0, 0, 0, 1.0, 1.0, 0, 0, 0, 0, 1.0, 1.0, 0, 0, 1.0, 0, ) self.vertexes_GL = (GLfloat * len( self.vertexes))(*self.vertexes) glGenBuffers(1, self.vbo) glBindBuffer(GL_ARRAY_BUFFER, self.vbo) glBufferData( GL_ARRAY_BUFFER, len(self.vertexes_GL) * 4, self.vertexes_GL, GL_STATIC_DRAW) glBindBuffer(GL_ARRAY_BUFFER, 0)
def SetColors(self, colors): if not iterable(colors): return if len(colors) < self.dataNum: return self.colors = colors workingColors = self.colors # workingData, self.dataNum, workingColors = self.GetWorkingSet(self.data, self.dataNum, self.colors) self.colorsNum = len(workingColors) self.colors_vbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.colors_vbo) glBufferData(GL_ARRAY_BUFFER, workingColors.nbytes, workingColors, GL_STATIC_DRAW) glColorPointer(3, GL_FLOAT, 0, None) glBindBuffer(GL_ARRAY_BUFFER, 0) print "Color is ready"
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 _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 _bind_vao_mat_col_id(self, vao, mat: glm.array, col: glm.array, ids: glm.array) -> None: vbo = glGenBuffers(3) glBindBuffer(GL_ARRAY_BUFFER, vbo[0]) glBufferData(GL_ARRAY_BUFFER, mat.nbytes, mat.ptr, GL_STATIC_DRAW) glBindVertexArray(vao) # modelmats glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, 64, ctypes.c_void_p(0)) glEnableVertexAttribArray(3) glVertexAttribPointer(4, 4, GL_FLOAT, GL_FALSE, 64, ctypes.c_void_p(16)) # sizeof(glm::vec4) glVertexAttribDivisor(3, 1) glEnableVertexAttribArray(4) glVertexAttribDivisor(4, 1) glVertexAttribPointer(5, 4, GL_FLOAT, GL_FALSE, 64, ctypes.c_void_p(32)) # 2 * sizeof(glm::vec4) glEnableVertexAttribArray(5) glVertexAttribDivisor(5, 1) glVertexAttribPointer(6, 4, GL_FLOAT, GL_FALSE, 64, ctypes.c_void_p(48)) # 3 * sizeof(glm::vec4) glEnableVertexAttribArray(6) glVertexAttribDivisor(6, 1) # colors glBindBuffer(GL_ARRAY_BUFFER, vbo[1]) glBufferData(GL_ARRAY_BUFFER, col.nbytes, col.ptr, GL_STATIC_DRAW) glVertexAttribPointer(7, 4, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0)) glEnableVertexAttribArray(7) glVertexAttribDivisor(7, 1) # ids for picking glBindBuffer(GL_ARRAY_BUFFER, vbo[2]) glBufferData(GL_ARRAY_BUFFER, ids.nbytes, ids.ptr, GL_STATIC_DRAW) # it should be GL_INT here, yet only GL_FLOAT works. huh?? glVertexAttribPointer(8, 1, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0)) glEnableVertexAttribArray(8) glVertexAttribDivisor(8, 1) glEnableVertexAttribArray(0) glBindVertexArray(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 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 store_data_in_attribute_list(self, attribute_number: int, data: np.ndarray, dim: int = 3, datatype: int = GL_FLOAT) -> None: """ Stores the position information of the vertices at attribute 0 of the Vertex Array Object. It handles the necessary VBO Args: (int) attribute_number: The attribute number of the VAO where we want the data to be stored (np.ndarray) data: Data to be stored (int) dim: The dimension number of the individual data point. E.g 3 for (x, y, z) coordinates """ vbo_id = glGenBuffers(1) self.__vbos.append(vbo_id) glBindBuffer(GL_ARRAY_BUFFER, vbo_id) glBufferData(GL_ARRAY_BUFFER, data.nbytes, data, GL_STATIC_DRAW) glVertexAttribPointer(attribute_number, dim, datatype, GL_FALSE, 0, None) # Unbind VBO glBindBuffer(GL_ARRAY_BUFFER, 0)
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 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 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 __init__(self, n=1): vbo = glGenBuffers(n) if n == 1: vbo = [vbo] self.vbo = [Buffer(gl_buffer_id) for gl_buffer_id in vbo]
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)
if not self.vbo_isinit: self.vbo_init() #--- vertices glBindBuffer(GL_ARRAY_BUFFER, self.vbo_id_data) #--- TODO ck if only y/signal value can be copied step 2 glBufferSubData(GL_ARRAY_BUFFER,0,4*len(self.vbo_data_signal), self.vbo_data_signal) """ index buffer GLuint elementbuffer; glGenBuffers(1, &elementbuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_STATIC_DRAW); // Index buffer glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer); // Draw the triangles ! glDrawElements( GL_TRIANGLES, // mode indices.size(), // count GL_UNSIGNED_INT, // type -> GL_UNSIGNED_SHORT (void*)0 // element array buffer offset );
def make_buffer(target, buffer_data, size): buf = glGenBuffers(1) glBindBuffer(target, buf) glBufferData(target, size, buffer_data, GL_STATIC_DRAW) return buf
def create_surface(rows, cols, size, fun, gen_textures, gen_relief=False): normals_vec = np.zeros((rows * cols, 3), dtype=np.float32) vertices_list = [] texcoords_list = [] faces_list = [] indices_list = [] if not gen_relief: for z in range(0, rows): for x in range(0, cols): xx = -size / 2 + x * size / cols zz = -size / 2 + z * size / rows try: yy = fun(xx, zz) if yy < -size / 2: yy = -size / 2 if yy > size / 2: yy = size / 2 except (ArithmeticError, ValueError): yy = 0.0 vertices_list.append([xx, yy, zz]) if gen_textures: texcoords_list.append( [x / float(cols - 1), z / float(rows - 1)]) else: buff1 = [] vertices_list_twodimensional = [] for z in range(0, rows): buff1.clear() for x in range(0, cols): xx = -size / 2 + x * size / cols zz = -size / 2 + z * size / rows yy = 0.0 buff1.append([xx, yy, zz]) vertices_list_twodimensional.append(buff1.copy()) for i in range(0, 150): radius = randint(1, 15) z = randint(0, rows - 1) x = randint(0, cols - 1) for iz in range(z - radius, z + radius): if iz < 0 or iz > rows - 1: continue else: for ix in range(x - radius, x + radius): if ix < 0 or ix > cols - 1: continue else: if 2 * radius**2 - ( (z - iz)**2 + (x - ix)**2 ) > vertices_list_twodimensional[iz][ix][1]**(2): vertices_list_twodimensional[iz][ix][1] = ( 2 * radius**2 - ((z - iz)**2 + (x - ix)**2))**(1 / 2) else: continue v = vertices_list_twodimensional.copy() vec_lines = [] for ii in range(0, 10): i = 2 * ii for z in range(0, rows - 1): for x in range(0, cols - 1): xx = -size / 2 + x * size / cols zz = -size / 2 + z * size / rows if v[z][x][1] < i and v[z][x + 1][1] < i and v[z + 1][x][1] < i and v[z + 1][x + 1][1] < i or \ v[z][x][1] >= i and v[z][x + 1][1] >= i and v[z + 1][x][1] >= i and v[z + 1][x + 1][1] >= i: continue elif v[z][x][1] >= i and v[z][x + 1][1] < i and v[ z + 1][x][1] < i and v[z + 1][x + 1][1] < i: vec_lines.append([xx + 0.25, i, zz]) vec_lines.append([xx, i, zz + 0.25]) elif v[z][x][1] < i and v[z][x + 1][1] >= i and v[ z + 1][x][1] < i and v[z + 1][x + 1][1] < i: vec_lines.append([xx + 0.25, i, zz]) vec_lines.append([xx + 0.5, i, zz + 0.25]) elif v[z][x][1] < i and v[z][x + 1][1] < i and v[ z + 1][x][1] >= i and v[z + 1][x + 1][1] < i: vec_lines.append([xx + 0.25, i, zz + 0.5]) vec_lines.append([xx, i, zz + 0.25]) elif v[z][x][1] < i and v[z][x + 1][1] < i and v[ z + 1][x][1] < i and v[z + 1][x + 1][1] >= i: vec_lines.append([xx + 0.25, i, zz + 0.5]) vec_lines.append([xx + 0.5, i, zz + 0.25]) elif v[z][x][1] < i and v[z][x + 1][1] >= i and v[ z + 1][x][1] >= i and v[z + 1][x + 1][1] >= i: vec_lines.append([xx + 0.25, i, zz]) vec_lines.append([xx, i, zz + 0.25]) elif v[z][x][1] >= i and v[z][x + 1][1] < i and v[ z + 1][x][1] >= i and v[z + 1][x + 1][1] >= i: vec_lines.append([xx + 0.25, i, zz]) vec_lines.append([xx + 0.5, i, zz + 0.25]) elif v[z][x][1] >= i and v[z][x + 1][1] >= i and v[ z + 1][x][1] < i and v[z + 1][x + 1][1] >= i: vec_lines.append([xx + 0.25, i, zz + 0.5]) vec_lines.append([xx, i, zz + 0.25]) elif v[z][x][1] >= i and v[z][x + 1][1] >= i and v[ z + 1][x][1] >= i and v[z + 1][x + 1][1] < i: vec_lines.append([xx + 0.25, i, zz + 0.5]) vec_lines.append([xx + 0.5, i, zz + 0.25]) elif v[z][x][1] < i and v[z][x + 1][1] < i and v[z + 1][x][1] >= i and v[z + 1][x + 1][1] >= i or \ v[z][x][1] >= i and v[z][x + 1][1] >= i and v[z + 1][x][1] < i and v[z + 1][x + 1][1] < i: vec_lines.append([xx, i, zz + 0.25]) vec_lines.append([xx + 0.5, i, zz + 0.25]) elif v[z][x][1] >= i and v[z][x + 1][1] < i and v[z + 1][x][1] >= i and v[z + 1][x + 1][1] < i or \ v[z][x][1] < i and v[z][x + 1][1] >= i and v[z + 1][x][1] < i and v[z + 1][x + 1][1] >= i: vec_lines.append([xx + 0.25, i, zz]) vec_lines.append([xx + 0.25, i, zz + 0.5]) elif v[z][x][1] >= i and v[z][x + 1][1] < i and v[z + 1][x][1] < i and v[z + 1][x + 1][1] >= i or \ v[z][x][1] < i and v[z][x + 1][1] >= i and v[z + 1][x][1] >= i and v[z + 1][x + 1][1] < i: vec_lines.append([xx, i, zz + 0.25]) vec_lines.append([xx + 0.25, i, zz]) vec_lines.append([xx + 0.5, i, zz + 0.25]) vec_lines.append([xx + 0.25, i, zz + 0.5]) index_lines = [it for it in range(0, len(vec_lines))] vector_lines = np.array(vec_lines, dtype=np.float32) vector_line_indexes = np.array(index_lines, dtype=np.uint32) for z in range(0, rows): for x in range(0, cols): vertices_list.append(vertices_list_twodimensional[z][x]) primRestart = rows * cols vertices_vec = np.array(vertices_list, dtype=np.float32) if gen_textures: texcoords_vec = np.array(texcoords_list, dtype=np.float32) for x in range(0, cols - 1): for z in range(0, rows - 1): offset = x * cols + z if z == 0: indices_list.append(offset) indices_list.append(offset + rows) indices_list.append(offset + 1) indices_list.append(offset + rows + 1) else: indices_list.append(offset + 1) indices_list.append(offset + rows + 1) if z == rows - 2: indices_list.append(primRestart) indices_vec = np.array(indices_list, dtype=np.uint32) currFace = 1 for i in range(0, indices_vec.size - 2): index0 = indices_vec[i] index1 = indices_vec[i + 1] index2 = indices_vec[i + 2] face = np.array([0, 0, 0], dtype=np.int32) if (index0 != primRestart) and (index1 != primRestart) and ( index2 != primRestart): if currFace % 2 != 0: face[0] = indices_vec[i] face[1] = indices_vec[i + 1] face[2] = indices_vec[i + 2] currFace += 1 else: face[0] = indices_vec[i] face[1] = indices_vec[i + 2] face[2] = indices_vec[i + 1] currFace += 1 faces_list.append(face) faces = np.reshape(faces_list, newshape=(len(faces_list), 3)) for i in range(0, faces.shape[0]): A = np.array([ vertices_vec[faces[i, 0], 0], vertices_vec[faces[i, 0], 1], vertices_vec[faces[i, 0], 2] ], dtype=np.float32) B = np.array([ vertices_vec[faces[i, 1], 0], vertices_vec[faces[i, 1], 1], vertices_vec[faces[i, 1], 2] ], dtype=np.float32) C = np.array([ vertices_vec[faces[i, 2], 0], vertices_vec[faces[i, 2], 1], vertices_vec[faces[i, 2], 2] ], dtype=np.float32) edge1A = normalize(B - A) edge2A = normalize(C - A) face_normal = np.cross(edge1A, edge2A) normals_vec[faces[i, 0]] += face_normal normals_vec[faces[i, 1]] += face_normal normals_vec[faces[i, 2]] += face_normal for i in range(0, normals_vec.shape[0]): normals_vec[i] = normalize(normals_vec[i]) vao = glGenVertexArrays(1) vbo_vertices = glGenBuffers(1) vbo_normals = glGenBuffers(1) if gen_textures: vbo_texcoords = glGenBuffers(1) vbo_indices = 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) glBindBuffer(GL_ARRAY_BUFFER, vbo_normals) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(normals_vec), normals_vec.flatten(), GL_STATIC_DRAW) # glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_indices) glBufferData(GL_ELEMENT_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(indices_vec), indices_vec.flatten(), GL_STATIC_DRAW) if gen_textures: glBindBuffer(GL_ARRAY_BUFFER, vbo_texcoords) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(texcoords_vec), texcoords_vec.flatten(), GL_STATIC_DRAW) # glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(2) glEnable(GL_PRIMITIVE_RESTART) glPrimitiveRestartIndex(primRestart) # der_z_y = lambda x,y,z: z * math.cos(y) # der_y_z = lambda x,y,z: y * math.cos(z) # der_x_z = lambda x,y,z: x * math.cos(z) # der_z_x = lambda x,y,z: z * math.cos(x) # der_y_x = lambda x,y,z: y * math.cos(x) # der_x_y = lambda x,y,z: x * math.cos(y) # rot = lambda x,y,z: math.sqrt( (der_z_y(x,y,z) - der_y_z(x,y,z))**2 + (der_x_z(x,y,z) - der_z_x(x,y,z))**2 + (der_y_x(x,y,z) - der_x_y(x,y,z))**2 ) # # # max and min of rot lengths # max_rot = 0 # min_rot = 0 # rott_lst = [] # for i in vertices_list: # # rott = rot(i[0], i[1], i[2]) # rott_lst.append(rott) glBindVertexArray(0) if gen_relief: return (vao, indices_vec.size, vector_lines, vector_line_indexes) else: return (vao, indices_vec.size)
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 __init__(self, kind=GL_ARRAY_BUFFER): self.id = glGenBuffers(1) self.kind = kind
def __init__(self, data, size): self.m_RendererID = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.m_RendererID) glBufferData(GL_ARRAY_BUFFER, size, data, GL_STATIC_DRAW)
def build(self) -> bool: """ Build OpenGL Vertex Array for the object This function gets automatically called if `self._vao` does not exists in the first render cycle. Once the vba is built, geometry changes or material display mode changes will not be automatically effected. So, in every geometry or display mode change, a `build` call is necessary. If `self.static` is `True`, then the system assumes that another update call is not expected, thus frees `_normals`, `_textcoords`, `_vertices` and `_indices` lists to free memory. So in this case, calling `build` function twice will result in an invisible object (will not be drawn). Returns: bool """ if len(self._indices) == 0: return False # If we don't have a VAO yet, we need to create one if not self.has_vao: # Generate Vertex Array self._vao = glGenVertexArrays(1) # We need 5 buffers (vertex, normal, texcoord, color, indices) self._vbos = glGenBuffers(5) glBindVertexArray(self._vao) # Material shader must be built when there is an active binding # to vertex array self.material.build_shader() else: # Ok, we already have vertex array object, just bind it to modify glBindVertexArray(self._vao) # Turn python arrays into C type arrays using Numpy. # This is required for OpenGL. Python memory model is a bit # different than raw memory model of C (OpenGL) vertices = np.array(self._vertices, dtype=np.float32).flatten() normals = np.array(self._normals, dtype=np.float32).flatten() texcoords = np.array(self._texcoords, dtype=np.float32).flatten() colors = np.array(self._vertex_colors, dtype=np.float32).flatten() indices = np.array(self._indices, dtype=np.int32).flatten() self._calc_bounds() # OpenGL allocates buffers in different mechanisms between # STATIC and DYNAMIC draw modes. If you select STATIC, then OpenGL # will assume that object buffer will not change and allocate it in a # more suitable way. draw = GL_STATIC_DRAW if not self.static: draw = GL_DYNAMIC_DRAW # Buffer overflow, we need more space. if self._buffer_size < vertices.nbytes: self._buffer_size = vertices.nbytes self._buffer_size_changed = True if self._t_buffer_size < texcoords.nbytes: self._t_buffer_size = texcoords.nbytes self._t_buffer_size_changed = True # Bind Vertices glBindBuffer(GL_ARRAY_BUFFER, self._vbos[0]) glEnableVertexAttribArray(0) # shader layout location glVertexAttribPointer(0, 3, GL_FLOAT, False, 0, ctypes.c_void_p(0)) if self._buffer_size_changed: # glBufferData creates a new data area glBufferData(GL_ARRAY_BUFFER, self._buffer_size, vertices, draw) else: # glBufferSubData just replaces memory area in buffer so it is # much more efficient way to handle things. glBufferSubData(GL_ARRAY_BUFFER, 0, vertices.nbytes, vertices) # Bind Normals glBindBuffer(GL_ARRAY_BUFFER, self._vbos[1]) glEnableVertexAttribArray(1) # shader layout location glVertexAttribPointer(1, 3, GL_FLOAT, False, 0, ctypes.c_void_p(0)) if self._buffer_size_changed: glBufferData(GL_ARRAY_BUFFER, self._buffer_size, normals, draw) else: glBufferSubData(GL_ARRAY_BUFFER, 0, normals.nbytes, normals) # Bind TexCoords if len(self._texcoords) == len(self._vertices): glBindBuffer(GL_ARRAY_BUFFER, self._vbos[2]) glEnableVertexAttribArray(2) # shader layout location glVertexAttribPointer(2, 2, GL_FLOAT, False, 0, ctypes.c_void_p(0)) if self._t_buffer_size_changed: glBufferData( GL_ARRAY_BUFFER, self._t_buffer_size, texcoords, draw ) else: glBufferSubData( GL_ARRAY_BUFFER, 0, texcoords.nbytes, texcoords ) # Bind Vertex Colors if len(self._vertex_colors) == len(self._vertices): glBindBuffer(GL_ARRAY_BUFFER, self._vbos[4]) glEnableVertexAttribArray(3) # shader layout location glVertexAttribPointer(3, 3, GL_FLOAT, False, 0, ctypes.c_void_p(0)) self._has_vertex_colors = True if self._buffer_size_changed: glBufferData(GL_ARRAY_BUFFER, self._buffer_size, colors, draw) else: glBufferSubData(GL_ARRAY_BUFFER, 0, colors.nbytes, colors) self._buffer_size_changed = False self._t_buffer_size_changed = False # Bind Indices glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self._vbos[3]) glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.nbytes, indices, draw) self._vertex_count = len(indices) glBindVertexArray(0) glBindBuffer(GL_ARRAY_BUFFER, 0) if self.static: # we can clear this data to free some more memory glDeleteBuffers(4, self._vbos) self._vbos = [] self._needs_update = False return True
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 main(visualize): if args.config: config_path = args.config else: config_path = "config.yaml" with open(config_path) as file: config = yaml.load(file, Loader=yaml.FullLoader) teams, boxes, agents = generate_spatial_entities(config) agents_x_sorted = initial_sort(agents) if config["sotilaskoti"]["allow"]: # create queue to the sotilaskoti q = [] # table of meetings between agents, from the previous simulation step meets_prev = dict() if visualize: # verticies for area borders and inferred width and height of the map. # I.e. canvas contains map width and height in meters for computations fences_verts, canvas = generate_map(boxes, config) # verticies for traingles that represent agents agents_verts = generate_agents_verticies(config) if not glfw.init(): return window = glfw.create_window(config["window"][ "width"], config["window"]["height"], config["window"][ "title"], None, None) if not window: glfw.terminate() return glfw.make_context_current(window) # compile shader for on-the-fly configurable trianges shader = compile_shader() # create Buffer object in gpu VBO = glGenBuffers(2) # bind buffers glBindBuffer(GL_ARRAY_BUFFER, VBO[0]) glBufferData(GL_ARRAY_BUFFER, fences_verts.nbytes, fences_verts, GL_STATIC_DRAW) glBindBuffer(GL_ARRAY_BUFFER, VBO[1]) glBufferData(GL_ARRAY_BUFFER, agents_verts.nbytes, agents_verts, GL_STATIC_DRAW) fences_stride = fences_verts.strides[0] agents_stride = agents_verts.strides[0] # get the position from vertex shader # stride offset offset = ctypes.c_void_p(0) init_pos = glGetAttribLocation(shader, 'init_pos') glVertexAttribPointer(init_pos, 2, GL_FLOAT, GL_FALSE, agents_stride, offset) glEnableVertexAttribArray(init_pos) glUseProgram(shader) glClearColor(1.0, 1.0, 1.0, 1.0) """ Prepare directories to store: - source configuration files, - intermediate results in the form of meeting tables - output statistical reports """ if not os.path.exists("output"): os.makedirs("output") paths = { "configs" : os.path.join("output", "configs"), "meet_tables" : os.path.join("output", "meetings_tables"), "agents" : os.path.join("output", "agents"), "out_stats" : os.path.join("output", "stat_results"), } for path in paths.values(): if not os.path.exists(path): os.makedirs(path) if args.config: # in this usage scenario all identifiers are set manually # (unique tags are generated in meta-loop that launches these scripts) tag = args.name else: # in this usage scenario timestamp is autimatically appended to # distinguish between consequtive manual program launches timestamp = datetime.now().strftime("%H:%M:%S") tag = args.name +'_'+ timestamp # store the config file for the reference dump_config_path = os.path.join( paths["configs"], "config_"+ tag +".yaml") shutil.copy(config_path, dump_config_path) # store agents for the further move speed / infection spread correlating agents_souls_path = os.path.join( paths["agents"], "spatial_agents_"+ tag +".bin") with open(agents_souls_path, 'wb') as file: pickle.dump(agents, file) # create the file with agent meetings # originally a .bin file, is later compressed to the .bin.tar.bz2 format meets_table_path = os.path.join( paths["meet_tables"], "meet_table_"+ tag +".bin") with open(meets_table_path, 'wb') as file: # run until the end of the set simulation period T = config["simulationDuration"] * 24*60*60 dt = config[ "minSimulationStep"] eval_times = np.arange(0, T, dt) for eval_time in tqdm(eval_times): """ Transition agents between service and leave """ entities = (teams, boxes, agents) # some agents prefer to stay on the base during holidays stay_chance = config.get('dontGoOffDuty', 0.0) rotate_teams(entities, stay_chance, eval_time, dt) """ Transition agents to "Sotilaskoti" cafeteria and back """ if config["sotilaskoti"]["allow"]: queue_sotilaskoti(entities, q, eval_time, dt, config) """ Update agent positions (along one time step) """ increment_agent_positions(agents) """ Refresh the sorting of agents after the positions update """ x_sort(agents_x_sorted) """ Register new meetings between agents and export them to file """ meets_curr = detect_meetings(agents_x_sorted, eval_time, config, visualize) # each key is a meeting link between two agents # in the form {agent1_idx, agent2_idx} links_curr = set( meets_curr.keys() ) links_prev = set( meets_prev.keys() ) meets_new = dict() for link in links_curr: if link not in links_prev: meets_new[link] = meets_curr[link] if meets_new: timeline = {"timestamp" : eval_time, "meetings" : meets_new} pickle.dump(timeline, file) meets_prev = meets_curr """ Plot canvas if not specified otherwise (--no-visual option) """ if visualize: if glfw.window_should_close(window): break time_zero = time.time() glClear(GL_COLOR_BUFFER_BIT) """ Indicate current day in window title """ day_n = eval_time // (24*60*60) + 1 dayly_title = config["window"]["title"] +", day: "+ str(day_n) glfw.set_window_title(window, dayly_title) """ Draw borders (i.e. boxes, i.e. fences) - 1 px black outlines """ glBindBuffer(GL_ARRAY_BUFFER, VBO[0]) glVertexAttribPointer(init_pos, 2, GL_FLOAT, GL_FALSE, fences_stride, offset) glEnableVertexAttribArray(init_pos) transformLoc = glGetUniformLocation(shader, "dyn_pos") glUniform2f(transformLoc, 0.0, 0.0) transformLoc = glGetUniformLocation(shader, "dyn_color") glUniform4f(transformLoc, 0.0, 0.0, 0.0, 0.0) glDrawArrays(GL_TRIANGLES, 0, len(fences_verts)) """ Draw agents (i.e. conscripts and civilians) """ glBindBuffer(GL_ARRAY_BUFFER, VBO[1]) glVertexAttribPointer(init_pos, 2, GL_FLOAT, GL_FALSE, agents_stride, offset) glEnableVertexAttribArray(init_pos) for i, agent in enumerate(agents): poly_prop = np.zeros(1, [( "pos" , np.float32, 2), ("color", np.float32, 4)]) # absolute to relative coordinates, meters -> fractions x = (agent.x/canvas[ "width"]*2 - 1)*0.99 y = (agent.y/canvas["height"]*2 - 1)*0.99 poly_prop["pos"] = (x, y) transformLoc = glGetUniformLocation(shader, "dyn_pos") glUniform2f(transformLoc, *poly_prop["pos"].T) """ Agent triangle marker filling """ poly_prop["color"] = agent.color transformLoc = glGetUniformLocation(shader, "dyn_color") glUniform4f(transformLoc, *poly_prop["color"].T) if agent.conscripted: glDrawArrays(GL_TRIANGLES, 3, 6) else: glDrawArrays(GL_TRIANGLES, 0, 3) """ Marker outline """ transformLoc = glGetUniformLocation(shader, "dyn_color") glUniform4f(transformLoc, 0.0, 0.0, 0.0, 1.0) # black if agent.conscripted: glDrawArrays(GL_LINE_LOOP, 3, 6) else: glDrawArrays(GL_LINE_LOOP, 0, 3) glfw.swap_buffers(window) # FPS limited to 60 while(time.time() - time_zero < 1/60): time.sleep(0.001) glfw.poll_events() if visualize: glfw.terminate() """ Compress output file to save space """ compressed_path = os.path.join( paths["meet_tables"], "meet_table_"+ tag +".bin.tar.bz2") with tarfile.open(compressed_path, "w:bz2") as tar: tar.add(meets_table_path) # in case compressing went successful, remove the source file if os.path.exists(compressed_path): os.remove(meets_table_path)
def create_vaos(self) -> None: """Bind VAOs to define vertex data.""" self._vao, self._vao_picking, self._vao_outline = glGenVertexArrays(3) vbo = glGenBuffers(6) # --- standard viewcube --- vertices = glm.array.from_numbers( ctypes.c_float, 1.0, 1.0, 1.0, 0.7, 0.7, 0.7, 1.0, -1.0, 1.0, 0.7, 0.7, 0.7, 1.0, -1.0, -1.0, 0.4, 0.4, 0.4, 1.0, 1.0, -1.0, 0.4, 0.4, 0.4, -1.0, 1.0, -1.0, 0.4, 0.4, 0.4, -1.0, 1.0, 1.0, 0.7, 0.7, 0.7, -1.0, -1.0, 1.0, 0.7, 0.7, 0.7, -1.0, -1.0, -1.0, 0.4, 0.4, 0.4, ) indices = glm.array.from_numbers( ctypes.c_uint, 0, 1, 2, 2, 3, 0, 0, 3, 4, 4, 5, 0, 0, 5, 6, 6, 1, 0, 1, 6, 7, 7, 2, 1, 7, 4, 3, 3, 2, 7, 4, 7, 6, 6, 5, 4, ) glBindVertexArray(self._vao) glBindBuffer(GL_ARRAY_BUFFER, vbo[0]) glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices.ptr, 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, vertices.nbytes, vertices.ptr, GL_STATIC_DRAW) glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(12)) glEnableVertexAttribArray(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo[2]) glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.nbytes, indices.ptr, GL_STATIC_DRAW) # --- viewcube for picking --- vertices = glm.array.from_numbers( ctypes.c_float, 1.0, -1.0, 1.0, # 1 front (id = 0) -1.0, -1.0, 1.0, # 6 -1.0, -1.0, -1.0, # 7 1.0, -1.0, -1.0, # 2 1.0, 1.0, 1.0, # 0 top (id = 1) -1.0, 1.0, 1.0, # 5 -1.0, -1.0, 1.0, # 6 1.0, -1.0, 1.0, # 1 1.0, 1.0, 1.0, # 0 right (id = 2) 1.0, -1.0, 1.0, # 1 1.0, -1.0, -1.0, # 2 1.0, 1.0, -1.0, # 3 -1.0, -1.0, -1.0, # 7 bottom (id = 3) -1.0, 1.0, -1.0, # 4 1.0, 1.0, -1.0, # 3 1.0, -1.0, -1.0, # 2 -1.0, -1.0, -1.0, # 7 left (id = 4) -1.0, -1.0, 1.0, # 6 -1.0, 1.0, 1.0, # 5 -1.0, 1.0, -1.0, # 4 1.0, 1.0, 1.0, # 0 back (id = 5) 1.0, 1.0, -1.0, # 3 -1.0, 1.0, -1.0, # 4 -1.0, 1.0, 1.0, # 5 ) colors = np.zeros(72, dtype=np.float32) colors[::3] = np.arange(6).repeat(4) / 255.0 glBindVertexArray(self._vao_picking) glBindBuffer(GL_ARRAY_BUFFER, vbo[3]) 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) glBindBuffer(GL_ARRAY_BUFFER, vbo[4]) 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) # --- outlined face of viewcube --- border_colors = glm.array.from_numbers(ctypes.c_float, 0.0000, 0.4088, 0.9486).repeat(24) glBindVertexArray(self._vao_outline) glBindBuffer(GL_ARRAY_BUFFER, vbo[3]) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, vbo[5]) glBufferData(GL_ARRAY_BUFFER, border_colors.nbytes, border_colors.ptr, GL_STATIC_DRAW) glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0)) glEnableVertexAttribArray(1) # --- glBindVertexArray(0) glDeleteBuffers(6, vbo)
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 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 __enter__(self): if self.gl_identifier is None: self.gl_identifier = glGenBuffers(1) glBindBuffer(self.gl_bind_type, self.gl_identifier) return self
# 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)
def __init__(self, data): self.id = glGenBuffers(1) self.bind() glBufferData(GL_ARRAY_BUFFER, data.itemsize * len(data), data, GL_STATIC_DRAW) self.unbind()
# 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)
def create_field(rows, cols, size, fun, gen_textures, gen_relief=False): normals_vec = np.zeros((rows * cols, 3), dtype=np.float32) vertices_list = [] texcoords_list = [] faces_list = [] indices_list = [] if not gen_relief: for z in range(0, rows): for x in range(0, cols): # if (x**2 + z**2)**(1/2) <= cols: xx = -size / 2 + x * size / cols zz = -size / 2 + z * size / rows try: yy = fun(xx, zz) if yy < -size / 2: yy = -size / 2 if yy > size / 2: yy = size / 2 except (ArithmeticError, ValueError): yy = 0.0 vertices_list.append([xx, yy, zz]) if gen_textures: texcoords_list.append( [x / float(cols - 1), z / float(rows - 1)]) else: buff1 = [] vertices_list_mountain = [] for z in range(0, rows): del buff1[:] for x in range(0, cols): xx = -size / 2 + x * size / cols zz = -size / 2 + z * size / rows yy = 0.0 buff1.append([xx, yy, zz]) vertices_list_mountain.append(buff1[:]) for i in range(0, 250): radius = 12 z = randint(0, rows - 1) x = randint(0, cols - 1) for iz in range(z - radius, z + radius): if iz < 0 or iz > rows - 1: continue else: for ix in range(x - radius, x + radius): if ix < 0 or ix > cols - 1: continue else: if radius**2 - ( (z - iz + 10)**2 + (x - ix) ) > vertices_list_mountain[iz][ix][1]**(2): vertices_list_mountain[iz][ix][1] = ( radius**2 - ((z - iz + 10)**2 + (x - ix)))**(1 / 2) else: continue v = vertices_list_mountain[:] vec_lines = [] for ii in range(0, 10): i = 2 * ii for z in range(0, rows - 1): for x in range(0, cols - 1): xx = -size / 2 + x * size / cols zz = -size / 2 + z * size / rows if v[z][x][1] < i and v[z][x + 1][1] < i and v[z + 1][x][1] < i and v[z + 1][x + 1][1] < i or \ v[z][x][1] >= i and v[z][x + 1][1] >= i and v[z + 1][x][1] >= i and v[z + 1][x + 1][1] >= i: continue elif v[z][x][1] >= i and v[z][x + 1][1] < i and v[ z + 1][x][1] < i and v[z + 1][x + 1][1] < i: vec_lines.append([xx + 0.25, i, zz]) vec_lines.append([xx, i, zz + 0.25]) elif v[z][x][1] < i and v[z][x + 1][1] >= i and v[ z + 1][x][1] < i and v[z + 1][x + 1][1] < i: vec_lines.append([xx + 0.25, i, zz]) vec_lines.append([xx + 0.5, i, zz + 0.25]) elif v[z][x][1] < i and v[z][x + 1][1] < i and v[ z + 1][x][1] >= i and v[z + 1][x + 1][1] < i: vec_lines.append([xx + 0.25, i, zz + 0.5]) vec_lines.append([xx, i, zz + 0.25]) elif v[z][x][1] < i and v[z][x + 1][1] < i and v[ z + 1][x][1] < i and v[z + 1][x + 1][1] >= i: vec_lines.append([xx + 0.25, i, zz + 0.5]) vec_lines.append([xx + 0.5, i, zz + 0.25]) elif v[z][x][1] < i and v[z][x + 1][1] >= i and v[ z + 1][x][1] >= i and v[z + 1][x + 1][1] >= i: vec_lines.append([xx + 0.25, i, zz]) vec_lines.append([xx, i, zz + 0.25]) elif v[z][x][1] >= i and v[z][x + 1][1] < i and v[ z + 1][x][1] >= i and v[z + 1][x + 1][1] >= i: vec_lines.append([xx + 0.25, i, zz]) vec_lines.append([xx + 0.5, i, zz + 0.25]) elif v[z][x][1] >= i and v[z][x + 1][1] >= i and v[ z + 1][x][1] < i and v[z + 1][x + 1][1] >= i: vec_lines.append([xx + 0.25, i, zz + 0.5]) vec_lines.append([xx, i, zz + 0.25]) elif v[z][x][1] >= i and v[z][x + 1][1] >= i and v[ z + 1][x][1] >= i and v[z + 1][x + 1][1] < i: vec_lines.append([xx + 0.25, i, zz + 0.5]) vec_lines.append([xx + 0.5, i, zz + 0.25]) elif v[z][x][1] < i and v[z][x + 1][1] < i and v[z + 1][x][1] >= i and v[z + 1][x + 1][1] >= i or \ v[z][x][1] >= i and v[z][x + 1][1] >= i and v[z + 1][x][1] < i and v[z + 1][x + 1][1] < i: vec_lines.append([xx, i, zz + 0.25]) vec_lines.append([xx + 0.5, i, zz + 0.25]) elif v[z][x][1] >= i and v[z][x + 1][1] < i and v[z + 1][x][1] >= i and v[z + 1][x + 1][1] < i or \ v[z][x][1] < i and v[z][x + 1][1] >= i and v[z + 1][x][1] < i and v[z + 1][x + 1][1] >= i: vec_lines.append([xx + 0.25, i, zz]) vec_lines.append([xx + 0.25, i, zz + 0.5]) elif v[z][x][1] >= i and v[z][x + 1][1] < i and v[z + 1][x][1] < i and v[z + 1][x + 1][1] >= i or \ v[z][x][1] < i and v[z][x + 1][1] >= i and v[z + 1][x][1] >= i and v[z + 1][x + 1][1] < i: vec_lines.append([xx, i, zz + 0.25]) vec_lines.append([xx + 0.25, i, zz]) vec_lines.append([xx + 0.5, i, zz + 0.25]) vec_lines.append([xx + 0.25, i, zz + 0.5]) index_lines = [it for it in range(0, len(vec_lines))] vector_lines = np.array(vec_lines, dtype=np.float32) vector_line_indexes = np.array(index_lines, dtype=np.uint32) for z in range(0, rows): for x in range(0, cols): vertices_list.append(vertices_list_mountain[z][x]) primRestart = rows * cols vertices_vec = np.array(vertices_list, dtype=np.float32) print(len(vertices_list)) print(vertices_vec.size) print(len(indices_list)) print(size) if gen_textures: texcoords_vec = np.array(texcoords_list, dtype=np.float32) for x in range(0, cols - 1): for z in range(0, rows - 1): if ((50 - x)**2 + (50 - z)**2)**(1 / 2) <= (rows - 1) / 2 or gen_relief == True: offset = x * cols + z if z == 0: indices_list.append(offset) indices_list.append(offset + rows) indices_list.append(offset + 1) indices_list.append(offset + rows + 1) else: indices_list.append(offset + 1) indices_list.append(offset + rows + 1) if z == rows - 2: indices_list.append(primRestart) print(len(indices_list)) indices_vec = np.array(indices_list, dtype=np.uint32) print(indices_vec.size) currFace = 1 for i in range(0, indices_vec.size - 2): index0 = indices_vec[i] index1 = indices_vec[i + 1] index2 = indices_vec[i + 2] face = np.array([0, 0, 0], dtype=np.int32) if (index0 != primRestart) and (index1 != primRestart) and ( index2 != primRestart): if currFace % 2 != 0: face[0] = indices_vec[i] face[1] = indices_vec[i + 1] face[2] = indices_vec[i + 2] currFace += 1 else: face[0] = indices_vec[i] face[1] = indices_vec[i + 2] face[2] = indices_vec[i + 1] currFace += 1 faces_list.append(face) faces = np.reshape(faces_list, newshape=(len(faces_list), 3)) for i in range(0, faces.shape[0]): A = np.array([ vertices_vec[faces[i, 0], 0], vertices_vec[faces[i, 0], 1], vertices_vec[faces[i, 0], 2] ], dtype=np.float32) B = np.array([ vertices_vec[faces[i, 1], 0], vertices_vec[faces[i, 1], 1], vertices_vec[faces[i, 1], 2] ], dtype=np.float32) C = np.array([ vertices_vec[faces[i, 2], 0], vertices_vec[faces[i, 2], 1], vertices_vec[faces[i, 2], 2] ], dtype=np.float32) edge1A = normalize(B - A) edge2A = normalize(C - A) face_normal = np.cross(edge1A, edge2A) normals_vec[faces[i, 0]] += face_normal normals_vec[faces[i, 1]] += face_normal normals_vec[faces[i, 2]] += face_normal for i in range(0, normals_vec.shape[0]): normals_vec[i] = normalize(normals_vec[i]) vao = glGenVertexArrays(1) vbo_vertices = glGenBuffers(1) vbo_normals = glGenBuffers(1) if gen_textures: vbo_texcoords = glGenBuffers(1) vbo_indices = 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) glBindBuffer(GL_ARRAY_BUFFER, vbo_normals) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(normals_vec), normals_vec.flatten(), GL_STATIC_DRAW) # glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_indices) glBufferData(GL_ELEMENT_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(indices_vec), indices_vec.flatten(), GL_STATIC_DRAW) if gen_textures: glBindBuffer(GL_ARRAY_BUFFER, vbo_texcoords) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(texcoords_vec), texcoords_vec.flatten(), GL_STATIC_DRAW) glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(2) glEnable(GL_PRIMITIVE_RESTART) glPrimitiveRestartIndex(primRestart) glBindVertexArray(0) if gen_relief: return (vao, indices_vec.size, vector_lines, vector_line_indexes) else: return (vao, indices_vec.size)