How I spent my Christmas holidays

gravity02

The Christmas tradition here at Codevomit is to spend some hours in front of our computers and churn out code as soon as it comes to our minds. After all, that is what codevomit is all about.

The goal of the past year holidays was to gain some basic knowledge of Scalable Vector Graphics and, possibly, of Git. I see SVG employed almost everywhere today and I am always impressed by the nice visual results that you can get. I wondered what I would have been able to do with it. In order to achieve such an ambitious result, I choose an example that I first implemented in Visual Basic when I was about seventeen and since then it always kept going around my mind. This is the outcome I am sooo proud to present to you. It took about 8 – 9 hours to get the basic engine to work, then another countless hours of relentless play to fix some major issues and have a lot fun. The source code is here and it’s still under development since I am currently working on a 3D version (and it works surprisingly well!).

The application is a 2D discrete simulation of celestial bodies interacting with each other according to Newton’s Law of Universal Gravitation. Technically, it is simply a web page with a couple of javascript files or, as they like to call it nowadays, an HTML5 + Javascript application. No server side work is done except for the good old Apache serving the page.

Instructions

First, you have to select the kind of celestial body that you want to add to the simulation. In order to do that, click on one of the “mass” buttons. Then, click on the canvas and, while you are still holding the left mouse button, drag. You will see that a red line follows your mouse movement: that line is the initial speed vector that your body will have. The longer it is, the faster your object will go.

speed-vector

At this point, the objects are still immobile. The simulation can be started, stopped, reset, etc…, with the buttons at the bottom of the canvas. You can also enable traces with the corresponding button and get some nice draws like the one I pasted at the beginning of the post.

When you get a nice configuration, you can save it with the “SAVE” button. The state of the simulation is serialized to text (XHTML + JSON) and written in the textbox, from which you can copy it. You can restore it at any time: just paste the text back to the textbox and click the “RESTORE” button.