sâmbătă, 28 martie 2009

PyGame and OpenGL - part 1

OpenGL is an application programming interface.
The PyOpenGL modules has many functions and several matrices for working with 3D graphics.
This is one example how to use PyOpenGL.
I've successfully tested it under Linux.


import os
import sys
import pygame
from pygame import *
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *

def init_display(w, h):
pygame.display.set_mode( (w,h) , pygame.OPENGL | pygame.DOUBLEBUF )
glViewport(0, 0, w, h)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

glEnable(GL_LIGHTING)

glEnable(GL_LIGHT0)

glLight(GL_LIGHT0, GL_POSITION, (0, 0, 1, 0))
glMatrixMode(GL_PROJECTION);

glLoadIdentity();

gluOrtho2D(-1, 1, -1, 1);

glMatrixMode(GL_MODELVIEW);

def draw():
glClearColor(0.0, 0.0, 0.0, 1.0)
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
glColor(0,1,0)
glLight(GL_LIGHT0, GL_POSITION, (1, 1, 1, 0))
glMaterial(GL_FRONT, GL_AMBIENT, (0.1, 0.1, 0.1, 1.0))

glMaterial(GL_FRONT, GL_DIFFUSE, (1.0, 1.0, 1.0, 1.0))
glutSolidTorus(0.1,0.5,24,24)
pygame.display.flip()

def main():
pygame.init()
glutInit()
init_display(800, 600)
while 1:
event=pygame.event.poll ()
draw()
if event.type is KEYDOWN:
if event.key is K_ESCAPE:
sys.exit(0)
main()