Skip to content

Instantly share code, notes, and snippets.

@AnishN
Created October 2, 2017 08:43
Show Gist options
  • Select an option

  • Save AnishN/4f781bf5bce14c6e9495682f199a0ec1 to your computer and use it in GitHub Desktop.

Select an option

Save AnishN/4f781bf5bce14c6e9495682f199a0ec1 to your computer and use it in GitHub Desktop.
Hackish and SLOW implementation to pass an unsigned int [:, :, :] memoryview to glTexImage2D (OpenGL)
import contextlib
cdef class Texture:
def __cinit__(self, Image image):
self.image = image
glGenTextures(1, &self.id_)
self.unit = 0
def __dealloc__(self):
glDeleteTextures(1, &self.id_)
cdef _upload(self):
"""
#This version leads to a corrupted pixel mess!
cdef unsigned int first = self.image.pixels[0, 0, 0]
cdef void *pixels = &first
with self.bind():
glPixelStorei(GL_PACK_ALIGNMENT, 1)
glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_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)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, self.image.width, self.image.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels)
#glGenerateMipmap(GL_TEXTURE_2D)
"""
cdef int rgba_size = 4
cdef int width = self.image.width
cdef int height = self.image.height
cdef unsigned int * flat = <unsigned int *>calloc(width * height * rgba_size, sizeof(unsigned int))
cdef int x = 0
cdef int y = 0
cdef int z = 0
for x in range(width):
for y in range(height):
for z in range(rgba_size):
flat[x + height * (y + rgba_size * z)] = self.image.pixels[x, y, z]
with self.bind():
glPixelStorei(GL_PACK_ALIGNMENT, 1)
glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_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)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, self.image.width, self.image.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, &flat[0])
#glGenerateMipmap(GL_TEXTURE_2D)
free(<void *>flat)
@contextlib.contextmanager
def bind(self):
glActiveTexture(GL_TEXTURE0 + self.unit)
glBindTexture(GL_TEXTURE_2D, self.id_)
try:
yield
finally:
glBindTexture(GL_TEXTURE_2D, 0)
glActiveTexture(GL_TEXTURE0)
def set_unit(self, GLuint new_unit):
self.unit = new_unit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment