Sunday, April 8, 2012

HTML5 heat spreading simulation

I was reading an algorithm book the other day and found a rather interesting section about simulations.

I really like simulations and I think it's awesome that computers can calculate and display something from the real world.

I came across an algorithm called the "Gauss-Seidel iteration" which can be used to calculate heat spreading in 1D (stick) or 2D (hotplate).

I first implemented it in Java and was very happy with the performance so I decided to recode it in HTML5

this is the result-> http://chr1s.at/heat/

If your browser can't handle it, here are some screenshots:
When you click and drag the mouse somewhere you create a heat spot (rendered red). This is done by adding another grid behind the rendered grid which is used just to store the heat.

The ASCII render mode just replaces tile colors with the heat values of the field. Each number represents the heat of its tile.

The algorithm then recalculates the whole field and sets the color of each tile to the corresponding heat value.

This is the whole algorithm for calculating the tile values, it goes through every cell and performs its magic on it :D

for(var i=1;i<canvas.width/cellsize;i++)
        for(var j=1;j<canvas.height/cellsize;j++)
            field[i][j] = (0.25 * (field[i-1][j]+field[i+1][j]+field[i][j-1]+field[i][j+1]) + heat[i][j]);

If you press "C" and drag the mouse pointer around you cool off the area around the mouse pointer. You can make a "battle" between hot and cold spots. It really looks cool and the algorithm itself is just 3 lines of code.

Enjoy!

1 comment: