Example #1
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()
Example #2
0
    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)
Example #3
0
    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)
Example #4
0
    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 __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
Example #7
0
 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)
Example #8
0
    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)
Example #9
0
    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
Example #10
0
    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.
        """
        if dimensions == 1:
            texture_type = GL_TEXTURE_1D
            texture_store = glTexImage1D
        elif dimensions == 2:
            texture_type = GL_TEXTURE_2D
            texture_store = glTexImage2D
        elif dimensions == 3:
            texture_type = GL_TEXTURE_3D
            texture_store = glTexImage3D

        if components == 1:
            internal_format = GL_R32F
            texture_format = GL_RED
        if components == 2:
            internal_format = GL_RG32F
            texture_format = GL_RG
        if components == 3:
            internal_format = GL_RGB32F
            texture_format = GL_RGB
        if components == 4:
            internal_format = GL_RGBA32F
            texture_format = GL_RGBA

        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_store(*params)

        glTexParameterf(texture_type, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
        glTexParameterf(texture_type, GL_TEXTURE_MIN_FILTER, GL_NEAREST)

        self.__textures.append(dimensions)
Example #11
0
    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)
Example #12
0
    def draw(self, eyeX, horizonY, cardList):
        """draw the card in place, using small/large image data as needed """

        with pushMatrix():
            pos = num.array(self.center)
            pos[2] += self.z.x
            if self.zoom:
                full = [eyeX, horizonY, 6.3]
                pos = lerp(pos, full, self.zoom)
            glTranslatef(*pos)

            layers = [('thumb', 1, self.thumbImage.getData('thumb'))]
            if self.zoom:
                data = self.thumbImage.getData('full')
                if data is not None:
                    layers.append(('full', 1, data))
                    # once opacity is fadable, and it's at 1, then we
                    # can remove the thumb layer from the list.

                    layers.reverse() # fix opengl draw order so hires is on top

                    

            for size, opacity, imgData in layers:
                if imgData is None:
                    # need to unset tx here!
                    glCallList(cardList)
                    # or draw a blank border, maybe some load status
                    # indication
                else:
                    (w,h), textureData = imgData
                    glBindTexture(GL.GL_TEXTURE_2D, 0)
                    glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGB,
                                 w,
                                 h,
                                 0,
                                 GL.GL_RGB, GL.GL_UNSIGNED_BYTE, textureData)
                    glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER,
                                    GL.GL_LINEAR)
                    glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER,
                                    GL.GL_LINEAR)

                    # card facing +Z from -1<x<1 -1<y<1
                    glCallList(cardList)
Example #13
0
    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
Example #14
0
    def draw(self, eyeX, horizonY, cardList):
        """draw the card in place, using small/large image data as needed """

        with pushMatrix():
            pos = num.array(self.center)
            pos[2] += self.z.x
            if self.zoom:
                full = [eyeX, horizonY, 6.3]
                pos = lerp(pos, full, self.zoom)
            glTranslatef(*pos)

            layers = [('thumb', 1, self.thumbImage.getData('thumb'))]
            if self.zoom:
                data = self.thumbImage.getData('full')
                if data is not None:
                    layers.append(('full', 1, data))
                    # once opacity is fadable, and it's at 1, then we
                    # can remove the thumb layer from the list.

                    layers.reverse(
                    )  # fix opengl draw order so hires is on top

            for size, opacity, imgData in layers:
                if imgData is None:
                    # need to unset tx here!
                    glCallList(cardList)
                    # or draw a blank border, maybe some load status
                    # indication
                else:
                    (w, h), textureData = imgData
                    glBindTexture(GL.GL_TEXTURE_2D, 0)
                    glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGB, w, h, 0,
                                 GL.GL_RGB, GL.GL_UNSIGNED_BYTE, textureData)
                    glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER,
                                    GL.GL_LINEAR)
                    glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER,
                                    GL.GL_LINEAR)

                    # card facing +Z from -1<x<1 -1<y<1
                    glCallList(cardList)
Example #15
0
def load(file_path):
    img = Image.open(file_path, 'r').convert('RGB')

    img_data = np.array(img, dtype=np.uint8)
    width, height = img.size

    texture = glGenTextures(1)
    glActiveTexture(GL_TEXTURE0)
    glBindTexture(GL_TEXTURE_2D, texture)

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)

    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_MAG_FILTER, GL_LINEAR)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)

    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB,
                 GL_UNSIGNED_BYTE, img_data)

    return texture
Example #16
0
 def _initTextureEnv(self):  # called during draw method
     glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP)
     # [looks like a bug that we overwrite clamp with repeat, just below? bruce 060212 comment]
     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)
     if debug_pref("smoother textures",
                   Choice_boolean_False,
                   prefs_key=True):
         #bruce 060212 new feature (only visible in debug version so far);
         # ideally it'd be controllable per-jig for side-by-side comparison;
         # also, changing its menu item ought to gl_update but doesn't ##e
         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
         if self.have_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)
     glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL)
     return
Example #17
0
    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
Example #18
0
 def _initTextureEnv(self): # called during draw method
     glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP)
         # [looks like a bug that we overwrite clamp with repeat, just below? bruce 060212 comment]
     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)
     if debug_pref("smoother textures", Choice_boolean_False, prefs_key = True):
         #bruce 060212 new feature (only visible in debug version so far);
         # ideally it'd be controllable per-jig for side-by-side comparison;
         # also, changing its menu item ought to gl_update but doesn't ##e
         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
         if self.have_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)
     glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL)
     return
Example #19
0
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
Example #20
0
    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
Example #21
0
def _initTextureEnv(have_mipmaps):
    """
    have_mipmaps is boolean #doc

    Anything that calls this should eventually call
    glpane.kluge_reset_texture_mode_to_work_around_renderText_bug(),
    but only after all drawing using the texture is done.
    """
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP)
        # [looks like a bug that we overwrite clamp with repeat, just below?
        # bruce 060212 comment]
    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)
    if (0 and "kluge" and
        debug_pref("smoother textures", Choice_boolean_False,
                   prefs_key = True)): ###@@@ revise to param
        #bruce 060212 new feature (only visible in debug version so far);
        # ideally it'd be controllable per-jig for side-by-side comparison;
        # also, changing its menu item ought to gl_update but doesn't ##e
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
        if have_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)
    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL)
    return
    def createImage(self,
                    qimagepath,
                    layer,
                    textureRect,
                    drawRect,
                    hidden=False,
                    dynamicity=GL_STATIC_DRAW_ARB):
        '''
		Creates an rggTile instance, uploads the correct image to GPU if not in cache, and some other helpful things.
		'''
        #print "requested to create", qimagepath, layer, textureRect, drawRect, hidden
        layer = int(layer)
        texture = None
        found = False

        if qimagepath in self.qimages:
            qimg = self.qimages[qimagepath][0]
            if self.qimages[qimagepath][2] > 0:
                texture = self.qimages[qimagepath][1]
                found = True
        else:
            qimg = QImage(qimagepath)
            #print("created", qimagepath)

        if textureRect[2] == -1:
            textureRect[2] = qimg.width()

        if textureRect[3] == -1:
            textureRect[3] = qimg.height()

        if drawRect[2] == -1:
            drawRect[2] = qimg.width()

        if drawRect[3] == -1:
            drawRect[3] = qimg.height()

        image = tile(qimagepath, textureRect, drawRect, layer, hidden,
                     dynamicity, self)

        if found == False:
            img = None
            if self.npot == 0:
                w = nextPowerOfTwo(qimg.width())
                h = nextPowerOfTwo(qimg.height())
                if w != qimg.width() or h != qimg.height():
                    img = self.convertToGLFormat(qimg.scaled(w, h))
                else:
                    img = self.convertToGLFormat(qimg)
            else:
                img = self.convertToGLFormat(qimg)

            texture = int(glGenTextures(1))
            try:
                imgdata = img.bits().asstring(img.byteCount())
            except Exception as e:
                print(e)
                print("requested to create", qimagepath, layer, textureRect,
                      drawRect, hidden)
                for x in [0, 1, 2, 3]:
                    f_code = _getframe(
                        x
                    ).f_code  #really bad hack to get the filename and number
                    print("Doing it wrong in " + f_code.co_filename + ":" +
                          str(f_code.co_firstlineno))
                    print("Error: " + e)

            #print("created texture", texture)

            glBindTexture(self.texext, texture)

            if self.anifilt > 1.0:
                glTexParameterf(self.texext, GL_TEXTURE_MAX_ANISOTROPY_EXT,
                                self.anifilt)
            if self.npot == 3 and self.mipminfilter != -1:
                glTexParameteri(self.texext, GL_TEXTURE_MIN_FILTER,
                                self.mipminfilter)
                glTexParameteri(self.texext, GL_TEXTURE_MAG_FILTER,
                                self.magfilter)
            elif self.npot == 2 and self.mipminfilter != -1:
                glTexParameteri(self.texext, GL_TEXTURE_MIN_FILTER,
                                self.mipminfilter)
                glTexParameteri(self.texext, GL_TEXTURE_MAG_FILTER,
                                self.magfilter)
                glTexParameteri(self.texext, GL_GENERATE_MIPMAP, GL_TRUE)
            else:
                glTexParameteri(self.texext, GL_TEXTURE_MIN_FILTER,
                                self.minfilter)
                glTexParameteri(self.texext, GL_TEXTURE_MAG_FILTER,
                                self.magfilter)

            glTexParameteri(self.texext, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)
            glTexParameteri(self.texext, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE)
            glTexParameteri(self.texext, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)

            glTexImage2D(self.texext, 0, GL_RGBA, img.width(), img.height(), 0,
                         GL_RGBA, GL_UNSIGNED_BYTE, imgdata)

            if self.npot == 3 and self.mipminfilter != -1:
                glEnable(GL_TEXTURE_2D)
                glGenerateMipmap(GL_TEXTURE_2D)

            self.qimages[qimagepath] = [qimg, texture,
                                        1]  #texture, reference count
        else:
            self.qimages[qimagepath][2] += 1

        image.textureId = texture

        if layer not in self.images:
            self.images[layer] = []
            self.layers = list(self.images.keys())
            self.layers.sort()
            image.createLayer = True

        self.images[layer].append(image)
        self.allimgs.append(image)

        return image
Example #23
0
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
Example #24
0
def _initTextureEnv(have_mipmaps):
    """
    have_mipmaps is boolean #doc

    Anything that calls this should eventually call
    glpane.kluge_reset_texture_mode_to_work_around_renderText_bug(),
    but only after all drawing using the texture is done.
    """
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP)
    # [looks like a bug that we overwrite clamp with repeat, just below?
    # bruce 060212 comment]
    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)
    if (0 and "kluge" and debug_pref("smoother textures",
                                     Choice_boolean_False,
                                     prefs_key=True)):  ###@@@ revise to param
        #bruce 060212 new feature (only visible in debug version so far);
        # ideally it'd be controllable per-jig for side-by-side comparison;
        # also, changing its menu item ought to gl_update but doesn't ##e
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
        if have_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)
    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL)
    return
Example #25
0
    def draw_mesh(m, lighting_on):

        # Supply vertices
        glEnableClientState(GL_VERTEX_ARRAY)
        m.vbo['v'].bind()
        glVertexPointer(3, GL_FLOAT, 0, m.vbo['v'])
        m.vbo['v'].unbind()

        # Supply normals
        if 'vn' in m.vbo.keys():
            glEnableClientState(GL_NORMAL_ARRAY)
            m.vbo['vn'].bind()
            glNormalPointer(GL_FLOAT, 0, m.vbo['vn'])
            m.vbo['vn'].unbind()
        else:
            glDisableClientState(GL_NORMAL_ARRAY)

        # Supply colors
        if 'vc' in m.vbo.keys():
            glEnableClientState(GL_COLOR_ARRAY)
            m.vbo['vc'].bind()
            glColorPointer(3, GL_FLOAT, 0, m.vbo['vc'])
            m.vbo['vc'].unbind()
        else:
            glDisableClientState(GL_COLOR_ARRAY)

        if ('vt' in m.vbo.keys()) and hasattr(m, 'textureID'):
            glEnable(GL_TEXTURE_2D)
            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_MODULATE)
            glBindTexture(GL_TEXTURE_2D, m.textureID)

            glEnableClientState(GL_TEXTURE_COORD_ARRAY)
            m.vbo['vt'].bind()
            glTexCoordPointer(2, GL_FLOAT, 0, m.vbo['vt'])
            m.vbo['vt'].unbind()
        else:
            glDisable(GL_TEXTURE_2D)
            glDisableClientState(GL_TEXTURE_COORD_ARRAY)

        # Draw
        if len(m.f) > 0:
            # ie if it is triangulated
            if lighting_on:
                glEnable(GL_LIGHTING)
            else:
                glDisable(GL_LIGHTING)
            glDrawElementsui(GL_TRIANGLES, np.arange(m.f.size,
                                                     dtype=np.uint32))
        else:
            # not triangulated, so disable lighting
            glDisable(GL_LIGHTING)
            glPointSize(2)
            glDrawElementsui(GL_POINTS, np.arange(len(m.v), dtype=np.uint32))
        if hasattr(m, 'v_to_text'):

            glEnable(GL_TEXTURE_2D)
            glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
            glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
                            GL_LINEAR_MIPMAP_LINEAR)
            glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL)

            # glEnable(GL_TEXTURE_GEN_S)
            # glEnable(GL_TEXTURE_GEN_T)
            # glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR)
            # glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR)

            bgcolor = np.array(glGetDoublev(GL_COLOR_CLEAR_VALUE))
            fgcolor = 1. - bgcolor

            from .lines import Lines
            sc = float(np.max(np.max(m.v, axis=0) - np.min(m.v, axis=0))) / 10.

            cur_mtx = np.linalg.pinv(glGetFloatv(GL_MODELVIEW_MATRIX).T)
            xdir = cur_mtx[:3, 0]
            ydir = cur_mtx[:3, 1]

            glEnable(GL_LINE_SMOOTH)
            glEnable(GL_BLEND)
            glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

            for vidx, text in m.v_to_text.items():
                pos0 = m.v[vidx].copy()
                pos1 = m.v[vidx].copy()
                if hasattr(m, 'vn'):
                    pos1 += m.vn[vidx] * sc
                glLineWidth(5.0)
                ln = Lines(v=np.vstack((pos0, pos1)), e=np.array([[0, 1]]))
                glEnable(GL_LIGHTING)
                glColor3f(1. - 0.8, 1. - 0.8, 1. - 1.00)
                MeshViewerSingle.draw_lines(ln)

                glDisable(GL_LIGHTING)

                texture_id = get_textureid_with_text(text, bgcolor, fgcolor)
                glBindTexture(GL_TEXTURE_2D, texture_id)

                glPushMatrix()
                glTranslatef(pos1[0], pos1[1], pos1[2])

                dx = xdir * .10
                dy = ydir * .10
                if False:
                    glBegin(GL_QUADS)

                    glTexCoord2f(1., 0.)
                    glVertex3f(*(+dx + dy))

                    glTexCoord2f(1., 1.)
                    glVertex3f(*(+dx - dy))

                    glTexCoord2f(0., 1.)
                    glVertex3f(*(-dx - dy))

                    glTexCoord2f(0., 0.)
                    glVertex3f(*(-dx + dy))

                    # gluSphere(quadratic,0.05,32,32)
                    glEnd()
                else:
                    glBegin(GL_POLYGON)

                    for r in np.arange(0, np.pi * 2., .01):
                        glTexCoord2f(np.cos(r) / 2. + .5, np.sin(r) / 2. + .5)
                        glVertex3f(*(dx * np.cos(r) + -dy * np.sin(r)))

                    glEnd()
                glPopMatrix()