I have a simple window whose background color is set in a main loop with some global variables:
The global values at the top:
static GLfloat redIntensity = 0.0; //values for background color
static GLfloat greenIntensity = 0.0;
static GLfloat blueIntensity = 0.0;
The main:
int main(int argc, char** argv){
...
glutDisplayFunc(display);
...
glutKeyboardFunc(keyboard); //****
glutMainLoop();
return 0;
}
The display that actually sets the colors according to the global values:
void display(void){
glClear(GL_COLOR_BUFFER_BIT);
glPushMatrix();
glClearColor(redIntensity, greenIntensity, blueIntensity, 0.0);
...
... //other stuff here is polygon drawn in middle of screen
glPopMatrix();
glutSwapBuffers();
}
Within the keyboard function, I have a switch statement that should change the background color depending on which key is pressed, e.g :
...
case 'm':
{
redIntensity = 0.5;
greenIntensity = 0.0;
blueIntensity = 0.5;
bgc = MAGENTA; //another global thing to keep track of current color for other reasons...
}
...
glutPostRedisplay();
Unfortunately, with the glutPostRedisplay() call, the background color does not change immediately…the user must click somewhere else or press another key first. I read elsewhere that glutPostRedisplay() only QUEUES a redisplay, so I tried adding glFlush() in the line directly afterward. This still didn’t work, so I tried flat-out calling glutDisplayFunc(display) there instead. Once more, unsuccessful.
How can I force the color to change right after the key is pressed? Perhaps the ordering calls in main or elsewhere is causing an issue? Hmm…
OpenGL is a state machine. When glClear is called it uses the values previously set with glClearColor, glClearDepth, glClearStencil. So the solution is to put the glClearColor call before the glClear call in display.