Programming

Drawing rectangles in PyGTK: GDK vs. Cairo

Someone on the PyGTK mailing list just asked which is faster for drawing rectangles, GDK or Cairo.

I wasn't sure, so I wrote a silly little test program.  Note that it's not quite apples-to-apples as the Cairo rectangles have variable transparency while the GDK rectangles are opaque.

On my box, running Gentoo Linux and the latest stable versions of everything, the Cairo version draws 500 rectangles in about 0.01 to 0.03 seconds, while the GDK version takes about 0.13 to 0.14 seconds.  So Cairo is faster.

To run this, just cut-and-paste into an editor window, save the file as rectangles.py, and run "python rectangles.py"

#!/usr/bin/env python

"""GTK rectangle drawing speed test, GDK vs. Cairo

David Ripton 2008-12-03
MIT license
"""

import time
import random

import gtk

NUM_RECTS = 500

handle_id = None

def main():
    window = gtk.Window()
    window.connect("destroy", gtk.main_quit)
    window.set_default_size(800, 600)
    vbox = gtk.VBox()
    window.add(vbox)
    area = gtk.DrawingArea()
    vbox.pack_start(area)
    gdk_button = gtk.Button("GDK")
    gdk_button.connect("clicked", on_gdk_button_clicked, area)
    vbox.pack_start(gdk_button, expand=False)
    cairo_button = gtk.Button("Cairo")
    cairo_button.connect("clicked", on_cairo_button_clicked, area)
    vbox.pack_start(cairo_button, expand=False)
    window.show_all()
    gtk.main()

def on_gdk_button_clicked(button, area):
    global handle_id
    if handle_id is not None:
        area.disconnect(handle_id)
    handle_id = area.connect("expose-event", on_area_exposed_gdk)
    area.queue_draw()

def on_cairo_button_clicked(button, area):
    global handle_id
    if handle_id is not None:
        area.disconnect(handle_id)
    handle_id = area.connect("expose-event", on_area_exposed_cairo)
    area.queue_draw()

def on_area_exposed_gdk(area, event):
    t0 = time.time()
    width, height = area.window.get_size()
    colormap = area.get_colormap()
    gc = area.get_style().fg_gc[gtk.STATE_NORMAL]
    for ii in xrange(NUM_RECTS):
        r = random.randrange(0, 65535 + 1)
        g = random.randrange(0, 65535 + 1)
        b = random.randrange(0, 65535 + 1)
        gc.foreground = colormap.alloc_color(r, g, b)
        x = random.randrange(0, width)
        y = random.randrange(0, height)
        w = random.randrange(0, width - x)
        h = random.randrange(0, height - y)
        area.window.draw_rectangle(gc, True, x, y, w, h)
    t1 = time.time()
    print "gdk drew %d rectangles in %f seconds" % (NUM_RECTS, t1-t0)

def on_area_exposed_cairo(area, event):
    t0 = time.time()
    cr = area.window.cairo_create()
    width, height = area.window.get_size()
    for ii in xrange(NUM_RECTS):
        r = random.random()
        g = random.random()
        b = random.random()
        a = random.random()
        cr.set_source_rgba(r, g, b, a)
        x = random.randrange(0, width)
        y = random.randrange(0, height)
        w = random.randrange(0, width - x)
        h = random.randrange(0, height - y)
        cr.rectangle(x, y, w, h)
        cr.fill()
    t1 = time.time()
    print "cairo drew %d rectangles in %f seconds" % (NUM_RECTS, t1-t0)

if __name__ == "__main__":
    main()

screen shot of the cairo rectangles


Rant: It is way too hard to post code with WordPress. First I tried the "code" button, but all my indentation was destroyed (bad for any code, fatal for Python). Then I tried the "b-quote" button; same effect. Then I switched to HTML mode and hand-inserted a "pre" tag, which preserved the indentation. But WordPress then proceded to vandalize my code with "smart" quotes. (Have you ever seen anything with "smart" in its name that actually was?) Luckily it was simple to find and install the wpuntexturize plugin, a few lines of PHP that eradicate Moron Quotes. But why the hell are they there in the first place, let alone enabled by default, let alone enabled by default inside a "pre" tag?

Programming
Python
Rant

Comments (0)

Permalink

AmpChat WxPython support

Stephen Waterbury added a WxPython client to my AmpChat example program. (Mentioned earlier in this post.)

His Mercurial repository is here.

This is still just example code, but now it's an example of multiple things:

  • how to use Twisted AMP
  • how to use Twisted with PyGTK (trivial because gtk2reactor rocks)
  • how to make WxPython's mainloop run in parallel with Twisted's using threads
  • how to write the same simple GUI program in both PyGTK and WxPython
  • how to use Mercurial to contribute to a project without commit rights in the original repo

Anyone want to contribute a PyQT or Tk version?

Programming
Python

Comments (0)

Permalink

I'm no longer maintaining Colossus

I started Colossus in December 1997, almost 11 years ago. Yesterday I turned over leadership of the project to Clemens Katzer. That's a long time to maintain a software project, and it feels weird to me that I finally quit.

Colossus was my first large game project, my first large Java program, my first large GUI program, my first experience working on a complex game AI, and my first time managing a significant multi-programmer software project. Somehow it worked out pretty well, for the first few years. We had a pretty full-featured, stable Titan game, with somewhat dumb but working AI, and support for lots of cool variants. We had a rotating team of up to half a dozen developers at a time working on the game, and it was fun.

But then I added network play, and I didn't do a very good job. At the time there were no Java remote method libraries that had the features we needed, so I wrote everything myself with a simple string socket protocol, with lots of receiver threads. But I wasn't rigorous enough with thread synchronization, which meant walking the line between deadlock and corrupted game data. And gaining acceptable performance meant that a lot of logic that existed on the server side needed to be reproduced on the client side, but excessive coupling in the code base meant this couldn't be done cleanly and a lot of code got duplicated. I tried and tried to fix the mess, but couldn't put Humpty-Dumpty together again.

I finally decided to start over, in a better programming language (Python), with a better networking framework (Twisted), with a better overall design paradigm (game events flowing from the server to the client, using the Observer pattern to reduce coupling and allow complete reuse of the core game logic between the client and server) and with safe sane single-threaded code. Thus was born Slugathon. Unfortunately, as a new father I didn't have nearly as much free time as I did back when I started Colossus, and so Slugathon still isn't finished.

With Slugathon unfinished I felt obligated to keep maintaining Colossus, but I didn't really have my heart in it. I figured my job was to keep the project alive until a successor showed up to take it over. We had several guys on the team who were technically qualified to take over, but none seemed likely to put in the necessary amount of time on a consistent basis. Then Clemens joined, and not only submitted code for his pet features (the fun part that everyone wants to do) but started watching the bug tracker like a hawk, and talking to users about their bugs, and making special test builds so that users could test that their obscure hard-to-reproduce bugs were fixed, and adding documentation of which features went into which releases, and all the other not-fun crap that 90% of small volunteer open source projects can't find anyone to do. Around the same time, longtime contributor Peter Becker did a giant refactoring that reduced the amount of code duplication from disgusting to merely gross. And Clemens switched the server side from listener threads to NIO, reducing the total thread count from insane to merely scary.

Which meant I was no longer needed on Colossus. So I'm committing to releasing a stable, network-playable version of Slugathon by the end of 2008. And hoping that the Colossus team can continue cleaning up the mess I left them. Hopefully someday soon we'll have two stable networked Titan games instead of zero.

(By the way, I played a couple of four-human 2-AI networked Abyssal6 Colossus games this morning. It was great fun, even though both games had technical difficulties.)

Games
Programming
Python

Comments (0)

Permalink

Converting a svn working copy to a git-svn repo

I'm at Pycon, where we have wlan in the common areas but not in the hotel rooms (unless you pay $12/day extra). I'd like to be able to continue working on Slugathon in my room. I have a deep psychological need to check my changes in frequently.

For simple projects (one programmer, trunk only, no branches), svn is fine, until you lose your network connection to the svn server. For disconnected work on a project that lives in svn, you want git-svn. (Or maybe svk, but I don't know svk.)

Anyway, here's the recipe, starting from a working copy in ~/src/Slugathon

  1. cd ~/src/Slugathon
  2. svn status, to make sure I have no changes that aren't checked in
  3. svn info, to find the URL to the svn repository
  4. mkdir ~/src/Slugathon-git
  5. cd ~/src/Slugathon-git
  6. git svn init -t tags -b branches -T trunk URL (using URL from step 3)
  7. git svn fetch (this can be slow, for a large project, and you need net access)
  8. git log, to confirm that the history is right
  9. Ensure that the working copy has the expected files
  10. (optional) rm -rf ~/src/Slugathon; mv ~/src/Slugathon-git ~/src/Slugathon

Of course, this only helps if you know git and git-svn.  I know how to use them day-to-day, but I always have to lookup infrequent operations like this.

Programming

Comments (0)

Permalink

Twisted AMP chat example

I wrote a simple little PyGTK chat program a couple of months ago, to learn the Twisted AMP protocol.

Someone just asked about bidirectional AMP on the Twisted mailing list, which reminded me that I should publicize this example a bit.

It's in a Mercurial repository (browseable over the web if you don't want to bother with Mercurial) at
http://ripton.net/hg/ampchat

Programming
Python

Comments (1)

Permalink

"+" is valid in an email address, dammit

Dreamhost supports email addresses of the form base+whatever@domain.com

The mail goes to the same address as base@domain.com, but you can filter on the +whatever

It astounds me how many web pages refuse to accept an email address with a + in it as valid. It's valid. Really. I get the mail.

Parsing whether something is a valid email address is hard. (See the O'Reilly Mastering Regular Expressions book for a serious attempt.) If you're not willing to go to those lengths, Don't Try. You'll just make people with unusual-looking but valid email addresses mad.

If you really need the address to be valid, then send mail to it, and make the user do something to prove he received the mail.

If you don't, then trust the user. He knows more about his email address than you do.

Programming
Rant

Comments (0)

Permalink

SLOC counts for various version control systems

At work I'm currently using Git and Subversion and Mercurial for version control. Other people there are using Bazaar and CVS. Too many programs to learn! We need to eventually standardize on a primary third-generation distributed tool to replace Subversion, but it hasn't happened yet.

There are lots of opinions on which third-generation distributed version control system should replace Subversion. (I like Mercurial a lot, respect Git's power despite its ridiculous learning curve, and haven't used Bazaar enough to have a strong opinion about it, except that it used to be unusably slow.)

Here's one data point you won't see in all the comparisons: code size as measured by sloccount:

Name Version SLOC
CVS 1.12.12 136,873
Subversion 1.4.6 492,564
Mercurial 0.9.5 40,682
Git 1.5.4rc1 142,669
Bzr 1.1 125,637

Why is Subversion more than triple the size of any of its main competitors? C, two backends, language bindings, separate libraries for client and server, Apache / Webdav integration, separate admin tool, yadda yadda yadda. Do you really need all that?

Why is Mercurial less than a third the size of any of its main competitors? It's in Python, and there's definitely an aversion to feature creep, to the point where lots of features that would be core in other programs are extensions in Mercurial. (Note that the extensions that are bundled with the project are included in its SLOC number, while the ones you'd need to download separately are not.) What else? It is missing some features compared to, say, Git, but it's sure not missing two-thirds of them. Why is Bzr, which is also written in Python and has a roughly comparable feature set, three times as big?

How important is lean code? What features can the Mercurial team implement by the time Subversion merge tracking is done and stable? Is there actually anyone who can name all 143 programs that git put in my /usr/bin/ directory?

Linux
Programming

Comments (0)

Permalink