/* prac5c.c */ /* Purpose: use push/pop to change the effective coordinate system. */ #ifdef __APPLE__ #include #else #include #endif #include #include #include #define KEY_ESC 27 /* glut doesn't define this one */ void printHelp( void ) { fprintf(stdout, "\nTransformation ordering\n\n" "Escape key - exit the program\n\n"); } GLvoid keyboard( GLubyte key, GLint x, GLint y) { switch (key) { case KEY_ESC: /* exit when escape key is pressed */ exit(0); break; } } GLvoid specialkeys( GLint key, GLint x, GLint y) { switch (key) { case GLUT_KEY_F1: /* print Help information */ printHelp ( ); break; } } GLvoid checkError( const char* const label ) { GLenum error; error = glGetError(); while ( GL_NO_ERROR != error ) { fprintf( stderr,"%s: %s\n", label, gluErrorString(error) ); error = glGetError(); } } GLvoid drawTriangle( GLvoid ) { glBegin(GL_TRIANGLES); glVertex2f(0.0, 1.0); glVertex2f(-1.0, -1.0); glVertex2f(1.0, -1.0); glEnd(); } /* recursively draw the right branch of the tree */ GLvoid drawRightBranch(int levels) { if (levels-- > 0) { glPushMatrix(); glTranslatef(1.0, -2.0, 0.0); drawTriangle(); drawRightBranch(levels); glPopMatrix(); } } /* recursively draw the tree */ GLvoid drawTree(int levels) { /* set colour depending on level */ glColor3f(1.0/levels,0.0,1-1.0/levels); /* draw this level */ drawTriangle(); if (--levels > 0) { /* complete the whole right-most branch descending from here */ drawRightBranch(levels); /* draw the next left branch node */ glPushMatrix(); glTranslatef(-1.0, -2.0, 0.0); drawTree(levels); glPopMatrix(); } } GLvoid display( GLvoid ) { glClear( GL_COLOR_BUFFER_BIT ); /* Do all your OpenGL rendering here */ /* Set up the transformations. We want to start from scratch every time, not build up the transformations */ glLoadIdentity(); /* Draw the top triangle */ drawTree(5); checkError( "display" ); glFlush(); } GLvoid init( GLvoid ) { glClearColor( 1.0, 1.0, 1.0, 1.0); glColor3f(1.0,0.0,0.0); glLineWidth(3.0); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-6, 6, -10, 2, -2, 2); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } int main( int argc, char *argv[] ) { glutInit( &argc, argv ); glutInitDisplayMode( GLUT_SINGLE | GLUT_RGB ); glutCreateWindow( argv[0] ); init(); glutKeyboardFunc( keyboard ); glutSpecialFunc( specialkeys ); glutDisplayFunc( display ); printHelp( ); glutMainLoop(); return 0; }