# Demonstration of depth buffering # # This program takes the code from class 9's orbit3d demo, and adds depth # buffering calls. When depth buffering is active, the orbiting yellow # planet will be properly hidden by the blue and red planets when it passes # behind them. # Depth buffering is toggled on & off by pressing the space bar. import sys import time from OpenGL.GLUT import * from OpenGL.GL import * from OpenGL.GLU import * useDepthBuffer = 0 angle0 = 0 angle1 = 90 angle2 = 0 prevTime = time.time() def drawPlanet(radius, color): glColor3fv(color) glBegin(GL_QUADS) glVertex2f(-radius, -radius) glVertex2f(radius, -radius) glVertex2f(radius, radius) glVertex2f(-radius, radius) glEnd() def draw(): global angle0, angle1, angle2, useDepthBuffer if useDepthBuffer: glEnable(GL_DEPTH_TEST) else: glDisable(GL_DEPTH_TEST) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glLoadIdentity() # glTranslatef(0, 0, -2) drawPlanet(0.2, [0, 0, 1]) glPushMatrix() glRotatef(angle0, 1, 0, 0) glTranslatef(0.6, 0.0, 0.0) drawPlanet(0.1, [1, 0, 0]) glPopMatrix() glPushMatrix() glRotatef(angle1, 0, 1, 0) glTranslatef(0.7, 0.0, 0.0) drawPlanet(0.08, [1, 1, 0]) glPushMatrix() glRotatef(angle2, 0, 0, 1) glTranslatef(0.2, 0.0, 0.0) drawPlanet(0.03, [0.25, 1, 0.25]) glPopMatrix() glPopMatrix() glutSwapBuffers() def keyboard(key, x, y): if key == chr(27): sys.exit(0) elif key == ' ': global useDepthBuffer useDepthBuffer = not useDepthBuffer if useDepthBuffer: print "depth buffering on" else: print "depth buffering off" def update(): global angle0, angle1, angle2 global prevTime currentTime = time.time() deltaTime = currentTime - prevTime prevTime = currentTime angle0 = angle0 + 120 * deltaTime angle1 = angle1 + 60 * deltaTime angle2 = angle2 + 270 * deltaTime glutPostRedisplay() glutInit(sys.argv) glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH) glutInitWindowSize(400, 400) glutInitWindowPosition(0,0) glutCreateWindow(sys.argv[0]) glutDisplayFunc(draw) glutKeyboardFunc(keyboard) print "Hit space bar to toggle depth buffering on or off" print "Depth buffering is off to start with" glutIdleFunc(update) #glMatrixMode(GL_PROJECTION) #gluPerspective(60, 1, 1, 100) #glMatrixMode(GL_MODELVIEW) glEnable(GL_DEPTH_TEST) glutMainLoop()