def draw(self, uniforms, entities, models, textures=(), lights=(), *args, **kwargs): glUseProgram(self) # PREPARE SHADER glUniformMatrix4fv( # ctypes.data_as must be here and not at initialization. self.uniforms[b'perspective'], 1, GL_TRUE, uniforms.get(b'perspective').ctypes.data_as(POINTER(GLfloat)) ) glUniformMatrix4fv( self.uniforms[b'view'], 1, GL_TRUE, uniforms.get(b'view').ctypes.data_as(POINTER(GLfloat)) ) for i, entity in enumerate(lights): glUniform3f(self.uniforms[b'light[' + bytes(str(i), 'utf-8') + b'].position'], *entity.location) glUniform3f(self.uniforms[b'light[' + bytes(str(i), 'utf-8') + b'].color'], *entity.color) glUniform1f(self.uniforms[b'light[' + bytes(str(i), 'utf-8') + b'].constant'], entity.attenuation[0]) glUniform1f(self.uniforms[b'light[' + bytes(str(i), 'utf-8') + b'].linear'], entity.attenuation[1]) glUniform1f(self.uniforms[b'light[' + bytes(str(i), 'utf-8') + b'].quadratic'], entity.attenuation[1]) # PREPARE MODELS for model_index, texture_mapping in self.entities.items(): model = models[model_index] model.enable() # PREPARE TEXTURES glActiveTexture(GL_TEXTURE0) glActiveTexture(GL_TEXTURE0 + 1) for texture_list, entity_list in texture_mapping.items(): if hasattr(texture_list, '__iter__'): glBindTexture(GL_TEXTURE_2D, textures[0]) glUniform1i(self.uniforms[b'diffuse_texture'], 0) glBindTexture(GL_TEXTURE_2D, textures[1]) glUniform1i(self.uniforms[b'specular_texture'], 1) # textures[0].enable(slot=0) # textures[1].enable(slot=1) else: textures[texture_list].enable(slot=0) glUniform1i(self.uniforms[b'diffuse_texture'], 0) # PREPARE ENTITIES for entity in entity_list: glUniformMatrix4fv( self.uniforms[b'transformation'], 1, GL_TRUE, entity.get_transformation_matrix().ctypes.data_as(POINTER(GLfloat)) ) model.draw() glBindBuffer(GL_ARRAY_BUFFER, 0) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) glBindTexture(GL_TEXTURE_2D, 0) glDisableVertexAttribArray(0) glDisableVertexAttribArray(1) glDisableVertexAttribArray(2)
def uniform_sampler2D_setter_impl(loc, count, get_data_ptr_func, value, accessor, rectangle): if "texture_unit_bindings" not in accessor.__extensions_storage__: accessor.__extensions_storage__["texture_unit_bindings"] = dict([ (-1, -1) ]) # max + 1 == 0 bindings = accessor.__extensions_storage__["texture_unit_bindings"] loc_str = str(loc) if type(value) is int: texture_unit = value elif isinstance(value, Texture): if (value.target != GL_TEXTURE_2D) ^ rectangle: raise ValueError("Texture expected to be {} rectangle".format( "a" if rectangle else "not a")) if loc_str not in bindings: texture_unit = max(bindings.values()) + 1 bindings[loc_str] = texture_unit else: texture_unit = bindings[loc_str] glActiveTexture(GL_TEXTURE0 + texture_unit) glEnable(value.target) glBindTexture(value.target, value.id) else: raise TypeError("Sampler2D uniform got value of unsupported type") glUniform1iv(loc, count, get_data_ptr_func(texture_unit))
def __init__(self, width, height, scale=2): """ width, height: size of the window in pixels. scale: the size of the texture is (width//scale) x (height//scale). """ pyglet.window.Window.__init__(self, width, height, caption='GrayScott Simulation', visible=False, vsync=False) self.reaction_shader = Shader('./glsl/default.vert', './glsl/reaction.frag') self.render_shader = Shader('./glsl/default.vert', './glsl/render.frag') self.pattern = DEFAULT_PATTERN self.palette = DEFAULT_PALETTE self.tex_width = width // scale self.tex_height = height // scale self.uv_texture = create_uv_texture(width//scale, height//scale) gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(self.uv_texture.target, self.uv_texture.id) # use an invisible buffer to do the computation. with FrameBuffer() as self.fbo: self.fbo.attach_texture(self.uv_texture) # why do we need this? the reason is in the 'on_mouse_drag' function. self.mouse_down = False # put all patterns in a list for iterating over them. self._species = list(SPECIES.keys()) # set the uniforms and attributes in the two shaders. self.init_reaction_shader() self.init_render_shader()
def __init__(self, size: Tuple[int, int], component: int, data): self.width, self.height = size sized_format = (gl.GL_R8, gl.GL_RG8, gl.GL_RGB8, gl.GL_RGBA8)[component - 1] self.format = (gl.GL_R, gl.GL_RG, gl.GL_RGB, gl.GL_RGBA)[component - 1] gl.glActiveTexture(gl.GL_TEXTURE0 + 0) # If we need other texture unit... self.texture_id = texture_id = gl.GLuint() gl.glGenTextures(1, byref(self.texture_id)) if self.texture_id.value == 0: raise ShaderException("Cannot create Texture.") gl.glBindTexture(gl.GL_TEXTURE_2D, self.texture_id) gl.glPixelStorei(gl.GL_PACK_ALIGNMENT, 1) gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 1) try: gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, sized_format, self.width, self.height, 0, self.format, gl.GL_UNSIGNED_BYTE, data) except gl.GLException: raise gl.GLException( f"Unable to create texture. {gl.GL_MAX_TEXTURE_SIZE} {size}") gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) weakref.finalize(self, Texture.release, texture_id)
def use(self, unit: int = 0) -> None: """Bind the texture to a channel, :param int unit: The texture unit to bind the texture. """ gl.glActiveTexture(gl.GL_TEXTURE0 + unit) gl.glBindTexture(gl.GL_TEXTURE_2D, self._glo)
def __init__(self, width, height, aa): pyglet.window.Window.__init__( self, width, height, caption="Loxodromic transformation", resizable=True, visible=False, vsync=False, ) self._start_time = time.clock() self.shader = Shader(["./glsl/loxodrome.vert"], ["./glsl/loxodrome.frag"]) self.buffer = pyglet.image.get_buffer_manager().get_color_buffer() texture = create_image_texture(WOOD_TEXTURE) gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(gl.GL_TEXTURE_2D, texture) with self.shader: self.shader.vertex_attrib("position", [-1, -1, 1, -1, -1, 1, 1, 1]) self.shader.uniformf("iResolution", width, height, 0.0) self.shader.uniformf("iTime", 0.0) self.shader.uniformi("iTexture", 0) self.shader.uniformi("AA", aa)
def __init__(self, width, height, zoom): """ :param width & height: size of the main window in pixels. :param zoom: zoom factor of the scene. Keyboard control: 1. press `Enter` to save screenshots. 2. press `Esc` to exit. """ pyglet.window.Window.__init__(self, width, height, caption="Wang-Tile", resizable=True, visible=False, vsync=False) self._start_time = time.clock() self.shader = Shader(["./glsl/wang.vert"], ["./glsl/wang.frag"]) cubemap = create_cubemap_texture(CUBEMAP_IMAGES) gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(gl.GL_TEXTURE_CUBE_MAP, cubemap) with self.shader: self.shader.vertex_attrib("position", [-1, -1, 1, -1, -1, 1, 1, 1]) self.shader.uniformf("iResolution", width, height, 0.0) self.shader.uniformf("iTime", 0.0) self.shader.uniformf("zoom", zoom) self.shader.uniformi("cubemap", 0)
def __init__(self, width, height): """:param width & height: size of the main window in pixels. """ pyglet.window.Window.__init__( self, width, height, caption="Polyhedra Mirrors", resizable=True, visible=False, vsync=False, ) self._start_time = time.perf_counter() self.shader = Shader([os.path.join(GLSL_DIR, "default.vert")], [ os.path.join(GLSL_DIR, "common.frag"), os.path.join(GLSL_DIR, "data.frag"), os.path.join(GLSL_DIR, "main.frag") ]) wood = create_image_texture(WOOD_IMAGE) cubemap = create_cubemap_texture(CUBEMAP_IMAGES) gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(gl.GL_TEXTURE_CUBE_MAP, cubemap) gl.glActiveTexture(gl.GL_TEXTURE1) gl.glBindTexture(gl.GL_TEXTURE_2D, wood) with self.shader: self.shader.vertex_attrib("position", [-1, -1, 1, -1, -1, 1, 1, 1]) self.shader.uniformf("iResolution", self.width, self.height, 0.0) self.shader.uniformf("iTime", 0.0) self.shader.uniformi("iChannel0", 0) self.shader.uniformi("iChannel1", 1)
def __init__(self, width, height, zoom): """ :param width & height: size of the main window in pixels. :param zoom: zoom factor of the scene. """ pyglet.window.Window.__init__( self, width, height, caption="Wang-Tile", resizable=True, visible=False, vsync=False, ) self._start_time = time.perf_counter() self.shader = Shader(["./glsl/default.vert"], ["./glsl/wang.frag"]) cubemap = create_cubemap_texture(CUBEMAP_IMAGES) gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(gl.GL_TEXTURE_CUBE_MAP, cubemap) with self.shader: self.shader.vertex_attrib("position", [-1, -1, 1, -1, -1, 1, 1, 1]) self.shader.uniformf("iResolution", self.width, self.height, 0.0) self.shader.uniformf("iTime", 0.0) self.shader.uniformf("zoom", zoom) self.shader.uniformi("iChannel0", 0)
def __init__(self, width, height, pqr, AA=2): """ :param width and height: size of the window in pixels. :param pqr: Coxeter diagram of the tessellation. :param AA: antialiasing level. """ pyglet.window.Window.__init__( self, width, height, caption="Hyperbolic Honeycomb {}-{}-{}".format(*pqr), resizable=True, visible=False, vsync=False) self.pqr = pqr self._start_time = time.clock() self.shader = Shader(["./glsl/hyperbolic3d.vert"], ["./glsl/hyperbolic3d.frag"]) self.buffer = pyglet.image.get_buffer_manager().get_color_buffer() # create the texture texture = create_image_texture(IMG_PATH) gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(gl.GL_TEXTURE_2D, texture) with self.shader: self.shader.vertex_attrib("position", [-1, -1, 1, -1, -1, 1, 1, 1]) self.shader.uniformf("iResolution", self.width, self.height, 0.0) self.shader.uniformf("iTime", 0.0) self.shader.uniformi("iTexture", 0) self.shader.uniformf("pqr", *self.pqr) self.shader.uniformi("AA", AA)
def render(self): """Render all lights.""" gl.glEnable(gl.GL_TEXTURE_2D) gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(gl.GL_TEXTURE_2D, self.fbo.textures[0]) lighting_shader.bind() lighting_shader.uniformi('diffuse_tex', 0) gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_ONE, gl.GL_ONE) vpw = self.viewport.w vph = self.viewport.h vpx, vpy = self.viewport.position vpradius = sqrt(vpw * vpw + vph * vph) * 0.5 c = 0 for light in self.lights: lx, ly = light.position maxdist = light.radius + vpradius dx = vpx - lx * self.tilew dy = vpy - ly * self.tilew dist = sqrt(dx * dx + dy * dy) if dist < maxdist: self.render_light(light) c += 1 lighting_shader.unbind() # Draw ambient using a full-screen quad gl.glColor3f(*self.ambient) self.viewport.draw_quad() gl.glColor4f(1, 1, 1, 1) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
def setupFBOandTextures(self): self.framebufferA0 = (gl.GLuint * args["resolution"])() self.A0_tex = gl.GLuint(0) self.draw_buffersA0 = (gl.GLenum * args["resolution"])( gl.GL_COLOR_ATTACHMENT0) gl.glGenFramebuffers(args["resolution"], self.framebufferA0) gl.glGenTextures(1, ctypes.byref(self.A0_tex)) #create textures #A gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(gl.GL_TEXTURE_3D, self.A0_tex) gl.glTexImage3D(gl.GL_TEXTURE_3D, 0, gl.GL_RED, args["resolution"], args["resolution"], args["resolution"], 0, gl.GL_RED, gl.GL_FLOAT, 0) gl.glTexParameteri(gl.GL_TEXTURE_3D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_3D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR) #A for i in range(args["resolution"]): gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, self.framebufferA0[i]) gl.glFramebufferTexture3D(gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT0, gl.GL_TEXTURE_3D, self.A0_tex, 0, i) assert (gl.glCheckFramebufferStatus( gl.GL_FRAMEBUFFER) == gl.GL_FRAMEBUFFER_COMPLETE)
def draw(self): ''' Draw the windows. ''' self.program.use() data = list(self.root.get_data(0, 0)) data = (gl.GLfloat * len(data))(*data) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.buffer) gl.glBufferData(gl.GL_ARRAY_BUFFER, sizeof(data), data, gl.GL_DYNAMIC_DRAW) gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(gl.GL_TEXTURE_2D, self.texture) if self.textmanager.dirty: # only upload the texture to the GPU if it has actually changed gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, # level gl.GL_R8, self.textmanager.width, self.textmanager.height, 0, gl.GL_RED, gl.GL_UNSIGNED_BYTE, ctypes.create_string_buffer(self.textmanager.img.tobytes())) self.textmanager.dirty = False self.program.uniform1i(b"tex", 0) # set to 0 because the texture is bound to GL_TEXTURE0 self.program.vertex_attrib_pointer(self.buffer, b"position", 4) # self.program.vertex_attrib_pointer(self.buffer, b"texcoord", 2, stride=4 * sizeof(gl.GLfloat), offset=2 * sizeof(gl.GLfloat)) gl.glDrawArrays(gl.GL_QUADS, 0, len(data) // 4)
def buffer_texture(width, height): id_ = gl.GLuint() gl.glGenTextures(1, byref(id_)) gl.glPushAttrib(gl.GL_ENABLE_BIT | gl.GL_TEXTURE_BIT) gl.glActiveTexture(gl.GL_TEXTURE0) gl.glEnable(gl.GL_TEXTURE_2D) gl.glBindTexture(gl.GL_TEXTURE_2D, id_) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) gl.glTexImage2D( gl.GL_TEXTURE_2D, 0, gl.GL_RGBA, width, height, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, (gl.GLubyte * (width*height * 4))(), ) gl.glFlush() gl.glBindTexture(gl.GL_TEXTURE_2D, 0) gl.glPopAttrib() return id_
def on_draw(): gl.glClearColor(1.0,1.0,1.0,1.0) window.clear() # Compute gl.glViewport(0, 0, width, height) gl.glMatrixMode(gl.GL_PROJECTION) gl.glLoadIdentity() gl.glOrtho(0, 1, 0, 1, -1, 1) gl.glMatrixMode(gl.GL_MODELVIEW) gl.glActiveTexture( gl.GL_TEXTURE1 ) gl.glBindTexture(texture_s.target, texture_s.id) gl.glActiveTexture( gl.GL_TEXTURE0 ) gl.glBindTexture(texture_uv.target, texture_uv.id) gl.glBindFramebufferEXT(gl.GL_FRAMEBUFFER_EXT, framebuffer) reaction_shader.bind() texture_uv.blit(x=0.0, y=0.0, width=1.0, height=1.0) reaction_shader.unbind() gl.glBindFramebufferEXT(gl.GL_FRAMEBUFFER_EXT, 0) # Render gl.glViewport(0, 0, window.width, window.height) gl.glMatrixMode(gl.GL_PROJECTION) gl.glLoadIdentity() gl.glOrtho(0, 1, 0, 1, -1, 1) gl.glMatrixMode(gl.GL_MODELVIEW) color_shader.bind() texture_uv.blit(x=0.0, y=0.0, width=1.0, height=1.0) color_shader.bind()
def draw(self): """Draw the text to the back buffer""" # Border width self.box.setLineWidth( self.palette['lineWidth']) # Use 1 as base if border width is none #self.borderWidth = self.box.lineWidth # Border colour self.box.setLineColor(self.palette['lineColor'], colorSpace='rgb') #self.borderColor = self.box.lineColor # Background self.box.setFillColor(self.palette['fillColor'], colorSpace='rgb') #self.fillColor = self.box.fillColor if self._needVertexUpdate: #print("Updating vertices...") self._updateVertices() if self.fillColor is not None or self.borderColor is not None: self.box.draw() # self.boundingBox.draw() # could draw for debug purposes gl.glPushMatrix() self.win.setScale('pix') gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(gl.GL_TEXTURE_2D, self.glFont.textureID) gl.glEnable(gl.GL_TEXTURE_2D) gl.glDisable(gl.GL_DEPTH_TEST) gl.glEnableClientState(gl.GL_VERTEX_ARRAY) gl.glEnableClientState(gl.GL_COLOR_ARRAY) gl.glEnableClientState(gl.GL_TEXTURE_COORD_ARRAY) gl.glEnableClientState(gl.GL_VERTEX_ARRAY) gl.glVertexPointer(2, gl.GL_DOUBLE, 0, self.verticesPix.ctypes) gl.glColorPointer(4, gl.GL_DOUBLE, 0, self._colors.ctypes) gl.glTexCoordPointer(2, gl.GL_DOUBLE, 0, self._texcoords.ctypes) self.shader.bind() self.shader.setInt('texture', 0) self.shader.setFloat('pixel', [1.0 / 512, 1.0 / 512]) nVerts = len(self._text) * 4 gl.glDrawArrays(gl.GL_QUADS, 0, nVerts) self.shader.unbind() # removed the colors and font texture gl.glDisableClientState(gl.GL_COLOR_ARRAY) gl.glDisableClientState(gl.GL_TEXTURE_COORD_ARRAY) gl.glDisableVertexAttribArray(1) gl.glDisableClientState(gl.GL_VERTEX_ARRAY) gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(gl.GL_TEXTURE_2D, 0) gl.glDisable(gl.GL_TEXTURE_2D) if self.hasFocus: # draw caret line self.caret.draw() gl.glPopMatrix()
def set_state(self): self.program.use() gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(self.texture.target, self.texture.id) gl.glActiveTexture(gl.GL_TEXTURE1) gl.glBindTexture(self.normal_map.target, self.normal_map.id) gl.glEnable(gl.GL_DEPTH_TEST) gl.glDepthFunc(gl.GL_LESS)
def bind(self): gl.glActiveTexture(gl.GL_TEXTURE0 + self.slot) super(Texture, self).bind() self.uniforms['{}_isBound'.format(self.name)] = True try: self.uniforms.send() except UnboundLocalError: # TODO: Find a way to make binding and uniform-sending simple without requiring a bound shader. pass
def _bind_texture(self, i): gl.glActiveTexture((gl.GL_TEXTURE0, gl.GL_TEXTURE1, gl.GL_TEXTURE2)[i]) gl.glEnable(gl.GL_TEXTURE_2D) gl.glBindTexture(gl.GL_TEXTURE_2D, self.texture[i].id) gl.glTexEnvf(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_MODE, gl.GL_COMBINE) gl.glTexEnvf(gl.GL_TEXTURE_ENV, gl.GL_COMBINE_ALPHA, gl.GL_REPLACE if i == 0 else gl.GL_ADD) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST)
def _text_glyphs_gl(self): if not self._text_dlist: dl_index = glGenLists(1) glNewList(dl_index, GL_COMPILE) # stime=getTime() # self._text_box._te_start_gl() ### glActiveTexture(GL_TEXTURE0) glEnable(GL_TEXTURE_2D) glBindTexture(GL_TEXTURE_2D, self._text_box._current_glfont.atlas.texid) glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE) glTranslatef(self._position[0], -self._position[1], 0) glPushMatrix() ### getLineInfoByIndex = self._text_document.getLineInfoByIndex active_text_style_dlist = self._current_font_display_lists.get cell_width, cell_height = self._cell_size num_cols, num_rows = self._shape line_spacing = self._text_box._getPixelTextLineSpacing() line_count = self.getRowCountWithText() glColor4f(*self._text_box._toRGBA(self._font_color)) for r in range(line_count): cline, line_length, line_display_list, line_ords = getLineInfoByIndex( r) if line_display_list[0] == 0: line_display_list[0:line_length] = [ active_text_style_dlist(c) for c in line_ords ] glTranslatef( cline._trans_left * cell_width, -int(line_spacing / 2.0 + cline._trans_top * cell_height), 0) glCallLists(line_length, GL_UNSIGNED_INT, line_display_list[0:line_length].ctypes) cline._trans_left = 0 glTranslatef( -line_length * cell_width - cline._trans_left * cell_width, -cell_height + int(line_spacing / 2.0 + cline._trans_top * cell_height), 0) ### glPopMatrix() glBindTexture(GL_TEXTURE_2D, 0) glDisable(GL_TEXTURE_2D) glEndList() self._text_dlist = dl_index glCallList(self._text_dlist)
def upload(self): glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, self.handle) texture_data = bytes(self.image.flat) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, self.width, self.height, 0, self.format, self.type, texture_data) glFlush() self.uploaded = True
def draw(self, win=None): #set the window to draw to if win==None: win=self.win if win.winType=='pyglet': win.winHandle.switch_to() #work out next default depth if self.depth==0: thisDepth = self.win._defDepth self.win._defDepth += _depthIncrements[self.win.winType] else: thisDepth=self.depth GL.glPushMatrix() #scale and rotate prevScale = self.win.setScale(self._winScale) GL.glTranslatef(self._posRendered[0],self._posRendered[1],thisDepth)#NB depth is set already GL.glRotatef(self.ori,0.0,0.0,1.0) self.win.setScale('pix',None, prevScale) if self._useShaders: #then rgb needs to be set as glColor #setup color desiredRGB = (self.rgb*self.contrast+1)/2.0#RGB in range 0:1 and scaled for contrast if numpy.any(desiredRGB**2.0>1.0): desiredRGB=[0.6,0.6,0.4] GL.glColor4f(desiredRGB[0],desiredRGB[1],desiredRGB[2], self.opacity) else: #color is set in texture, so set glColor to white GL.glColor4f(1,1,1,1) GL.glDisable(GL.GL_DEPTH_TEST) #should text have a depth or just on top? #update list if necss and then call it if self.win.winType=='pyglet': #and align based on x anchor if self.alignHoriz=='right': GL.glTranslatef(-self.width,0,0)#NB depth is set already if self.alignHoriz in ['center', 'centre']: GL.glTranslatef(-self.width/2,0,0)#NB depth is set already #unbind the mask texture regardless GL.glActiveTexture(GL.GL_TEXTURE1) GL.glEnable(GL.GL_TEXTURE_2D) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) #unbind the main texture GL.glActiveTexture(GL.GL_TEXTURE0) GL.glEnable(GL.GL_TEXTURE_2D) #then allow pyglet to bind and use texture during drawing self.glyphStr.draw() GL.glDisable(GL.GL_TEXTURE_2D) else: #for pygame we should (and can) use a drawing list if self.needUpdate: self._updateList() GL.glCallList(self._listID) GL.glEnable(GL.GL_DEPTH_TEST) # Enables Depth Testing GL.glPopMatrix()
def usetTex(self, var, unit, target, tx): """ var : name of variable to write unit : texture unit target : target for glBindTexture tx : texture ID """ gl.glUniform1iARB(self.uniformLoc(var), unit) gl.glActiveTexture(gl.GL_TEXTURE0 + unit) gl.glBindTexture(target, tx)
def set_state(self): self.program.use() gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(self.texture.target, self.texture.id) # gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, # gl.GL_MIRRORED_REPEAT) # gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, # gl.GL_MIRRORED_REPEAT) gl.glEnable(gl.GL_DEPTH_TEST) gl.glDepthFunc(gl.GL_LESS)
def __init__(self, width, height, pattern, scale, video): """ width, height: size of the window in pixels. scale: the size of the texture is (width//scale) x (height//scale). pattern: the initial pattern. video: if non-zero then save frams from the beginning. """ pyglet.window.Window.__init__(self, width, height, caption='GrayScott Simulation', visible=False, vsync=False) # palette is used for coloring the pattern. self.pattern = pattern self.palette = np.array([(0.0, 0.0, 0.0, 0.0), (0.0, 1.0, 0.0, 0.2), (1.0, 1.0, 0.0, 0.21), (1.0, 0.0, 0.0, 0.4), (1.0, 1.0, 1.0, 0.6)]) # we use `reaction_shader` to do the computations in a backend framebuffer, # and `render_shader` to show the pattern in the frontend window buffer. self.reaction_shader = Shader('./glsl/default.vert', './glsl/reaction.frag') self.render_shader = Shader('./glsl/default.vert', './glsl/render.frag') # size of the texture. self.tex_width = width // scale self.tex_height = height // scale self.uv_texture = create_uv_texture(width // scale, height // scale) gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(self.uv_texture.target, self.uv_texture.id) # use an invisible buffer to do the computation. with FrameBuffer() as self.fbo: self.fbo.attach_texture(self.uv_texture) # why do we need this? the reason is in the 'on_mouse_drag' function. self.mouse_down = False # put all patterns in a list for iterating over them. self._species = list(SPECIES.keys()) # set the uniforms and varying attributes in the two shaders. self.init_reaction_shader() self.init_render_shader() self.frame_count = 0 self.video_on = video self.skip = 30 self.max_frames = 1000000
def create_texture(self, width, height): uv_grid = np.zeros((height, width, 4), dtype=np.float32) uv_grid[:, :, 0] = 1.0 r = 32 uv_grid[height//2-r : height//2+r, width//2-r : width//2+r, 0] = 0.50 uv_grid[height//2-r : height//2+r, width//2-r : width//2+r, 1] = 0.25 uv_texture = create_texture_from_array(uv_grid) # the texture is bind to unit '0'. gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(uv_texture.target, uv_texture.id) return uv_texture
def _startOfFlip(self): """Custom :py:class:`~Rift._startOfFlip` for HMD rendering. This finalizes the HMD texture before diverting drawing operations back to the on-screen window. This allows :py:class:`~Rift.flip` to swap the on-screen and HMD buffers when called. This function always returns `True`. Returns ------- True """ # nop if we are still setting up the window if not hasattr(self, '_eyeBuffers'): return True # direct draw being used, don't do FBO blit if self._directDraw: return True # Switch off multi-sampling # GL.glDisable(GL.GL_MULTISAMPLE) oldColor = self.color self.setColor((-1, -1, -1)) self.setBuffer('back', clear=True) self._prepareFBOrender() # need blit the framebuffer object to the actual back buffer # unbind the framebuffer as the render target GL.glDisable(GL.GL_BLEND) stencilOn = self.stencilTest self.stencilTest = False # before flipping need to copy the renderBuffer to the # frameBuffer GL.glActiveTexture(GL.GL_TEXTURE0) GL.glEnable(GL.GL_TEXTURE_2D) GL.glColor3f(1.0, 1.0, 1.0) # glColor multiplies with texture GL.glColorMask(True, True, True, True) # blit the textures to the back buffer for eye in ('left', 'right'): self._blitEyeBuffer(eye) GL.glEnable(GL.GL_BLEND) self._finishFBOrender() self.stencilTest = stencilOn self.setColor(oldColor) # This always returns True return True
def copy(self): ''' copy the contents of the texture to full window ''' gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0) self.program.use() gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(gl.GL_TEXTURE_2D, self.rendered_texture) self.program.uniform1i(b"tex", 0) self.program.vertex_attrib_pointer(self.vertex_buffer, b"position", 4, stride=4 * sizeof(gl.GLfloat)) gl.glDrawArrays(gl.GL_QUADS, 0, 4)
def _text_glyphs_gl(self): if not self._text_dlist: dl_index = glGenLists(1) glNewList(dl_index, GL_COMPILE) # stime=getTime() # self._text_box._te_start_gl() ### glActiveTexture(GL_TEXTURE0) glEnable(GL_TEXTURE_2D) glBindTexture( GL_TEXTURE_2D, self._text_box._current_glfont.atlas.texid) glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE) glTranslatef(self._position[0], -self._position[1], 0) glPushMatrix() ### getLineInfoByIndex = self._text_document.getLineInfoByIndex active_text_style_dlist = self._current_font_display_lists.get cell_width, cell_height = self._cell_size num_cols, num_rows = self._shape line_spacing = self._text_box._getPixelTextLineSpacing() line_count = self.getRowCountWithText() glColor4f(*self._text_box._toRGBA(self._font_color)) for r in range(line_count): cline, line_length, line_display_list, line_ords = getLineInfoByIndex( r) if line_display_list[0] == 0: line_display_list[0:line_length] = [ active_text_style_dlist(c) for c in line_ords] glTranslatef(cline._trans_left * cell_width, - int(line_spacing/2.0 + cline._trans_top * cell_height), 0) glCallLists(line_length, GL_UNSIGNED_INT, line_display_list[0:line_length].ctypes) cline._trans_left = 0 glTranslatef(-line_length * cell_width - cline._trans_left * cell_width, - cell_height + int(line_spacing/2.0 + cline._trans_top * cell_height), 0) ### glPopMatrix() glBindTexture(GL_TEXTURE_2D, 0) glDisable(GL_TEXTURE_2D) glEndList() self._text_dlist = dl_index glCallList(self._text_dlist)
def draw(self, win=None): """ Draw the current frame to a particular visual.Window (or to the default win for this object if not specified). The current position in the movie will be determined automatically. This method should be called on every frame that the movie is meant to appear""" if self.status==NOT_STARTED or (self.status==FINISHED and self.loop): self.play() elif self.status == FINISHED and not self.loop: return if win is None: win = self.win self._selectWindow(win) self._updateFrameTexture() #will check if it's needed yet in the function #make sure that textures are on and GL_TEXTURE0 is active GL.glActiveTexture(GL.GL_TEXTURE0) GL.glEnable(GL.GL_TEXTURE_2D) GL.glColor4f(1, 1, 1, self.opacity) # sets opacity (1,1,1 = RGB placeholder) GL.glPushMatrix() self.win.setScale('pix') #move to centre of stimulus and rotate vertsPix = self.verticesPix array = (GL.GLfloat * 32)( 1, 1, #texture coords vertsPix[0,0], vertsPix[0,1], 0., #vertex 0, 1, vertsPix[1,0], vertsPix[1,1], 0., 0, 0, vertsPix[2,0], vertsPix[2,1], 0., 1, 0, vertsPix[3,0], vertsPix[3,1], 0., ) GL.glPushAttrib(GL.GL_ENABLE_BIT) GL.glEnable(GL.GL_TEXTURE_2D) GL.glBindTexture(GL.GL_TEXTURE_2D, self._texID) GL.glPushClientAttrib(GL.GL_CLIENT_VERTEX_ARRAY_BIT) #2D texture array, 3D vertex array GL.glInterleavedArrays(GL.GL_T2F_V3F, 0, array) GL.glDrawArrays(GL.GL_QUADS, 0, 4) GL.glPopClientAttrib() GL.glPopAttrib() GL.glPopMatrix() #unbind the textures GL.glActiveTexture(GL.GL_TEXTURE0) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) GL.glDisable(GL.GL_TEXTURE_2D)#implicitly disables 1D
def write(self, data: Union[bytes, Buffer], level: int = 0, viewport=None) -> None: """Write byte data to the texture. This can be bytes or a :py:class:`~arcade.gl.Buffer`. :param Union[bytes,Buffer] data: bytes or a Buffer with data to write :param int level: The texture level to write :param tuple viewport: The are of the texture to write. 2 or 4 component tuple """ # TODO: Support writing to layers using viewport + alignment if self._samples > 0: raise ValueError("Writing to multisample textures not supported") x, y, w, h = 0, 0, self._width, self._height if viewport: if len(viewport) == 2: w, h = viewport elif len(viewport) == 4: x, y, w, h = viewport else: raise ValueError("Viewport must be of length 2 or 4") if isinstance(data, Buffer): gl.glBindBuffer(gl.GL_PIXEL_UNPACK_BUFFER, data.glo) gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(self._target, self._glo) gl.glPixelStorei(gl.GL_PACK_ALIGNMENT, 1) gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 1) gl.glTexSubImage2D(self._target, level, x, y, w, h, self._format, self._type, 0) gl.glBindBuffer(gl.GL_PIXEL_UNPACK_BUFFER, 0) else: byte_size, data = data_to_ctypes(data) gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(self._target, self._glo) gl.glPixelStorei(gl.GL_PACK_ALIGNMENT, 1) gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 1) gl.glTexSubImage2D( self._target, # target level, # level x, # x offset y, # y offset w, # width h, # height self._format, # format self._type, # type data, # pixel data )
def _on_draw(self): gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) STRIDE = 8 self.program.use() self.program.vertex_attrib_pointer(self.buffer, b"position", 4, stride=STRIDE * ctypes.sizeof(gl.GLfloat)) self.program.vertex_attrib_pointer( self.buffer, b"color", 4, stride=STRIDE * ctypes.sizeof(gl.GLfloat), offset=4 * ctypes.sizeof(gl.GLfloat)) if self.terrain.dirty or not self._cached_terrain_data: data = (float(d) for (x, y, z, c, u, v, (r, g, b, a), lum) in self.terrain.vertex_data() for d in (x + u, y + v, z, 1, r * lum, g * lum, b * lum, a)) data = (gl.GLfloat * (STRIDE * self.terrain.nb_vertices()))(*data) self._cached_terrain_data = data else: data = self._cached_terrain_data gl.glBufferData(gl.GL_ARRAY_BUFFER, ctypes.sizeof(data), data, gl.GL_DYNAMIC_DRAW) gl.glDrawArrays(gl.GL_TRIANGLES, 0, self.terrain.nb_vertices()) self.sprite_program.use() gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(gl.GL_TEXTURE_2D, self.sprite_texture) self.sprite_program.uniform1i(b'tex', 0) x, y, cp = self.pointed utex = [0.0, 1.0 / 16, 1.0 / 16, 0.0] vtex = [0.0, 0.0, 1.0 / 16, 1.0 / 16] data = (float(d) for (x, y, z, c, u, v, (r, g, b, a), lum) in self.terrain.vertex_data_tile(x, y) for d in (x + u, y + v, z + 1.0 / 256, 1, utex[(c - cp) % 4], vtex[(c - cp) % 4], 0.0, 0.0)) data = (gl.GLfloat * (STRIDE * 6))(*data) gl.glBufferData(gl.GL_ARRAY_BUFFER, ctypes.sizeof(data), data, gl.GL_DYNAMIC_DRAW) gl.glDrawArrays(gl.GL_TRIANGLES, 0, 6)
def blit(self, x, y, z=0, width=None, height=None): x1 = x - self.anchor_x y1 = y - self.anchor_y x2 = x1 + (width is None and self.width or width) y2 = y1 + (height is None and self.height or height) vertices = x1, y1, z, x2, y1, z, x2, y2, z, x1, y2, z gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(self.target, self.id) pyglet.graphics.draw_indexed(4, gl.GL_TRIANGLES, [0, 1, 2, 0, 2, 3], ('v3f', vertices), ('t3f', self.tex_coords)) gl.glBindTexture(self.target, 0)
def initialize_gl(self): self.program = GlProgram(shaders.vertex_sprite, shaders.fragment_sprite) self.program.uniform2f(b'offset', 0, 0) self.buffer = gl.GLuint(0) gl.glGenBuffers(1, ctypes.pointer(self.buffer)) gl.glActiveTexture(gl.GL_TEXTURE0) self.sprite_texture = gltexture.make_texture('sprites.png') gl.glBindTexture(gl.GL_TEXTURE_2D, self.sprite_texture) self.program.uniform1i(b'tex', 0) gl.glEnable(gl.GL_BLEND) gl.glEnable(gl.GL_DEPTH_TEST) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
def bind(self, texture, lut=None): ''' Bind the program, i.e. use it. ''' Shader.bind(self) if lut is not None: gl.glActiveTexture(gl.GL_TEXTURE1) gl.glBindTexture(lut.target, lut.id) self.uniformi('lut', 1) gl.glEnable(texture.target) gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(texture.target, texture.id) self.uniformi('texture', 0) self.uniformf('elevation', self._elevation) self.uniformf('pixel', 1.0/texture.width, 1.0/texture.height) self.uniformf('gridsize', *self._gridsize) self.uniformf('gridwidth', *self._gridwidth) self.uniformi('lighted', self._lighted)
def __init__(self, width, height, pattern, scale=2): ''' width, height: size of the window in pixels. scale: the size of the texture is (width//scale) x (height//scale). pattern: a name in dict 'species'. ''' pyglet.window.Window.__init__(self, width, height, caption='GrayScott Simulation', visible=False, vsync=False) # we will need two shaders, one for computing the reaction and diffusion, # and one for coloring the uv_texture. self.reaction_shader = Shader.from_files('default.vert', 'reaction.frag') self.render_shader = Shader.from_files('default.vert', 'render.frag') self.pattern = pattern self.palette = GrayScott.palette_default self.tex_width = width // scale self.tex_height = height // scale self.uv_texture = self.create_texture(width // scale, height // scale) # the texture is bind to unit '0'. gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(self.uv_texture.target, self.uv_texture.id) # set the uniforms and attributes in the two shaders. self.set_reation_shader() self.set_render_shader() # we need a framebuffer to do the offscreen rendering. # once we finished computing the reaction-diffusion step with the reaction_shader, # we render the result to this 'invisible' buffer since we do not want to show it. # the final image is further colored and will be rendered to the window. with FrameBuffer() as self.fbo: self.fbo.attach_texture(self.uv_texture) # why do we need this? # the reason is in the 'on_mouse_drag' function. self.mouse_down = False
def on_draw(self): self.camera.update_matrices() # bind textures gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(gl.GL_TEXTURE_2D_ARRAY, self.texture_manager.texture_array) gl.glUniform1i(self.shader_sampler_location, 0) # draw stuff gl.glEnable(gl.GL_DEPTH_TEST) gl.glClearColor(0.0, 0.0, 0.0, 1.0) self.clear() gl.glDrawElements(gl.GL_TRIANGLES, len(self.grass.indices), gl.GL_UNSIGNED_INT, None)
def __setup_data_buffer(self): data_ptr = ct.cast( np.ctypeslib.as_ctypes(self.__data), ct.POINTER(ct.c_float) ) self.__data_buffer = util.buffer() gl.glBindBuffer(gl.GL_TEXTURE_BUFFER, self.__data_buffer.value) gl.glBufferData(gl.GL_TEXTURE_BUFFER, ct.sizeof(ct.c_float)*self.__data.size, data_ptr, gl.GL_STATIC_DRAW) if self.__data_texture is None: self.__data_texture = util.texture() gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(gl.GL_TEXTURE_BUFFER, self.__data_texture.value) gl.glTexBuffer(gl.GL_TEXTURE_BUFFER, gl.GL_R32F, self.__data_buffer.value) self.__data_altered = False
def __init__(self, width, height, pattern, scale=2): ''' width, height: size of the window in pixels. scale: the size of the texture is (width//scale) x (height//scale). pattern: a name in dict 'species'. ''' pyglet.window.Window.__init__(self, width, height, caption='GrayScott Simulation', visible=False, vsync=False) # we will need two shaders, one for computing the reaction and diffusion, # and one for coloring the uv_texture. self.reaction_shader = Shader.from_files('default.vert', 'reaction.frag') self.render_shader = Shader.from_files('default.vert', 'render.frag') self.pattern = pattern self.palette = GrayScott.palette_default self.tex_width = width // scale self.tex_height = height // scale self.uv_texture = create_uv_texture(width // scale, height // scale) # the texture is bind to unit '0'. gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(self.uv_texture.target, self.uv_texture.id) # set the uniforms and attributes in the two shaders. self.init_reaction_shader() self.init_render_shader() # we need a framebuffer to do the offscreen rendering. # once we finished computing the reaction-diffusion step with the reaction_shader, # we render the result to this 'invisible' buffer since we do not want to show it. # the final image is further colored and will be rendered to the window. with FrameBuffer() as self.fbo: self.fbo.attach_texture(self.uv_texture) # why do we need this? # the reason is in the 'on_mouse_drag' function. self.mouse_down = False
def _create_texture(textureID=None, texture_size=None): # create a texture for Rendering Color if textureID is not None: rgb_texture = textureID else: rgb_texture = (c_uint * 1)() ; gl.glGenTextures(1, rgb_texture) rgb_texture = rgb_texture[0] width, height = texture_size gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(gl.GL_TEXTURE_2D, rgb_texture) gl.glTexParameterf(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE) gl.glTexParameterf(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGBA, width, height, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, None) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST) return rgb_texture
def apply(self): gl.glEnable(gl.GL_LIGHTING) for s in self.shaders: s.bind() for i, t in enumerate(self.textures): gl.glActiveTexture(gl.GL_TEXTURE0 + i) gl.glEnable(gl.GL_TEXTURE_2D) gl.glBindTexture(gl.GL_TEXTURE_2D, t.id) self.parameters["tex[%u]" % i] = i for k in self.parameters.keys(): if type(self.parameters[k]) == type(0): for s in self.shaders: s.uniformi(k, self.parameters[k]) if type(self.parameters[k]) == type(0.0): for s in self.shaders: s.uniformf(k, self.parameters[k]) a = self.ambient_rgb d = self.diffuse_rgb s = self.specular_rgb gl.glMaterialfv(gl.GL_FRONT_AND_BACK, gl.GL_AMBIENT, raw(a[0], a[1], a[2], 1.0)) gl.glMaterialfv(gl.GL_FRONT_AND_BACK, gl.GL_DIFFUSE, raw(d[0], d[1], d[2], 1.0)) gl.glMaterialfv(gl.GL_FRONT_AND_BACK, gl.GL_SPECULAR, raw(s[0], s[1], s[2], 1.0)) gl.glMaterialf(gl.GL_FRONT_AND_BACK, gl.GL_SHININESS, self.shininess)
def _text_glyphs_gl(self): if not self._text_dlist: dl_index = glGenLists(1) glNewList(dl_index, GL_COMPILE) #stime=getTime() #self._text_box._te_start_gl() ### glActiveTexture(GL_TEXTURE0) glEnable( GL_TEXTURE_2D ) glBindTexture( GL_TEXTURE_2D, self._text_box._current_glfont.atlas.texid) glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE ) glTranslatef( self._position[0], -self._position[1], 0 ) glPushMatrix() ### hjust=self._horz_justification vjust=self._vert_justification pad_left_proportion=0 pad_top_proportion=0 if hjust=='center': pad_left_proportion=0.5 elif hjust=='right': pad_left_proportion=1.0 if vjust=='center': pad_top_proportion=0.5 elif vjust=='bottom': pad_top_proportion=1.0 getLineInfoByIndex=self._text_document.getLineInfoByIndex active_text_style_dlist=self._current_font_display_lists.get cell_width,cell_height=self._cell_size num_cols,num_rows=self._shape line_spacing=self._text_box._getPixelTextLineSpacing() line_count=min(num_rows,self._text_document.getParsedLineCount()) apply_padding=pad_left_proportion or (pad_top_proportion and line_count>1) trans_left=0 trans_top=0 glColor4f(*self._text_box._toRGBA(self._font_color)) for r in range(line_count): line_length,line_display_list,line_ords=getLineInfoByIndex(r) if line_display_list[0]==0: line_display_list[0:line_length]=[active_text_style_dlist(c) for c in line_ords] if apply_padding: empty_cell_count=num_cols-line_length empty_line_count=num_rows-line_count trans_left=int((empty_cell_count+1)*pad_left_proportion)*cell_width trans_top=int(empty_line_count*pad_top_proportion)*cell_height glTranslatef(trans_left,-int(line_spacing/2.0+trans_top),0) glCallLists(line_length,GL_UNSIGNED_INT,line_display_list[0:line_length].ctypes) glTranslatef(-line_length*cell_width-trans_left,-cell_height+int(line_spacing/2.0+trans_top),0) ### glPopMatrix() glBindTexture( GL_TEXTURE_2D,0 ) glDisable( GL_TEXTURE_2D ) glEndList() #print 'GL_TIME: %.3f'%((etime-stime)*1000.0) self._text_dlist=dl_index glCallList(self._text_dlist)
def __exit__(self, exc_type, exc_val, exc_tb): self.unbind() gl.glActiveTexture(gl.GL_TEXTURE0)
def __enter__(self): gl.glActiveTexture(gl.GL_TEXTURE0 + self.slot) self.bind() return self
def __set_uniforms(self): # projection matrix (proj) proj_loc = gl.glGetUniformLocation(self.__prog.value, "proj") proj_matrix = self.__proj_matrix() proj_matrix_ptr = ct.cast( \ ct.pointer(np.ctypeslib.as_ctypes(proj_matrix)), ct.POINTER(ct.c_float) ) gl.glUniformMatrix4fv(proj_loc, 1, gl.GL_TRUE, proj_matrix_ptr) # voxel spacing voxel_spacing_loc = gl.glGetUniformLocation(self.__prog.value, "voxel_spacing") gl.glUniform3f(voxel_spacing_loc, self.__voxel_spacing[0]*self.__downsample, self.__voxel_spacing[1]*self.__downsample, self.__voxel_spacing[2]*self.__downsample) # voxel size voxel_size_loc = gl.glGetUniformLocation(self.__prog.value, "voxel_size") gl.glUniform3f(voxel_size_loc, self.__voxel_size[0]*self.__downsample, self.__voxel_size[1]*self.__downsample, self.__voxel_size[2]*self.__downsample) # data; not technically a "uniform" but a texture data_loc = gl.glGetUniformLocation(self.__prog.value, "data") gl.glUniform1i(data_loc, 0) gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(gl.GL_TEXTURE_BUFFER, self.__data_texture.value) # dims dims_loc = gl.glGetUniformLocation(self.__prog.value, "dims") gl.glUniform3i(dims_loc, self.__data.shape[0]/self.__downsample, self.__data.shape[1]/self.__downsample, self.__data.shape[2]/self.__downsample) # global_opacity global_opacity_loc = gl.glGetUniformLocation(self.__prog.value, "global_opacity") gl.glUniform1f(global_opacity_loc, self.__opacity) # min value min_value_loc = gl.glGetUniformLocation(self.__prog.value, "min_value") gl.glUniform1f(min_value_loc, self.__min_value) # saturation value saturation_value_loc = gl.glGetUniformLocation(self.__prog.value, "saturation_value") gl.glUniform1f(saturation_value_loc, self.__saturation_value) # downsample downsample_loc = gl.glGetUniformLocation(self.__prog.value, "downsample") gl.glUniform1i(downsample_loc, self.__downsample)
def unapply(self): for i in range(len(self.textures)): gl.glActiveTexture(gl.GL_TEXTURE0 + i) gl.glDisable(gl.GL_TEXTURE_2D) for s in self.shaders: s.unbind()
def main(level_file): clock = events.dispatcher('Clock') keyboard = events.dispatcher('Keyboard') pygame.init() pygame.display.gl_set_attribute(pygame.GL_ALPHA_SIZE, 8) pygame.display.set_mode((1000, 600), pygame.OPENGL | pygame.DOUBLEBUF | pygame.RESIZABLE) handle_resize(1000, 600) screen_center = (500, 300) camera_offset = 230 gl.glEnable(gl.GL_TEXTURE_2D) gl.glEnable(gl.GL_BLEND) gl.glBlendEquation(gl.GL_FUNC_ADD) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) gl.glClearColor(0, 0, 0, 1) tick_event = pygame.event.Event(constants.TICK) datadir = find_datadir() loader = pyglet.resource.Loader(datadir) player1 = viking(datadir, clock, keyboard, pygame.K_a, pygame.K_d, pygame.K_w, pygame.K_j) player2 = viking(datadir, clock, keyboard, pygame.K_LEFT, pygame.K_RIGHT, pygame.K_UP, pygame.K_RETURN) player2.location[0] = 900 entities = [player1, player2] scream = pygame.mixer.Sound(os.path.join(datadir, 'wilhelm.wav')) background = load_sprite(datadir, 'background') backgroundbuf = GLBuffer(4 * 4, numpy.float32, gl.GL_STATIC_DRAW) backgroundbuf[:] = background.xyuv if level_file is None: walls = [components.hitbox((-5, -5), (10, 610)), components.hitbox((995, -5), (10, 610)), components.hitbox((-5, 595), (1010, 5)), ] else: walls = level.load(level_file) for w in walls: numpy.round(w.point, out=w.point) numpy.round(w.size, out=w.size) walls_tlbr = numpy.empty((2, len(walls), 2)) walls_tlbr[0] = [w.point for w in walls] walls_tlbr[1] = [w.point + w.size for w in walls] # vertex positions for walls quads = numpy.empty((len(walls), 4, 2), dtype=numpy.float32) quads[:, 0, :] = [w.point for w in walls] quads[:, 2, :] = [w.size for w in walls] quads[:, 2, :] += quads[:, 0, :] quads[:, 1, 0] = quads[:, 0, 0] quads[:, 1, 1] = quads[:, 2, 1] quads[:, 3, 0] = quads[:, 2, 0] quads[:, 3, 1] = quads[:, 0, 1] wallbuf = GLBuffer(quads.size, numpy.float32, gl.GL_STATIC_DRAW) wallbuf[:] = quads del quads # contains vertex and texture positions for sprites entitybuf = GLBuffer(dtype=numpy.float32) # walls program wallprog = shaders.wall() spriteprog = shaders.sprite() dragonprog = shaders.psycho() dragonpalette = load_texture(os.path.join(datadir, 'wallpalette.png'), dimensions=1) dragonsprite_scales = load_sprite(datadir, 'dragon_scales') dragonsprite_contours = load_sprite(datadir, 'dragon_contours') dragonbuf = GLBuffer(4 * 4, numpy.float32, gl.GL_STATIC_DRAW) dragonbuf[:] = dragonsprite_scales.xyuv + (-100, 145, 0, 0) contourbuf = GLBuffer(4 * 4, numpy.float32, gl.GL_STATIC_DRAW) contourbuf[:] = dragonsprite_contours.xyuv + (-100, 145, 0, 0) debug_draw = False pause = False do_frame = False ticks_done = 0 while True: start = time.clock() key_events = [] resize_event = None for event in pygame.event.get(): if event.type == pygame.QUIT: return 0 elif event.type == pygame.KEYDOWN or event.type == pygame.KEYUP: key_events.append(event) elif event.type == pygame.VIDEORESIZE: resize_event = event if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: return 0 if event.key == pygame.K_F2: debug_draw = not debug_draw elif event.key == pygame.K_F3: entities.append(sheep(datadir, clock)) elif event.key == pygame.K_F4: entities.append(drake(datadir, clock)) elif event.key == pygame.K_F5: entities.append(floaty_sheep(datadir, clock)) elif event.key == pygame.K_p: pause = not pause elif event.key == pygame.K_PERIOD and pause: do_frame = True if resize_event: handle_resize(resize_event.w, resize_event.h) screen_center = (resize_event.w // 2, resize_event.h // 2) background.xyuv[:, :2] = [[0, 0], [0, resize_event.h], [resize_event.w, resize_event.h], [resize_event.w, 0]] backgroundbuf[:] = background.xyuv if (not pause) or do_frame: for event in key_events: keyboard.dispatch(event) location = components.entity.location delta = numpy.array(location) motion_a = components.entity.motion_a motion_v = components.entity.motion_v active_tl = components.entity.active_tl active_br = components.entity.active_br passive_tl = components.entity.passive_tl passive_br = components.entity.passive_br instances = components.entity._all[:components.entity._nentities] do_translate = components.entity.translate_all GROUNDED = intern('grounded') motion_a[:] = (0, constants.G) clock.dispatch(tick_event) for thing in entities: thing.tags.discard(GROUNDED) motion_v[:] += motion_a collisions.resolve_passive_active_collisions(instances, active_tl, active_br, passive_tl, passive_br) attempts = 0 adjust_significant = True rppc = collisions.resolve_passive_passive_collisions rwc = collisions.resolve_wall_collisions grounded_mask = numpy.zeros((len(instances),), dtype=bool) stop = numpy.empty((len(instances),2), dtype=bool) adjust, sides = rwc(motion_v, passive_tl, passive_br, walls_tlbr[0], walls_tlbr[1]) numpy.logical_or.reduce(sides.reshape(-1, 2, 2), out=stop, axis=2) motion_v[stop] = 0 do_translate(motion_v[:]) while attempts < 20 and adjust_significant: adjust, sides, done_impulse = rppc(motion_v, passive_tl, passive_br) grounded_mask |= sides[:,3] adjust *= 0.5 do_translate(adjust) adjust_significant = not numpy.allclose(adjust, 0, atol=0.125) adjust_significant |= done_impulse > 0.125 del adjust, sides adjust, sides = rwc(motion_v, passive_tl, passive_br, walls_tlbr[0], walls_tlbr[1]) adjust_significant |= not numpy.allclose(adjust, 0, atol=0.5) do_translate(adjust) numpy.logical_or.reduce(sides.reshape(-1, 2, 2), out=stop, axis=2) motion_v[stop] = 0 grounded_mask |= sides[:,3] attempts += 1 for thing in numpy.compress(grounded_mask, instances): thing.tags.add(GROUNDED) do_frame = False ticks_done += 1 dead = [] gl.glLoadIdentity() gl.glEnableVertexAttribArray(0) gl.glUseProgram(spriteprog.id) gl.glBindTexture(gl.GL_TEXTURE_2D, background.texid) spriteprog['texture'] = 0 with backgroundbuf.bound: gl.glVertexAttribPointer(0, 4, gl.GL_FLOAT, gl.GL_FALSE, 0, 0) gl.glDrawArrays(gl.GL_TRIANGLE_FAN, 0, 4) # Now move camera camera_location = (screen_center - numpy.round(entities[0].location)) + (0, camera_offset) gl.glTranslated(camera_location[0], camera_location[1], 0.0) for thing in entities: if thing.hitpoints <= 0 or thing.location[1] > 10000: dead.append(thing) continue for thing in dead: scream.play() if thing.name == 'Player': thing.hitpoints = 100 thing.location[:] = (500, -10) thing.motion_v[:] = 0 if thing.physics is not None: thing.physics.last_position[:] = thing.location else: entities.remove(thing) thing.dispose() xyuv = numpy.empty((4, 4), dtype=numpy.float32) texid = [0] * len(entities) with entitybuf.bound: for n, thing in enumerate(entities): xyuv[:] = thing.graphics.sprite.xyuv xy = xyuv[:, 0:2] xy[:] += thing.graphics.anchor xy[:] += thing.location numpy.round(xy, out=xy) offset = n * 16 entitybuf[offset:] = xyuv texid[n] = thing.graphics.sprite.texid #print('Loaded data for entity', n, xyuv, 'texid', texid[n]) gl.glVertexAttribPointer(0, 4, gl.GL_FLOAT, gl.GL_FALSE, 0, 0) for n, t in enumerate(texid): gl.glBindTexture(gl.GL_TEXTURE_2D, t) gl.glDrawArrays(gl.GL_TRIANGLE_FAN, n * 4, 4) # draw walls gl.glUseProgram(wallprog.id) wallprog['color'] = (162.0/255.0, 153.0/255.0, 118.0/255.0, 1.0) with wallbuf.bound: gl.glVertexAttribPointer(0, 2, gl.GL_FLOAT, gl.GL_FALSE, 0, 0) gl.glDrawArrays(gl.GL_QUADS, 0, len(walls) * 8) # draw some shaders gl.glUseProgram(dragonprog.id) gl.glBindTexture(gl.GL_TEXTURE_2D, dragonsprite_scales.texid) gl.glActiveTexture(gl.GL_TEXTURE0 + 1) gl.glBindTexture(gl.GL_TEXTURE_1D, dragonpalette) gl.glActiveTexture(gl.GL_TEXTURE0) dragonprog['texture'] = 0 dragonprog['palette'] = 1 dragonprog['perturb'] = (ticks_done % 1024) / 128 dragonprog['shift'] = ticks_done / 600 with dragonbuf.bound: gl.glVertexAttribPointer(0, 4, gl.GL_FLOAT, gl.GL_FALSE, 0, 0) gl.glDrawArrays(gl.GL_TRIANGLE_FAN, 0, 4) # now draw the rest of the f****n' dragon gl.glUseProgram(spriteprog.id) gl.glBindTexture(gl.GL_TEXTURE_2D, dragonsprite_contours.texid) spriteprog['texture'] = 0 with contourbuf.bound: gl.glVertexAttribPointer(0, 4, gl.GL_FLOAT, gl.GL_FALSE, 0, 0) gl.glDrawArrays(gl.GL_TRIANGLE_FAN, 0, 4) if debug_draw: gl.glUseProgram(wallprog.id) wallprog['color'] = (0.89, 0.89, 0.89, 1.0) quads = numpy.zeros((len(entities), 4, 2), dtype=numpy.float32) quads[:, 0, :] = components.entity.passive_tl quads[:, 2, :] = components.entity.passive_br quads[:, 1, 0] = quads[:, 0, 0] quads[:, 1, 1] = quads[:, 2, 1] quads[:, 3, 0] = quads[:, 2, 0] quads[:, 3, 1] = quads[:, 0, 1] gl.glVertexAttribPointer(0, 2, gl.GL_FLOAT, gl.GL_FALSE, 0, quads.ctypes.data) gl.glDrawArrays(gl.GL_QUADS, 0, quads.size // 2) gl.glColor3f(1, 1, 1) gl.glEnable(gl.GL_TEXTURE_2D) #screen.fill((120, 50, 50), pygame.Rect(0, 10, player1.hitpoints * 2, 10)) #screen.fill((120, 50, 50), pygame.Rect(1000 - player2.hitpoints * 2, 10, player2.hitpoints * 2, 10)) pygame.display.flip() delta = time.clock() - start if delta < constants.FRAME: time.sleep(constants.FRAME - delta)