好的,以下是一个简单的OpenGL程序,用于显示一个带纹理的立方体并实现旋转:
```python
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
# 设置窗口尺寸
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
# 定义立方体的顶点坐标
vertices = (
( 1, -1, -1),
( 1, 1, -1),
(-1, 1, -1),
(-1, -1, -1),
( 1, -1, 1),
( 1, 1, 1),
(-1, -1, 1),
(-1, 1, 1)
)
# 定义立方体的边
edges = (
(0,1),
(0,3),
(0,4),
(2,1),
(2,3),
(2,7),
(6,3),
(6,4),
(6,7),
(5,1),
(5,4),
(5,7)
)
# 定义立方体的面
surfaces = (
(0,1,2,3),
(3,2,7,6),
(6,7,5,4),
(4,5,1,0),
(1,5,7,2),
(4,0,3,6)
)
# 定义纹理坐标
tex_coords = (
(0, 0),
(1, 0),
(1, 1),
(0, 1)
)
# 加载纹理
def load_texture(filename):
texture_surface = pygame.image.load(filename)
texture_data = pygame.image.tostring(texture_surface, "RGB", 1)
width = texture_surface.get_width()
height = texture_surface.get_height()
texture = glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, texture)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexImage2D(GL_TEXTURE_2D, 0, 3, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, texture_data)
return texture
# 绘制立方体
def draw_cube(texture):
glEnable(GL_TEXTURE_2D)
glBindTexture(GL_TEXTURE_2D, texture)
glBegin(GL_QUADS)
for surface in surfaces:
for i, vertex in enumerate(surface):
glTexCoord2fv(tex_coords[i])
glVertex3fv(vertices[vertex])
glEnd()
glDisable(GL_TEXTURE_2D)
# 初始化OpenGL
def init_opengl():
glClearColor(0.0, 0.0, 0.0, 1.0)
glClearDepth(1.0)
glEnable(GL_DEPTH_TEST)
glDepthFunc(GL_LEQUAL)
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)
# 主函数
def main():
pygame.init()
display = (WINDOW_WIDTH, WINDOW_HEIGHT)
pygame.display.set_mode(display, DOUBLEBUF|OPENGL)
init_opengl()
texture = load_texture("texture.png")
glMatrixMode(GL_PROJECTION)
gluPerspective(45, (display[0]/display[1]), 0.1, 50.0)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glTranslatef(0.0, 0.0, -5.0)
clock = pygame.time.Clock()
angle = 0
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
glPushMatrix()
glRotatef(angle, 1, 1, 1)
draw_cube(texture)
glPopMatrix()
pygame.display.flip()
angle += 0.5
clock.tick(60)
if __name__ == "__main__":
main()
```
其中,`vertices`、`edges`、`surfaces` 和 `tex_coords` 定义了立方体的几何信息和纹理坐标,`load_texture` 函数用于加载纹理,`draw_cube` 函数用于绘制立方体,`init_opengl` 函数用于初始化 OpenGL,`main` 函数则是主函数,其中使用 Pygame 初始化窗口和 OpenGL,设置透视投影矩阵和模型视图矩阵,然后在主循环中不断旋转并绘制立方体。