def init_context(name, modelview_matrix, projection_matrix): state = get_state() with open(state["shaders"][name]['vertex_shader_path']) as f: vertex_shader_text = f.read() vertex_shader = shaders.compileShader(vertex_shader_text, GL_VERTEX_SHADER) with open(state["shaders"][name]['fragment_shader_path']) as f: fragment_shader_text = f.read() fragment_shader = shaders.compileShader(fragment_shader_text, GL_FRAGMENT_SHADER) shader = shaders.compileProgram(vertex_shader, fragment_shader) #print "init interface state: ", state position_location = glGetAttribLocation(shader, 'position') normal_location = glGetAttribLocation(shader, 'normal') color_location = glGetAttribLocation(shader, 'color') modelview_location = glGetUniformLocation(shader, 'modelViewMatrix') projection_location = glGetUniformLocation(shader, 'projectionMatrix') contexts[name] = { 'shader': shader, 'modelview': { 'location': modelview_location, 'matrix': modelview_matrix }, 'projection': { 'location': projection_location, 'matrix': projection_matrix }, 'position_location': position_location, 'color_location': color_location, 'normal_location': normal_location, 'thing': state[name] }
def __init__(self): super(PrimitiveShader, self).__init__(PrimitiveShader.primitiveVertex, PrimitiveShader.primitiveFragment) # Get our shader entry points self.attrib_position = glGetAttribLocation(self.program, 'position') self.attrib_color = glGetAttribLocation(self.program, 'color') self.uniform_modelCamera = glGetUniformLocation(self.program, 'modelToCameraMatrix') self.uniform_projection = glGetUniformLocation(self.program, 'projectionMatrix') self.uniform_alpha = glGetUniformLocation(self.program, 'alpha')
def reload(self): """ Reload or build for the first time the attribute cache. This can be quite expensive so it is only done on shader linking. If the shader was linked outside the api, you have to call this manually. """ prog = self.prog() if prog is None: raise RuntimeError('Shader was freed') maxlength = getattr(prog, 'max_attribute_length') name_buf = (c_char * maxlength)() name_buf_ptr = cast(name_buf, POINTER(c_char)) type_buf = GLenum(0) name_buf_length = GLint(0) buf_size = GLint(0) self.cache = {} for i in range(getattr(prog, 'attributes_count')): glGetActiveAttrib(prog.pid, i, maxlength, byref(name_buf_length), byref(buf_size), byref(type_buf), name_buf_ptr) type = type_buf.value name_len = name_buf_length.value name = bytes(name_buf)[0:name_len].decode('UTF-8') size = buf_size.value loc = GLint(glGetAttribLocation( prog.pid, name)) #Kept in a c_int to quickly send the value when setting self.cache_item_build(loc, size, name, type)
def add_attribute(self, vid, data, name): """Add array vertex attribute for shaders.""" if data.ndim > 1: data = data.flatten() glBindBuffer(GL_ARRAY_BUFFER, self.__vbo_id[vid]) glBufferData(GL_ARRAY_BUFFER, data.nbytes, data, GL_STATIC_DRAW) glVertexAttribPointer(glGetAttribLocation(self.__program, name), 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(vid) self.__attributes.append(data)
def attribute_location(self, name): """ Helper function to get location of an OpenGL attribute variable Parameters ---------- name : str Name of the variable for which location is to be returned Returns ------- value : int Integer describing location """ return glGetAttribLocation(self.program_id, name)
def __init__(self, vertex_shader: Union[str, None] = None, fragment_shader: Union[str, None] = None, geometry_shader: Union[str, None] = None, view_matrix_name: str = 'view_matrix', projection_matrix_name: str = 'projection_matrix', model_matrix_name: str = 'model_matrix', instanced_attribs=(), obj=None): super().__init__('Material', obj) self.__vertex_shader = vertex_shader self.__fragment_shader = fragment_shader self.__geometry_shader = geometry_shader self.__attributes: Dict[str, int] = {} self.__uniforms: Dict[str, int] = {} self.view_matrix_name = view_matrix_name self.projection_matrix_name = projection_matrix_name self.model_matrix_name = model_matrix_name self.__instanced_attribs = set(instanced_attribs) self.__attributes_values: Union[Dict[str, np.ndarray]] = {} self.__uniforms_values: Union[Dict[str, np.ndarray]] = {} self.__attributes_types = {} self.__uniforms_types = {} if self.__vertex_shader and self.__fragment_shader: program = compileProgram( *[compileShader(shader, const) for shader, const in [(self.__vertex_shader, GL_VERTEX_SHADER), (self.__fragment_shader, GL_FRAGMENT_SHADER), (self.__geometry_shader, GL_GEOMETRY_SHADER)] if shader] ) self.__program = program num_active_attribs = glGetProgramiv(program, GL_ACTIVE_ATTRIBUTES) for u in range(num_active_attribs): name, size, type_ = glGetActiveAttrib(program, u) location = glGetAttribLocation(program, name) name = name.decode("utf-8") self.__attributes_types[name] = type_ self.__attributes[name] = location self.__attributes_values[name] = np.array([]) num_active_uniforms = glGetProgramiv(program, GL_ACTIVE_UNIFORMS) for u in range(num_active_uniforms): name, size, type_ = glGetActiveUniform(program, u) location = glGetUniformLocation(program, name) name = name.decode("utf-8") self.__uniforms_types[name] = type_ self.__uniforms[name] = location self.__uniforms_values[name] = np.array([])
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 __init__(self, vertex_shader, fragment_shader): self.vert = vertex_shader self.frag = fragment_shader self._models_and_VAOs = [] self._program = shaders.compileProgram(self.vert.shader, self.frag.shader) self.VAOs = [] # get uniform locations self.uniforms = {} self.ins = {} for var in self.vert.vars: if var.cls == "uniform": loc = glGetUniformLocation(self._program, var.name) if loc == -1: print( "WARNING: Uniform " + var.name + " returned -1; this indicates that the var is not being used by the program." ) else: self.uniforms[var.name] = (loc, var.type) if var.cls == "in" or var.cls == "inout" or var.cls == "varying": loc = glGetAttribLocation(self._program, var.name) if loc == -1: print( "WARNING: Attribute " + var.name + " returned -1; this indicates that the var is not being used by the program." ) self.ins[var.name] = (loc, var.type) for var in self.frag.vars: if var.cls == "uniform" and var.name not in self.uniforms: loc = glGetUniformLocation(self._program, var.name) if loc == -1: print( "WARNING: Attribute " + var.name + " location returned -1; this indicates that the var is not being used by the program." ) self.uniforms[var.name] = [loc, var.type]
def attributelocation(self, name): if name not in self.attributelocs: self.attributelocs[name] = glGetAttribLocation(self.program, name) return self.attributelocs[name]
def attributeLocation(self, name): return glGetAttribLocation(self.program_id, name)
def __get__(self, inst, owner): if inst not in self._values: self._values[inst] = glGetAttribLocation(inst.program, self.name) return self._values[inst]
def getAttribLocation(self, name): return glGetAttribLocation(self.__programId, name)
def aloc(self,n): return glGetAttribLocation(self.program_id, n)
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 attribLocation(self, name): return glGetAttribLocation(self.program_id, name)
def get_attributes(program, names): return dict((name, glGetAttribLocation(program, name)) for name in names)
def attribLocation(self, name): return glGetAttribLocation(self.shader_program, name)