July 29, 2008

A Trackball Camera for Pyglet

A week or so ago, I needed to write a simple OpenGL demonstration program. I decided to use pyglet since it is such a great utility. Of course, it is always nice to be able to move around your demo, so I looked for a "trackball" to control the camera. But, I came up empty.

So, to scratch that itch, I remembered & found the old GLUT example code in trackball.c and ported it to python. It wasn't that hard to do, but looking at how the code worked it brought back that in 1993 every cycle certainly counted. I refactored it significantly.

I also pushed the manipulation of the GL_MODELVIEW matrix into this class. It seemed a nice way to separate the code and make it into a proper camera. Anyway, a short while later and out popped my code and you can get it by going to


To use it, there are just a few public entrypoints.

Initialize the camera with a radius from the center/focus point:

tbcam = TrackballCamera(5.0)

After adjusting your projection matrix, set the modelview matrix.

tbcam.update_modelview()

On each primary mouse click, scale the x & y to [-1,1] and call:

tbcam.mouse_roll(x,y,False) # the final flag indicates this is a 'click' not a 'drag'

On each primary mouse drag:

tbcam.mouse_roll(x,y)

Mouse movements adjust the modelview projection matrix directly.

There is also a routine for mouse_zoom(x,y)

I hope you can find this useful.