Animating with Greenlets

Post date: 24-Nov-2008 08:35:30

Over the weekend I started building some basic animation into Faultline, and I hit the classic problem of maintain state for multiple animation effects, while also trying to provide a responsive GUI. A neat solution is available in Greenlets - a lightweight tasklet library that came out of the work done on the Stackless Python project.

Greenlets are like threads, but without the locking problems (since only one is ever running at any time.) They allow you to freeze methods at any point and switch between them, allowing the creation of co-routines and more elegantly structured code. In Faultline I switch to each animation effect greenlet once per frame - they each complete one frame's worth of changes and then switch back to the main task. As a result each effect is a very simple method wrapped in a greenlet - something like this:

g_tile = greenlet(tile.move_tile)

...tile declaration...

def move_tile(self):

while self.height < self.destination:

self.height += self.speed

self.speed += 1

greenlet.getcurrent().parent.switch()

[similar code in Faultline: field.py, r23.]

So each time we switch to the g_tile greenlet, it runs through one iteration of the animation and switches back to it's parent.

This is a pretty trivial example, but as the animation effects get more complicated the advantages of wrapping them in greenlets will get steadily greater. This style of programming also has the potential to make network and UI code more elegant too. I'm pretty excited about how handy this library is - we'll see if it introduces any interesting coding problems...