Search code examples
copenglglut

Dynamically change the colour of the material


Before calling glutMainLoop() I initialise the lights and material colours:

glShadeModel(GL_FLAT);

glMaterialfv(GL_FRONT, GL_AMBIENT, (const GLfloat[]){1,0.2,0} );
glMaterialfv(GL_FRONT, GL_DIFFUSE, (const GLfloat[]){1,0.6,0} );
glMaterialfv(GL_FRONT, GL_SPECULAR, (const GLfloat[]){1,0.8,0} );
glMaterialfv(GL_FRONT, GL_SHININESS, (const GLfloat[]){1,1,0} );

glLightfv(GL_LIGHT0, GL_AMBIENT, (const GLfloat[]){1,1,1});
glLightfv(GL_LIGHT0, GL_DIFFUSE, (const GLfloat[]){1,1,1});
glLightfv(GL_LIGHT0, GL_SPECULAR, (const GLfloat[]){1,1,1});

glEnable(GL_LIGHT0);
glEnable(GL_LIGHTING);

Now during the execution of the program I want to change the material colour.
I have a keyboard function that changes the material colours and then calls glutPostRedisplay():

glMaterialfv(GL_FRONT, GL_AMBIENT, (const GLfloat[]){0,0.2,1} );
glMaterialfv(GL_FRONT, GL_DIFFUSE, (const GLfloat[]){0,0.6,1} );
glMaterialfv(GL_FRONT, GL_SPECULAR, (const GLfloat[]){0,0.8,1} );
glMaterialfv(GL_FRONT, GL_SHININESS, (const GLfloat[]){0,1,1} );
glutPostRedisplay();

But that's a problem, since if I call that function the objects that I draw disappear. So I draw a teapot but if I change the color pressing a key it disappears.


Solution

  • Before calling glutMainLoop() I initialise the lights and material colour

    Wrong approach. OpenGL is not initialized. It's a state based drawing machine and you're supposed to set each state right before you draw something that requires that state. This also means that you don't put OpenGL operations into user interaction and event handlers. Put everything in the drawing code, right where you need it, when you need it.