I just happened to stumble across a feature of flash’s BitmapData class that I hadn’t noticed before: paletteMap()
With paletteMap() you can switch the color values of the pixels in a BitmapData using mapping arrays. The function will basicly take the red, green or blue value of a pixel (0-255), and then replace it with the value found at the corresponding index in the mapping array. Doing this is a lot faster than using the setPixel method.
To try this out, I applied it to the fractal code I used in an earlier post. In this particular case I can assign an index value to each pixel, instead of a color, and then simply use a single array for the palette mapping.
So first I set an index value for each pixel in the bitmap data, and the palette data (The palette data will retain the original values, and I will use it to map against when I set the values for my bitmap).
bitmapData.setPixel(ix, iy, iteration);
paletteData.setPixel(ix, iy, iteration);
And now, my render loop only need to do 128 steps, one for each index. this is much quicker than looping through all 320×240 pixels.
for(i in 0...128) {
r = i + colorModifier;
g = i + colorModifier + r;
b = i + colorModifier + g;
rgbArray[i] = (r<<16 | g<<8 | b);
}
...
bitmapData.paletteMap(paletteData, bitmapData.rect, new Point(0,0), rgbArray, rgbArray, rgbArray);
The performance gain is pretty awesome. The setPixel version ran at about 50-60 fps on my machine at 320x240.This paletteMap version runs at 1000+ fps! (Takes less than 1 ms to render). Nice.
And here's a version running at 1024x768 with 512 iterations.
Also, as a curious side note, I happend to notice that "flash.Lib.current.stage.stageHeight" is not a good thing to use in a loop (duh) :) Replacing it with an inlined static variable reduced fractal generation time with several hundred ms.
The full haXe source is available here if you want it.