public
Created

Mandelbrot Image Generator using DevIL

  • Download Gist
Mandelbrot.hs
Haskell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
import Data.Complex
import Codec.Image.DevIL
import Data.Array.Unboxed
import System.Directory
import Control.Monad
 
main = ilInit
>> doesFileExist path
>>= flip when (removeFile path)
>> writeImage path image
 
path = "fractal2.png"
 
image :: UArray (Int, Int, Int) Word8
image = render (400,320) (-2.2,-1.5) (1.2,1.5) mandel
 
mb = maxBound :: Word8
 
render (width,height) (lx,ly) (hx,hy) f = listArray ((0,0,0), (height, width, 3)) $
do y <- [0..height]
x <- [0..width]
 
f (normalize width (lx,hx) x) (normalize height (ly,hy) y)
 
mandel :: Double -> Double -> [Word8]
mandel x y = if d > 20 then [0,0,0,mb] else [v, p `div` 3, v, mb] -- R,G,B,A
where
p = ceiling $ fromIntegral mb * (phase $ is !! 10) / (2 * pi)
v = mb `div` fromIntegral d
d = 1 + length (take 20 $ takeWhile (<3) res)
res = map magnitude is
is = iterate (step com) com
com = x :+ y
step c p = p**2 + c
 
normalize :: Int -> (Double, Double) -> Int -> Double
normalize s (l,h) i = l + (h - l) * i' / s' where [s', i'] = map fromIntegral [s,i]

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.