本文要点在于Python扩展库pyopengl的应用,关于OpenGL函数参数含义可以查阅有关资料。
import sys
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
class MyPyOpenGLTest:
def __init__(self, width = 640, height = 480, title = b'OpenGL--gradient color'):
glutInit(sys.argv)
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH)
glutInitWindowSize(width, height)
self.window = glutCreateWindow(title)
self.InitGL(width, height)
glutDisplayFunc(self.Draw)
glutIdleFunc(self.Draw)
#绘图方法
def Draw(self):
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
#平移
glTranslatef(-2.0, 0.0, -8.0)
#绘制二维多边形
glBegin(GL_POLYGON)
glColor3f(1.0, 0.0, 0.0)
glVertex3f(0.0, 3.0, 0.0)
glColor3f(0.0, 1.0, 0.0)
glVertex3f(2.0, -2.0, 0.0)
glColor3f(0.0, 0.0, 1.0)
glVertex3f(-2.0, -2.0, 0.0)
glEnd()
#平移
glTranslatef(3.5, 1.5, 0.0)
#缩放
glScale(0.5, 0.5, 0.5)
#绘制二维多边形
glBegin(GL_POLYGON)
glColor3f(1.0, 1.0, 0.0)
glVertex3f(0.0, 3.0, 0.0)
glColor3f(0.0, 1.0, 1.0)
glVertex3f(2.0, -2.0, 0.0)
glColor3f(1.0, 0.0, 1.0)
glVertex3f(-2.0, -2.0, 0.0)
glEnd()
glTranslatef(0.0, -4.0, 0.0)
glScale(0.5, 0.5, 0.5)
#绕z轴旋转45度
glRotatef(45.0, 0.0, 0, 1)
#绘制二维多边形
glBegin(GL_POLYGON)
glColor3f(0, 1.0, 0.5)
glVertex3f(0.0, 3.0, 0.0)
glColor3f(0.5, 1.0, 0.0)
glVertex3f(2.0, -2.0, 0.0)
glColor3f(1.0, 0.0, 0.5)
glVertex3f(-2.0, -2.0, 0.0)
glEnd()
glutSwapBuffers()
def InitGL(self, width, height):
glClearColor(1.0, 1.0, 1.0, 0.0)
glClearDepth(1.0)
glDepthFunc(GL_LESS)
#单色渲染
#glShadeModel(GL_FLAT)
#平滑渲染模式
glShadeModel(GL_SMOOTH)
glEnable(GL_POINT_SMOOTH)
glEnable(GL_LINE_SMOOTH)
glEnable(GL_POLYGON_SMOOTH)
glHint(GL_POINT_SMOOTH_HINT,GL_NICEST)
glHint(GL_LINE_SMOOTH_HINT,GL_NICEST)
glHint(GL_POLYGON_SMOOTH_HINT,GL_FASTEST)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(45.0, float(width)/float(height), 0.1, 100.0)
glMatrixMode(GL_MODELVIEW)
def MainLoop(self):
glutMainLoop()
if __name__ == '__main__':
w = MyPyOpenGLTest()
w.MainLoop()
运行效果如图: