Fractals in C#: Plasma Fractals
Plasma fractals generate images based on random varying of vlaues across the image, allowing for vairations which include plasma, terrain or cloud-like images.
So, what is a plasma fractal exactly? A plasma fractal is generated by taking a rectangle with a width x and height y. Then to each corner in the rectangle, assign a random value between 0 and 1.
The next step is to find the midpoint of each side, and at that point, calculate the average value of the two points that this point is bisecting. A midpoint is also calculated, which is in the centre of the rectangle, which is the average of all four corners plus a random displacement.
Then for each of the four rectangle bounded by the new points, repeat the process, until all the pixels have been calculated.
After the values have been calculated, the values can be converted to colours using any method you like. Using the raw values unaltered will create a greyscale image very well with only adjusting the value to put it in the correct range.
Now, in the code to do this, first, we have a few global variables
The roughness is amount in which we are going to vary the value by for the midpoint.gBigSize is defined as the width plus the height of the image we are generating. FastRandom is a random number generator, which works exactly like the builtin random number generator, except that it is faster.
Our starting point is the Generate function that return a two-dimensional array of values where each entry in the array corresponds to an xy coordinate and the value is the calculated value, which will be converted into a colour.
This function sets the four initial corners, and sets the global variables, and then starts the recursion to generate the rest of the points by calling DivideGrid, which is what follows next. The most import point here is that the array containing the points is passed as a reference variable to DivideGrid, so that as it recurses, it can update the points accordingly.
If the rectangle is bigger than a pixel, then this function now calculates the average for the four edges, as well as the average of all four corners with the displacement added for the centre.
After this the values are rectified, so that the values stay within the bounds set, and the DivideGrid function is called again for each new rectangle.
If the rectangle is a pixel big, then we have reached the base case, and only the centre is calculated and assigned. At this point the function does not recurse any deeper but now returns.
Lastly we just have Rectify and Displace which we have dealt with already. Displace just calcualtes a random displacement based on the size of the rectangle and the roughness.
The full source code is available at https://github.com/sjmeunier/fractalize.
Originally posted on my old blog, Smoky Cogs, on 30 Sep 2009