OpenGL texture map all white

Alec Jacobson

June 28, 2010

weblog/

After a long battle today, I found a bug that was making all my textures render white. Here's pseudo code of what I had:

Bugged code

GLwidget.h
class GLwidget : QGLWidget {
  GLWidget();
  ...
  void initializeGL();
  void paintGL();
  ...
}
GLwidget.cpp
GLWidget::GLWidget(){
  // code that generates texture
  makeMyTexture(...);
  // opengl calls that setup texture in GL land
  glGenTextures(1, &texName);
  glBindTexture(GL_TEXTURE_2D, texName);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
  ...
  glTexImage2D(GL_TEXTURE_2D, ...) ;
}
  ...
void GLWidget ::initializeGL(){
  // opengl initialization code
}
void GLWidget :: paintGL(){
  // code that actually uses the texture
  glEnable(GL_TEXTURE_2D)
  ...
  glDisable(GL_TEXTURE_2D)
}
My GLWidget class inherited from a class that called initializeGL and paintGL at the appropriate times. The only problem was that I was building and setting my texture in the class constructor before initializeGL() was ever called. Then when it was, it wiped out my texture. The correct order should be:

Correct

GLwidget.cpp
GLWidget::GLWidget(){
  ...
}
void GLWidget ::initializeGL(){
  // opengl initialization code
  ...
  // code that generates texture
  makeMyTexture(...);
  // opengl calls that setup texture in GL land
  glGenTextures(1, &texName);
  glBindTexture(GL_TEXTURE_2D, texName);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
  ...
  glTexImage2D(GL_TEXTURE_2D, ...) ;
}
void GLWidget :: paintGL(){
  // code that actually uses the texture
  glEnable(GL_TEXTURE_2D)
  ...
  glDisable(GL_TEXTURE_2D)
}
Initialize your texture after you have initialized opengl.