Skip to main content

Lighting in OpenGL

Short answer

To apply lighting, enable GL_LIGHTING and a light, set its position and color components (ambient, diffuse, specular), define the surface’s material properties (ambient/diffuse/specular colors and shininess), and specify a unit normal for each polygon or vertex before its vertices. OpenGL then shades the polygon according to the Blinn-Phong reflection model.

How can we use lighting in OpenGL (how is lighting applied to a polygon surface)?

OpenGL lighting is based on the Phong illumination model (ambient + diffuse + specular); fixed-function OpenGL actually uses the Blinn–Phong form, which computes the specular term with the halfway vector H. To use it, we must specify the lights, the material of the surfaces and the surface normals.

Steps

  1. Enable lighting, a light and depth testing:
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);          // at least 8 lights: GL_LIGHT0 ... GL_LIGHT7
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_SMOOTH);      // Gouraud shading (GL_FLAT for flat)
  1. Define the light properties:
GLfloat pos[]     = {1.0f, 1.0f, 1.0f, 0.0f};  // w = 0: directional, w = 1: point
GLfloat ambient[] = {0.2f, 0.2f, 0.2f, 1.0f};
GLfloat diffuse[] = {1.0f, 1.0f, 1.0f, 1.0f};
GLfloat specular[]= {1.0f, 1.0f, 1.0f, 1.0f};
glLightfv(GL_LIGHT0, GL_POSITION, pos);
glLightfv(GL_LIGHT0, GL_AMBIENT,  ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE,  diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, specular);
  1. Define the material of the polygon (reflection coefficients):
GLfloat mat_d[] = {0.8f, 0.2f, 0.2f, 1.0f};
GLfloat mat_s[] = {1.0f, 1.0f, 1.0f, 1.0f};
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, mat_d);
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_s);
glMaterialf (GL_FRONT, GL_SHININESS, 50.0f);   // exponent n
  1. Give the unit normal of each polygon (or vertex) before its vertices, since lighting uses N:
glBegin(GL_POLYGON);
    glNormal3f(0.0f, 0.0f, 1.0f);
    glVertex3f(0, 0, 0); glVertex3f(1, 0, 0);
    glVertex3f(1, 1, 0); glVertex3f(0, 1, 0);
glEnd();

OpenGL then calculates the colour of each vertex using the ambient, diffuse and specular terms and interpolates it over the polygon (Gouraud shading when GL_SMOOTH is used). If glEnable(GL_COLOR_MATERIAL) is used, glColor sets the material colour.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Graphics chapter 9 questions →