Here I will show you how to use opengl light within your opengl application.
You enable the depth, the lighting, and which light you are using.
To perform basic lighting, you will need to
* Enable lighting support by OpenGL : When lighting is enabled, it automatically generates colors for your models
* Enable a light source :
* Provide information about the surface you will be lighting
a. Surface normals
b. Material properties
1.Enable depth Support
Firstly clear the depth buffer glClearDepth(1);
Secondly enable depth testing glEnable(GL_DEPTH_TEST);
2.Enable OpenGL lighting support
glEnable(GL_LIGHTING);
3.Enable the light ranging from GL_LIGHT0 -> GL_LIGHT4
glEnable(GL_LIGHT0); or glEnable(GL_LIGHT1)/glEnable(GL_LIGHT2) etc
Rest is pretty clear if you go through the code listed below
#include < GL/glut.h >
GLfloat angle = 0.0;
void drawPlane()
{
// Draw a red x-axis, a green y-axis, and a blue z-axis. Each of the
// axes are ten units long.
glBegin(GL_LINES);
glColor3f(1, 0, 0); glVertex3f(-10, 0, 0); glVertex3f(10, 0, 0);
glColor3f(0, 1, 0); glVertex3f(0, -10, 0); glVertex3f(0, 10, 0);
glColor3f(1, 1, 1); glVertex3f(0, 0, -10); glVertex3f(0, 0, 10);
glEnd();
}
void drawCube (void)
{
//Color will not work if this is not enabled
glEnable(GL_COLOR_MATERIAL);
glRotatef(angle, 1.0, 0.0, 0.0);
glRotatef(angle, 0.0, 1.0, 0.0);
glRotatef(angle, 0.0, 0.0, 1.0);
glColor3f(1.0, 0.0, 0.0);
glutSolidCube(2);
}
void init (void)
{
glEnable(GL_DEPTH_TEST);
glEnable (GL_LIGHTING);
glEnable (GL_LIGHT0);
}
void display (void)
{
glClearColor (0.0,0.0,0.0,1.0);
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
gluLookAt (0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
drawPlane();
drawCube();
glutSwapBuffers();
angle ++;
}
void reshape (int w, int h)
{
glViewport (0, 0, (GLsizei)w, (GLsizei)h);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
gluPerspective (60, (GLfloat)w / (GLfloat)h, 1.0, 100.0);
glMatrixMode (GL_MODELVIEW);
}
int main (int argc, char **argv) {
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
glutInitWindowSize (500, 500);
glutInitWindowPosition (100, 100);
glutCreateWindow ("OpenGL Lighting");
init ();
glutDisplayFunc (display);
glutIdleFunc (display);
glutReshapeFunc (reshape);
glutMainLoop ();
return 0;
}
No comments:
Post a Comment