Wed
Apr 15th

Beautiful Algorithms 1: Fire Part 2

Yesterday I introduced Processing and Ruby Processing in Part 1.  This part is the meat and potatoes of the tutorial: the fire algorithm and the Ruby that generates it.

The Algorithm

You can watch a screencast of the fire algorithm in action here: fire-processing-rb.  It looks like a sophisticated animation: waves of fire rise up from the bottom of the window at different angles and gradually get thinner, moving through red, orange and yellow until they fade away.  Modelling this using shapes would be incredibly complicated.  Fortunately, creating this illusion is deceptively simple.

To make fire, generate random colours at the bottom of the screen:  a row of pixels of red, orange and yellow.  Then move up a row and take the pixels to the left and right, and the original pixel below, and average the colours for each of them.

For each frame of the animation (so 30 times a second), repeat this process for every row on the screen.

The Algorithm Again in a Numbered List

Just in case that was confusing, here’s the fire algorithm again in a list:

  1. Create a row of pixels at the bottom of the screen that are random shades of red, orange and yellow
  2. Move up a line
  3. Loop through each pixel on this line averaging the pixels around the current pixel
  4. Once the top of the screen is reached, draw the results and go to 1

Colours

The colours in this algorithm are important: red, orange and yellow banded shades must be created so the algorithm will appear to blend between them.  I’ve stored the colours in an array like this:

Although this doesn’t look too exciting, it’s a major part of creating the fire illusion.

Averaging Pixels

The pixel colours are averaged, but a cap on their maximum brightness is used, along with a gradual reduction in brightness.  I’ve set a variable that controls the intensity of the flame so you can experiment with it.

The Result

Here is the result in my fire-p5r repository: fire.rb — you can run this with rp5 run fire.rb.

If you’d like to improve on my algorithm, try making it work with Processing’s pixels array rather than rect, and drawing rectangles of pixels.  This should work faster than using rect.

Comments (View)
Related Posts Widget for Blogs by LinkWithin