import sys, time, math from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * from dmsgl import * camera = OrthoCamera(-25,25, 0,50, -25,25) point0 = Vector([-10, 25, 0]) velocity0 = Vector([0, 0, 0]) mass0 = 1 point1 = Vector([10, 25, 0]) velocity1 = Vector([0, 0, 0]) mass1 = 10 springConstant = 1 restLength = 15 light = Light() material = Material(diffuse=Color.Grey70) ball0Xform = SimpleTransform(translate=point0) ball1Xform = SimpleTransform(translate=point1) active = False def draw(): Color.Black.clear() camera.apply() light.apply() material.apply() ball0Xform.pushApply() gluSphere(quadric, 1.0, 32, 16) ball0Xform.pop() ball1Xform.pushApply() gluSphere(quadric, 1.0, 32, 16) ball1Xform.pop() material.disable() Color.Red.apply() glBegin(GL_LINES) glVertex3fv(point0) glVertex3fv(point1) glEnd() glutSwapBuffers() def keyboard(key, x, y): global active if key == chr(27): sys.exit(0) elif key == ' ': active = not active prevTime = time.time() def update(): global prevTime, active, velocity0, velocity1, point0, point1, ballXform0, ballXform1 t = time.time() dt = t - prevTime prevTime = t if active: v = point1 - point0 displacement = v.length() - restLength v.normalize() force = springConstant * displacement * v accel = force / mass0 velocity0 += accel * dt point0 += velocity0 * dt ball0Xform.translate = point0 accel = -force / mass1 velocity1 += accel * dt point1 += velocity1 * dt ball1Xform.translate = point1 glutPostRedisplay() glutInit([]) glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH) glutInitWindowSize(400,400) glutCreateWindow(sys.argv[0]) glutDisplayFunc(draw) glutKeyboardFunc(keyboard) glutIdleFunc(update) glEnable(GL_DEPTH_TEST) quadric = gluNewQuadric() glutMainLoop()