Skip to content

Instantly share code, notes, and snippets.

@sordina
Created August 10, 2011 12:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sordina/1136725 to your computer and use it in GitHub Desktop.
Save sordina/1136725 to your computer and use it in GitHub Desktop.
Mandelbrot Image Generator using DevIL
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]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment