Robin Berjon

The Joys of an Idle Weekend

JayTracer: A Trivial Raytracer In Javascript

Back in the late XXth century I used to be a big fan of the Persistence of Vision Raytracer (aka POV-Ray). My general lack of design taste, at best very fuzzy understanding of what I was doing, and a sluggish P166 combined to keep me from ever doing anything really good with it, but still I toiled the nights away making shiny metal balls that would reflect checkerboards in misty mornings.

That's why when I saw XQSharp's excellent tutorial on “Building an XQuery raytracer” (yes indeed, with XQuery) I couldn't resist. I just had to toy with porting it to Javascript. I'd be hard-pressed to give you a good reason why, and I do indeed know that it's been done before (and better, too!). I guess I wanted to toy directly with how it's done, and also liked the idea of seeing how XQuery and Javascript compare at this sort of task (which neither was really designed for in the first place). So at the weekend I took a few hours and ported the code over, tweaking a few things here and there. On my (slow) MacBook Air a 640x480 version of this scene takes 55 seconds to render, which isn't bad (the XQSharp guys apparently needed 8 minutes for theirs on presumably faster hardware — I'm surprised at the difference). One thing that's interesting to note is that it's fewer than 250 lines of code. Something real would need many more, but there's a lot of trivial 3D that can be done without going crazy. Anyway, the result is this:

You can go play with the test page and grab the source code if you wish. Note that it doesn't produce the image until it's done with it, so you might have to wait in front of your browser doing very much nothing for a while.