Let there be light!

Until this point, we haven't worried about lighting. In fact, we just assumed that light would be there so that we could see our images. OpenGL has a light setting that lights everything equally. This setting is turned on, by default, until we tell OpenGL that we would like to handle the lighting.

Imagine what our scene would look like if there was no lighting. In fact, this is going to happen to you some day. You will have everything set up and ready to roll, you'll run the program, and you'll get a big, black, nothing! What's wrong? You forgot to turn on the lights! Just as shown in the following image:

Let there be light!

Just like real life, if you don't have a source of light, you aren't going to see anything. OpenGL has many types of lights. One common light is ambient light. Ambient light appears to come from all directions at the same time, similarly to how sunlight fills up a room.

Let there be light!

Lighting is very important in 3D games, and most games have multiple light sources to add realism to the game.

Defining a light source

Let's take over and define our own light source. Add the following lines of code to the top of the DrawTexturedCube function:

glEnable(GL_LIGHTING);
GLfloat ambientLight[] = { 0.0f, 0.0f, 1.0f, 1.0f };
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambientLight);
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT, GL_AMBIENT);

Run the program, then come back to see what is happening:

  • glEnable(GL_LIGHTING) tells OpenGL that we want to take control of the lighting now. Remember: once you enable lighting, it's up to you. In fact, if you enable lighting and don't define any lights, then you will get a completely black scene.
  • Next, we define a color for our light. In this case, we are creating a blue light.
  • Now we tell OpenGL what type of lighting we would like to use with glLightModelfv. In this case, we are turning on a blue, ambient light.
  • Light has to have a material to reflect from. So, we use glEnable(GL_COLOR_MATERIAL) to tell OpenGL to use a material that will reflect color.
  • The call to glColorMaterial(GL_FRONT, GL_AMBIENT) tells OpenGL that the front of this material should reflect light as if it was ambient light. Remember, ambient light comes from all directions.

Of course, you have already seen the result. Our cube is blue! Play around with different colors. We only have time to barely scratch the surface on lighting. You will also want to learn about diffuse lighting. Diffuse lights fade with distance. With a diffuse light, you not only set up the color, but you also place the light at a certain location.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.79.241