def load_stack(self, stack): print('stack shape', stack.shape) s = np.array(stack, dtype=np.uint8, order='F') print(s.shape) w, h, d = s.shape print('shape', s.shape) stack_texture = glGenTextures(1) print(stack_texture) glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_3D, stack_texture) glTexParameter(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameter(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glPixelStorei(GL_UNPACK_ALIGNMENT, 1) # glTexParameter(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) # glTexParameter(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) # glTexParameter(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE) glTexImage3D(GL_TEXTURE_3D, 0, GL_R8, d, h, w, 0, GL_RED, GL_UNSIGNED_BYTE, s) print("made 3D texture") return stack_texture, s.shape
def _createTexture(self): surface = self._textureImage width = surface.get_width() height = surface.get_height() raw = pygame.image.tostring(surface, "RGBA", 0) texture = glGenTextures(1) # glGenTextures fails by returning 0, particularly if there's no GL # context yet. assert texture != 0 glBindTexture(GL_TEXTURE_2D, texture) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, raw) return texture
def load_texture(self, img: Image) -> None: img_data = np.fromstring(img.tobytes(), np.uint8) width, height = img.size self._texture = glGenTextures(1) glPixelStorei(GL_UNPACK_ALIGNMENT, 1) glBindTexture(GL_TEXTURE_2D, self._texture) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) mode = GL_RGBA if img.mode == "RGB": mode = GL_RGB glTexImage2D( GL_TEXTURE_2D, 0, mode, width, height, 0, mode, GL_UNSIGNED_BYTE, img_data, ) glGenerateMipmap(GL_TEXTURE_2D)
def render_planar_update(self, rx, ry, rw, rh, x_scale=1, y_scale=1): log("%s.render_planar_update%s pixel_format=%s", self, (rx, ry, rw, rh, x_scale, y_scale), self.pixel_format) if self.pixel_format not in ("YUV420P", "YUV422P", "YUV444P", "GBRP"): #not ready to render yet return if self.pixel_format == "GBRP": self.set_rgbP_paint_state() self.gl_marker("painting planar update, format %s", self.pixel_format) divs = get_subsampling_divs(self.pixel_format) glEnable(GL_FRAGMENT_PROGRAM_ARB) for texture, index in ((GL_TEXTURE0, 0), (GL_TEXTURE1, 1), (GL_TEXTURE2, 2)): glActiveTexture(texture) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[index]) tw, th = self.texture_size log("%s.render_planar_update(..) texture_size=%s, size=%s", self, self.texture_size, self.size) glBegin(GL_QUADS) for x,y in ((0, 0), (0, rh), (rw, rh), (rw, 0)): ax = min(tw, x) ay = min(th, y) for texture, index in ((GL_TEXTURE0, 0), (GL_TEXTURE1, 1), (GL_TEXTURE2, 2)): (div_w, div_h) = divs[index] glMultiTexCoord2i(texture, ax//div_w, ay//div_h) glVertex2i(int(rx+ax*x_scale), int(ry+ay*y_scale)) glEnd() if self.pixel_format == "GBRP": self.unset_rgbP_paint_state()
def _loadTexture(self): """ Load texture data from current image object """ ix, iy, image = self.image_obj.getTextureData() # allocate texture object if never yet done [bruce 060207 revised all related code, to fix bug 1059] if self.tex_name is None: self.tex_name = glGenTextures(1) # note: by experiment (iMac G5 Panther), this returns a single number (1L, 2L, ...), not a list or tuple, # but for an argument >1 it returns a list of longs. We depend on this behavior here. [bruce 060207] # initialize texture data glBindTexture(GL_TEXTURE_2D, self.tex_name) # 2d texture (x and y size) glPixelStorei(GL_UNPACK_ALIGNMENT, 1) self.have_mipmaps = False if debug_pref("smoother tiny textures", Choice_boolean_False, prefs_key=True): #bruce 060212 new feature; only takes effect when image is reloaded for some reason (like "load image" button) gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, ix, iy, GL_RGBA, GL_UNSIGNED_BYTE, image) self.have_mipmaps = True else: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, ix, iy, 0, GL_RGBA, GL_UNSIGNED_BYTE, image) # 0 is mipmap level, GL_RGBA is internal format, ix, iy is size, 0 is borderwidth, # and (GL_RGBA, GL_UNSIGNED_BYTE, image) describe the external image data. [bruce 060212 comment] ## self._initTextureEnv() #bruce 060207 do this in draw method, not here self.assy.o.gl_update() return
def render(self, model, view_matrix, projection_matrix): glUseProgram(self.program) glEnableVertexAttribArray(self.texcoords) glEnableVertexAttribArray(self.vertices) glUniformMatrix4fv( self.model_view_matrix, 1, GL_TRUE, np.dot(view_matrix, model.matrix) ) glUniformMatrix4fv( self.projection_matrix, 1, GL_TRUE, projection_matrix ) for group in model.groups: glBindTexture(GL_TEXTURE_2D, group.material.texture) glUniform1i(self.texture, 0) glVertexAttribPointer( self.vertices, 3, GL_FLOAT, GL_FALSE, 0, group.vertex_buffer ) glVertexAttribPointer( self.texcoords, 2, GL_FLOAT, GL_FALSE, 0, group.texcoord_buffer ) glDrawArrays(GL_TRIANGLES, 0, len(group.vertex_buffer)) glDisableVertexAttribArray(self.vertices) glDisableVertexAttribArray(self.texcoords)
def render(self, viewBox): if not self.intersectsBox(viewBox): return if self.shouldRefresh: self.refresh() self.shouldRefresh = False glColor3f(1, 1, 1) img = self.textureData pic_ny, pic_nx = img.shape tex_nx,tex_ny = getTexSize(pic_nx,pic_ny) picTexRatio_x = float(pic_nx) / tex_nx picTexRatio_y = float(pic_ny) / tex_ny (x,y) = self.pos[:2] glBindTexture(GL_TEXTURE_2D, self.texture) glBegin(GL_QUADS) glTexCoord2f(0, picTexRatio_y) glVertex2f(x, y) glTexCoord2f(picTexRatio_x, picTexRatio_y) glVertex2f(x + self.size[0], y) glTexCoord2f(picTexRatio_x, 0) glVertex2f(x + self.size[0], y + self.size[1]) glTexCoord2f(0, 0) glVertex2f(x, y + self.size[1]) glEnd()
def load_texture(path): import pygame #Cargo la imagen a memoria. pygame se hace cargo de decodificarla correctamente surf = pygame.image.load(path) surf = pygame.transform.flip(surf, False, True) #Obtengo la matriz de colores de la imagen en forma de un array binario #Le indico el formato en que quiero almacenar los datos (RGBA) y que invierta la matriz, para poder usarla correctamente con OpenGL image = pygame.image.tostring(surf, 'RGBA', 1) #Obentego las dimensiones de la imagen ix, iy = surf.get_rect().size #Creo una textura vacia en memoria de video, y me quedo con el identificador (texid) para poder referenciarla texid = glGenTextures(1) #Activo esta nueva textura para poder cargarle informacion glBindTexture(GL_TEXTURE_2D, texid) #Seteo los tipos de filtro a usar para agrandar y achivar la textura glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) #Cargo la matriz de colores dentro de la textura #Los parametros que le paso son: # - Tipo de textura, en este caso GL_TEXTURE_2D # - Nivel de mipmap, en este caso 0 porque no estoy usando mas niveles # - Formato en que quiero almacenar los datos en memoria de video, GL_RGB en este caso, porque no necesito canal Alfa # - Ancho de la textura # - Alto de la textura # - Grosor en pixels del borde, en este caso 0 porque no quiero agregar borde a al imagen # - Formato de los datos de la imagen, en este caso GL_RGBA que es como lo leimos con pygame.image # - Formato de los canales de color, GL_UNSIGNED_BYTE quiere decir que son 8bits para cada canal # - La imagen, en este caso la matriz de colores que creamos con pygame.image.tostring glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, ix, iy, 0, GL_RGBA, GL_UNSIGNED_BYTE, image) #Una vez que tengo todo cargado, desactivo la textura para evitar que se dibuje por error mas adelante #Cada vez que quiera usarla, puedo hacer glBindTexture con el identificador (texid) que me guarde al crearla glBindTexture(GL_TEXTURE_2D, 0) #devuelvo el identificador de la textura para que pueda ser usada mas adelante return texid
def update_texture_rgb24(self, img_data, x, y, width, height, rowstride): drawable = self.glarea.get_gl_drawable() context = self.glarea.get_gl_context() if not drawable.gl_begin(context): raise Exception("** Cannot create OpenGL rendering context!") assert self.textures is not None glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[0]) glPixelStorei(GL_UNPACK_ROW_LENGTH, rowstride/3) if self.current_mode == GLClientWindow.MODE_YUV: raise Exception("** YUV -> RGB mode change unimplemented!") elif self.current_mode == GLClientWindow.MODE_UNINITIALIZED: log("Creating new RGB texture") w, h = self.get_size() # First time we draw must be full image assert w == width and h == height glEnable(GL_TEXTURE_RECTANGLE_ARB) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGB, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0) self.current_mode = GLClientWindow.MODE_RGB log("Updating RGB texture") glTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, img_data) drawable.gl_end() self.render_image()
def render_yuv_update(self, rx, ry, rw, rh): debug("render_yuv_update %sx%s at %sx%s pixel_format=%s", rw, rh, rx, ry, self.pixel_format) if self.pixel_format not in (YUV420P, YUV422P, YUV444P): #not ready to render yet return self.gl_marker("Painting YUV update") divs = get_subsampling_divs(self.pixel_format) glEnable(GL_FRAGMENT_PROGRAM_ARB) glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.yuv_shader[0]) for texture, index in ((GL_TEXTURE0, 0), (GL_TEXTURE1, 1), (GL_TEXTURE2, 2)): glActiveTexture(texture) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[index]) tw, th = self.texture_size debug("render_yuv_update texture_size=%s, size=%s", self.texture_size, self.size) glBegin(GL_QUADS) for x, y in ((rx, ry), (rx, ry + rh), (rx + rw, ry + rh), (rx + rw, ry)): ax = min(tw, x) ay = min(th, y) for texture, index in ((GL_TEXTURE0, 0), (GL_TEXTURE1, 1), (GL_TEXTURE2, 2)): (div_w, div_h) = divs[index] glMultiTexCoord2i(texture, ax / div_w, ay / div_h) glVertex2i(ax, ay) glEnd()
def drawShadowMaps(lights, layerLoc): """ draws shadow maps for debugging. note that a special shader is required to display the depth-component-only textures """ i = 0 for light in lights: if light.shadowMapArray==None: continue shadowMapArray = light.shadowMapArray shadowMaps = shadowMapArray.shadowMaps glBindTexture( GL_TEXTURE_2D_ARRAY, shadowMapArray.texture.glID ) glTexParameteri( GL_TEXTURE_2D_ARRAY, GL_TEXTURE_COMPARE_MODE, GL_NONE ) for j in range(len(shadowMaps)): glViewport(130*i, 0, 128, 128) glUniform1f(layerLoc, float(j)) glBegin(GL_QUADS) glVertex3f(-1.0, -1.0, 0.0) glVertex3f( 1.0, -1.0, 0.0) glVertex3f( 1.0, 1.0, 0.0) glVertex3f(-1.0, 1.0, 0.0) glEnd() i += 1 if shadowMapArray.textureType=="sampler2DArrayShadow": glTexParameteri( GL_TEXTURE_2D_ARRAY, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE ) else: glTexParameteri( GL_TEXTURE_2D_ARRAY, GL_TEXTURE_COMPARE_MODE, GL_NONE )
def update_texture_rgb24(self, img_data, x, y, width, height, rowstride): drawable = self.glarea.get_gl_drawable() context = self.glarea.get_gl_context() if not drawable.gl_begin(context): raise Exception("** Cannot create OpenGL rendering context!") assert self.textures is not None glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[0]) glPixelStorei(GL_UNPACK_ROW_LENGTH, rowstride / 3) if self.current_mode == GLClientWindow.MODE_YUV: raise Exception("** YUV -> RGB mode change unimplemented!") elif self.current_mode == GLClientWindow.MODE_UNINITIALIZED: log("Creating new RGB texture") w, h = self.get_size() # First time we draw must be full image assert w == width and h == height glEnable(GL_TEXTURE_RECTANGLE_ARB) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGB, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0) self.current_mode = GLClientWindow.MODE_RGB log("Updating RGB texture") glTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, img_data) drawable.gl_end() self.render_image()
def makeGLTexture(image_data: np.ndarray, w: int, h: int, repeat=False) -> int: """Loading pygame.Surface as OpenGL texture :return New Texture key""" # getting data from pygame.Surface # bind new texture key = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, key) # SETTING UP glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) # настройка сжатия glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) # настройка растяжения if repeat: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) glTexImage2D(GL_TEXTURE_2D, GL_ZERO, GL_RGBA, w, h, GL_ZERO, GL_RGBA, GL_UNSIGNED_BYTE, image_data) # # unbind new texture glBindTexture(GL_TEXTURE_2D, 0) return key
def draw(self): """ Draws each frame. """ print("draw()") # DRAW STUFF HERE glDisable(GL_TEXTURE_RECTANGLE_ARB) glColor4f(1.0, 0.8, 0.2, 1.0) glPushMatrix() glScale(0.5, 0.5, 1.0) draw_square() glPopMatrix() glColor4f(1.0, 1.0, 0.0, 0.8) num = 64 for i in range(num): x = (i / float(num)) * 4 - 2 draw_line(float(x), -2.0, float(x), 2.0) draw_line(-2.0, float(x), 2.0, float(x)) if self.texture_id is not None: glColor4f(1.0, 1.0, 1.0, 1.0) glEnable(GL_TEXTURE_RECTANGLE_ARB) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.texture_id) glPushMatrix() glScale(0.4, 0.3, 1.0) draw_textured_square(320, 240) glPopMatrix() else: print "No texture to draw"
def LoadTexture(path): # запросим у OpenGL свободный индекс текстуры texture = glGenTextures(1) # сделаем текстуру активной glBindTexture(GL_TEXTURE_2D, texture) # загружаем изображение-текстуру image = Image.open(path) image = image.transpose(Image.FLIP_TOP_BOTTOM) img_data = image.convert("RGBA").tobytes() glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.width, image.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, img_data) glGenerateMipmap(GL_TEXTURE_2D) # установим параметры фильтрации текстуры - линейная фильтрация glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) # установим параметры "оборачиваниея" текстуры - отсутствие оборачивания glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) #GL_REPEAT glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) #GL_REPEAT # возвращаем текстуру return texture
def _do_paint_rgb24(self, img_data, x, y, width, height, rowstride, options, callbacks): debug( "%s._do_paint_rgb24(x=%d, y=%d, width=%d, height=%d, rowstride=%d)", self, x, y, width, height, rowstride) drawable = self.gl_init() if not drawable: debug("%s._do_paint_rgb24(..) drawable is not set!", self) return False try: self.set_rgb24_paint_state() # Compute alignment and row length row_length = 0 alignment = 1 for a in [2, 4, 8]: # Check if we are a-aligned - ! (var & 0x1) means 2-aligned or better, 0x3 - 4-aligned and so on if (rowstride & a - 1) == 0: alignment = a # If number of extra bytes is greater than the alignment value, # then we also have to set row_length # Otherwise it remains at 0 (= width implicitely) if (rowstride - width * 3) > a: row_length = width + (rowstride - width * 3) / 3 self.gl_marker( "RGB24 update at %d,%d, size %d,%d, stride is %d, row length %d, alignment %d" % (x, y, width, height, rowstride, row_length, alignment)) # Upload data as temporary RGB texture glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_RGB]) glPixelStorei(GL_UNPACK_ROW_LENGTH, row_length) glPixelStorei(GL_UNPACK_ALIGNMENT, alignment) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0) glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, 4, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, img_data) # Draw textured RGB quad at the right coordinates glBegin(GL_QUADS) glTexCoord2i(0, 0) glVertex2i(x, y) glTexCoord2i(0, height) glVertex2i(x, y + height) glTexCoord2i(width, height) glVertex2i(x + width, y + height) glTexCoord2i(width, 0) glVertex2i(x + width, y) glEnd() # Present update to screen self.present_fbo(drawable) # present_fbo has reset state already finally: drawable.gl_end() return True
def bind_depth_texture(self, size): """Create depth texture for shadow map.""" width, height = size texture_type = GL_TEXTURE_2D self.__depth_map_fbo = glGenFramebuffers(1) depth_map = self.__textures_ids[len(self.__textures)] glBindTexture(texture_type, depth_map) self.__textures.append(2) glTexImage2D(texture_type, 0, GL_DEPTH_COMPONENT, width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, None) glTexParameteri(texture_type, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexParameteri(texture_type, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(texture_type, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameteri(texture_type, GL_TEXTURE_WRAP_T, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LESS) glBindFramebuffer(GL_FRAMEBUFFER, self.__depth_map_fbo) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depth_map, 0) glDrawBuffer(GL_NONE) glReadBuffer(GL_NONE) glBindFramebuffer(GL_FRAMEBUFFER, 0)
def bind(self): """Makes this texture the current texture for the current context by calling glBindTexture. If this texture has not previously been used with the current context, do_setup() is called to allocate and initialise a representation of the texture.""" gl_id = self.gl_id() glBindTexture(self._gl_type, gl_id)
def save_FBO(self): bw, bh = self.size glEnable(GL_TEXTURE_RECTANGLE_ARB) glBindFramebuffer(GL_READ_FRAMEBUFFER, self.offscreen_fbo) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO]) glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO], 0) glReadBuffer(GL_COLOR_ATTACHMENT0) glViewport(0, 0, bw, bh) size = bw*bh*4 data = numpy.empty(size) img_data = glGetTexImage(GL_TEXTURE_RECTANGLE_ARB, 0, GL_BGRA, GL_UNSIGNED_BYTE, data) img = Image.frombuffer("RGBA", (bw, bh), img_data, "raw", "BGRA", bw*4) img = ImageOps.flip(img) kwargs = {} if SAVE_BUFFERS=="jpeg": kwargs = { "quality" : 0, "optimize" : False, } t = time.time() tstr = time.strftime("%H-%M-%S", time.localtime(t)) filename = "./W%i-FBO-%s.%03i.%s" % (self.wid, tstr, (t*1000)%1000, SAVE_BUFFERS) log("do_present_fbo: saving %4ix%-4i pixels, %7i bytes to %s", bw, bh, size, filename) img.save(filename, SAVE_BUFFERS, **kwargs) glBindFramebuffer(GL_READ_FRAMEBUFFER, 0) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, 0) glDisable(GL_TEXTURE_RECTANGLE_ARB)
def _draw_zero_plane_xy(self, color, texture_id=None, scale=1.0): glPushMatrix() # glColor3f(*rgb_to_f(*color)) apply_texture = texture_id is not None if apply_texture: glColor3f(1, 1, 1) glBindTexture(GL_TEXTURE_2D, self._textures[texture_id]) glTexCoord2f(1.0 * scale, 0.0 * scale) else: glColor3f(*rgb_to_f(*color)) glBegin(GL_POLYGON) size = self._size / 2 glVertex3f(size, size, 0) if apply_texture: glTexCoord2f(1.0 * scale, 1.0 * scale) glVertex3f(size, -size, 0) if apply_texture: glTexCoord2f(0.0 * scale, 1.0 * scale) glVertex3f(-size, -size, 0) if apply_texture: glTexCoord2f(0.0 * scale, 0.0 * scale) glVertex3f(-size, size, 0) # if texture is not None: # glBindTexture(GL_TEXTURE_2D, ) glEnd() glPopMatrix()
def create_float_texture(self, data, size, dimensions=2, components=3): """Bind texture with floating point vectors within. dimensions: dimensionality of the texture vector, matrix, 3D matrix. components: dimensionality of texture element number or 2D, 3D, 4D vector. """ texture_type = get_texture_type(dimensions) texture_constructor = get_texture_constructor(dimensions) internal_format = get_color_internal_format(components) texture_format = get_color_format(components) glBindTexture(texture_type, self.__textures_ids[len(self.__textures)]) glPixelStorei(GL_UNPACK_ALIGNMENT, 1) # HACK: Python <3.5 doesn't allow to use *size # within enumerable arguments params = ([texture_type, 0, internal_format] + list(size) + [0, texture_format, GL_FLOAT, data.flatten()]) texture_constructor(*params) glTexParameterf(texture_type, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameterf(texture_type, GL_TEXTURE_MIN_FILTER, GL_NEAREST) self.__textures.append(dimensions)
def init_back_texture(self, width, height): if self.fbo is None: self.fbo = glGenFramebuffers(1) glActiveTexture(GL_TEXTURE0 + 1) if self.bfTex is not None: glDeleteTextures([self.bfTex]) self.bfTex = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, self.bfTex) glTexParameter(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameter(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) w = int(width) h = int(height) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, w, h, 0, GL_RGBA, GL_FLOAT, None) glBindFramebuffer(GL_FRAMEBUFFER, self.fbo) glFramebufferTexture2D(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, self.bfTex, 0) glBindFramebuffer(GL_FRAMEBUFFER, 0) glBindTexture(GL_TEXTURE_2D, 0)
def __init__(self, face: freetype.Face, char: str) -> None: if face.load_char(char, freetype.FT_LOAD_RENDER): raise RuntimeError('failed to load char \'%s\'' % char) glyph = face.glyph bitmap = glyph.bitmap assert bitmap.pixel_mode == freetype.FT_PIXEL_MODE_GRAY, \ "We haven't implemented support for other pixel modes" glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT) glPixelStorei(GL_UNPACK_LSB_FIRST, GL_FALSE) glPixelStorei(GL_UNPACK_ROW_LENGTH, 0) glPixelStorei(GL_UNPACK_ALIGNMENT, 1) self._texture_id = glGenTextures(1) self._width = bitmap.width self._height = bitmap.rows self._descender = glyph.bitmap_top - self._height self._bearing_x = glyph.bitmap_left self._advance = numpy.array( [face.glyph.advance.x / 64.0, face.glyph.advance.y / 64.0]) glBindTexture(GL_TEXTURE_2D, self._texture_id) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) data = numpy.array(bitmap.buffer, numpy.ubyte).reshape(self._height, self._width) glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, self._width, self._height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, numpy.flipud(data)) glPopClientAttrib()
def _do_paint_rgb24(self, img_data, x, y, w, h, rowstride, options, callbacks): log("do_paint_rgb24(%s bytes, %s, %s, %s, %s, %s, %s, %s)", len(img_data), x, y, w, h, rowstride, options, callbacks) ww, wh = self.size if x+w>ww or y+h>wh: log("do_paint_rgb24: ignoring paint which would overflow the backing area") return drawable = self.gl_init() if not drawable: log("do_paint_rgb24: cannot paint yet..") return try: #cleanup if we were doing yuv previously: if self.pixel_format!=GLPixmapBacking.RGB24: self.remove_shader() self.pixel_format = GLPixmapBacking.RGB24 glEnable(GL_TEXTURE_RECTANGLE_ARB) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[0]) glPixelStorei(GL_UNPACK_ROW_LENGTH, rowstride/3) for texture in (GL_TEXTURE1, GL_TEXTURE2): glActiveTexture(texture) glDisable(GL_TEXTURE_RECTANGLE_ARB) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, x, y, w, h, GL_RGB, GL_UNSIGNED_BYTE, img_data) glBegin(GL_QUADS) for rx,ry in ((x, y), (x, y+h), (x+w, y+h), (x+w, y)): glTexCoord2i(rx, ry) glVertex2i(rx, ry) glEnd() finally: self.gl_end(drawable)
def _draw(self, transformation_matrix: numpy.ndarray): glUseProgram(self._shader) glUniformMatrix4fv( self._transform_location, 1, GL_FALSE, transformation_matrix.T.astype(numpy.float32), ) glUniform1i(self._texture_location, 0) try: glBindVertexArray(self._vao) except GLError: # There seems to be errors randomly when binding the VBO log.debug( f"Failed binding the OpenGL state for {self}. Trying to reload it." ) self.unload() self._setup() glBindVertexArray(self._vao) glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, self._texture) glDrawArrays(self.draw_mode, self.draw_start, self.draw_count) glBindVertexArray(0) glUseProgram(0)
def render_planar_update(self, rx, ry, rw, rh, x_scale=1, y_scale=1): log("%s.render_planar_update%s pixel_format=%s", self, (rx, ry, rw, rh, x_scale, y_scale), self.pixel_format) if self.pixel_format not in ("YUV420P", "YUV422P", "YUV444P", "GBRP"): #not ready to render yet return if self.pixel_format == "GBRP": # Set GL state for planar RGB: change fragment program glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.shaders[RGBP2RGB_SHADER]) self.gl_marker("painting planar update, format %s", self.pixel_format) divs = get_subsampling_divs(self.pixel_format) glEnable(GL_FRAGMENT_PROGRAM_ARB) for texture, index in ((GL_TEXTURE0, TEX_Y), (GL_TEXTURE1, TEX_U), (GL_TEXTURE2, TEX_V)): glActiveTexture(texture) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[index]) tw, th = self.texture_size log("%s.render_planar_update(..) texture_size=%s, size=%s", self, self.texture_size, self.size) glBegin(GL_QUADS) for x,y in ((0, 0), (0, rh), (rw, rh), (rw, 0)): ax = min(tw, x) ay = min(th, y) for texture, index in ((GL_TEXTURE0, TEX_Y), (GL_TEXTURE1, TEX_U), (GL_TEXTURE2, TEX_V)): (div_w, div_h) = divs[index] glMultiTexCoord2i(texture, ax//div_w, ay//div_h) glVertex2i(int(rx+ax*x_scale), int(ry+ay*y_scale)) glEnd() for texture in (GL_TEXTURE0, GL_TEXTURE1, GL_TEXTURE2): glActiveTexture(texture) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, 0) glDisable(GL_FRAGMENT_PROGRAM_ARB) if self.pixel_format == "GBRP": # Reset state to our default (YUV painting) glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.shaders[YUV2RGB_SHADER]) glActiveTexture(GL_TEXTURE0)
def _loadTexture(self): """ Load texture data from current image object """ ix, iy, image = self.image_obj.getTextureData() # allocate texture object if never yet done [bruce 060207 revised all related code, to fix bug 1059] if self.tex_name is None: self.tex_name = glGenTextures(1) # note: by experiment (iMac G5 Panther), this returns a single number (1L, 2L, ...), not a list or tuple, # but for an argument >1 it returns a list of longs. We depend on this behavior here. [bruce 060207] # initialize texture data glBindTexture(GL_TEXTURE_2D, self.tex_name) # 2d texture (x and y size) glPixelStorei(GL_UNPACK_ALIGNMENT,1) self.have_mipmaps = False if debug_pref("smoother tiny textures", Choice_boolean_False, prefs_key = True): #bruce 060212 new feature; only takes effect when image is reloaded for some reason (like "load image" button) gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, ix, iy, GL_RGBA, GL_UNSIGNED_BYTE, image) self.have_mipmaps = True else: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, ix, iy, 0, GL_RGBA, GL_UNSIGNED_BYTE, image) # 0 is mipmap level, GL_RGBA is internal format, ix, iy is size, 0 is borderwidth, # and (GL_RGBA, GL_UNSIGNED_BYTE, image) describe the external image data. [bruce 060212 comment] ## self._initTextureEnv() #bruce 060207 do this in draw method, not here self.assy.o.gl_update() return
def drawTexture(self, texture, dx, dy, dw, dh, x, y, w, h, r): ''' texture is an int textureRect is a list of size 4, determines which square to take from the texture drawRect is a list of size 4, is used to determine the drawing size ''' glBindTexture(self.texext, texture) glPushMatrix() glTranslatef(dx + dw / 2, dy + dh / 2, 0) glRotatef(r, 0, 0, 1.0) glTranslatef(-1 * (dx + dw / 2), -1 * (dy + dh / 2), 0) glBegin(GL_QUADS) #Top-left vertex (corner) glTexCoord2f(x, y + h) #image/texture glVertex3f(dx, dy, 0) #screen coordinates #Bottom-left vertex (corner) glTexCoord2f(x + w, y + h) glVertex3f((dx + dw), dy, 0) #Bottom-right vertex (corner) glTexCoord2f(x + w, y) glVertex3f((dx + dw), (dy + dh), 0) #Top-right vertex (corner) glTexCoord2f(x, y) glVertex3f(dx, (dy + dh), 0) glEnd() glPopMatrix()
def get_gl_info_string(glpane): # grantham 20051129 """Return a string containing some useful information about the OpenGL implementation. Use the GL context from the given QGLWidget glpane (by calling glpane.makeCurrent()). """ glpane.makeCurrent() #bruce 070308 added glpane arg and makeCurrent call gl_info_string = '' gl_info_string += 'GL_VENDOR : "%s"\n' % glGetString(GL_VENDOR) gl_info_string += 'GL_VERSION : "%s"\n' % glGetString(GL_VERSION) gl_info_string += 'GL_RENDERER : "%s"\n' % glGetString(GL_RENDERER) gl_info_string += 'GL_EXTENSIONS : "%s"\n' % glGetString(GL_EXTENSIONS) from utilities.debug_prefs import debug_pref, Choice_boolean_False if debug_pref("get_gl_info_string call glAreTexturesResident?", Choice_boolean_False): # Give a practical indication of how much video memory is available. # Should also do this with VBOs. # I'm pretty sure this code is right, but PyOpenGL seg faults in # glAreTexturesResident, so it's disabled until I can figure that # out. [grantham] [bruce 070308 added the debug_pref] all_tex_in = True tex_bytes = '\0' * (512 * 512 * 4) tex_names = [] tex_count = 0 tex_names = glGenTextures(1024) glEnable(GL_TEXTURE_2D) while all_tex_in: glBindTexture(GL_TEXTURE_2D, tex_names[tex_count]) gluBuild2DMipmaps(GL_TEXTURE_2D, 4, 512, 512, GL_RGBA, GL_UNSIGNED_BYTE, tex_bytes) tex_count += 1 glTexCoord2f(0.0, 0.0) glBegin(GL_QUADS) glVertex2f(0.0, 0.0) glVertex2f(1.0, 0.0) glVertex2f(1.0, 1.0) glVertex2f(0.0, 1.0) glEnd() glFinish() residences = glAreTexturesResident(tex_names[:tex_count]) all_tex_in = reduce(lambda a,b: a and b, residences) # bruce 070308 sees this exception from this line: # TypeError: reduce() arg 2 must support iteration glDisable(GL_TEXTURE_2D) glDeleteTextures(tex_names) gl_info_string += "Could create %d 512x512 RGBA resident textures\n" \ % tex_count return gl_info_string
def get_gl_info_string(glpane): # grantham 20051129 """Return a string containing some useful information about the OpenGL implementation. Use the GL context from the given QGLWidget glpane (by calling glpane.makeCurrent()). """ glpane.makeCurrent() #bruce 070308 added glpane arg and makeCurrent call gl_info_string = '' gl_info_string += 'GL_VENDOR : "%s"\n' % glGetString(GL_VENDOR) gl_info_string += 'GL_VERSION : "%s"\n' % glGetString(GL_VERSION) gl_info_string += 'GL_RENDERER : "%s"\n' % glGetString(GL_RENDERER) gl_info_string += 'GL_EXTENSIONS : "%s"\n' % glGetString(GL_EXTENSIONS) from utilities.debug_prefs import debug_pref, Choice_boolean_False if debug_pref("get_gl_info_string call glAreTexturesResident?", Choice_boolean_False): # Give a practical indication of how much video memory is available. # Should also do this with VBOs. # I'm pretty sure this code is right, but PyOpenGL seg faults in # glAreTexturesResident, so it's disabled until I can figure that # out. [grantham] [bruce 070308 added the debug_pref] all_tex_in = True tex_bytes = '\0' * (512 * 512 * 4) tex_names = [] tex_count = 0 tex_names = glGenTextures(1024) glEnable(GL_TEXTURE_2D) while all_tex_in: glBindTexture(GL_TEXTURE_2D, tex_names[tex_count]) gluBuild2DMipmaps(GL_TEXTURE_2D, 4, 512, 512, GL_RGBA, GL_UNSIGNED_BYTE, tex_bytes) tex_count += 1 glTexCoord2f(0.0, 0.0) glBegin(GL_QUADS) glVertex2f(0.0, 0.0) glVertex2f(1.0, 0.0) glVertex2f(1.0, 1.0) glVertex2f(0.0, 1.0) glEnd() glFinish() residences = glAreTexturesResident(tex_names[:tex_count]) all_tex_in = reduce(lambda a, b: a and b, residences) # bruce 070308 sees this exception from this line: # TypeError: reduce() arg 2 must support iteration glDisable(GL_TEXTURE_2D) glDeleteTextures(tex_names) gl_info_string += "Could create %d 512x512 RGBA resident textures\n" \ % tex_count return gl_info_string
def bind_texture(self, clamp=False, use_mipmaps=True, decal=False, pixmap=False): """ bind our texture, and set texture-related GL params as specified. Anything that calls this should eventually call self.kluge_reset_texture_mode_to_work_around_renderText_bug(), but only after all drawing using the texture is done. """ # Notes [some of this belongs in docstring]: #e - we might want to pass these tex params as one chunk, or a flags word #e - we might want to optim for when they don't change # - most of them have default values like the old code had implicitly, but not pixmap, which old code had as implicitly true # - pixmap is misnamed, it doesn't use the pixmap ops, tho we might like to use those from the same image data someday have_mipmaps, tex_name = self.loaded_texture_data ## texture_helpers.setup_to_draw_texture_name(have_mipmaps, tex_name) # let's inline that instead, including its call of _initTextureEnv, and then modify it [061126] glBindTexture(GL_TEXTURE_2D, tex_name) # modified from _initTextureEnv(have_mipmaps) in texture_helpers.py if clamp: glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP) else: glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) if not pixmap: glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) if have_mipmaps and use_mipmaps: glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR) else: glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) else: glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) if decal: glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL) else: # see red book p410-411 -- can use GL_DECAL, GL_REPLACE, GL_MODULATE, GL_BLEND, GL_ADD, GL_COMBINE. # (Except that I can't import GL_COMBINE (iMac G5) so maybe it's not always available.) # GL_DECAL leaves fragment alpha unchanged and uses texture alpha to mix its color with fragment color # (fragment data comes from the polygon's alpha & color as if drawn untextured). # GL_REPLACE just discards fragment data in favor of texture data incl alpha -- that would be a better default. # [later 070404: now it is the default.] # Eventually permit all these values -- for now just let decal = False mean GL_REPLACE. [070403] # ## print "getTextureData", self, self._image.getTextureData() # presence of correct alpha is plausible from this # (in testexpr_11pd2). By itself, it does make a difference (alpha 0 places are black in testexpr_11pd2, not blue # (probably a leaked color) like in testexpr_11pd1), but self.blend is also needed to make it translucent. glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE) return
def update_planar_textures(self, x, y, width, height, img, pixel_format, scaling=False): assert self.textures is not None, "no OpenGL textures!" log("%s.update_planar_textures%s", self, (x, y, width, height, img, pixel_format)) divs = get_subsampling_divs(pixel_format) if self.pixel_format is None or self.pixel_format != pixel_format or self.texture_size != ( width, height): self.pixel_format = pixel_format self.texture_size = (width, height) self.gl_marker("Creating new planar textures, pixel format %s" % pixel_format) # Create textures of the same size as the window's glEnable(GL_TEXTURE_RECTANGLE_ARB) for texture, index in ((GL_TEXTURE0, 0), (GL_TEXTURE1, 1), (GL_TEXTURE2, 2)): (div_w, div_h) = divs[index] glActiveTexture(texture) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[index]) glEnable(GL_TEXTURE_RECTANGLE_ARB) mag_filter = GL_NEAREST if scaling or (div_w > 1 or div_h > 1): mag_filter = GL_LINEAR glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, mag_filter) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0) glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_LUMINANCE, width / div_w, height / div_h, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, None) self.gl_marker("updating planar textures: %sx%s %s" % (width, height, pixel_format)) rowstrides = img.get_rowstride() img_data = img.get_pixels() assert len(rowstrides) == 3 and len(img_data) == 3 for texture, index in ((GL_TEXTURE0, 0), (GL_TEXTURE1, 1), (GL_TEXTURE2, 2)): (div_w, div_h) = divs[index] glActiveTexture(texture) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[index]) glPixelStorei(GL_UNPACK_ROW_LENGTH, rowstrides[index]) pixel_data = img_data[index] log("texture %s: div=%s, rowstride=%s, %sx%s, data=%s bytes", index, divs[index], rowstrides[index], width / div_w, height / div_h, len(pixel_data)) glTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, 0, 0, width / div_w, height / div_h, GL_LUMINANCE, GL_UNSIGNED_BYTE, pixel_data)
def gl_init(self): drawable = self.gl_begin() w, h = self.size debug("GL Pixmap backing size: %d x %d, drawable=%s", w, h, drawable) if not drawable: return None if not self.gl_setup: # Ask GL to send us all debug messages if GL_DEBUG_OUTPUT and gl_debug_callback and glInitDebugKHR() == True: glEnable(GL_DEBUG_OUTPUT) glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS) glDebugMessageCallback(gl_debug_callback, None) glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, None, GL_TRUE) # Initialize string_marker GL debugging extension if available if glInitStringMarkerGREMEDY and glInitStringMarkerGREMEDY() == True: log.info("Extension GL_GREMEDY_string_marker available. Will output detailed information about each frame.") else: # General case - running without debugger, extension not available glStringMarkerGREMEDY = None # Initialize frame_terminator GL debugging extension if available if glInitFrameTerminatorGREMEDY and glInitFrameTerminatorGREMEDY() == True: glFrameTerminatorGREMEDY = None self.gl_marker("Initializing GL context for window size %d x %d" % (w, h)) # Initialize viewport and matrices for 2D rendering glViewport(0, 0, w, h) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0.0, w, h, 0.0, -1.0, 1.0) glMatrixMode(GL_MODELVIEW) #TODO glEnableClientState(GL_VERTEX_ARRAY) #TODO glEnableClientState(GL_TEXTURE_COORD_ARRAY) # Clear to white glClearColor(1.0, 1.0, 1.0, 1.0) # Default state is good for YUV painting: # - fragment program enabled # - render to offscreen FBO glEnable(GL_FRAGMENT_PROGRAM_ARB) if self.textures is None: self.textures = glGenTextures(5) debug("textures for wid=%s of size %s : %s", self.wid, self.size, self.textures) if self.offscreen_fbo is None: self.offscreen_fbo = glGenFramebuffers(1) # Define empty FBO texture and set rendering to FBO glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO]) glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGB, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0) glBindFramebuffer(GL_FRAMEBUFFER, self.offscreen_fbo) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO], 0) glClear(GL_COLOR_BUFFER_BIT) self.gl_setup = True return drawable
def gl_init(self): drawable = self.gl_begin() w, h = self.size debug("%s.gl_init() GL Pixmap backing size: %d x %d, drawable=%s", self, w, h, drawable) if not drawable: return None if not self.debug_setup: self.debug_setup = True self.gl_init_debug() if not self.gl_setup: self.gl_marker("Initializing GL context for window size %d x %d" % (w, h)) # Initialize viewport and matrices for 2D rendering glViewport(0, 0, w, h) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0.0, w, h, 0.0, -1.0, 1.0) glMatrixMode(GL_MODELVIEW) # Could be more optimal to use vertex arrays: # glEnableClientState(GL_VERTEX_ARRAY) # glEnableClientState(GL_TEXTURE_COORD_ARRAY) # Clear background to transparent black glClearColor(0.0, 0.0, 0.0, 0.0) # Default state is good for YUV painting: # - fragment program enabled # - YUV fragment program bound # - render to offscreen FBO if self.textures is None: self.gl_init_textures() # Define empty FBO texture and set rendering to FBO glEnable(GL_FRAGMENT_PROGRAM_ARB) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO]) # nvidia needs this even though we don't use mipmaps (repeated through this file): glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0) glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, self.texture_pixel_format, w, h, 0, self.texture_pixel_format, GL_UNSIGNED_BYTE, None) glBindFramebuffer(GL_FRAMEBUFFER, self.offscreen_fbo) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO], 0) glClear(GL_COLOR_BUFFER_BIT) # Create and assign fragment programs if not self.shaders: self.gl_init_shaders() # Bind program 0 for YUV painting by default glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.shaders[YUV2RGB_SHADER]) self.gl_setup = True return drawable
def _draw_jig(self, glpane, color, highlighted=False): """ Draw a ESP Image jig as a plane with an edge and a bounding box. """ glPushMatrix() glTranslatef(self.center[0], self.center[1], self.center[2]) q = self.quat glRotatef(q.angle * 180.0 / math.pi, q.x, q.y, q.z) #bruce 060207 extensively revised texture code re fixing bug 1059 if self.tex_name is not None and self.image_obj: # self.image_obj condition is needed, for clear_esp_image() to work textureReady = True glBindTexture( GL_TEXTURE_2D, self.tex_name ) # maybe this belongs in draw_plane instead? Put it there later. ##e self._initTextureEnv() # sets texture params the way we want them else: textureReady = False drawPlane(self.fill_color, self.width, self.width, textureReady, self.opacity, SOLID=True, pickCheckOnly=self.pickCheckOnly) hw = self.width / 2.0 corners_pos = [ V(-hw, hw, 0.0), V(-hw, -hw, 0.0), V(hw, -hw, 0.0), V(hw, hw, 0.0) ] drawLineLoop(color, corners_pos) # Draw the ESP Image bbox. if self.show_esp_bbox: wo = self.image_offset eo = self.edge_offset drawwirecube(color, V(0.0, 0.0, 0.0), V(hw + eo, hw + eo, wo), 1.0) #drawwirebox # This is for debugging purposes. This draws a green normal vector using # local space coords. Mark 050930 if 0: from graphics.drawing.CS_draw_primitives import drawline drawline(green, V(0.0, 0.0, 0.0), V(0.0, 0.0, 1.0), 0, 3) glPopMatrix() # This is for debugging purposes. This draws a yellow normal vector using # model space coords. Mark 050930 if 0: from graphics.drawing.CS_draw_primitives import drawline from utilities.constants import yellow drawline(yellow, self.center, self.center + self.planeNorm, 0, 3)
def draw(self): """Binds the vao, binds the texture, draws the vertices.""" glBindVertexArray(self.vao) glBindTexture(GL_TEXTURE_2D, self.tex) if self.mat is not None: self.mat.bind(self.shader) glDrawArrays(self.shape, 0, self.leng) glBindTexture(GL_TEXTURE_2D, 0) glBindVertexArray(0)
def __init__(self): self._texId = glGenTextures(1) self._width = None self._height = None # Bind an ID for this texture glBindTexture(GL_TEXTURE_2D, self._texId) # Use bilinear filtering if the texture has to be scaled glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
def do_paint_rgb(self, rgb_format, img_data, x, y, width, height, rowstride, options, callbacks): log("%s.do_paint_rgb(%s, %s bytes, x=%d, y=%d, width=%d, height=%d, rowstride=%d, options=%s)", self, rgb_format, len(img_data), x, y, width, height, rowstride, options) context = self.gl_context() if not context: log("%s._do_paint_rgb(..) no context!", self) fire_paint_callbacks(callbacks, False, "no opengl context") return if not options.get("paint", True): fire_paint_callbacks(callbacks) return try: upload, img_data = self.pixels_for_upload(img_data) with context: self.gl_init() self.set_rgb_paint_state() #convert it to a GL constant: pformat = PIXEL_FORMAT_TO_CONSTANT.get(rgb_format.decode()) assert pformat is not None, "could not find pixel format for %s" % rgb_format self.gl_marker("%s update at (%d,%d) size %dx%d (%s bytes), using GL %s format=%s", rgb_format, x, y, width, height, len(img_data), upload, CONSTANT_TO_PIXEL_FORMAT.get(pformat)) # Upload data as temporary RGB texture glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_RGB]) self.set_alignment(width, rowstride, rgb_format) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST) set_texture_level() glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER) glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, self.texture_pixel_format, width, height, 0, pformat, GL_UNSIGNED_BYTE, img_data) # Draw textured RGB quad at the right coordinates glBegin(GL_QUADS) glTexCoord2i(0, 0) glVertex2i(x, y) glTexCoord2i(0, height) glVertex2i(x, y+height) glTexCoord2i(width, height) glVertex2i(x+width, y+height) glTexCoord2i(width, 0) glVertex2i(x+width, y) glEnd() self.paint_box(options.get("encoding"), options.get("delta", -1)>=0, x, y, width, height) # Present update to screen self.present_fbo(x, y, width, height, options.get("flush", 0)) # present_fbo has reset state already fire_paint_callbacks(callbacks) except Exception as e: log("Error in %s paint of %i bytes, options=%s)", rgb_format, len(img_data), options) fire_paint_callbacks(callbacks, False, "OpenGL %s paint error: %s" % (rgb_format, e))
def gl_init(self): drawable = self.gl_begin() w, h = self.size log("%s.gl_init() GL Pixmap backing size: %d x %d, drawable=%s", self, w, h, drawable) if not drawable: return None if not self.debug_setup: self.debug_setup = True self.gl_init_debug() if not self.gl_setup: self.gl_marker("Initializing GL context for window size %d x %d" % (w, h)) # Initialize viewport and matrices for 2D rendering glViewport(0, 0, w, h) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0.0, w, h, 0.0, -1.0, 1.0) glMatrixMode(GL_MODELVIEW) # Could be more optimal to use vertex arrays: # glEnableClientState(GL_VERTEX_ARRAY) # glEnableClientState(GL_TEXTURE_COORD_ARRAY) # Clear background to transparent black glClearColor(0.0, 0.0, 0.0, 0.0) # we don't use the depth (2D only): glDisable(GL_DEPTH_TEST) # only do alpha blending in present_fbo: glDisable(GL_BLEND) # Default state is good for YUV painting: # - fragment program enabled # - YUV fragment program bound # - render to offscreen FBO if self.textures is None: self.gl_init_textures() # Define empty FBO texture and set rendering to FBO glEnable(GL_FRAGMENT_PROGRAM_ARB) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO]) # nvidia needs this even though we don't use mipmaps (repeated through this file): glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0) glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, self.texture_pixel_format, w, h, 0, self.texture_pixel_format, GL_UNSIGNED_BYTE, None) glBindFramebuffer(GL_FRAMEBUFFER, self.offscreen_fbo) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO], 0) glClear(GL_COLOR_BUFFER_BIT) # Create and assign fragment programs if not self.shaders: self.gl_init_shaders() # Bind program 0 for YUV painting by default glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.shaders[YUV2RGB_SHADER]) self.gl_setup = True return drawable
def _draw_jig(self, glpane, color, highlighted = False): """ Draw an ESPImage jig (self) as a plane with an edge and a bounding box. @note: this is not called during graphicsMode.Draw_model as with most Jigs, but during graphicsMode.Draw_after_highlighting. """ glPushMatrix() glTranslatef( self.center[0], self.center[1], self.center[2]) q = self.quat glRotatef( q.angle*180.0/math.pi, q.x, q.y, q.z) #bruce 060207 extensively revised texture code re fixing bug 1059 if self.tex_name is not None and self.image_obj: # self.image_obj cond is needed, for clear_esp_image() to work textureReady = True glBindTexture(GL_TEXTURE_2D, self.tex_name) # review: maybe this belongs in draw_plane instead? self._initTextureEnv() # sets texture params the way we want them else: textureReady = False drawPlane(self.fill_color, self.width, self.width, textureReady, self.opacity, SOLID = True, pickCheckOnly = self.pickCheckOnly ) hw = self.width/2.0 corners_pos = [V(-hw, hw, 0.0), V(-hw, -hw, 0.0), V( hw, -hw, 0.0), V( hw, hw, 0.0)] drawLineLoop(color, corners_pos) # Draw the ESP Image bbox. if self.show_esp_bbox: wo = self.image_offset eo = self.edge_offset drawwirecube(color, V(0.0, 0.0, 0.0), V(hw + eo, hw + eo, wo), 1.0) #drawwirebox # This is for debugging purposes. This draws a green normal vector # using local space coords. [Mark 050930] if 0: from graphics.drawing.CS_draw_primitives import drawline drawline(green, V(0.0, 0.0, 0.0), V(0.0, 0.0, 1.0), 0, 3) glpane.kluge_reset_texture_mode_to_work_around_renderText_bug() glPopMatrix() # This is for debugging purposes. This draws a yellow normal vector # using model space coords. [Mark 050930] if 0: from graphics.drawing.CS_draw_primitives import drawline from utilities.constants import yellow drawline(yellow, self.center, self.center + self.planeNorm, 0, 3)
def gl_init(self): #must be called within a context! #performs init if needed if not self.debug_setup: self.debug_setup = True self.gl_init_debug() if not self.gl_setup: w, h = self.size self.gl_marker("Initializing GL context for window size %d x %d", w, h) # Initialize viewport and matrices for 2D rendering glViewport(0, 0, w, h) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0.0, w, h, 0.0, -1.0, 1.0) glMatrixMode(GL_MODELVIEW) # Mesa docs claim: this hint can improve the speed of texturing #when perspective-correct texture coordinate interpolation isn't needed, #such as when using a glOrtho() projection: glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST) # Could be more optimal to use vertex arrays: # glEnableClientState(GL_VERTEX_ARRAY) # glEnableClientState(GL_TEXTURE_COORD_ARRAY) # Clear background to transparent black glClearColor(0.0, 0.0, 0.0, 0.0) # we don't use the depth (2D only): glDisable(GL_DEPTH_TEST) # only do alpha blending in present_fbo: glDisable(GL_BLEND) # Default state is good for YUV painting: # - fragment program enabled # - YUV fragment program bound # - render to offscreen FBO if self.textures is None: self.gl_init_textures() # Define empty FBO texture and set rendering to FBO glEnable(GL_FRAGMENT_PROGRAM_ARB) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO]) # nvidia needs this even though we don't use mipmaps (repeated through this file): glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0) glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, self.texture_pixel_format, w, h, 0, self.texture_pixel_format, GL_UNSIGNED_BYTE, None) glBindFramebuffer(GL_FRAMEBUFFER, self.offscreen_fbo) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO], 0) glClear(GL_COLOR_BUFFER_BIT) # Create and assign fragment programs if not self.shaders: self.gl_init_shaders() # Bind program 0 for YUV painting by default glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.shaders[YUV2RGB_SHADER]) self.gl_setup = True
def update_texture_yuv(self, img_data, x, y, width, height, rowstrides, pixel_format): assert x==0 and y==0 assert self.textures is not None, "no OpenGL textures!" if self.pixel_format is None or self.pixel_format!=pixel_format or self.texture_size!=(width, height): self.pixel_format = pixel_format self.texture_size = (width, height) divs = get_subsampling_divs(pixel_format) debug("GL creating new YUV textures for pixel format %s using divs=%s", pixel_format, divs) self.gl_marker("Creating new YUV textures") # Create textures of the same size as the window's glEnable(GL_TEXTURE_RECTANGLE_ARB) for texture, index in ((GL_TEXTURE0, 0), (GL_TEXTURE1, 1), (GL_TEXTURE2, 2)): (div_w, div_h) = divs[index] glActiveTexture(texture) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[index]) glEnable(GL_TEXTURE_RECTANGLE_ARB) mag_filter = GL_NEAREST if div_w > 1 or div_h > 1: mag_filter = GL_LINEAR glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, mag_filter) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_LUMINANCE, width/div_w, height/div_h, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, 0) debug("Assigning fragment program") glEnable(GL_FRAGMENT_PROGRAM_ARB) if not self.yuv_shader: self.yuv_shader = [ 1 ] glGenProgramsARB(1, self.yuv_shader) glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.yuv_shader[0]) prog = GL_COLORSPACE_CONVERSIONS glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, len(prog), prog) err = glGetString(GL_PROGRAM_ERROR_STRING_ARB) if err: #FIXME: maybe we should do something else here? log.error(err) self.gl_marker("Updating YUV textures") divs = get_subsampling_divs(pixel_format) U_width = 0 U_height = 0 for texture, index in ((GL_TEXTURE0, 0), (GL_TEXTURE1, 1), (GL_TEXTURE2, 2)): (div_w, div_h) = divs[index] glActiveTexture(texture) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[index]) glPixelStorei(GL_UNPACK_ROW_LENGTH, rowstrides[index]) glTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, x, y, width/div_w, height/div_h, GL_LUMINANCE, GL_UNSIGNED_BYTE, img_data[index]) if index == 1: U_width = width/div_w U_height = height/div_h elif index == 2: if width/div_w != U_width: log.error("Width of V plane is %d, differs from width of corresponding U plane (%d), pixel_format is %d", width/div_w, U_width, pixel_format) if height/div_h != U_height: log.error("Height of V plane is %d, differs from height of corresponding U plane (%d)", height/div_h, U_height)
def bind_texture(self, i): """Rebind texture for current program and shaders.""" dimensions = self.__textures[i] if dimensions == 1: texture_type = GL_TEXTURE_1D elif dimensions == 2: texture_type = GL_TEXTURE_2D elif dimensions == 3: texture_type = GL_TEXTURE_3D glBindTexture(texture_type, self.__textures_ids[i])
def _update_texture(self, w, h, pixels): print("update_texture id=%s" % self.drawing_area.texture_id) if self.drawing_area.texture_id is not None: glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.drawing_area.texture_id) glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGB, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, pixels) glPixelStorei(GL_UNPACK_ALIGNMENT, 1) glTexParameterf(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameterf(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
def main(path=None): glutInit(sys.argv) if sys.platform == 'darwin': if not path: path = dialog() if not path: sys.exit(0) glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE) glutInitWindowPosition(0, 0) glutInitWindowSize(730, 650) win = glutCreateWindow(b'MIDI Player') (width, height, img) = read_image(join(dirname(__file__), 'mixer.ppm')) glPixelStorei(GL_UNPACK_ALIGNMENT, 1) texture = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, texture) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, img) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glMatrixMode(GL_TEXTURE) glLoadIdentity() glScale(1 / width, 1 / height, 1) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0, 730, 0, 650, 0, 1) player = Player(win, path, width, height) glutDisplayFunc(player.display_func) glutKeyboardFunc(player.keyboard_func) glutMouseFunc(player.mouse_func) glutMotionFunc(player.motion_func) glutIdleFunc(player.process_events) submenus = [] for instrument in range(128): if instrument % 8 == 0: submenus.append([ families[instrument // 8], glutCreateMenu(player.change_instrument) ]) glutAddMenuEntry(instruments[instrument].encode('ascii'), instrument) glutCreateMenu(player.change_instrument) for family, submenu in submenus: glutAddSubMenu(family.encode('ascii'), submenu) glutAttachMenu(GLUT_RIGHT_BUTTON) glutMainLoop()
def finalizar_renderizado(self): """Renderiza la textura final, obtenida en el framebuffer.""" # Desactivar el framebuffer no_usar_fbos() # Activar la textura glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, self.fbos[0].textura) # Renderiza la imagen principal self.shader.usar() if self.shader else None self.renderizar_cuad(0., 0., self.tam[0], self.tam[1]) no_usar_shaders() if self.shader else None
def _set_texture(self, name, value): from OpenGL.GL import glActiveTexture, glBindTexture, glUniform1i, \ GL_TEXTURE0, GL_TEXTURE_2D gl_texture_unit = self._assign_texture(name) glActiveTexture(GL_TEXTURE0 + gl_texture_unit) glBindTexture(GL_TEXTURE_2D, value._gl_handle) glUniform1i(self._uniform_handles.get(name), gl_texture_unit) # it seems that this unit should be activated before using # the framebuffer glActiveTexture(GL_TEXTURE0)
def finalizar_renderizado(self): """Renderiza la textura final, obtenida en el framebuffer 0.""" self.renderizar_por_pasos(True, (0, self.shader_h, self.fbos[0], self.fbos[1]), (1, self.shader_v, self.fbos[1], None)) # Pequeño render lateral sin usar el programa (textura del framebuffer) glActiveTexture(GL_TEXTURE0) self.renderizar_cuad(self.ventana[0]-160, 0., self.ventana[0], 120.) glBindTexture(GL_TEXTURE_2D, self.fbos[1].textura) self.renderizar_cuad(self.ventana[0]-160, 130., self.ventana[0], 250.)
def bind_texture(self, clamp = False, use_mipmaps = True, decal = False, pixmap = False): """ bind our texture, and set texture-related GL params as specified. Anything that calls this should eventually call self.kluge_reset_texture_mode_to_work_around_renderText_bug(), but only after all drawing using the texture is done. """ # Notes [some of this belongs in docstring]: #e - we might want to pass these tex params as one chunk, or a flags word #e - we might want to optim for when they don't change # - most of them have default values like the old code had implicitly, but not pixmap, which old code had as implicitly true # - pixmap is misnamed, it doesn't use the pixmap ops, tho we might like to use those from the same image data someday have_mipmaps, tex_name = self.loaded_texture_data ## texture_helpers.setup_to_draw_texture_name(have_mipmaps, tex_name) # let's inline that instead, including its call of _initTextureEnv, and then modify it [061126] glBindTexture(GL_TEXTURE_2D, tex_name) # modified from _initTextureEnv(have_mipmaps) in texture_helpers.py if clamp: glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP) else: glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) if not pixmap: glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) if have_mipmaps and use_mipmaps: glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR) else: glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) else: glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) if decal: glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL) else: # see red book p410-411 -- can use GL_DECAL, GL_REPLACE, GL_MODULATE, GL_BLEND, GL_ADD, GL_COMBINE. # (Except that I can't import GL_COMBINE (iMac G5) so maybe it's not always available.) # GL_DECAL leaves fragment alpha unchanged and uses texture alpha to mix its color with fragment color # (fragment data comes from the polygon's alpha & color as if drawn untextured). # GL_REPLACE just discards fragment data in favor of texture data incl alpha -- that would be a better default. # [later 070404: now it is the default.] # Eventually permit all these values -- for now just let decal = False mean GL_REPLACE. [070403] # ## print "getTextureData", self, self._image.getTextureData() # presence of correct alpha is plausible from this # (in testexpr_11pd2). By itself, it does make a difference (alpha 0 places are black in testexpr_11pd2, not blue # (probably a leaked color) like in testexpr_11pd1), but self.blend is also needed to make it translucent. glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE) return
def use(self, tex_unit): """Makes the given texture as active in the rendering pipeline. :param tex_unit: OpenGL texture image unit to make active. :type tex_unit: int """ self.tex_unit = tex_unit glActiveTexture(GL_TEXTURE0 + self.tex_unit) glBindTexture(self.tex_type, self.tex_id) glBindSampler(self.tex_unit, self.sampler) yield glBindTexture(self.tex_type, 0)
def main(path=None): glutInit(sys.argv) if sys.platform == 'darwin': if not path: path = dialog() if not path: sys.exit(0) glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE) glutInitWindowPosition(0, 0) glutInitWindowSize(730, 650) win = glutCreateWindow(b'MIDI Player') (width, height, img) = read_image(join(dirname(__file__), 'mixer.ppm')) glPixelStorei(GL_UNPACK_ALIGNMENT, 1) texture = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, texture) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, img) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glMatrixMode(GL_TEXTURE) glLoadIdentity() glScale(1/width, 1/height, 1) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0, 730, 0, 650, 0, 1) player = Player(win, path, width, height) glutDisplayFunc(player.display_func) glutKeyboardFunc(player.keyboard_func) glutMouseFunc(player.mouse_func) glutMotionFunc(player.motion_func) glutIdleFunc(player.process_events) submenus = [] for instrument in range(128): if instrument % 8 == 0: submenus.append([families[instrument // 8], glutCreateMenu(player.change_instrument)]) glutAddMenuEntry(instruments[instrument].encode('ascii'), instrument) glutCreateMenu(player.change_instrument) for family, submenu in submenus: glutAddSubMenu(family.encode('ascii'), submenu) glutAttachMenu(GLUT_RIGHT_BUTTON) glutMainLoop()
def _do_paint_rgb24(self, img_data, x, y, width, height, rowstride, options, callbacks): debug("%s._do_paint_rgb24(x=%d, y=%d, width=%d, height=%d, rowstride=%d)", self, x, y, width, height, rowstride) drawable = self.gl_init() if not drawable: debug("%s._do_paint_rgb24(..) drawable is not set!", self) return False try: self.set_rgb24_paint_state() # Compute alignment and row length row_length = 0 alignment = 1 for a in [2, 4, 8]: # Check if we are a-aligned - ! (var & 0x1) means 2-aligned or better, 0x3 - 4-aligned and so on if (rowstride & a-1) == 0: alignment = a # If number of extra bytes is greater than the alignment value, # then we also have to set row_length # Otherwise it remains at 0 (= width implicitely) if (rowstride - width * 3) > a: row_length = width + (rowstride - width * 3) / 3 self.gl_marker("RGB24 update at %d,%d, size %d,%d, stride is %d, row length %d, alignment %d" % (x, y, width, height, rowstride, row_length, alignment)) # Upload data as temporary RGB texture glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_RGB]) glPixelStorei(GL_UNPACK_ROW_LENGTH, row_length) glPixelStorei(GL_UNPACK_ALIGNMENT, alignment) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0) glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, 4, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, img_data) # Draw textured RGB quad at the right coordinates glBegin(GL_QUADS) glTexCoord2i(0, 0) glVertex2i(x, y) glTexCoord2i(0, height) glVertex2i(x, y+height) glTexCoord2i(width, height) glVertex2i(x+width, y+height) glTexCoord2i(width, 0) glVertex2i(x+width, y) glEnd() # Present update to screen self.present_fbo(drawable) # present_fbo has reset state already finally: drawable.gl_end() return True
def __init__(self, w, h, format=GL_RGBA, internalFormat=None): self._id = glGenTextures(1); self._w = w self._h = h if internalFormat is None: internalFormat = format # crashes _sometimes_ when self._w * self._h > 888*888 glBindTexture(GL_TEXTURE_2D, self._id); glTexImage2D(GL_TEXTURE_2D, 0, format, self._w, self._h, 0, internalFormat, GL_UNSIGNED_BYTE, None); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glBindTexture(GL_TEXTURE_2D, 0);
def update_texture_yuv(self, img_data, x, y, width, height, rowstrides, pixel_format): window_width, window_height = self.size assert self.textures is not None, "no OpenGL textures!" if self.pixel_format is None or self.pixel_format!=pixel_format: self.pixel_format = pixel_format divs = self.get_subsampling_divs(pixel_format) log("GL creating new YUV textures for pixel format %s using divs=%s", pixel_format, divs) # Create textures of the same size as the window's glEnable(GL_TEXTURE_RECTANGLE_ARB) for texture, index in ((GL_TEXTURE0, 0), (GL_TEXTURE1, 1), (GL_TEXTURE2, 2)): div = divs[index] glActiveTexture(texture) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[index]) glEnable(GL_TEXTURE_RECTANGLE_ARB) mag_filter = GL_NEAREST if div>1: mag_filter = GL_LINEAR glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, mag_filter) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_LUMINANCE, window_width/div, window_height/div, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, 0) log("Assigning fragment program") glEnable(GL_FRAGMENT_PROGRAM_ARB) if not self.yuv_shader: self.yuv_shader = [ 1 ] glGenProgramsARB(1, self.yuv_shader) glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.yuv_shader[0]) prog = GL_COLORSPACE_CONVERSIONS glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, len(prog), prog) err = glGetString(GL_PROGRAM_ERROR_STRING_ARB) if err: #FIXME: maybe we should do something else here? log.error(err) glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.yuv_shader[0]) # Clamp width and height to the actual texture size if x + width > window_width: width = window_width - x if y + height > window_height: height = window_height - y divs = self.get_subsampling_divs(pixel_format) for texture, index in ((GL_TEXTURE0, 0), (GL_TEXTURE1, 1), (GL_TEXTURE2, 2)): div = divs[index] glActiveTexture(texture) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[index]) glPixelStorei(GL_UNPACK_ROW_LENGTH, rowstrides[index]) glTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, x, y, width/div, height/div, GL_LUMINANCE, GL_UNSIGNED_BYTE, img_data[index]) glFlush()