Friday, June 10, 2011

Fourth OpenGL Program : Draw a Rotating Box with Key Interaction

In this program I start to put a key interaction. The function that provide such functionality is void captureKeyPressed(unsigned char key, int x, int y). The program can zoom in or zoom out box by pressing = and - keys. The program is listed below :
/*
Joko Adianto
This Source Code is released under GPL
*/
#include "GL/freeglut.h"
int window;
float r;
float ztranslation;
void drawBox()
{
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
glLoadIdentity();
glTranslatef(0.0f,0.0f,ztranslation);
glRotatef(r,1.0f,1.0f,1.0f);
//Front
glBegin(GL_QUADS);
glColor3f(1.0f,0.0f,0.0f);
glVertex3f(1.0f, 1.0f, 0.0f);
glVertex3f(1.0f, -1.0f, 0.0f);
glVertex3f(-1.0f,-1.0f,0.0f);
glVertex3f(-1.0f,1.0f, 0.0f);
glEnd();
//Back
glBegin(GL_QUADS);
glColor3f(0.0f,1.0f,0.0f);
glVertex3f(1.0f, 1.0f, -1.0f);
glVertex3f(1.0f, -1.0f, -1.0f);
glVertex3f(-1.0f,-1.0f,-1.0f);
glVertex3f(-1.0f,1.0f, -1.0f);
glEnd();
//Left
glBegin(GL_QUADS);
glColor3f(0.0f,0.0f,1.0f);
glVertex3f(-1.0f, 1.0f, 0.0f);
glVertex3f(-1.0f, 1.0f, -1.0f);
glVertex3f(-1.0f,-1.0f,-1.0f);
glVertex3f(-1.0f,-1.0f, 0.0f);
glEnd();
//Right
glBegin(GL_QUADS);
glColor3f(0.0f,1.0f,1.0f);
glVertex3f(1.0f, 1.0f, 0.0f);
glVertex3f(1.0f, 1.0f, -1.0f);
glVertex3f(1.0f,-1.0f,-1.0f);
glVertex3f(1.0f,-1.0f, 0.0f);
glEnd();
//Top
glBegin(GL_QUADS);
glColor3f(0.33f,0.33f,0.34f);
glVertex3f(-1.0f, 1.0f, -1.0f);
glVertex3f(1.0f, 1.0f, -1.0f);
glVertex3f(1.0f,1.0f,0.0f);
glVertex3f(-1.0f,1.0f, 0.0f);
glEnd();
//Top
glBegin(GL_QUADS);
glColor3f(0.33f,0.33f,0.0f);
glVertex3f(-1.0f, -1.0f, -1.0f);
glVertex3f(1.0f, -1.0f, -1.0f);
glVertex3f(1.0f,-1.0f,0.0f);
glVertex3f(-1.0f,-1.0f, 0.0f);
glEnd(); r = r +0.2f;
glutSwapBuffers();
}

void captureKeyPressed(unsigned char key, int x, int y)
{
if (key == 27) /*ASCII code value for escape key*/
{
glutDestroyWindow(window);
exit(0);
}
if (key == 61) /*ASCII code value for = key*/
{
ztranslation++;
}
if (key == 45) /*ASCII code value for - key*/
{
ztranslation--;
}
}


int main(int argc, char **argv)
{
ztranslation = -50.0f;
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA | GLUT_DEPTH );
glutInitWindowSize(640, 640);
glutInitWindowPosition(100, 100);
window = glutCreateWindow("Display a rotating box : zoom in and out");
glutDisplayFunc(&drawBox);
glutIdleFunc(&drawBox);
glutKeyboardFunc(&captureKeyPressed);
glClearDepth(1.0);
glDepthFunc(GL_LESS);
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_SMOOTH);
glMatrixMode(GL_PROJECTION);
gluPerspective(45.0f,(GLfloat)640/640,0.1f,100.0f);
glMatrixMode(GL_MODELVIEW);
glutMainLoop();
return 0;
}