/* simple6.c draws a cube in 3D OpenGL 1.x Laura Toma */ #include #include #include #include #ifdef __APPLE__ #include #else #include #endif GLfloat red[3] = {1.0, 0.0, 0.0}; GLfloat green[3] = {0.0, 1.0, 0.0}; GLfloat blue[3] = {0.0, 0.0, 1.0}; GLfloat black[3] = {0.0, 0.0, 0.0}; GLfloat white[3] = {1.0, 1.0, 1.0}; GLfloat gray[3] = {0.5, 0.5, 0.5}; GLfloat yellow[3] = {1.0, 1.0, 0.0}; GLfloat magenta[3] = {1.0, 0.0, 1.0}; GLfloat cyan[3] = {0.0, 1.0, 1.0}; /* forward declarations of functions */ void display(void); void keypress(unsigned char key, int x, int y); //draw [-1,1] x [-1,1] rectangle at specified z void draw_xy_rect(GLfloat z, GLfloat r, GLfloat g, GLfloat b) { glBegin(GL_POLYGON); glColor3f(r,g,b); glVertex3f(-1,-1, z); glVertex3f(-1,1, z); glVertex3f(1,1, z); glVertex3f(1,-1, z); glEnd(); } void draw_cube(GLfloat z1, GLfloat z2) { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); //front face at z=z1 with RED draw_xy_rect(z1,1,0,0); //back face at z=z2 woth BLUE draw_xy_rect(z2,0,0,1); //draw the sides glColor3fv(yellow); glBegin(GL_POLYGON); glVertex3f(-1,-1, z1); glVertex3f(-1,1, z1); glVertex3f(-1,1, z2); glVertex3f(-1,-1, z2); glEnd(); glBegin(GL_POLYGON); glColor3fv(cyan); glVertex3f(1,-1, z1); glVertex3f(1,1, z1); glVertex3f(1,1, z2); glVertex3f(1,-1, z2); glEnd(); } void keypress(unsigned char key, int x, int y) { switch(key) { case 'q': exit(0); break; } } void display(void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //this won't show anything, because it's right on the edge of the //view frustrum and the camera is inside it at (0,0,0) //draw_cube(1, -1); we need to translate it first glTranslatef(0,0,-3); draw_cube(1, -1); glFlush(); } int main(int argc, char** argv) { /* open a window */ glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(500, 500); glutInitWindowPosition(100,100); glutCreateWindow(argv[0]); /* OpenGL init */ glClearColor(0, 0, 0, 0); /* set background color black*/ /* initial view */ glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60, 1, 1, 10.0); /* aspect=1; the frustrum is from z=-1 to z=-10 */ /* DEFAULT: camera is at (0,0,0) looking along negative z axis */ glMatrixMode(GL_MODELVIEW); /* callback functions */ glutDisplayFunc(display); glutKeyboardFunc(keypress); /* event handler */ glutMainLoop(); return 0; }