June 4, 2007 will

OpenGL sample code for PyGame

I've uploaded a simple example of how to use OpenGL with PyGame. It's a listing from my forthcoming book, Beginning Game Development with Python and PyGame, and demonstrates how to initialize OpenGL, create a light and draw a simple 3D 'world'. It also shows how to use the camera matrix to create a simple 'fly-cam'.

To run it you will need PyOpenGL, which you can download from the website, or from the command line if you have Easy Install (type easy_install PyOpenGL). Use the cursor keys to look around, and the Q/A keys to move forward and back. You can also press Z and X to roll the camera.

Download simpleopengl.py

Here's a screenshot.

pyg3d

I'm impressed by the ease of using OpenGL with PyGame. It's a one liner to create an OpenGL display, and the OpenGL bindings work well. With good use of display lists or vertex arrays, performance can be on par with commercial games. To put it in perspective, you could render an entire 3D object in less time it takes to draw a simple 2D sprite. I hope people take advantage of it, because the 'casual games' market is huge right now, and Python could give developers a serious advantage in getting games to market quickly!

Update: I experimented with recording the demo using Fraps, which worked rather nicely - I may even consider buying it! I didn't realize it was recording audio though, or I may have chosen a different soundtrack (it recorded a portion of mp3 I was listening to). Hope nobody sues me. Here's the a video of the demo.

Use Markdown for formatting
*Italic* **Bold** `inline code` Links to [Google](http://www.google.com) > This is a quote > ```python import this ```
your comment will be previewed here
gravatar
Sean Berry

This is really great, thanks!

gravatar
Robb Drinkwater

Will,
Thanks for sharing this. Great coding. It gave me a huge leg up on understanding GL in PyGame and a great start on my (non-commercial) project.
But you didn't include any GNU license... and I'd like to give credit where it's due.
Also, did you write the matrix44 & vector3 classes? Very elegant and infinitely useful... they should be part of the standard library.
(BTW If you are not the author, do you know who is? Again: credit due)

So thanks again for the great code!
rd

gravatar
Richard

Well,I like to say thank you this gets me closer to understandig opengl. Since my compt refuses to let me play anymore it claims it cannot open the gl,weird ha, mohaa.os was before ME i SWITCH TO,WINDOWS XP HOME EDITION.MORE POWER TO YA SOON i SHALL PLAY AGAIN.

gravatar
Jon

Hi, I'm getting the following error, any ideas how to fix it. Thanks.

Traceback (most recent call last):
File "firstopengl.py", line 231, in
run()
File "firstopengl.py", line 225, in run
map.render()
File "firstopengl.py", line 133, in render
cube.render()
File "firstopengl.py", line 73, in render
glColor( self.color )
File "build/bdist.macosx-10.3-fat/egg/OpenGL/GL/exceptional.py", line 207, in glColor
KeyError: 1

gravatar
Will

Hi Jon,

Are you running the latest version of PyOpenGL?

Try replacing the glColor line with the following:

glColor( *self.color )

Will

gravatar
Jon

Hi Will,

Thanks Will that's fixed it. What was the cause of the error if you don't mind me asking ?

BTW do you know when your book will be available in the UK ?

Cheers
Jon

gravatar
Will

I'm guessing that the version of PyOpenGL I was using expands Python sequences and calls an appropriate glColor*v function in C. The version you are using must require four separate values. If I'm right you could also do glColorv(self color), which is probably more efficient.

The book should be out everywhere on the 24th, but Amazon.co.uk are showing the wrong date!

gravatar
rudbol

I'm getting this error trying to run "firstopengl":

Traceback (most recent call last):
File "/home/rudin/Skrivebord/python-bok/firstopengl.py", line 184, in
run()
File "/home/rudin/Skrivebord/python-bok/firstopengl.py", line 169, in run
camera_matrix.translate += movement * time_passed_seconds
File "/usr/lib/python2.5/site-packages/gameobjects/vector3.py", line 247, in __radd__
ox, oy, oz = lhs
ValueError: too many values to unpack

petzolt@online.no

gravatar
Sahadev Tarei

I’m guessing that the version of PyOpenGL I was using expands Python sequences and calls an appropriate glColor*v function in C. The version you are using must require four separate values. If I’m right you could also do glColorv(self color), which is probably more efficient.

gravatar
Ryan
When I run the demo under Ubuntu 8.10 it works great, but under Vista and OSX all the cubes are black. Any ideas?
gravatar
Will McGugan
Hi Ryan, I reproduced the black cubes issue on Ubuntu by upgrading OpenGL to the latest version (3.0.0c1) via easy_install.

It seems that in the latest version, glColor wont accept colours as an iterable of 3 value and requires 3 distinct value. Fortunately the fix is easy, just insert an asterisk to unpack the color.

So the start of the Cube's render method should look like this:

     def render(self):
        glColor( *self.color )
gravatar
Adam
I've just updated from Ubuntu 8.10 to 9.04 and it seems to have broken something. It doesn't crash, but does seem to compress all the cubes into a single flat panel. I am now using pygame to 1.8.1 and pyopengl to 3.0.0b6-3.

Any idea what could have caused it? Other pygame opengl things seem to work fine (e.g. pygame NeHe samples).
gravatar
Ryan
I just had the same problem.
gravatar
Adam
It seems as though this is a python 2.5 vs 2.6 problem. Explicitly using “python2.5” instead of “python” seems to solve it.
gravatar
Adam
This may be a Python 2.6 vs Python 2.5 problem. Explicitly using “Python2.5” to execute it works fine, but “Python” (which defaults to 2.6 on Ubuntu 9.04) doesnt. Of course, it could be different libraries for different python versions too.
gravatar
gnatinator
Just so you're aware, this example is broken in the last two versions of PyOpenGL for Windows (3.0.0c1 and 3.0.0). All polygons get rendered black.
gravatar
Will McGugan
gnatinator, See this reply for a solution
gravatar
joC
Hi Will, thanks for the book. I'm having lots of fun.

Get this error when I try to run firstopengl.py. (Running Ubuntu 9.04):

jo@tux:~/pygameBook/Chapter09$ python firstopengl.py
get fences failed: -1
param: 6, val: 0
Traceback (most recent call last):
File “firstopengl.py”, line 237, in <module>
run()
File “firstopengl.py”, line 230, in run
map.render()
File “firstopengl.py”, line 141, in render
cube.render()
File “firstopengl.py”, line 94, in render
glVertex( vertices )
File “/usr/lib/python2.6/dist-packages/OpenGL/GL/exceptional.py”, line 133, in glVertex
return glVertexDispatch( args )
ctypes.ArgumentError: argument 1: <type ‘exceptions.TypeError’>: byref() argument must be a ctypes instance, not ‘tuple’

I've added the * to the start of the Cube render method, but get the same error, so it's not related to that.

Any clues?
gravatar
joC
Well, the rendering of that error message is abysmal! Sorry about that.
I'm sure you'll get the drift.
gravatar
pelle
joC, I found this page after googling for that exact error message. The solution I found (and that was pure trial and error; I have no idea what I am doing) was to change the four calls to glVertex to glVertex3dv.

I'm using python 2.5.2
OpenGL.__version__ ‘3.0.0b6’
gravatar
Manuel
Thank you very much for this useful example!
Did you spend a thought on how to avoid upcoming deprecation issues when using glBegin and glVertex in pyOpenGL 3.1?
I have no idea what to use else.
gravatar
konaya
Using Ubuntu 10.10, Python 2.6.6, I get yet another odd problem. The entire “PyGame” part is coloured green, as is a wee bit of the “face”. The rest is coloured a light skin tone. Why's this?

Screenshot: http://i54.tinypic.com/2h7p0er.jpg
gravatar
Adam
Hi! On ubuntu 11.10 with python 2.7.2, I got the green cubes problem, as mentioned earlier. To solve it I moved the glColor( *self.color ) command between the glBegin-glEnd statements. It seems to me, that this is an OpenGl library bug.
gravatar
Bill Nye
W = Move Forward
A = Move Left
S = Move Backward
D = Move Right
Q = Strafe Left
E = Strafe Right
Mouse = Move Camera
ESC = Quit (the only one you got right)

Havent you ever actually PLAYED a video game before?
gravatar
hfcoder
can somebody solve this code to me?
(i never used pyOpenGL before)
(sorry my bad English )
gravatar
ORyan
The link to your demo is down. Getting 404. Is it still available?
gravatar
Will McGugan
@ORyan It's back up!
gravatar
Jamall
Hi Will

Can't seem to run any pyopengl applications on my Win7 64bit setup. Using python 3.3 but keep getting error saying _init_ takes 2 positional arguments but only one given. Any help would be appreciated please as I'd like to get to grips with python and opengl. Thanks.
gravatar
Tom
Hi Will

I get the following error when i try to run “simpleopengl.py”.

Traceback (most recent call last):
File “firstopengl.py”, line 233, in <module>
run()
File “firstopengl.py”, line 149, in run
screen = pygame.display.set_mode(SCREEN_SIZE, HWSURFACE|OPENGL|DOUBLEBUF)
pygame.error: Couldn't find matching GLX visual

Any ideas how to fix it. I'm running the default version of Raspbian on a Raspberry Pi with pyopengl installed.
gravatar
Tom
Hi Will

I get the following error when i try to run “simpleopengl.py”.

Traceback (most recent call last):
File “firstopengl.py”, line 233, in <module>
run()
File “firstopengl.py”, line 149, in run
screen = pygame.display.set_mode(SCREEN_SIZE, HWSURFACE|OPENGL|DOUBLEBUF)
pygame.error: Couldn't find matching GLX visual

Any ideas how to fix it. I'm running the default version of Raspbian on a Raspberry Pi with pyopengl installed.
gravatar
Tom
Sorry for the double comment my browser is very slow.
gravatar
Frostlock
Thanks for this! It really helped me to properly implement the “camera” in my pygame-opengl project :)

Cheers!

gravatar
Jorge A. Gomes
Good example code.

It could be updated to expose today's rendering techniques (anything that does not use glBegin/glEnd calls).
gravatar
petermwale

Hey...Will...am studying game dev using your book...now I just have a blank PyOpenGL window...but the code is as u wrote...and also can u help me find that Matrix44 module pleade

gravatar
emmanuel akanni

Traceback (most recent call last): File "C:/Users/Emma/AppData/Local/Programs/Python/Python38-32/opengl.py", line 11, in <module> from gameobjects.matrix44 import * ModuleNotFoundError: No module named 'gameobjects'