/* prac7b.c */ /* Purpose: Investigate the depth buffer */ #ifdef __APPLE__ #include #else #include #endif #include #include #define KEY_ESC 27 /* glut doesn't define this one */ /* Global Constants and Variables */ static GLfloat mNearClip = 10.0; /* near clipping plane */ static GLfloat mFarClip = 20.0; /* far clipping plane */ static GLfloat mLocation = 0.0; /* sphere location as measured from the middle of the near and far clipping planes */ void printHelp( void ) { fprintf(stdout, "\n Depth Buffer\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; case ' ': mLocation -= 0.1; glutPostRedisplay(); printf("%f\n", mLocation); 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(); } } void reshape(GLint width, GLint height) { GLdouble aspect; aspect = (GLdouble)width / (GLdouble)height; /* We still want the output to cover the whole window */ glViewport(0, 0, width, height); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); gluPerspective(50, aspect, mNearClip, mFarClip); glMatrixMode( GL_MODELVIEW ); } /* Draw a grid in the XY plane */ void drawXYGrid(void) { static const GLfloat max = 20; int i; glBegin(GL_LINES); for(i=-max; i <=max; ++i) { glVertex2f(-max, i); glVertex2f(max, i); glVertex2f(i, -max); glVertex2f(i, max); } glEnd(); } GLvoid display( GLvoid ) { glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); /* Do all your OpenGL rendering here */ glLoadIdentity(); /* Reset the ModelView transformation every time we draw */ /* Translate our origin to midway between the near and far clipping plane */ glTranslatef(0, 0, -(mNearClip+mFarClip)/2); glColor3f(0.0, 0.0, 1.0); drawXYGrid(); glColor3f(0.0, 1.0, 1.0); glTranslatef(0, 0, mLocation); glutSolidSphere(2.0, 20, 20); checkError( "display" ); glFlush(); } void init( void ) { glClearColor( 1.0, 1.0, 1.0, 1.0); glColor3f(1.0,0.0,0.0); glLineWidth(3.0); glEnable(GL_DEPTH_TEST); } int main( int argc, char *argv[] ) { glutInit( &argc, argv ); glutInitDisplayMode( GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH ); /* Remember to call glEnable(GL_DEPTH_TEST) later */ glutCreateWindow( argv[0] ); init(); glutKeyboardFunc( keyboard ); glutSpecialFunc( specialkeys ); glutDisplayFunc( display ); glutReshapeFunc( reshape ); printHelp( ); glutMainLoop(); return 0; }