|
We add a new action to our kGLView class to change the lighting. We also add some arrays to hold the lights that we will be creating, and a boolean so that we know what the current state of the lighting is. You will also set up your NIB to include a Lights menu item. Set it to initially be checked (or "on").
GLfloat LightAmbient [4];
GLfloat LightDiffuse [4];
GLfloat LightPosition[4];
bool lighting;
- (IBAction)changeLighting:(id)sender;
|
Here's the code for changeLighting. In this, we will be marking a check next to the state, so when lighting is on, there is a check beside the menu item, and when lighting is off, the menu item is left blank.
if( lighting )
{ glDisable( GL_LIGHTING ); [sender setState: NSOffState]; }
else
{ glEnable( GL_LIGHTING ); [sender setState: NSOnState]; }
lighting = !lighting;
|
We need to add the lighting to initGL. We need to set up the light's position and color, then we need to turn the light on. If we don't turn the light on, then the scene will be black when we start (because lighting is enabled, there must be a light on if you don't want a dark screen).
glEnable(GL_LIGHTING);
lighting = true;
LightAmbient[0] = 0.5f;
LightAmbient[1] = 0.5f;
LightAmbient[2] = 0.5f;
LightAmbient[3] = 1.0f;
LightDiffuse[0] = 1.0f;
LightDiffuse[1] = 1.0f;
LightDiffuse[2] = 1.0f;
LightDiffuse[3] = 1.0f;
LightPosition[0]= 0.0f;
LightPosition[1]= 0.0f;
LightPosition[2]= 2.0f;
LightPosition[3]= 1.0f;
glLightfv(GL_LIGHT1, GL_AMBIENT, LightAmbient);
glLightfv(GL_LIGHT1, GL_DIFFUSE, LightDiffuse);
glLightfv(GL_LIGHT1, GL_POSITION,LightPosition);
glEnable(GL_LIGHT1);
|
Now, your lights will work. Go ahead, try it.
Oops, did I forget to mention they won't work normally? You need to specify normals for your lights to work properly! Luckily, this is a very simple operation in the case of our box. A normal is a line pointing outward from the box. Because it's a box, we will specify 8 normals, one for each side.
You call for your normal as soon as you enter your drawing mode. The normal will be different on each side, but is translated and rotated just like any of the other calls in OpenGL that have to do with drawing.
glBegin(drawing_type);
glNormal3f( 0.0f, 1.0f, 0.0f);
|
There we go! Now your dice work exactly as you'd expect when it comes to lighting. Try turning the lighting on and off to see the different effect that lighting makes.
|
|