def __initiate_textures(self, number_of_textures): """Generate textures.""" if number_of_textures == 1: self.__textures_ids = [glGenTextures(1)] elif number_of_textures > 1: self.__textures_ids = glGenTextures(number_of_textures) self.__textures = []
def gl_init_textures(self): assert self.offscreen_fbo is None assert self.shaders is None self.textures = glGenTextures(N_TEXTURES) self.offscreen_fbo = glGenFramebuffers(1) self.tmp_fbo = glGenFramebuffers(1) log("%s.gl_init_textures() textures: %s, offscreen fbo: %s, tmp fbo: %s", self, self.textures, self.offscreen_fbo, self.tmp_fbo)
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 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 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 __init__(self, textureData, pos, size, histogramScale, layer, shouldDelayAllocation=False): ## Array of pixel brightnesses self.textureData = textureData ## XYZ position tuple, in microns. NB the Z portion is ignored # for rendering purposes and is mostly just kept around so we know # the Z altitude at which the tile was collected, for later use. self.pos = pos ## width/height tuple, in microns self.size = size ## Box describing space we occupy: (upper left corner, lower right corner) self.box = (self.pos[:2], (self.pos[0] + self.size[0], self.pos[1] + self.size[1])) ## Grouping this tile belongs to, used to toggle display self.layer = layer ## OpenGL texture ID self.texture = glGenTextures(1) self.scaleHistogram(histogramScale[0], histogramScale[1]) # Indicate refresh required after scaling histogram. self.shouldRefresh = False if not shouldDelayAllocation: self.bindTexture() self.refresh()
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 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 gl_init_textures(self): assert self.offscreen_fbo is None assert self.shaders is None self.textures = glGenTextures(6) self.offscreen_fbo = self._gen_fbo() self.tmp_fbo = self._gen_fbo() log("%s.gl_init_textures() textures: %s, offscreen fbo: %s, tmp fbo: %s", self, self.textures, self.offscreen_fbo, self.tmp_fbo)
def parse_mtl(filename): contents = {} mtl = None for line in open(filename, "r"): if line.startswith('#'): continue values = line.split() if not values: continue if values[0] == 'newmtl': mtl = contents[values[1]] = {} elif mtl is None: raise ValueError("mtl file doesn't start with newmtl stmt") elif values[0] == 'map_Kd': # load the texture referred to by this declaration mtl[values[0]] = values[1] surf_file = mtl['map_Kd'] if surf_file.endswith('.tga'): TGA_Header surf = pygame.image.load() image = pygame.image.tostring(surf, 'RGBA', 1) ix, iy = surf.get_rect().size texid = mtl['texture_Kd'] = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, texid) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, ix, iy, 0, GL_RGBA, GL_UNSIGNED_BYTE, image) else: mtl[values[0]] = list(map(float, values[1:])) return contents
def _setup_texture(self, context_id: str): """Set up the texture for a given context""" gl_texture = self._gl_textures[context_id] = glGenTextures( 1 ) # Create the texture location glBindTexture(GL_TEXTURE_2D, gl_texture) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) glBindTexture(GL_TEXTURE_2D, gl_texture) glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, self._image_width, self._image_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, self._image, ) glBindTexture(GL_TEXTURE_2D, 0) log.info("Finished setting up texture atlas in OpenGL")
def gl_init_textures(self): assert self.offscreen_fbo is None assert self.shaders is None self.textures = glGenTextures(5) self.offscreen_fbo = glGenFramebuffers(1) debug("%s.gl_init_textures() textures: %s, offscreen fbo: %s", self, self.textures, self.offscreen_fbo)
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 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_configure_event(self, event): ClientWindow.do_configure_event(self, event) drawable = self.glarea.get_gl_drawable() context = self.glarea.get_gl_context() self.yuv420_shader = None # Re-create textures self.current_mode = GLClientWindow.MODE_UNINITIALIZED if not drawable.gl_begin(context): raise Exception("** Cannot create OpenGL rendering context!") w, h = self.get_size() log("Configure widget size: %d x %d" % (w, h)) glViewport(0, 0, w, h) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0.0, w, h, 0.0, -1.0, 1.0) glMatrixMode(GL_MODELVIEW) glEnableClientState(GL_VERTEX_ARRAY) glEnableClientState(GL_TEXTURE_COORD_ARRAY) glDisable(GL_FRAGMENT_PROGRAM_ARB) if self.textures is None: self.textures = glGenTextures(3) drawable.gl_end()
def __init__(self, parent: wx.Window): display_attributes = wx.glcanvas.GLAttributes() display_attributes.PlatformDefaults().MinRGBA( 8, 8, 8, 8).DoubleBuffer().Depth(24).EndList() super().__init__( parent, display_attributes, size=parent.GetClientSize(), style=wx.WANTS_CHARS, ) if sys.platform == "linux": # setup the OpenGL context. This apparently fixes #84 self._context = glcanvas.GLContext(self) else: context_attributes = wx.glcanvas.GLContextAttrs() context_attributes.CoreProfile().OGLVersion( 3, 3).Robust().ResetIsolation().EndList() self._context = glcanvas.GLContext( self, ctxAttrs=context_attributes) # setup the OpenGL context self.SetCurrent(self._context) self._context_identifier = str( uuid.uuid4()) # create a UUID for the context. Used to get shaders self._gl_texture_atlas = glGenTextures( 1) # Create the atlas texture location self._setup_opengl() # set some OpenGL states
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 _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 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 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 __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 set_texture(m): texture_data = np.array(m.texture_image, dtype='int8') m.textureID = glGenTextures(1) glPixelStorei(GL_UNPACK_ALIGNMENT, 1) glBindTexture(GL_TEXTURE_2D, m.textureID) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, texture_data.shape[1], texture_data.shape[0], 0, GL_BGR, GL_UNSIGNED_BYTE, texture_data.flatten()) glHint(GL_GENERATE_MIPMAP_HINT, GL_NICEST) # must be GL_FASTEST, GL_NICEST or GL_DONT_CARE glGenerateMipmap(GL_TEXTURE_2D)
def gl_init_textures(self): assert self.offscreen_fbo is None assert self.shaders is None self.textures = glGenTextures(5) if hasattr(glGenFramebuffers, "pyConverters") and len(glGenFramebuffers.pyConverters)==1: #single argument syntax: self.offscreen_fbo = glGenFramebuffers(1) else: self.offscreen_fbo = c_uint(1) glGenFramebuffers(1, self.offscreen_fbo) log("%s.gl_init_textures() textures: %s, offscreen fbo: %s", self, self.textures, self.offscreen_fbo)
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 __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 make_texture( filename=None, image=None, interpolate=True, alpha=False, integer=False, maxlod=None): if image == None: image = pygame.image.load(filename) pixels = pygame.image.tostring(image, "RGBA" if alpha else "RGB", True) texture = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, texture) glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST if interpolate else GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) if maxlod is not None: glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_LOD, maxlod) if alpha: if integer: targetformat = GL_RGBA8UI sourceformat = GL_RGBA_INTEGER else: targetformat = GL_RGBA8 sourceformat = GL_RGBA else: if integer: targetformat = GL_RGB8UI sourceformat = GL_RGB_INTEGER else: targetformat = GL_RGB8 sourceformat = GL_RGB glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE) glTexImage2D( GL_TEXTURE_2D, 0, targetformat, image.get_width(), image.get_height(), 0, sourceformat, GL_UNSIGNED_BYTE, pixels) print glGetTexLevelParameteriv( GL_TEXTURE_2D, 0, GL_TEXTURE_INTERNAL_FORMAT) return texture
def __init__(self, vertex, fragment, number_of_buffers=0, number_of_textures=0): """Initialize program with shaders.""" self.__program = glCreateProgram() self.__current_shaders = {} self.__shaders = {GL_VERTEX_SHADER: [], GL_FRAGMENT_SHADER: []} self.__depth_map_fbo = None self.__attributes = [] if not isinstance(vertex, list): vertex = [vertex] for v in vertex: self.__load_shader(get_shader_path(v), GL_VERTEX_SHADER) if not isinstance(fragment, list): fragment = [fragment] for f in fragment: self.__load_shader(get_shader_path(f), GL_FRAGMENT_SHADER) self.change_shader(0, 0) glLinkProgram(self.__program) assert glGetProgramiv(self.__program, GL_LINK_STATUS) == GL_TRUE self.__vao_id = glGenVertexArrays(1) glBindVertexArray(self.__vao_id) if number_of_buffers == 1: self.__vbo_id = [glGenBuffers(number_of_buffers)] elif number_of_buffers > 1: self.__vbo_id = glGenBuffers(number_of_buffers) if number_of_textures == 1: self.__textures_ids = [glGenTextures(1)] elif number_of_textures > 1: self.__textures_ids = glGenTextures(number_of_textures) self.__textures = []
def paint_rgb24(self, img_data, x, y, width, height, rowstride): # OpenGL begin if not self.gldrawable.gl_begin(self.glcontext): log.error("OUCH") return False # Upload texture if not self.texture: self.texture = glGenTextures(1) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.texture) 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); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE) glPixelStorei(GL_UNPACK_ROW_LENGTH, rowstride/3) glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, img_data); vtxarrays=1 if vtxarrays == 1: texcoords = [ [ 0, 0 ], [ 0, height], [ width, height], [ width, 0] ] vtxcoords = texcoords glVertexPointeri(vtxcoords) glTexCoordPointeri(texcoords) glDrawArrays(GL_QUADS, 0, 4); else: glBegin(GL_QUADS); glTexCoord2i(0, 0); glVertex2i(0, 0); glTexCoord2i(0, height); glVertex2i(0, height); glTexCoord2i(width, height); glVertex2i(width, height); glTexCoord2i(width, 0); glVertex2i(width, 0); glEnd() # OpenGL end #self.gldrawable.swap_buffers() # self.gldrawable.swap_buffers() glFinish() self.gldrawable.gl_end()
def _C_tex_name(self): """ define self.tex_name -- allocate a texture name """ # code copied from texture_helpers.loadTexture (even though we call it, below, for its other code): tex_name = glGenTextures(1) if debug_glGenTextures and seen_before(('debug_glGenTextures', self.filename)): #070313 using env.seen_before (rename env module (cad/src) -> global_env? for now, basic imports seen_before via py_utils.) #k I'm not sure if, after certain reloads, I should expect to routinely see this message as textures get reloaded. 070313 print "debug fyi: same filename seen before, in glGenTextures -> %r for %r" % (tex_name, self) # 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] tex_name = int(tex_name) # make sure it worked as expected assert tex_name != 0 return tex_name
def config_texture(self): w, h = self.size pixels = "\0" * w * h * 4 # Create Texture print("glBindTexture(GL_TEXTURE_RECTANGLE_ARB) size=%s" % str(self.size)) self.texture_id = glGenTextures(1) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.texture_id) print("done") glPixelStorei(GL_UNPACK_ALIGNMENT, 1) glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGB, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, pixels) glTexParameterf(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameterf(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
def load_texture(cls, file_name): texture = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, texture) # Set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) # Set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) # load image image = Image.open(file_name) img_data = numpy.array(list(image.getdata()), numpy.uint8) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image.width, image.height, 0, GL_RGB, GL_UNSIGNED_BYTE, img_data) glEnable(GL_TEXTURE_2D) return texture
def gl_id(self): """Returns the OpenGL texture number corresponding to this texture in the current context. May trigger allocation of a new texture and a call to do_setup(). Does not bind the texture, unless a new texture is allocated, in which case the current texture binding may be changed as a side effect.""" share_group = current_share_group() gl_id = self._gl_id.get(share_group) if gl_id is None: gl_id = glGenTextures(1) # print "GLTexture: assigned id %d for %s in share group %s" % ( # gl_id, self, share_group) ### self._gl_id[share_group] = gl_id call_when_not_compiling_display_list(lambda: self._setup(gl_id)) return gl_id
def read_texture(filename): image_data = 0 is_hdr = False size = () if OpenEXR.isOpenExrFile(filename): is_hdr = True img = OpenEXR.InputFile(filename) FLOAT = Imath.PixelType(Imath.PixelType.FLOAT) (r, g, b) = ( img.channel(chan, FLOAT) for chan in ('R', 'G', 'B')) dw = img.header()['dataWindow'] size = (dw.max.x - dw.min.x + 1, dw.max.y - dw.min.y + 1) r_data = np.fromstring(r, dtype=np.float32) g_data = np.fromstring(g, dtype=np.float32) b_data = np.fromstring(b, dtype=np.float32) image_data = np.dstack((r_data, g_data, b_data)) img.close() else: try: image = Image.open(filename) except IOError as ex: print('IOError: failed to open texture file %s' % filename) return -1 print('opened file: size=', image.size, 'format=', image.format) image_data = np.array(list(image.getdata()), np.uint8) size = image.size image.close() texture_id= glGenTextures(1) glPixelStorei(GL_UNPACK_ALIGNMENT, 4) glBindTexture(GL_TEXTURE_2D, texture_id) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0) 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) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) if is_hdr: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, size[0], size[1], 0, GL_RGB, GL_FLOAT, image_data) else: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, size[0], size[1], 0, GL_RGB, GL_UNSIGNED_BYTE, image_data) return texture_id
def texturit(filn: str) -> int: """Import a Texture and return the texture buffer handle. Better by RGBA formatted, too.""" wa = glGenTextures(1) with Image.open(filn) as i: ix, iy, im = i.size[0], i.size[1], i.tobytes('raw', 'RGBA') glBindTexture(GL_TEXTURE_2D, wa) glTexParameter(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) glTexParameter(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) glTexParameter(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexParameter(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, ix, iy, 0, GL_RGBA, GL_UNSIGNED_BYTE, im) glGenerateMipmap(GL_TEXTURE_2D) glBindTexture(GL_TEXTURE_2D, 0) return wa
def create(self, width, height): self.texture = glGenTextures(1) glBindTexture(GL_TEXTURE_CUBE_MAP, self.texture) for i in range(6): glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_DEPTH_COMPONENT, width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, None) glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE)
def _create_texture(self): pixels = "\0" * 320 * 240 * 4 w = 320 h = 240 # Create Texture tex_id = glGenTextures(1) print("glBindTexture(GL_TEXTURE_RECTANGLE_ARB)") glBindTexture(GL_TEXTURE_RECTANGLE_ARB, tex_id) print("done") glPixelStorei(GL_UNPACK_ALIGNMENT, 1) glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGB, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, pixels) glTexParameterf(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameterf(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST) self.texture_id = tex_id
def __init__(self, resource_context: ResourceManager, asset_key: str): self._contents = {} current_mtl: dict = None file_data = resource_context.load('assets', asset_key) for line in file_data: line = line.decode("utf-8") # Convert bytes line to a string if line.startswith('#'): # Ignore comments in the file. continue values = line.split() if not values: # Ignore empty lines. continue attribute_name = values[0] if attribute_name == 'newmtl': # Create a new empty material. current_mtl = self._contents[values[1]] = {} elif current_mtl is None: raise ValueError("mtl file must start with newmtl statement") elif attribute_name == 'map_Kd': # Diffuse texture map - load the image into memory. image_name = values[1] image_file_data = resource_context.load('assets', image_name) with Image.open(image_file_data) as image: image_width, image_height = image.size image = image.convert("RGBA").tobytes("raw", "RGBA") # Bind the image as a texture that can be used for rendering. texture_id = glGenTextures(1) current_mtl['texture_Kd'] = texture_id # pylint: disable=unsupported-assignment-operation glBindTexture(GL_TEXTURE_2D, texture_id) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image_width, image_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image) else: # Store the values for this attribute as a list of float values. current_mtl[attribute_name] = list(map(float, values[1:])) # pylint: disable=unsupported-assignment-operation
def render_to_texture(self, text): """Renders the given string to a texture object. :param text: Text to render. :type text: str :returns: The resulting texture object. :rtype: :class:`renderer.Texture` """ # render the text to a SDL_Surface structure surf_ptr = ttf.TTF_RenderText_Solid( self.font, text.encode('utf8'), sdl.SDL_Color()) if not surf_ptr: raise SDLError('failed to render text to surface: {}'.format( ttf.TTF_GetError())) # retrieve a pointer to pixel data surf = surf_ptr.contents pixels = ctypes.cast(surf.pixels, ctypes.POINTER(ctypes.c_char)) # create and fill an OpenGL rectangle texture (that is, a texture which # can have arbitrary non-power-of-two size and is accessed using # UV coordinates which are linearly mapped to the texture size) tex = glGenTextures(1) glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, tex) glTexStorage2D(GL_TEXTURE_2D, 1, GL_R8, surf.w, surf.h) glTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, surf.w, surf.h, GL_RED, GL_UNSIGNED_BYTE, pixels) glBindTexture(GL_TEXTURE_2D, 0) sdl.SDL_FreeSurface(surf_ptr) return Texture(tex, surf.w, surf.h, GL_TEXTURE_2D)
def from_matrix(cls, matrix): """Creates a texture from given matrix file. :param matrix: The matrix. :type matrix: list :returns: The texture instance. :rtype: :class:`renderer.Texture` """ w, h = len(matrix[0]), len(matrix) grid = bytes(chain.from_iterable(reversed(matrix))) tex = glGenTextures(1) glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, tex) # This code is necessary to handle non-power-of-two textures with small # sizes. # TODO: refactor this param_ids = [ GL_UNPACK_ALIGNMENT, GL_UNPACK_ROW_LENGTH, GL_UNPACK_SKIP_ROWS, GL_UNPACK_SKIP_PIXELS, ] old_params = { p: glGetInteger(p) for p in param_ids } glPixelStorei(GL_UNPACK_ALIGNMENT, 1) glPixelStorei(GL_UNPACK_ROW_LENGTH, 0) glPixelStorei(GL_UNPACK_SKIP_ROWS, 0) glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0) glTexStorage2D(GL_TEXTURE_2D, 1, GL_R8, w, h) glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_RED, GL_UNSIGNED_BYTE, grid) for p, v in old_params.items(): glPixelStorei(p, v) glBindTexture(GL_TEXTURE_2D, 0) return Texture(tex, w, h, GL_TEXTURE_2D)
def from_image(cls, image): """Creates a texture from given image file. :param image: Image. :type image: :class:`PIL.Image` :returns: The texture instance. :rtype: :class:`renderer.Texture` """ w, h = image.size tex = glGenTextures(1) glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, tex) glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGB8, w, h) glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_RGB, GL_UNSIGNED_BYTE, image.tobytes()) glBindTexture(GL_TEXTURE_2D, 0) return Texture(tex, w, h)
def gl_init(self): drawable = self.gl_begin() w, h = self.size log("GL Pixmap backing size: %d x %d, drawable=%s", w, h, drawable) if not drawable: return None if not self.gl_setup: glViewport(0, 0, w, h) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0.0, w, h, 0.0, -1.0, 1.0) glMatrixMode(GL_MODELVIEW) glEnableClientState(GL_VERTEX_ARRAY) glEnableClientState(GL_TEXTURE_COORD_ARRAY) glDisable(GL_FRAGMENT_PROGRAM_ARB) if self.textures is None: self.textures = glGenTextures(3) self.gl_setup = True return drawable
def __init__(self, imagefile, points=[], alpha=1.0): super(ImageActor, self).__init__() im = Image.open(imagefile) # Try to open the image file try: ix, iy, image = im.size[0], im.size[1], im.tostring("raw", "RGBA", 0, -1) except SystemError: ix, iy, image = im.size[0], im.size[1], im.tostring("raw", "RGBX", 0, -1) # get a texture buffer glActiveTexture(GL_TEXTURE0) self.texid = glGenTextures(1) # Bind the texture glBindTexture(GL_TEXTURE_2D, self.texid) glPixelStorei(GL_UNPACK_ALIGNMENT,1) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) # Upload the image glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, ix, iy, 0, GL_RGBA, GL_UNSIGNED_BYTE, image) # Generate the points for the billboard if points == []: points = [Point(0,0), Point(ix,0), Point(ix,-iy), Point(0,-iy)] if len(points) != 4: raise Exception("Image needs 4 points, %d provided" % len(points)) # Generate the UV map uv = [Point(0,1), Point(1,1), Point(1,0), Point(0,0)] a = [] for i in [0,1,2,0,2,3]: point = points[i] tex = uv[i] a.extend([point.x, point.y, tex.x, tex.y]) # Assign the VBO super(ImageActor, self)._assignVBO(a) self.alpha = float(alpha)
def loadTexture(image_obj, tex_name = 0): #e arg want_mipmaps """ Load texture data from current image object; return have_mipmaps, tex_name (also leave that texture bound, BTW) """ # note: some of this code has been copied into exprs/images.py, class # texture_holder [bruce 061125] ix, iy, image = image_obj.getTextureData() # allocate texture object if necessary if not tex_name: tex_name = glGenTextures(1) # It's deprecated to let this happen much. [070308] print "debug fyi: texture_helpers.loadTexture allocated tex_name %r" %\ (tex_name,) # 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] tex_name = int(tex_name) # make sure it worked as expected assert tex_name != 0 # initialize texture data glBindTexture(GL_TEXTURE_2D, tex_name) # 2d texture (x and y size) glPixelStorei(GL_UNPACK_ALIGNMENT,1) ###k what's this? have_mipmaps = False ##want_mipmaps = debug_pref("smoother tiny textures", ## Choice_boolean_False, prefs_key = True) want_mipmaps = True if want_mipmaps: gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, ix, iy, GL_RGBA, GL_UNSIGNED_BYTE, image) 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] return have_mipmaps, tex_name
def load_texture(image): image = limit_pixels_count(image, args.pixels_limit) width, height = image.size image = image.tostring("raw", "RGBX", 0, -1) # Create Texture _id = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, _id) glPixelStorei(GL_UNPACK_ALIGNMENT, 1) glTexImage2D( GL_TEXTURE_2D, 0, 3, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image ) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL) return _id
def __init__(self, stack, spacing): s = np.array(stack, dtype=np.uint8, order='F') w, h, d = s.shape stack_texture = glGenTextures(1) 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) self.stack_texture = stack_texture self.shape = s.shape
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_extensions = glGetString(GL_EXTENSIONS) gl_extensions = gl_extensions.strip() gl_extensions = gl_extensions.replace(" ", "\n* ") gl_info_string += 'GL_EXTENSIONS : \n* %s\n' % gl_extensions if debug_pref("Graphics Card Info: 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 pass if True: ## or could be a debug_pref("Graphics Card Info: get all GL_MAX symbols?") #bruce 090314 new feature import OpenGL.GL symbols = [x for x in dir(OpenGL.GL) if x.startswith('GL_MAX_')] symbols.sort() gl_info_string += '\n' for symbol in symbols: try: numeric_symbol = getattr(OpenGL.GL, symbol) intval = glGetInteger(numeric_symbol) except: # this happens to most symbols, not sure why if debug_flags.atom_debug: print_compact_traceback( "%s = ??: " % symbol ) # overkill, only the exception itself matters # typical output (on Bruce's MacBookPro, 090314): ## GL_MAX_4D_TEXTURE_SIZE_SGIS = ??: ## <type 'exceptions.KeyError'>: ## ('Unknown specifier GL_MAX_4D_TEXTURE_SIZE_SGIS (33080)', ## 'Failure in cConverter <OpenGL.converters.SizedOutput object at 0x1457fab0>', ## [GL_MAX_4D_TEXTURE_SIZE_SGIS], 1, <OpenGL.wrapper.glGetIntegerv object at 0x1458aa30>) ## [graphics_card_info.py:122] [wrapper.py:676] [converters.py:195] [converters.py:234] pass pass ## gl_info_string += "%s = ??\n" % symbol else: gl_info_string += "%s = %r\n" % (symbol, intval) continue pass return gl_info_string
def setupTransforms(self, transforms): # note: this is only called from test_drawing.py (as of before 090302) """ Fill a block of transforms. Depending on the setting of TEXTURE_XFORMS and UNIFORM_XFORMS, the transforms are either in texture memory, or in a uniform array of mat4s ("constant memory"), or unsupported (error if we need any here). @param transforms: A list of transform matrices, where each transform is a flattened list (or Numpy array) of 16 numbers. """ self.n_transforms = nTransforms = len(transforms) if not self.supports_transforms(): assert not nTransforms, "%r doesn't support transforms" % self return self.setActive(True) # Must activate before setting uniforms. assert self._has_uniform("n_transforms") # redundant with following glUniform1iARB(self._uniform("n_transforms"), self.n_transforms) # The shader bypasses transform logic if n_transforms is 0. # (Then location coordinates are in global modeling coordinates.) if nTransforms > 0: if UNIFORM_XFORMS: # Load into constant memory. The GL_EXT_bindable_uniform # extension supports sharing this array of mat4s through a VBO. # XXX Need to bank-switch this data if more than N_CONST_XFORMS. C_transforms = numpy.array(transforms, dtype = numpy.float32) glUniformMatrix4fvARB(self._uniform("transforms"), # Don't over-run the array size. min(len(transforms), N_CONST_XFORMS), GL_TRUE, # Transpose. C_transforms) elif TEXTURE_XFORMS: # Generate a texture ID and bind the texture unit to it. self.transform_memory = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, self.transform_memory) ## These seem to have no effect with a vertex shader. ## glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) ## glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) # XXX Needed? glEnable(GL_TEXTURE_2D) # Load the transform data into the texture. # # Problem: SIGSEGV kills Python in gleTextureImagePut under # glTexImage2D with more than 250 transforms (16,000 bytes.) # Maybe there's a 16-bit signed size calculation underthere, that's # overflowing the sign bit... Work around by sending transforms to # the texture unit in batches with glTexSubImage2D.) glTexImage2D(GL_TEXTURE_2D, 0, # Level zero - base image, no mipmap. GL_RGBA32F_ARB, # Internal format is floating point. # Column major storage: width = N, height = 4 * RGBA. nTransforms, 4 * 4, 0, # No border. # Data format and type, null pointer to allocate space. GL_RGBA, GL_FLOAT, None) # XXX Split this off into a setTransforms method. batchSize = 250 nBatches = (nTransforms + batchSize-1) / batchSize for i in range(nBatches): xStart = batchSize * i xEnd = min(nTransforms, xStart + batchSize) xSize = xEnd - xStart glTexSubImage2D(GL_TEXTURE_2D, 0, # Subimage x and y offsets and sizes. xStart, 0, xSize, 4 * 4, # List of matrices is flattened into a sequence. GL_RGBA, GL_FLOAT, transforms[xStart:xEnd]) continue # Read back to check proper loading. if CHECK_TEXTURE_XFORM_LOADING: mats = glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_FLOAT) nMats = len(mats) print "setupTransforms\n[[", for i in range(nMats): nElts = len(mats[i]) perLine = 8 nLines = (nElts + perLine-1) / perLine for line in range(nLines): jStart = perLine * line jEnd = min(nElts, jStart + perLine) for j in range(jStart, jEnd): print "%.2f" % mats[i][j], continue if line < nLines-1: print "\n ", pass if i < nMats-1: print "]\n [", pass continue print "]]" pass else: # should never happen if SUPPORTS_XFORMS is defined correctly assert 0, "can't setupTransforms unless UNIFORM_XFORMS or TEXTURE_XFORMS is set" pass self.setActive(False) # Deactivate again. return