def upload(self): """Upload the local atlas data into graphics card memory """ if not self.textureID: self.textureID = gl.GLuint(0) gl.glGenTextures(1, ctypes.byref(self.textureID)) logging.debug("Uploading Texture Font {} to graphics card".format( self.name)) gl.glBindTexture(gl.GL_TEXTURE_2D, self.textureID) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR) if self.format == 'alpha': gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_ALPHA, self.width, self.height, 0, gl.GL_ALPHA, gl.GL_UNSIGNED_BYTE, self.data.ctypes) else: gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, self.width, self.height, 0, gl.GL_RGB, gl.GL_UNSIGNED_BYTE, self.data.ctypes) logging.debug("Upload of Texture Font {} complete".format(self.name)) gl.glBindTexture(gl.GL_TEXTURE_2D, 0)
def _link(self): for attachment, tex in zip(COLOR_ATTACHMENTS, self.textures): gl.glBindTexture(gl.GL_TEXTURE_2D, tex) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_REPEAT) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_REPEAT) 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) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGBA32F, self.width, self.height, 0, gl.GL_RGBA, gl.GL_FLOAT, None) gl.glFramebufferTexture2D(gl.GL_FRAMEBUFFER, attachment, gl.GL_TEXTURE_2D, tex, 0) gl.glBindRenderbuffer(gl.GL_RENDERBUFFER, self.depthbuf) gl.glRenderbufferStorage(gl.GL_RENDERBUFFER, gl.GL_DEPTH_COMPONENT16, self.width, self.height) gl.glFramebufferRenderbuffer(gl.GL_FRAMEBUFFER, gl.GL_DEPTH_ATTACHMENT, gl.GL_RENDERBUFFER, self.depthbuf) assert gl.glCheckFramebufferStatus(gl.GL_FRAMEBUFFER) == gl.GL_FRAMEBUFFER_COMPLETE, \ "Framebuffer is not complete!"
def __init__(self, env, sync=True, tps=60, aspect_ratio=None): obs = env.reset() self._image = self.get_image(obs, env) assert len(self._image.shape ) == 3 and self._image.shape[2] == 3, 'must be an RGB image' image_height, image_width = self._image.shape[:2] if aspect_ratio is None: aspect_ratio = image_width / image_height # guess a screen size that doesn't distort the image too much but also is not tiny or huge display = pyglet.canvas.get_display() screen = display.get_default_screen() max_win_width = screen.width * 0.9 max_win_height = screen.height * 0.9 win_width = image_width win_height = int(win_width / aspect_ratio) while win_width > max_win_width or win_height > max_win_height: win_width //= 2 win_height //= 2 while win_width < max_win_width / 2 and win_height < max_win_height / 2: win_width *= 2 win_height *= 2 win = pyglet.window.Window(width=win_width, height=win_height) self._key_handler = pyglet.window.key.KeyStateHandler() win.push_handlers(self._key_handler) win.on_close = self._on_close gl.glEnable(gl.GL_TEXTURE_2D) self._texture_id = gl.GLuint(0) gl.glGenTextures(1, ctypes.byref(self._texture_id)) gl.glBindTexture(gl.GL_TEXTURE_2D, self._texture_id) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP) 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) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGBA8, image_width, image_height, 0, gl.GL_RGB, gl.GL_UNSIGNED_BYTE, None) self._env = env self._win = win # self._render_human = render_human self._key_previous_states = {} self._steps = 0 self._episode_steps = 0 self._episode_returns = 0 self._prev_episode_returns = 0 self._tps = tps self._sync = sync self._current_time = 0 self._sim_time = 0 self._max_sim_frames_per_update = 4
def poll(dt): out = next(itr, False) if out is False: if args.pause: label.text = "Done. ('q' to quit)" else: pyglet.app.exit() elif out is not None: name, buf = out real_dt = time.time() - last_time[0] last_time[0] = time.time() if buf.dtype == np.uint8: fmt = gl.GL_UNSIGNED_BYTE elif buf.dtype == np.uint16: fmt = gl.GL_UNSIGNED_SHORT else: label.text = 'Unsupported format: ' + buf.dtype return h, w, ch = buf.shape gl.glEnable(tex.target) gl.glBindTexture(tex.target, tex.id) gl.glTexImage2D(tex.target, 0, gl.GL_RGB8, w, h, 0, gl.GL_RGBA, fmt, buf.tostring()) gl.glDisable(tex.target) label.text = '%s (%g fps)' % (name, 1./real_dt) else: label.text += '.'
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 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 create_image_texture(imgfile): """Create a 2D texture from an image file. """ image = pyglet.image.load(imgfile) data = image.get_data("RGBA", image.width * 4) tex = gl.GLuint() gl.glGenTextures(1, ct.pointer(tex)) gl.glBindTexture(gl.GL_TEXTURE_2D, tex) 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.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE) gl.glTexImage2D( gl.GL_TEXTURE_2D, 0, gl.GL_RGBA, image.width, image.height, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, data, ) gl.glBindTexture(tex, 0) return tex
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 create_texture(self, cls, rectangle=False, force_rectangle=False): '''Create a texture containing this image. If the image's dimensions are not powers of 2, a TextureRegion of a larger Texture will be returned that matches the dimensions of this image. :Parameters: `cls` : class (subclass of Texture) Class to construct. `rectangle` : bool ``True`` if a rectangle can be created; see `AbstractImage.get_texture`. :rtype: cls or cls.region_class ''' _is_pow2 = lambda v: (v & (v - 1)) == 0 target = gl.GL_TEXTURE_2D if rectangle and not (_is_pow2(self.width) and _is_pow2(self.height)): if gl.gl_info.have_extension('GL_ARB_texture_rectangle'): target = gl.GL_TEXTURE_RECTANGLE_ARB elif gl.gl_info.have_extension('GL_NV_texture_rectangle'): target = gl.GL_TEXTURE_RECTANGLE_NV texture = cls.create_for_size(target, self.width, self.height) subimage = False if texture.width != self.width or texture.height != self.height: texture = texture.get_region(0, 0, self.width, self.height) subimage = True internalformat = self._get_internalformat(self.format) gl.glBindTexture(texture.target, texture.id) gl.glTexParameteri(texture.target, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE) gl.glTexParameteri(texture.target, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE) gl.glTexParameteri(texture.target, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) gl.glTexParameteri(texture.target, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR) if subimage: width = texture.owner.width height = texture.owner.height blank = (ctypes.c_ubyte * (width * height * 4))() gl.glTexImage2D(texture.target, texture.level, internalformat, width, height, 1, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, blank) internalformat = None self.blit_to_texture(texture.target, texture.level, 0, 0, 0, internalformat) return texture
def poll(dt): out = next(itr, False) if out is False: if args.pause: label.text = "Done. ('q' to quit)" else: pyglet.app.exit() elif out is not None: name, buf = out real_dt = time.time() - last_time[0] last_time[0] = time.time() if buf.dtype == np.uint8: fmt = gl.GL_UNSIGNED_BYTE elif buf.dtype == np.uint16: fmt = gl.GL_UNSIGNED_SHORT else: label.text = 'Unsupported format: ' + buf.dtype return h, w, ch = buf.shape gl.glEnable(tex.target) gl.glBindTexture(tex.target, tex.id) gl.glTexImage2D(tex.target, 0, gl.GL_RGB8, w, h, 0, gl.GL_RGBA, fmt, buf.tostring()) gl.glDisable(tex.target) label.text = '%s (%g fps)' % (name, 1. / real_dt) else: label.text += '.'
def get_offscreen_fbo(width, height, msaa_samples=4): fbo = Framebuffer() # using None for the format specifier in Texture.create means we have to # allocate memory ourselves, which is important here because we seem to # need to pass nullptr to allocation routine's destination arg (why?). if msaa_samples > 1: fbo._colour_texture = Texture.create( width, height, target=gl.GL_TEXTURE_2D_MULTISAMPLE, internalformat=None) gl.glTexImage2DMultisample(gl.GL_TEXTURE_2D_MULTISAMPLE, msaa_samples, gl.GL_RGB, width, height, True) else: fbo._colour_texture = Texture.create(width, height, internalformat=None) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, width, height, 0, gl.GL_RGB, gl.GL_UNSIGNED_BYTE, None) fbo.attach_texture(gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT0, fbo._colour_texture) fbo._depth_rb = Renderbuffer(width, height, gl.GL_DEPTH_COMPONENT, samples=msaa_samples) fbo.attach_renderbuffer(gl.GL_FRAMEBUFFER, gl.GL_DEPTH_ATTACHMENT, fbo._depth_rb) assert fbo.is_complete, \ "FramebufferObject not complete after attaching all buffers (bug?); " \ f"status {{fbo.get_status()}}" return fbo
def data(self, buffer_type, data, offset): if buffer_type != "texture": gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.buffers[buffer_type]) if buffer_type == "color": offset *= 16 else: offset *= 12 gl_data = to_gl_float(data) length = len(data) * 4 gl.glBufferSubData(gl.GL_ARRAY_BUFFER, offset, length, gl_data) if buffer_type == "vertex": self.vertex_count += int(len(data) / 3) else: self.buffers["texture"] = gl.GLuint(0) gl.glGenTextures(1, self.buffers["texture"]) gl.glBindTexture(data.target, data.id) gl.glTexParameterf(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glTexParameterf(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, texture.width, texture.height, 0, gl.GL_RGB, gl.GL_UNSIGNED_BYTE, texture_data)
def build_buffer(): buffer = gl.GLuint(0) gl.glGenFramebuffers(1, ctypes.byref(buffer)) gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, buffer) texture = gl.GLuint(0) gl.glGenTextures(1, ctypes.byref(texture)) gl.glEnable(gl.GL_TEXTURE_2D) gl.glBindTexture(gl.GL_TEXTURE_2D, texture) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGBA, BUF_WIDTH, BUF_HEIGHT, 0, gl.GL_RGBA, gl.GL_FLOAT, 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) gl.glFramebufferTexture2D(gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT0, gl.GL_TEXTURE_2D, texture, 0) if (gl.glCheckFramebufferStatus(gl.GL_FRAMEBUFFER) != gl.GL_FRAMEBUFFER_COMPLETE): raise RuntimeError('Framebuffer incomplete !') gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0) gl.glBindTexture(gl.GL_TEXTURE_2D, 0) gl.glDisable(gl.GL_TEXTURE_2D) return buffer, texture
def setupFBOandTextures(self): self.framebufferA0 = (gl.GLuint * args["outResolution"])() self.A0_tex = gl.GLuint(0) self.A1_tex = gl.GLuint(0) self.draw_buffersA0 = (gl.GLenum * args["outResolution"])(gl.GL_COLOR_ATTACHMENT0) gl.glGenFramebuffers(args["outResolution"], self.framebufferA0) gl.glGenTextures(1, ctypes.byref(self.A0_tex)) gl.glGenTextures(1, ctypes.byref(self.A1_tex)) #create textures #A gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(gl.GL_TEXTURE_2D, self.A0_tex) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGBA, self.dimx, self.dimy, 0, gl.GL_RGBA, gl.GL_FLOAT, self.Ap) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR) gl.glActiveTexture(gl.GL_TEXTURE1) gl.glBindTexture(gl.GL_TEXTURE_3D, self.A1_tex) gl.glTexImage3D(gl.GL_TEXTURE_3D, 0, gl.GL_RED, args["outResolution"], args["outResolution"], args["outResolution"], 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["outResolution"]): gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, self.framebufferA0[i]) gl.glFramebufferTexture3D(gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT0, gl.GL_TEXTURE_3D, self.A1_tex, 0, i) assert(gl.glCheckFramebufferStatus(gl.GL_FRAMEBUFFER) == gl.GL_FRAMEBUFFER_COMPLETE)
def __init__(self, width, height, wwidth, wheight): self.width = width self.height = height self.windowwidth = wwidth self.windowheight = wheight self.framebuffer = gl.GLuint(0) self.rendered_texture = Texture() gl.glGenFramebuffers(1, ctypes.byref(self.framebuffer)) gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, self.framebuffer) # Set up the texture as the target for color output with self.rendered_texture: gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGBA32F, self.width, self.height, 0, gl.GL_RGB, gl.GL_UNSIGNED_BYTE, 0) 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) gl.glFramebufferTexture2D(gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT0, gl.GL_TEXTURE_2D, self.rendered_texture.name, 0) if gl.glCheckFramebufferStatus( gl.GL_FRAMEBUFFER) != gl.GL_FRAMEBUFFER_COMPLETE: raise ValueError('Framebuffer not set up completely') gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0)
def load_texture(): global textureIDs filepath = os.path.join(os.path.dirname(__file__), 'data/ca.jpg') img = Image.open(filepath) w, h = img.size gl.glBindTexture(gl.GL_TEXTURE_2D, textureIDs[0]) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, w, h, 0, gl.GL_RGB, gl.GL_UNSIGNED_BYTE, img.tobytes())
def __init__(self, width, height, window, num_color_attachments=1, mapping_mode=None, provide_depth=False, provide_stencil=False): """"Create an arbitrary layer framebuffer, I'll add stencil and depthbuffers if I ever package this for resuse, in pyweek, those args are pretty much placeholders""" if mapping_mode is None: mapping_mode = gl.GL_NEAREST assert not provide_stencil, 'stencil buffer not implemented' assert not provide_depth, 'depth buffer not implemented' self.window = window self.width = width self.height = height self.bufferId = gl.GLuint(0) self.textureIds = [] self.buffer_args = [] #create the vram objects? gl.glGenFramebuffers(1, rf(self.bufferId)) gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, self.bufferId) for bufferIndex in range(num_color_attachments): newTex = gl.GLuint(0) gl.glGenTextures(1, rf(newTex)) self.textureIds.append(newTex) gl.glBindTexture(gl.GL_TEXTURE_2D, newTex) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, width, height, 0, gl.GL_RGB, gl.GL_UNSIGNED_INT, 0) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, mapping_mode) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, mapping_mode) gl.glFramebufferTexture2D(gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT0 + bufferIndex, gl.GL_TEXTURE_2D, newTex, 0) self.buffer_args.append(gl.GL_COLOR_ATTACHMENT0 + bufferIndex) #assign one of the vram objects to the framebuffer cache? if provide_depth: self.buffer_args.append(gl.GL_DEPTH_ATTACHMENT) if provide_stencil: self.buffer_args.append(gl.GL_STENCIL_ATTACHMENT) self.buffers_provided = (gl.GLenum * len(self.buffer_args))(*self.buffer_args) gl.glDrawBuffers(len(self.buffer_args), self.buffers_provided) self.textures = [ Texture(self.width, self.height, gl.GL_TEXTURE_2D, texId.value) for texId in self.textureIds ] assert gl.glCheckFramebufferStatus( gl.GL_FRAMEBUFFER ) == gl.GL_FRAMEBUFFER_COMPLETE, "I don't know why this happened, but at least I can find out"
def _texture_2d(self, data): """Create a 2D texture""" # Make sure we unpack the pixel data with correct alignment # or we'll end up with corrupted textures gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, self._alignment) gl.glPixelStorei(gl.GL_PACK_ALIGNMENT, self._alignment) # Create depth 2d texture if self._depth: gl.glTexImage2D( self._target, 0, # level gl.GL_DEPTH_COMPONENT24, self._width, self._height, 0, gl.GL_DEPTH_COMPONENT, gl.GL_FLOAT, data, ) self.compare_func = "<=" # Create normal 2d texture else: try: format_info = pixel_formats[self._dtype] except KeyError: raise ValueError( f"dype '{self._dtype}' not support. Supported types are : {tuple(pixel_formats.keys())}" ) try: ( _format, _internal_format, self._type, self._component_size, ) = format_info self._format = _format[self._components] self._internal_format = _internal_format[self._components] gl.glTexImage2D( self._target, # target 0, # level self._internal_format, # internal_format self._width, # width self._height, # height 0, # border self._format, # format self._type, # type data, # data ) except gl.GLException as ex: raise gl.GLException( ( f"Unable to create texture: {ex} : dtype={self._dtype} size={self.size} components={self._components} " "MAX_TEXTURE_SIZE = {self.ctx.limits.MAX_TEXTURE_SIZE}" ) )
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 _updateFrameTexture(self): if self._nextFrameT is None: # movie has no current position, need to reset the clock # to zero in order to have the timing logic work # otherwise the video stream would skip frames until the # time since creating the movie object has passed self._videoClock.reset() self._nextFrameT = 0 #only advance if next frame (half of next retrace rate) if self._nextFrameT > self.duration: self._onEos() elif (self._numpyFrame is not None) and \ (self._nextFrameT > (self._videoClock.getTime()-self._retraceInterval/2.0)): return None self._numpyFrame = self._mov.get_frame(self._nextFrameT) useSubTex=self.useTexSubImage2D if self._texID is None: self._texID = GL.GLuint() GL.glGenTextures(1, ctypes.byref(self._texID)) useSubTex=False #bind the texture in openGL GL.glEnable(GL.GL_TEXTURE_2D) GL.glBindTexture(GL.GL_TEXTURE_2D, self._texID)#bind that name to the target GL.glTexParameteri(GL.GL_TEXTURE_2D,GL.GL_TEXTURE_WRAP_S,GL.GL_REPEAT) #makes the texture map wrap (this is actually default anyway) GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1) # data from PIL/numpy is packed, but default for GL is 4 bytes #important if using bits++ because GL_LINEAR #sometimes extrapolates to pixel vals outside range if self.interpolate: GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR) if useSubTex is False: GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGB8, self._numpyFrame.shape[1],self._numpyFrame.shape[0], 0, GL.GL_RGB, GL.GL_UNSIGNED_BYTE, self._numpyFrame.ctypes) else: GL.glTexSubImage2D(GL.GL_TEXTURE_2D, 0, 0, 0, self._numpyFrame.shape[1], self._numpyFrame.shape[0], GL.GL_RGB, GL.GL_UNSIGNED_BYTE, self._numpyFrame.ctypes) else: 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) if useSubTex is False: GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGB8, self._numpyFrame.shape[1],self._numpyFrame.shape[0], 0, GL.GL_BGR, GL.GL_UNSIGNED_BYTE, self._numpyFrame.ctypes) else: GL.glTexSubImage2D(GL.GL_TEXTURE_2D, 0, 0, 0, self._numpyFrame.shape[1], self._numpyFrame.shape[0], GL.GL_BGR, GL.GL_UNSIGNED_BYTE, self._numpyFrame.ctypes) GL.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_MODE, GL.GL_MODULATE)#?? do we need this - think not! if not self.status==PAUSED: self._nextFrameT += self._frameInterval
def create(cls, width, height, target=gl.GL_TEXTURE_2D, internalformat=gl.GL_RGBA, min_filter=None, mag_filter=None): """Create a Texture Create a Texture with the specified dimentions, target and format. On return, the texture will be bound. :Parameters: `width` : int Width of texture in pixels. `height` : int Height of texture in pixels. `target` : int GL constant giving texture target to use, typically ``GL_TEXTURE_2D``. `internalformat` : int GL constant giving internal format of texture; for example, ``GL_RGBA``. If ``None``, the texture will be created but not initialized. `min_filter` : int The minifaction filter used for this texture, commonly ``GL_LINEAR`` or ``GL_NEAREST`` `mag_filter` : int The magnification filter used for this texture, commonly ``GL_LINEAR`` or ``GL_NEAREST`` :rtype: :py:class:`~pyglet.image.Texture` """ min_filter = min_filter or cls.default_min_filter mag_filter = mag_filter or cls.default_mag_filter tex_id = gl.GLuint() gl.glGenTextures(1, byref(tex_id)) gl.glBindTexture(target, tex_id.value) if target != gl.GL_TEXTURE_2D_MULTISAMPLE: gl.glTexParameteri(target, gl.GL_TEXTURE_MIN_FILTER, min_filter) gl.glTexParameteri(target, gl.GL_TEXTURE_MAG_FILTER, mag_filter) if internalformat is not None: blank = (gl.GLubyte * (width * height * 4))() gl.glTexImage2D(target, 0, internalformat, width, height, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, blank) gl.glFlush() texture = cls(width, height, target, tex_id.value) texture.min_filter = min_filter texture.mag_filter = mag_filter if target is gl.GL_TEXTURE_RECTANGLE: texture.tex_coords = (0, 0, 0, width, 0, 0, width, height, 0, 0, height, 0) else: texture.tex_coords = cls.tex_coords return texture
def create_texture_from_array(array): """Create a pyglet texture instance from a numpy ndarray.""" height, width = array.shape[:2] texture = pyglet.image.Texture.create_for_size(gl.GL_TEXTURE_2D, width, height, gl.GL_RGBA32F_ARB) gl.glBindTexture(texture.target, texture.id) gl.glTexImage2D(texture.target, texture.level, gl.GL_RGBA32F_ARB, width, height, 0, gl.GL_RGBA, gl.GL_FLOAT, array.ctypes.data) gl.glBindTexture(texture.target, 0) return texture
def createFramebuffer(width, height): """Function for setting up additional buffer""" # create a new framebuffer fboId = GL.GLuint() GL.glGenFramebuffers(1, ctypes.byref(fboId)) GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, fboId) # create a texture to render to, required for warping texId = GL.GLuint() GL.glGenTextures(1, ctypes.byref(texId)) GL.glBindTexture(GL.GL_TEXTURE_2D, texId) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR) GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA32F_ARB, int(width), int(height), 0, GL.GL_RGBA, GL.GL_FLOAT, None) GL.glFramebufferTexture2D(GL.GL_FRAMEBUFFER, GL.GL_COLOR_ATTACHMENT0, GL.GL_TEXTURE_2D, texId, 0) # create a render buffer rbId = GL.GLuint() GL.glGenRenderbuffers(1, ctypes.byref(rbId)) GL.glBindRenderbuffer(GL.GL_RENDERBUFFER, rbId) GL.glRenderbufferStorage( GL.GL_RENDERBUFFER, GL.GL_DEPTH24_STENCIL8, int(width), int(height)) GL.glFramebufferRenderbuffer( GL.GL_FRAMEBUFFER, GL.GL_DEPTH_ATTACHMENT, GL.GL_RENDERBUFFER, rbId) GL.glFramebufferRenderbuffer( GL.GL_FRAMEBUFFER, GL.GL_STENCIL_ATTACHMENT, GL.GL_RENDERBUFFER, rbId) GL.glBindRenderbuffer(GL.GL_RENDERBUFFER, 0) # clear the buffer GL.glClear(GL.GL_COLOR_BUFFER_BIT) GL.glClear(GL.GL_STENCIL_BUFFER_BIT) GL.glClear(GL.GL_DEPTH_BUFFER_BIT) GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, 0) return fboId, texId, rbId
def create_texture_from_ndarray(array): height, width = array.shape[:2] texture = pyglet.image.Texture.create_for_size(gl.GL_TEXTURE_2D, width, height, gl.GL_RGBA32F_ARB) gl.glBindTexture(texture.target, texture.id) gl.glTexImage2D(texture.target, texture.level, gl.GL_RGBA32F_ARB, width, height, 0, gl.GL_RGBA, gl.GL_FLOAT, array.ctypes.data) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE) gl.glBindTexture(texture.target, 0) return texture
def create_uv_texture(width, height): """Create a pyglet texture instance from a numpy ndarray.""" uv_grid = np.zeros((height, width, 4), dtype=np.float32) uv_grid[:, :, 0] = 1.0 uv_grid[height//2, width//2, 1] = 1.0 texture = pyglet.image.Texture.create_for_size(gl.GL_TEXTURE_2D, width, height, gl.GL_RGBA32F_ARB) gl.glBindTexture(texture.target, texture.id) gl.glTexImage2D(texture.target, texture.level, gl.GL_RGBA32F_ARB, width, height, 0, gl.GL_RGBA, gl.GL_FLOAT, uv_grid.ctypes.data) gl.glBindTexture(texture.target, 0) return texture
def load_chessboard(): global texture_ids, chessboard_image chessboard = make_chessboard(CHESS_HNUM, CHESS_VNUM, CHESS_MARGIN, CHESS_BLOCKSIZE) filepath = os.path.join(DATA_DIRPATH, 'chessboard.png') cv2.imwrite(filepath, chessboard) chessboard_image = Image.open(filepath) tw, th = chessboard_image.width, chessboard_image.height gl.glBindTexture(gl.GL_TEXTURE_2D, texture_ids[0]) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, tw, th, 0, gl.GL_RGB, gl.GL_UNSIGNED_BYTE, chessboard_image.tobytes())
def __init__(self, width, height): self.id = gl.GLuint(0) gl.glGenTextures(1, ctypes.byref(self.id)) self.bind() gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGBA, width, height, 0, gl.GL_RGBA, gl.GL_FLOAT, 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) self.unbind()
def load_texture(tex_path): from pyglet import gl logger.debug('loading texture "%s"' % os.path.basename(tex_path)) import pyglet img = pyglet.image.load(tex_path) tex = img.get_texture() gl.glEnable(tex.target) gl.glBindTexture(tex.target, tex.id) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, img.width, img.height, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, img.get_image_data().get_data('RGBA', img.width * 4)) return tex
def create_texture_from_array(array): ''' create a pyglet texture instance from a numpy ndarray. remember that we have not bound it to any texture unit. ''' height, width = array.shape[:2] texture = pyglet.image.Texture.create_for_size(gl.GL_TEXTURE_2D, width, height, gl.GL_RGBA32F_ARB) gl.glBindTexture(texture.target, texture.id) gl.glTexImage2D(texture.target, texture.level, gl.GL_RGBA32F_ARB, width, height, 0, gl.GL_RGBA, gl.GL_FLOAT, array.ctypes.data) gl.glBindTexture(texture.target, 0) return texture
def create_cubemap_texture(imgfiles): """Create a cubemap texture from image files. :param imgfiles: a list of six strings specifying the path to the cubemap images. In the order [pos+X, pos-X, pos+Y, ..., pos-Z] """ if len(imgfiles) != 6: raise ValueError( "exactly six images are required for a cubemap texture") # generate a new texture cubemap = gl.GLuint() gl.glGenTextures(1, ct.pointer(cubemap)) # bind it to `GL_TEXTURE_CUBE_MAP` and set the filter and wrap mode gl.glBindTexture(gl.GL_TEXTURE_CUBE_MAP, cubemap) gl.glTexParameteri(gl.GL_TEXTURE_CUBE_MAP, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_CUBE_MAP, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR_MIPMAP_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_CUBE_MAP, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE) gl.glTexParameteri(gl.GL_TEXTURE_CUBE_MAP, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE) gl.glTexParameteri(gl.GL_TEXTURE_CUBE_MAP, gl.GL_TEXTURE_WRAP_R, gl.GL_CLAMP_TO_EDGE) # it seems we need to flip the images to make the cubemap look correct faces = [ImageOps.flip(Image.open(img)) for img in imgfiles] # set the faces of the cubemap texture for i, face in enumerate(faces): width, height = face.size try: data = face.tobytes("raw", "RGBX", 0, -1) except TypeError: data = face.tobytes("raw", "RGBA", 0, -1) gl.glTexImage2D( gl.GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.GL_RGBA, width, height, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, data, ) gl.glGenerateMipmap(gl.GL_TEXTURE_CUBE_MAP) gl.glBindTexture(gl.GL_TEXTURE_CUBE_MAP, 0) return cubemap
def create_cubemap_texture(imgfiles): """Create a cubemap texture from image files. """ if len(imgfiles) != 6: raise ValueError( "exactly six images are required for a cubemap texture") # generate a new texture cubemap = gl.GLuint() gl.glGenTextures(1, ct.pointer(cubemap)) # bind it to `GL_TEXTURE_CUBE_MAP` and set the filter and wrap mode gl.glBindTexture(gl.GL_TEXTURE_CUBE_MAP, cubemap) gl.glTexParameteri(gl.GL_TEXTURE_CUBE_MAP, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_CUBE_MAP, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR_MIPMAP_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_CUBE_MAP, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE) gl.glTexParameteri(gl.GL_TEXTURE_CUBE_MAP, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE) gl.glTexParameteri(gl.GL_TEXTURE_CUBE_MAP, gl.GL_TEXTURE_WRAP_R, gl.GL_CLAMP_TO_EDGE) faces = [Image.open(img) for img in imgfiles] # set the faces of the cubemap texture for i, face in enumerate(faces): width, height = face.size try: data = face.tobytes("raw", "RGBX", 0, -1) except TypeError: data = face.tobytes("raw", "RGBA", 0, -1) gl.glTexImage2D( gl.GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.GL_RGBA, width, height, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, data, ) gl.glGenerateMipmap(gl.GL_TEXTURE_CUBE_MAP) gl.glBindTexture(gl.GL_TEXTURE_CUBE_MAP, 0) return cubemap
def make_texture(filename, indexed=False): name = gl.GLuint(0) gl.glGenTextures(1, pointer(name)) gl.glBindTexture(gl.GL_TEXTURE_2D, name) 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) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE) image = PIL.Image.open(filename) if indexed: assert image.mode == 'P' else: image = image.convert('RGBA') logging.debug('loading {} mode={}'.format(filename, image.mode)) width, height = image.size if indexed: assert len(image.tobytes()) == width * height gl.glTexImage2D( gl.GL_TEXTURE_2D, 0, # level gl.GL_R8, width, height, 0, gl.GL_RED, gl.GL_UNSIGNED_BYTE, ctypes.create_string_buffer(image.tobytes())) else: assert len(image.tobytes()) == width * height * 4 gl.glTexImage2D( gl.GL_TEXTURE_2D, 0, # level gl.GL_RGBA8, width, height, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, ctypes.create_string_buffer(image.tobytes())) gl.glBindTexture(gl.GL_TEXTURE_2D, 0) return name
def setup_framebuffer(): gl.glGenFramebuffers(1, ctypes.byref(framebuffer)) gl.glGenTextures(1, ctypes.byref(rendered_texture)) gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, framebuffer) # Set up the texture as the target for color output gl.glBindTexture(gl.GL_TEXTURE_2D, rendered_texture) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, FB_WIDTH, FB_HEIGHT, 0, gl.GL_RGB, gl.GL_UNSIGNED_BYTE, 0) 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) gl.glFramebufferTexture2D(gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT0, gl.GL_TEXTURE_2D, rendered_texture, 0) draw_buffers = (gl.GLenum * 1)(gl.GL_COLOR_ATTACHMENT0) gl.glDrawBuffers(1, draw_buffers) assert gl.glCheckFramebufferStatus(gl.GL_FRAMEBUFFER) == gl.GL_FRAMEBUFFER_COMPLETE
def create_uv_texture(width, height): ''' create a pyglet texture instance from a numpy ndarray. remember that we have not bound it to any texture unit. ''' 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 texture = pyglet.image.Texture.create_for_size(gl.GL_TEXTURE_2D, width, height, gl.GL_RGBA32F_ARB) gl.glBindTexture(texture.target, texture.id) gl.glTexImage2D(texture.target, texture.level, gl.GL_RGBA32F_ARB, width, height, 0, gl.GL_RGBA, gl.GL_FLOAT, uv_grid.ctypes.data) gl.glBindTexture(texture.target, 0) return texture
def make_texture(filename, indexed=False): name = gl.GLuint(0) gl.glGenTextures(1, pointer(name)) gl.glBindTexture(gl.GL_TEXTURE_2D, name) 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) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE) image = PIL.Image.open(filename) if indexed: assert image.mode == 'P' else: image = image.convert('RGBA') logging.debug('loading {} mode={}'.format(filename, image.mode)) width, height = image.size if indexed: assert len(image.tobytes()) == width * height gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, # level gl.GL_R8, width, height, 0, gl.GL_RED, gl.GL_UNSIGNED_BYTE, ctypes.create_string_buffer(image.tobytes())) else: assert len(image.tobytes()) == width * height * 4 gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, # level gl.GL_RGBA8, width, height, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, ctypes.create_string_buffer(image.tobytes())) gl.glBindTexture(gl.GL_TEXTURE_2D, 0) return name
def upload(self): ''' Upload atlas data into video memory. ''' glEnable( GL_TEXTURE_2D ) if self.texid is None: self.texid = GLuint(0) glGenTextures(1,ctypes.byref(self.texid)) glBindTexture( GL_TEXTURE_2D, self.texid ) glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP ) glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP ) glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ) glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ) if self.depth == 1: glTexImage2D( GL_TEXTURE_2D, 0, GL_ALPHA, self.width, self.height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, self.data.ctypes ) elif self.depth == 3: glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, self.width, self.height, 0, GL_RGB, GL_UNSIGNED_BYTE, self.data.ctypes ) else: glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, self.width, self.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, self.data.ctypes ) glBindTexture( GL_TEXTURE_2D, 0 )
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 create_point_texture(size, feather=0): """Create and load a circular grayscale image centered in a square texture with a width and height of size. The radius of the circle is size / 2. Since size is used as the texture width and height, it should typically be a power of two. Feather determines the softness of the edge of the circle. The default, zero, creates a hard edged circle. Larger feather values create softer edges for blending. The point at the center of the texture is always white. Return the OpenGL texture name (id) for the resulting texture. This value can be passed directy to a texturizer or glBindTexture """ from pyglet import gl assert feather >= 0, 'Expected feather value >= 0' coords = range(size) texel = (gl.GLfloat * size**2)() r = size / 2.0 c = feather + 1.0 for y in coords: col = y * size for x in coords: d = math.sqrt((x - r)**2 + (y - r)**2) if d < r and (1.0 - 1.0 / (d / r - 1.0)) < 100: texel[x + col] = c**2 / c**(1.0 - 1.0 / (d / r - 1.0)) else: texel[x + col] = 0 id = gl.GLuint() gl.glGenTextures(1, ctypes.byref(id)) gl.glBindTexture(gl.GL_TEXTURE_2D, id.value) gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 4) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_LUMINANCE, size, size, 0, gl.GL_LUMINANCE, gl.GL_FLOAT, ctypes.byref(texel)) gl.glFlush() return id.value
def resize(self, width, height): ''' resizes the framebuffer to the given dimensions ''' gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, self.fbo) gl.glBindTexture(gl.GL_TEXTURE_2D, self.rendered_texture) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, width, height, 0, gl.GL_RGB, gl.GL_UNSIGNED_BYTE, 0) 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) gl.glFramebufferTexture2D(gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT0, gl.GL_TEXTURE_2D, self.rendered_texture, 0) gl.glBindRenderbuffer(gl.GL_RENDERBUFFER, self.depthrenderbuffer) gl.glRenderbufferStorage(gl.GL_RENDERBUFFER, gl.GL_DEPTH_COMPONENT, width, height) gl.glFramebufferRenderbuffer(gl.GL_FRAMEBUFFER, gl.GL_DEPTH_ATTACHMENT, gl.GL_RENDERBUFFER, self.depthrenderbuffer) gl.glBindRenderbuffer(gl.GL_RENDERBUFFER, self.pickingbuffer) gl.glRenderbufferStorage(gl.GL_RENDERBUFFER, gl.GL_R16UI, width, height) gl.glFramebufferRenderbuffer(gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT1, gl.GL_RENDERBUFFER, self.pickingbuffer) draw_buffers = (gl.GLenum * 2)(gl.GL_COLOR_ATTACHMENT0, gl.GL_COLOR_ATTACHMENT1) gl.glDrawBuffers(2, draw_buffers) if gl.glCheckFramebufferStatus(gl.GL_FRAMEBUFFER) != gl.GL_FRAMEBUFFER_COMPLETE: logging.error('setting up fbo failed') gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0)
def __init__(self, imagedata, imagedatatype, size): self.size=( float(size[0]),float(size[1]) ) self.texcoords=(0.0,0.0,1.0,1.0) self.padding=(0,0,0,0) self._header_bar=[0,0,None,None] self.width, self.height = size[0], size[1] id = c.c_uint() gl.glGenTextures(1, c.byref(id)) self.id = id.value texture_data = (c.c_ubyte * (self.width * self.height * 4))() for i, u in enumerate(imagedata): texture_data[i]= u gl.glBindTexture(gl.GL_TEXTURE_2D, self.id) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGBA, self.width, self.height, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, texture_data) gl.glTexParameteri(gl.GL_TEXTURE_2D,gl.GL_TEXTURE_MAG_FILTER,gl.GL_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_2D,gl.GL_TEXTURE_MIN_FILTER,gl.GL_LINEAR) gl.glBindTexture(gl.GL_TEXTURE_2D, 0)
def blit_to_texture(self, target, level, x, y, z, internalformat=None): '''Draw this image to to the currently bound texture at `target`. If `internalformat` is specified, glTexImage is used to initialise the texture; otherwise, glTexSubImage is used to update a region. ''' data_format = self.format data_pitch = abs(self._current_pitch) # Determine pixel format from format string matrix = None format, type = self._get_gl_format_and_type(data_format) if format is None: if (len(data_format) in (3, 4) and gl.gl_info.have_extension('GL_ARB_imaging')): # Construct a color matrix to convert to GL_RGBA def component_column(component): try: pos = 'RGBA'.index(component) return [0] * pos + [1] + [0] * (3 - pos) except ValueError: return [0, 0, 0, 0] # pad to avoid index exceptions lookup_format = data_format + 'XXX' matrix = (component_column(lookup_format[0]) + component_column(lookup_format[1]) + component_column(lookup_format[2]) + component_column(lookup_format[3])) format = { 3: gl.GL_RGB, 4: gl.GL_RGBA}.get(len(data_format)) type = gl.GL_UNSIGNED_BYTE gl.glMatrixMode(gl.GL_COLOR) gl.glPushMatrix() gl.glLoadMatrixf((gl.GLfloat * 16)(*matrix)) else: # Need to convert data to a standard form data_format = { 1: 'L', 2: 'LA', 3: 'RGB', 4: 'RGBA'}.get(len(data_format)) format, type = self._get_gl_format_and_type(data_format) # Workaround: don't use GL_UNPACK_ROW_LENGTH if gl.current_context._workaround_unpack_row_length: data_pitch = self.width * len(data_format) # Get data in required format (hopefully will be the same format it's # already in, unless that's an obscure format, upside-down or the # driver is old). data = self._convert(data_format, data_pitch) if data_pitch & 0x1: alignment = 1 elif data_pitch & 0x2: alignment = 2 else: alignment = 4 row_length = data_pitch / len(data_format) gl.glPushClientAttrib(gl.GL_CLIENT_PIXEL_STORE_BIT) gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, alignment) gl.glPixelStorei(gl.GL_UNPACK_ROW_LENGTH, row_length) self._apply_region_unpack() gl.glTexParameteri(target, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE) gl.glTexParameteri(target, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE) gl.glTexParameteri(target, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) gl.glTexParameteri(target, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR) if target == gl.GL_TEXTURE_3D: assert not internalformat gl.glTexSubImage3D(target, level, x, y, z, self.width, self.height, 1, format, type, data) elif internalformat: gl.glTexImage2D(target, level, internalformat, self.width, self.height, 0, format, type, data) else: gl.glTexSubImage2D(target, level, x, y, self.width, self.height, format, type, data) gl.glPopClientAttrib() if matrix: gl.glPopMatrix() gl.glMatrixMode(gl.GL_MODELVIEW)
def _genTex2D(self): """Generate an empty texture in OpenGL""" for face in range(6): gl.glTexImage2D(self.target0 + face, 0, self.internal_fmt, self.width, self.height, 0, self.pixel_fmt, gl.GL_UNSIGNED_BYTE, 0)
def _genTex2D(self): """Creates an empty texture in OpenGL.""" gl.glTexImage2D(self.target0, 0, self.internal_fmt, self.width, self.height, 0, self.pixel_fmt, gl.GL_UNSIGNED_BYTE, 0)
window = pyglet.window.Window(fullscreen=True, caption='Gray-Scott Reaction Diffusion', visible = False, vsync=False, resizable=True) window.set_location(window.screen.width/2 - window.width/2, window.screen.height/2 - window.height/2) # texture_s holds species # ----------------------- P = np.zeros((height,width,4), dtype=np.float32) P[:,:] = species['Bacteria 2'] data = P.ctypes.data texture_s = pyglet.image.Texture.create_for_size( gl.GL_TEXTURE_2D, width, height, gl.GL_RGBA32F_ARB) gl.glBindTexture(texture_s.target, texture_s.id) gl.glTexImage2D(texture_s.target, texture_s.level, gl.GL_RGBA32F_ARB, width, height, 0, gl.GL_RGBA, gl.GL_FLOAT, data) gl.glBindTexture(texture_s.target, 0) # texture_uv holds U & V values (red and green channels) # ------------------------------------------------------ UV = np.zeros((height,width,4), dtype=np.float32) UV[:,:,0] = 1.0 r = 32 UV[height/2-r:height/2+r, width/2-r:width/2+r, 0] = 0.50 UV[height/2-r:height/2+r, width/2-r:width/2+r, 1] = 0.25 data = UV.ctypes.data texture_uv = pyglet.image.Texture.create_for_size( gl.GL_TEXTURE_2D, width, height, gl.GL_RGBA32F) gl.glBindTexture(texture_uv.target, texture_uv.id) gl.glTexImage2D(texture_uv.target, texture_uv.level, gl.GL_RGBA32F_ARB, width, height, 0, gl.GL_RGBA, gl.GL_FLOAT, data)
def __init__(self, width, height): """Creates a FBO""" self.initialized = False assert self.supported() self.width = width self.height = height self.framebuffer_id = ctypes.c_uint(0) self.depthbuffer_id = ctypes.c_uint(0) self.texture_id = ctypes.c_uint(0) # Frame buffer gl.glGenFramebuffersEXT( 1, # number of buffers created ctypes.byref(self.framebuffer_id), # dest. id ) self.initialized = True with self._bound_context(gl.GL_FRAMEBUFFER_EXT): # Depth buffer gl.glGenRenderbuffersEXT( 1, # no. of buffers created ctypes.byref(self.depthbuffer_id), # dest. id ) gl.glBindRenderbufferEXT( gl.GL_RENDERBUFFER_EXT, # target self.depthbuffer_id, # id ) gl.glRenderbufferStorageEXT( gl.GL_RENDERBUFFER_EXT, # target gl.GL_DEPTH_COMPONENT, # internal format self.width, self.height, # size ) gl.glFramebufferRenderbufferEXT( gl.GL_FRAMEBUFFER_EXT, # target gl.GL_DEPTH_ATTACHMENT_EXT, # attachment point gl.GL_RENDERBUFFER_EXT, # renderbuffer target self.depthbuffer_id, # renderbuffer id ) # Target Texture gl.glGenTextures( 1, # no. of textures ctypes.byref(self.texture_id), # dest. id ) gl.glBindTexture( gl.GL_TEXTURE_2D, # target self.texture_id, # texture id ) # Black magic (props to pyprocessing!) # (nearest works, as well as linear) gl.glTexParameteri( gl.GL_TEXTURE_2D, # target gl.GL_TEXTURE_MAG_FILTER, # property name gl.GL_LINEAR, # value ) gl.glTexParameteri( gl.GL_TEXTURE_2D, # target gl.GL_TEXTURE_MIN_FILTER, # property name gl.GL_LINEAR, # value ) # Attach texture to FBO gl.glTexImage2D( gl.GL_TEXTURE_2D, # target 0, # mipmap level (0=default) gl.GL_RGBA8, # internal format self.width, self.height, # size 0, # border gl.GL_RGBA, # format gl.GL_UNSIGNED_BYTE, # type None, # data ) gl.glFramebufferTexture2DEXT( gl.GL_FRAMEBUFFER_EXT, # target gl.GL_COLOR_ATTACHMENT0_EXT, # attachment point gl.GL_TEXTURE_2D, # texture target self.texture_id, # tex id 0, # mipmap level ) # sanity check status = gl.glCheckFramebufferStatusEXT(gl.GL_FRAMEBUFFER_EXT) assert status == gl.GL_FRAMEBUFFER_COMPLETE_EXT
def _setup_tex(self): self._height, self._width = self._arr.shape gl.glTexImage2D (self.target, 0, self.dst_format, self._width, self._height, 0, self.src_format, self.src_type, 0) self.update()