To make OpenGL use lighting calculations when drawing objects, enable GL_LIGHTING:
glEnable(GL_LIGHTING);
Next, you must define at least one light source. You have to enable it, and can assign it a color and position. e.g.:
GLfloat white[4] = { 1, 1, 1, 1 }; GLfloat lightPos[4] = {0, 1, 0, 0}; glEnable(GL_LIGHT0); glLightfv(GL_LIGHT0, GL_DIFFUSE, white); glLightfv(GL_LIGHT0, GL_POSITION, lightPos);
Example: gluQuadrics-lit.c
For objects to have a color other than the default grey, you must set their material properties. These define how the objects reflect the light that shines on them.
GLfloat blue[4] = { .1, .4, 1, 1 }; GLfloat white[4] = { 1, 1, 1, 1 }; glMaterialfv(GL_FRONT, GL_DIFFUSE, blue); glMaterialfv(GL_FRONT, GL_AMBIENT, blue); glMaterialfv(GL_FRONT, GL_SPECULAR, white); glMaterialf(GL_FRONT, GL_SHININESS, 120.0);
Example: glutGeometry-lit.c
To calculate how much light reflects off of a surface, OpenGL needs to know which direction the surface is facing. It combines this information with the direction that the light is shining to compute the diffuse component of the lighting.
A normal vector, defined with glNormal, is a vector perpendicular to the surface, thus defining the surface's orientation.
glBegin(GL_QUADS); glNormal3f(-0.707, 0.0, 0.707); glVertex3f(-9.0, 1.0, -7.0); glVertex3f(-3.0, 1.0, -1.0); glVertex3f(-3.0, 7.0, -1.0); glVertex3f(-9.0, 7.0, -7.0); glEnd();
Example 1: squares-lit.c
Example 2: waves-lit.c