Tuesday, February 21, 2012

box2d.js: Box2D on the Web is Getting Faster

Box2D is a popular open source 2D physics library, used for example in Angry Birds. It's been ported to various platforms, including JavaScript through a previous port to ActionScript. box2d.js is a new port, straight from C++ to JavaScript using Emscripten. Here is a demo.

Last December, Joel Webber benchmarked various versions of Box2D. Of the JavaScript versions, the best (Mandreel's build) was 12x slower than C. Emscripten did worse, which was not surprising since back then Emscripten could not yet support all LLVM optimizations. Recently however that support has landed, so I ran the numbers and on the trunk version of SpiderMonkey (Firefox's JavaScript engine), Emscripten's version is now around 6x slower than C. That's twice as fast as the previous best result from December (three times as fast as Emscripten's result at that time).

That should get even faster as JavaScript engines and the compilers to JavaScript continue to improve. The rate of improvement is quite fast in fact, you will likely see a big difference between stable and development versions of browsers when running processing-intensive code like Box2D.

Aside from speed, it's important that the compiled code be easily usable. box2d.js uses the Emscripten bindings generator to wrap compiled C++ classes in friendly JavaScript classes, see the demo code for an example. Basically, you can write natural JavaScript like new Box2D.b2Vec2(0.0, -10.0) and it will call the compiled code for you.

(And of course, box2d.js is zlib licensed, like Box2D - usable for free in any way.)


  1. Great Project. Im really interested in this. However I do not get my complete code from other Box2D JS ports running with your code. Is there maybe the possibility that you can also upload a version using the original variable names instead of the shortened and also non-minified? This would enable me to debug my code more efficiently and would be awesome!

  2. With regard to my previous post:
    Now I found the unminified version (https://raw.github.com/kripken/box2d.js/2b903238945bf3d5126f12d553c7c41f95bfb535/box2d.js)
    But it is also not that suited for debugging :)

    My problem is that

    var jd = new b2RevoluteJointDef();
    jd.Initialize(body1, body2, body1.GetWorldCenter());

    creates a b2Joint instead of a b2RevoluteJoint.

    Is this maybe a problem with class inheritance?
    Maybe you can't help because it's a Box2D problem but maybe its also an error of Emscripten.