Search code examples
pythonopengltexturespyopengl

uv mapping python OpenGL triangles


Im trying to display a simple immediate mode sets of textured polygons with pyOpenGL with no luck. I have lashed together some code that loads a some geometry data and that all works fine and as far as I can tell I have all the code to add a texture to it but just getting white polys.

Here's the important bits of the code:

self.img = PIL.Image.open('/projects/openGL_robot_face/facemap.png')
self.image_data = numpy.array(list(self.img.getdata()), numpy.uint8)

def paintGL(self):
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)


    texture = glGenTextures( 1)
    glPixelStorei(GL_UNPACK_ALIGNMENT,1)
    glBindTexture(GL_TEXTURE_2D, texture)
    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, self.img.size[0], self.img.size[1], 0, GL_RGB, GL_UNSIGNED_BYTE, self.image_data)

    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()
    glTranslate(0.0, 0.0, -50.0)
    glScale(20.0, 20.0, 20.0)
    glRotate(self.yRotDeg, 0.2, 1.0, 0.3)
    glTranslate(-0.5, -0.5, -0.5)

    glBegin(GL_TRIANGLES)
    for vert in self.poly_verts:
        glTexCoord2f(vert[6], vert[7])
        glVertex3f(vert[0], vert[1], vert[2])

    glEnd()

Solution

  • Have you enabled textures in OpenGL, using :

    glEnable(GL_TEXTURE_2D)
    

    Also, you should not create the texture on each Paint call, you should create it once and for all (with glGenTextures, and glTex*), then store the texture ID, and do the strict minimum during Paint, which is binding with the texture.

    def paintGL(self):
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    
        glEnable(GL_TEXTURE_2D)
        glBindTexture(GL_TEXTURE_2D, texture)
    
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()
        glTranslate(0.0, 0.0, -50.0)
        glScale(20.0, 20.0, 20.0)
        glRotate(self.yRotDeg, 0.2, 1.0, 0.3)
        glTranslate(-0.5, -0.5, -0.5)
    
        glBegin(GL_TRIANGLES)
        for vert in self.poly_verts:
            glTexCoord2f (vert[6], vert[7]);
            glVertex3f(vert[0], vert[1], vert[2])
    
        glEnd()
        glDisable(GL_TEXTURE_2D)
    

    Unfortunately I cannot try the answer right now so this is purely from the top of my head. You could probably benefit from this previous post : Render a textured rectangle with PyOpenGL