pythonopenglpyopenglopengl-compat

Texture wrapping an entire sphere in PyOpenGL


I copied the corrected code here to apply my own texture from a solar imaging dataset onto an OpenGL sphere. In doing so I noticed that the texture does not wrap entirely around the sphere - only the "front half" - and the lighting shadow is not applied (also evident in the answer to that question).

How do you modify the code to wrap the texture around the entire sphere?

Here is the texture image which is data in a 360-degree longitude x sine(latitude) format (which actually should be transformed to longitude x latitude before applying to the sphere, but that's a detail...):

enter image description here

And here's the result of the texture mapping which shows that the image is only applied to the front/visible hemisphere:

enter image description here


Solution

  • To wrap a texture around a sphere you have to distribute the texture coordinates quadratic around the sphere. This is provided by gluNewQuadric, gluQuadricTexture and gluSphere:

    class MyWnd:
        def __init__(self):
            self.texture_id = 0
            self.angle = 0
    
        def run_scene(self):
            glutInit()
            glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH)
            glutInitWindowSize(400, 400)
            glutCreateWindow(b'Minimal sphere OpenGL')
            self.lightning()
            self.texture_id = self.read_texture('data/worldmap1.jpg')
            glutDisplayFunc(self.draw_sphere)
            glMatrixMode(GL_PROJECTION)
            gluPerspective(40, 1, 1, 40)
            glutMainLoop()
    
        def draw_sphere(self):
            glMatrixMode(GL_MODELVIEW)
            glLoadIdentity()
            gluLookAt(math.cos(self.angle)*4, math.sin(self.angle)*4, 0, 0, 0, 0, 0, 0, 1)
            self.angle = self.angle+0.04
            glEnable(GL_DEPTH_TEST)
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
            glBindTexture(GL_TEXTURE_2D, self.texture_id)
        
            glEnable(GL_TEXTURE_2D)
    
            qobj = gluNewQuadric()
            gluQuadricTexture(qobj, GL_TRUE)
            gluSphere(qobj, 1, 50, 50)
            gluDeleteQuadric(qobj)
    
            glDisable(GL_TEXTURE_2D)
        
            glutSwapBuffers()
            glutPostRedisplay()        
    

    See the preview:

    See also Immediate mode and legacy OpenGL