/* use x, y, z for rotation. use SPACE to turn on and turn off lighting */

#include <GL/glut.h>
#include <stdlib.h>

int lighting_state = 1;

int xRotate = 5;
int yRotate = 10;
int zRotate = 0;

void myInit() {
	
	glClearColor (1.0, 1.0, 1.0, 1.0);
	
	glEnable (GL_LIGHTING);
	
	glMatrixMode (GL_PROJECTION);
	glLoadIdentity();
	glOrtho (-50.0, 50.0, -50.0, 50.0, -50.0, 50.0);
	glMatrixMode (GL_MODELVIEW);
}

void display () {
	
	GLfloat ligth0_position[] = {-49.0, 49.0, 10.0};
	GLfloat ligth0_ambient[] = {0.5, 0.1, 0.1, 1.0};
	GLfloat ligth0_diffuse[] = {0.5, 0.1, 0.1, 1.0};
	GLfloat ligth0_specular[] = {1.0, 0.1, 0.1, 1.0};
	
	GLfloat material0_ambient[] = {0.5, 0.5, 0.5, 1.0};
	GLfloat material0_diffuse[] = {0.8, 0.5, 0.5, 1.0};
	GLfloat material0_specular[] = {0.9, 0.5, 0.5, 1.0};
	
	glClear (GL_COLOR_BUFFER_BIT);
	
	if (lighting_state == 1) {
		glEnable (GL_LIGHT0);
	
		glLightfv (GL_LIGHT0, GL_POSITION, ligth0_position);
		glLightfv (GL_LIGHT0, GL_AMBIENT, ligth0_ambient);
		glLightfv (GL_LIGHT0, GL_DIFFUSE, ligth0_diffuse);
		glLightfv (GL_LIGHT0, GL_SPECULAR, ligth0_specular);
		
		glMaterialfv (GL_FRONT_AND_BACK, GL_AMBIENT, material0_ambient);
		glMaterialfv (GL_FRONT_AND_BACK, GL_DIFFUSE, material0_diffuse);
		glMaterialfv (GL_FRONT_AND_BACK, GL_SPECULAR, material0_specular);
		glMaterialf (GL_FRONT_AND_BACK, GL_SHININESS, 10.0);
	}
	else
		glDisable (GL_LIGHT0);
	
	glPushMatrix ();
	glRotatef (xRotate, 1.0, 0.0, 0.0);
	glRotatef (yRotate, 0.0, 1.0, 0.0);
	glRotatef (zRotate, 0.0, 0.0, 1.0);
	
	/* draw the table */
	glBegin (GL_POLYGON);
		glVertex3f (-25.0, -7.0, -25.0);
		glVertex3f (25.0, -7.0, -25.0);
		glVertex3f (25.0, -7.0, 25.0);
		glVertex3f (-25.0, -7.0, 25.0);
	glEnd();
	/* the legs */
	glLineWidth (4);
	glBegin (GL_LINES);
		glVertex3f (-25.0, -7.0, -25.0);
		glVertex3f (-25.0, -14.0, -25.0);
		glVertex3f (25.0, -7.0, -25.0);
		glVertex3f (25.0, -14.0, -25.0);
		glVertex3f (25.0, -7.0, 25.0);
		glVertex3f (25.0, -14.0, 25.0);
		glVertex3f (-25.0, -7.0, 25.0);
		glVertex3f (-25.0, -14.0, 25.0);
	glEnd();
	
	glutSolidTeapot (10.0);
	glPopMatrix();
	glFlush();
}

void keyReact (unsigned char key, int x, int y) {
	
	switch (key) {
	case ' ':
		if (lighting_state == 0)
			lighting_state = 1;
		else
			lighting_state = 0;
		break;
	case 'x':
		xRotate++; break;
	case 'X':
		xRotate--; break;
	case 'y':
		yRotate++; break;
	case 'Y':
		yRotate--; break;
	case 'z':
		zRotate++; break;
	case 'Z':
		zRotate--; break;
	case 'q':
		exit (0);
	}
	glutPostRedisplay();
}

int main (int argc, char *argv[]) {
	
	glutInit (&argc, argv);
	glutInitDisplayMode (GLUT_RGB | GLUT_SINGLE);
	glutCreateWindow ("teapot");
	glutInitWindowPosition (0, 0);
	glutInitWindowSize (400, 400);
	glutDisplayFunc(display);
	glutKeyboardFunc (keyReact);
	myInit();
	glutMainLoop();
	
	return 0;
}

