def draw(self, frame): # The gneneral plan here is: # 1. Get the dots in the range of 0-255. # 2. Create a texture with the dots data. # 3. Draw the texture, scaled up with nearest-neighbor. # 4. Draw a mask over the dots to give them a slightly more realistic look. gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) gl.glLoadIdentity() # Draw the dots in this color: #gl.glColor3f(1.0, 0.5, 0.25) gl.glScalef(1, -1, 1) gl.glTranslatef(0, -DMD_SIZE[1]*DMD_SCALE, 0) #data = frame.get_data_mult() #this new jk_get_data will read the dots using the dmd function #and convert them via the map to rGB. data = self.jk_get_data(frame) image = pyglet.image.ImageData(DMD_SIZE[0], DMD_SIZE[1], 'RGB', data, pitch=DMD_SIZE[0] * 3) gl.glTexParameteri(image.get_texture().target, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) image.blit(0, 0, width=DMD_SIZE[0]*DMD_SCALE, height=DMD_SIZE[1]*DMD_SCALE) del image gl.glScalef(DMD_SCALE/float(MASK_SIZE), DMD_SCALE/float(MASK_SIZE), 1.0) gl.glColor4f(1.0, 1.0, 1.0, 1.0) self.mask_texture.blit_tiled(x=0, y=0, z=0, width=DMD_SIZE[0]*MASK_SIZE, height=DMD_SIZE[1]*MASK_SIZE)
def load_image(filename, anchor_x=None, anchor_y=None): 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 ) img = pyglet.image.load(filename)#.get_texture(rectangle=True) img.anchor_x = anchor_x if anchor_x is not None else img.width // 2 img.anchor_y = anchor_y if anchor_y is not None else img.height // 2 return img
def get_sprite(filename): image = pyglet.image.load(os.path.join('sprites', filename)) texture = image.get_texture() gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) texture.width = texture.width * settings.scale texture.height = texture.height * settings.scale return texture
def tex_from_m(m, resize=4): #m = m.T shape = m.shape m = np.clip(m, -1, 1) m += 1 m /= 2 m *= 255 # we need to flatten the array m.shape = -1 # convert to GLubytes tex_data = (gl.GLubyte * m.size)( *m.astype('uint8') ) # create an image # pitch is 'texture width * number of channels per element * per channel size in bytes' img = pyglet.image.ImageData(shape[1], shape[0], "I", tex_data, pitch = shape[1] * 1 * 1) texture = img.get_texture() gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) texture.width = shape[1] * resize texture.height = -shape[0] * resize return texture
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 from_atlas(cls, name, firstgid, file, tile_width, tile_height): image = pyglet.image.load(file) rows = image.height // tile_height columns = image.width // tile_width image_grid = pyglet.image.ImageGrid(image, rows, columns) atlas = pyglet.image.TextureGrid(image_grid) id = firstgid ts = cls(name, {}) ts.firstgid = firstgid for j in range(rows-1, -1, -1): for i in range(columns): tile_image = image.get_region(atlas[j, i].x, atlas[j, i].y, atlas[j, i].width, atlas[j, i].height) # Set texture clamping to avoid mis-rendering subpixel edges gl.glBindTexture(tile_image.texture.target, id) gl.glTexParameteri(tile_image.texture.target, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE) gl.glTexParameteri(tile_image.texture.target, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE) ts[id] = Tile(id, {}, tile_image) id += 1 return ts
def register_font(name, filename, width, height, font_map=None): """ Register a PixFont. :Parameters: `name` : string Name of the font. It will be used to access it using `pixfont.get_font` and `pixfont.free_font`. `filename`: string File name of the image containing the pixel font. `width` : int Width of a character. `height`: int Height of a character. `font_map` : string (optional) String containing all the characters in the pixel font. By default the map is: `abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!?()@:/'., ` After a font is registered by `register_font`, it can be used by obtaining a PixFont object with `pixfont.get_font`. """ _map = font_map or default_map _fonts[name] = PixFont(name=name, image=pyglet.resource.image(filename), width=width, height=height, font_map=_map) gl.glTexParameteri(_fonts[name].texture.target, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glTexParameteri(_fonts[name].texture.target, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST)
def texture_from_data(internalformat, size, data_format, data_type, data): '''Create texture from a data buffer (whatever can be passed as pointer to ctypes) internalformat - GL_RGBA8 or GL_RGB8 recommended size - a 1-, 2- or 3-tuple describing the image sizes data_format - see 'format' parameter of glDrawPixels data_type - see 'type' parameter of glDrawPixels data - pointer to memory''' size = list(size) dimensions = len(size) binding = getattr(gl, 'GL_TEXTURE_BINDING_{0:d}D'.format(dimensions)) target = getattr(gl,'GL_TEXTURE_{0:d}D'.format(dimensions)) texImage = getattr(gl,'glTexImage{0:d}D'.format(dimensions)) oldbind = ctypes.c_uint(0) gl.glGetIntegerv(binding, ctypes.cast(ctypes.byref(oldbind), ctypes.POINTER(ctypes.c_int))) texid = ctypes.c_uint(0) gl.glEnable(target) gl.glGenTextures(1, ctypes.byref(texid)) gl.glBindTexture(target, texid) gl.glTexParameteri(target, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR) gl.glTexParameteri(target, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) args = [target, 0, internalformat] + size + [0, data_format, data_type, data] texImage(*args) gl.glBindTexture(target, oldbind) return texid
def setup(): """ Basic OpenGL configuration. """ # Set the color of "clear", i.e. the sky, in rgba. gl.glClearColor(0.5, 0.69, 1.0, 1) # Enable culling (not rendering) of back-facing facets -- facets that aren't # visible to you. gl.glEnable(gl.GL_CULL_FACE) #gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_DST_ALPHA) #gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) gl.glBlendFunc(gl.GL_ZERO, gl.GL_SRC_COLOR) gl.glEnable(gl.GL_BLEND) gl.glAlphaFunc(gl.GL_GREATER, 0.5); gl.glEnable(gl.GL_ALPHA_TEST); # Set the texture minification/magnification function to GL_NEAREST (nearest # in Manhattan distance) to the specified texture coordinates. GL_NEAREST # "is generally faster than GL_LINEAR, but it can produce textured images # with sharper edges because the transition between texture elements is not # as smooth." 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.glTexEnvi(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_MODE, gl.GL_MODULATE) setup_fog()
def get_blocky_image(name): import pyglet.gl as gl image = pyglet.resource.image(name) gl.glBindTexture(image.target, image.id) gl.glTexParameteri(image.target, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glTexParameteri(image.target, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST) return image
def filter(self, value: Tuple[int, int]): if not isinstance(value, tuple) or not len(value) == 2: raise ValueError("Texture filter must be a 2 component tuple (min, mag)") self._filter = value self.use() gl.glTexParameteri(self._target, gl.GL_TEXTURE_MIN_FILTER, self._filter[0]) gl.glTexParameteri(self._target, gl.GL_TEXTURE_MAG_FILTER, self._filter[1])
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 __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 on_resize(self, w, h): super().on_resize(w, h) self.label.x = w / 2 self.label.y = h / 2 scale = min(w // self.base_width, h // self.base_height) gl.glLoadIdentity() gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glScalef(scale, scale, scale)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) gl.glTextureParameteri(self.name, gl.GL_TEXTURE_COMPARE_MODE, gl.GL_NONE) #gl.glTextureParameteri(self.name, gl.GL_DEPTH_TEXTURE_MODE, gl.GL_LUMINANCE) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_BORDER) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_BORDER)
def load_image(self, path): image = pyglet.image.load(path) texture = image.get_texture() texture.anchor_x = image.width // 2 texture.anchor_y = image.height // 2 gl.glBindTexture(gl.GL_TEXTURE_2D, texture.id) gl.glTexParameteri(texture.target, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) return image
def load_sprite(filename, anchor_x=None, anchor_y=None, batch=None): 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 ) img = pyglet.image.load(filename)#.get_texture(rectangle=True) img.anchor_x = anchor_x if anchor_x is not None else img.width // 2 img.anchor_y = anchor_y if anchor_y is not None else img.height // 2 sprite = CollideSprite(img, batch=batch) return sprite
def __init__(self, atlas_img, coords_file): img = pyglet.image.load( atlas_img ) self.atlas = pyglet.image.atlas.TextureAtlas( img.width, img.height ) self.atlas.texture = img.texture gl.glTexParameteri( img.texture.target, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE ) gl.glTexParameteri( img.texture.target, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE ) self.map = dict([ (k, pyglet.image.TextureRegion( rect[0], rect[1], 0, rect[2], rect[3], self.atlas.texture )) for k, rect in simplejson.load(open(coords_file)).items()])
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 __init__(self,filename): DummyTile.__init__(self,filename) 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 = pyglet.image.load(self.filename) image.anchor_x = image.width // 2 image.anchor_y = image.height // 2 pyglet.sprite.Sprite.__init__(self,image) self.highlighted = False
def draw_sprites(): 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) for item in world: if hasattr(item, "sprite"): item.sprite.x = item.position.x item.sprite.y = item.position.y item.sprite.rot = item.angle * RADIANS_TO_DEGREES item.sprite.render()
def solid_pattern(): if 'solid' in _bg_textures: return _bg_textures['solid'] data = '%c%c%c%c' % (255, 255, 255, 255) im = pyglet.image.ImageData(1, 1, 'RGBA', data) # have this image repeat gl.glBindTexture(im.texture.target, im.texture.id) 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) return im
def set_state(self): pyglet.graphics.TextureGroup.set_state(self) 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) # To Allow Normal Rendering when Buffering with FrameBufferObject # Without this option : problem with alpha blending when rendering buffered GUI textures gl.glBlendFuncSeparate(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA, gl.GL_ONE, gl.GL_ONE_MINUS_SRC_ALPHA)
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 on_draw(self): arcade.start_render() # Pixel perfect settings (in OpenGL) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) self.sprites.draw(filter=gl.GL_NEAREST) for button in self.button_list: button.draw()
def __init__(self): gl.glEnable(gl.GL_TEXTURE_2D) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) self.window = Window(width=640, height=360, resizable=True) self.window.config.alpha_size = 8 gl.glEnable(gl.GL_BLEND) self.window.set_caption('KeysManiac (development build)') Grid.set_factor_from_resolution(*self.window.get_size()) self.window.push_handlers(self) self.scene = None
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 addTexture(self, imgPath): dir, file = path.split(imgPath) if dir not in resource.path: resource.path.append(dir) resource.reindex() texture = resource.texture(file) self.textures.append(texture) gl.glBindTexture(texture.target, texture.id) gl.glGenerateMipmap(gl.GL_TEXTURE_2D) 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_NEAREST_MIPMAP_LINEAR)
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 _scale_texture(texture, width, height): """Scale the given texture to the given size. :param texture: The texture to scale. :type texture: pyglet.image.Texture :param width int: New width of texture, in pixels. :param height int: New height of texture, in pixels. """ glBindTexture(GL_TEXTURE_2D, texture.id) texture.width = width texture.height = height glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
def __init__(self, ax): self.rect = ViewPort(ax) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) path = Path(__file__).parents[1] / 'images/controls.png' image = pyglet.image.load(path) self.scale = 2.0 self.image_sprite = pyglet.sprite.Sprite(image, x=-image.width // 2, y=-image.height // 2)
def __init__(self, filename): DummyTile.__init__(self, filename) 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 = pyglet.image.load(self.filename) image.anchor_x = image.width // 2 image.anchor_y = image.height // 2 pyglet.sprite.Sprite.__init__(self, image) self.highlighted = False
def _view_image_array(self): if self.force_scale: self.original_image_array = self.image_array[:] for i in range(len(self.image_array)): img, intensity = self.image_array[i] img = ptpscale(intensity) img = np.minimum(np.maximum(img, 0), 255).astype('B') self.image_array[i] = (img, intensity) else: self.original_image_array = None self.window.set_caption(self.name + ' - %d' % self.fcnt) img = self._stack([img for img, _ in self.image_array]) intensity = self._stack([ii for _, ii in self.image_array]) self.color_mask = np.hstack([[len(ii.shape)==3] * ii.shape[1] for _, ii in self.image_array]) # FIXME: split image_array if self.image is None: resize = True else: resize = img.shape != self.prev_image_shape self.prev_image_shape = img.shape if len(img.shape) == 3: f = 'RGB' pitch = -img.shape[1] * 3 else: f = 'I' pitch = -img.shape[1] self.image = pyglet.image.ImageData(img.shape[1], img.shape[0], f, img.tostring(), pitch) texture = get_texture(self.image) glTexParameteri(texture.target, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(texture.target, GL_TEXTURE_MIN_FILTER, GL_NEAREST) if resize: self.on_resize(self.window.width, self.window.height) self.intensity = intensity while True: self._dispatch_events() if not DebugViewer.paused: self.mystep = DebugViewer.step_counter break elif self.mystep < DebugViewer.step_counter: self.mystep += 1 break
def render(self, texture): x, y, scale_width, scale_height = self.get_scale() glLoadIdentity() if True: # oldschool? glBindTexture(texture.target, texture.id) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) # glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE) # glTexParameteri(texture.target, # GL_TEXTURE_MAG_FILTER, GL_NEAREST) # glTexParameteri(texture.target, # GL_TEXTURE_MIN_FILTER, GL_NEAREST) texture.blit(x, y, width=scale_width, height=scale_height)
def imshow(self, arr): H, W, C = arr.shape assert C==3 image = pyglet.image.ImageData(W, H, 'RGB', arr.tobytes(), pitch=W*-3) self.clear() self.switch_to() self.dispatch_events() texture = image.get_texture() gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) texture.width = W texture.height = H texture.blit(0, 0, width=self.win_w, height=self.win_h) self.flip()
def __init__(self, clip_file_pattern: str): self._window = pyglet.window.Window(fullscreen=True) self._window.event(self.on_draw) self._window.event(self.on_key_press) self._player = pyglet.media.Player() self._clips: List[Clip] = [] self._clip_file_pattern = clip_file_pattern self.video_y: Optional[int] = 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)
def on_draw(self): self.__window.clear() glClearColor(*self.__background_color) if self.__scene is not None: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) # draw batches self.__camera.focus(self.__window.width, self.__window.height) self.__scene.draw() # draw specific batches for the hud self.__camera.hud_mode(self.__window.width, self.__window.height) self.__scene.draw_head_display()
def dashed_pattern(width): if width in _bg_textures: return _bg_textures[width] color1 = '%c%c%c%c' % (255, 255, 255, 255) color2 = '%c%c%c%c' % (0, 0, 0, 0) hw = width // 4 data = color1 * hw * 3 + color2 * hw im = pyglet.image.ImageData(width, 1, 'RGBA', data) # have this image repeat gl.glBindTexture(im.texture.target, im.texture.id) 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) return im
def render_img(img, x, y, w, h): img_data = pyglet.image.ImageData( img.shape[1], img.shape[0], 'RGB', img.tobytes()) tex = img_data.get_texture() gl.glEnable(gl.GL_TEXTURE_2D) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glBindTexture(gl.GL_TEXTURE_2D, tex.id) pyglet.graphics.draw_indexed(4, gl.GL_TRIANGLE_STRIP, [0, 1, 2, 0, 2, 3], ('v2f', (x, y+h, x+w, y+h, x+w, y, x, y)), ('t3f', tex.tex_coords), ) gl.glDisable(gl.GL_TEXTURE_2D)
def draw_obj(body, tex): gl.glEnable(gl.GL_TEXTURE_2D) gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) 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.glBindTexture(gl.GL_TEXTURE_2D, tex.id) transformed = [world_to_screen(body.GetWorldPoint(p)) for p in POINTS] gl.glBegin(gl.GL_QUADS) for p, tc in zip(transformed, TEX_COORDS): gl.glTexCoord2f(*tc) gl.glVertex2f(*p) gl.glEnd()
def _view_image_array(self): if self.force_scale: self.original_image_array = self.image_array[:] for i in range(len(self.image_array)): img, intensity = self.image_array[i] img = ptpscale(intensity) img = np.minimum(np.maximum(img, 0), 255).astype('B') self.image_array[i] = (img, intensity) else: self.original_image_array = None self.window.set_caption(self.name + ' - %d' % self.fcnt) img = self._stack([img for img, _ in self.image_array]) intensity = self._stack([ii for _, ii in self.image_array]) self.color_mask = np.hstack([len(ii.shape)==3] * ii.shape[1] for _, ii in self.image_array) # FIXME: split image_array if self.image is None: resize = True else: resize = img.shape != self.prev_image_shape self.prev_image_shape = img.shape if len(img.shape) == 3: f = 'RGB' pitch = -img.shape[1] * 3 else: f = 'I' pitch = -img.shape[1] self.image = pyglet.image.ImageData(img.shape[1], img.shape[0], f, img.tostring(), pitch) glTexParameteri(self.image.texture.target, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(self.image.texture.target, GL_TEXTURE_MIN_FILTER, GL_NEAREST) if resize: self.on_resize(self.window.width, self.window.height) self.intensity = intensity while True: self._dispatch_events() if not DebugViewer.paused: self.mystep = DebugViewer.step_counter break elif self.mystep < DebugViewer.step_counter: self.mystep += 1 break
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 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 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 on_draw(self): w, h = self.width, self.height side = max(w, h) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) self.clear() for text in self.textures: text.blit(-(side-w)/2, -(side-h)/2, 0, side, side)
def init_gl(): gl.glClearDepth(1.0) gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) gl.glDepthFunc(gl.GL_LEQUAL) gl.glEnable(gl.GL_DEPTH_TEST) gl.glDepthFunc(gl.GL_LEQUAL) gl.glShadeModel(gl.GL_SMOOTH) gl.glHint(gl.GL_PERSPECTIVE_CORRECTION_HINT, gl.GL_NICEST) 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)
def on_draw(self): image_data = pyglet.image.ImageData(64, 32, "L", self.processor.display.data) texture = image_data.get_texture() # Forces the sprite to be scaled nearest neighbour glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) # Scale the sprite to the window size texture.width = self.width texture.height = self.height # Draw the texture on screen texture.blit(0, 0)
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 on_draw(self): """ Called automatically, redraws the debug window. """ texture = self.create_texture() # Forces the sprite to be scaled nearest neighbour glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) # Scale the sprite to the window size texture.width = self.width texture.height = self.height # Draw the texture on screen texture.blit(0, 0) del texture
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 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 get_sprites(self, scale): sprites = [] batch = pyglet.graphics.Batch() for y, row in enumerate(self.tiles): for x, tile in enumerate(row): if tile: s_x = self.tile_size[0] * scale * x s_y = self.tile_size[1] * scale * y with_transforms = tile.get_transformed() sprite = pyglet.sprite.Sprite(with_transforms, x=s_x, y=s_y, batch=batch) sprite.scale = scale gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) sprites.append(sprite) return sprites, batch
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 init_gl(self): """Basic OpenGL configuration.""" # Set the color of "clear", i.e. the sky, in rgba. glClearColor(0.5, 0.69, 1.0, 1) # Enable culling (not rendering) of back-facing facets -- facets that aren't # visible to you. glEnable(GL_CULL_FACE) # Set the texture minification/magnification function to GL_NEAREST (nearest # in Manhattan distance) to the specified texture coordinates. GL_NEAREST # "is generally faster than GL_LINEAR, but it can produce textured images # with sharper edges because the transition between texture elements is not # as smooth." glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) self.init_gl_fog()