TUTORIAL 1 - OpenGL Fundamentals

1  2  3  4  5  6  7  8  9  10  11  12  13

Spot Light

An entirely different type of light are the spot lights. The biggest difference is, that this time the light source is a distinct point within the scene and the light is conically emitted in one direction. The definition of the spotlight is basically the same as the definition of a distant light. We only have to change the last number in the position from 0.0 to 1.0 to specify that we have a spot light instead of a distant light and the parameters regarding the light cone must be defined:

   // set light position
   GLfloat lightPos[]={0.0,0.0,60.0,1.0};
   glLightfv(GL_LIGHT0,GL_POSITION,lightPos);

   // set spot light parameters
   GLfloat spotDir[]={0.0,1.0,-1.0};            	// define spot direction
   glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, spotDir);
   glLightf(GL_LIGHT0, GL_SPOT_CUTOFF,40.0);    	// set cutoff angle
   glLightf(GL_LIGHT0, GL_SPOT_EXPONENT,7.0);   	// set focusing strength

On the first glance this is everything we have to change compared to the above described example with the teapot and if we scene would consist only of the teapot it would work. However if we use for example a height relief the lighting won't work. The reason for this difference is, that by using the glut command for the teapot, there were automatically surface normals generated. In case of a user defined height relief we have to generate the surface normals by ourselves. Fortunately this is pretty simple by using the vector product. The vector product of two vectors produces always a vector, that is perpendicular to both original vectors.

Mathematically the cross product can be calculated component wise:

With this formula we can calculate the surface normals:

glNormal3f(Cx, Cy, Cz);

One problem we still would have is, that the length of the normals would be different for the different normals, what would cause unexpected lighting effects. To avoid this, we have to normalize all of the normal vectors to the same value - usually 1.0. This could either be done by dividing each component by the length of the normal vector or we could leave this task to OpenGL by using the following command:

glEnable(GL_NORMALIZE);

Putting everything together the spot light could look like in the image below.

previous   next