import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
verticies = (
(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)
)
def Cube():
glBegin(GL_LINES)
for edge in edges:
for vertex in edge:
glVertex3fv(verticies[vertex])
glEnd()
def main():
pygame.init()
display = (800,600)
pygame.display.set_mode(display, DOUBLEBUF|OPENGL)
gluPerspective(45, (display[0]/display[1]), 0.1, 50.0)
glTranslatef(0.0,0.0, -5)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
glRotatef(1, 3, 1, 1)
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
Cube()
pygame.display.flip()
pygame.time.wait(10)
main()
This is some example code taken from https://pythonprogramming.net that creates a simple cube and draws it on screen. It has and accompanying tutorial playlist featured here.
You will need to have the seperate PyOpenGL installed which can be found here.
In the example code he first creates a list of vertices and a list of edges that references the index of each vertex. He then creates a simple Cube class which loops through each vertex and connects them with lines.
In the main function when pygame.display.set_mode()
is called, it should have the DOUBLEBUF
tag to create a double buffer, and the OPENGL
tag to have pygame create an OpenGL-renderable display. You can find more info on the Pygame display module at the Pygame docs here.
He then creates the OpenGL perspective with gluPerspective
with the FOV, Aspect-ratio, and near and far clipping planes glTranslatef
translates the display (in this case -5 on the z axis.
In the main loop, among the normal Pygame code, glClear
clears the display with the flags being what is meant to be cleared, and the Cube()
class which creates the wireframe cube that was mentioned earlier.
Hopefully this helps you on the track learning PyOpenGL in Pygame.