Voronoi diagram generator
Created on:
/Main.hs 1.3 KB (text/plain)
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. -- the main module just handles the graphical stuff
  2. module Main where
  3. import Voronoi
  4. import Codec.Picture
  5. import System.Random
  6. import System.Environment
  7. -- generates a random list of numbers, using a seed and a maximum value
  8. randomList :: (Random a, Num a) => Int -> a -> [a]
  9. randomList seed max = randomRs (0, max) (mkStdGen seed)
  10. -- generate an image from a voronoi diagram v of resolution res by res
  11. image v res = ImageRGB8 $ generateImage
  12. (\x y -> toColour
  13. (findCell v (fromIntegral x, fromIntegral y)))
  14. res res
  15. -- converts a cellId to a colour
  16. toColour :: CellId -> PixelRGB8
  17. toColour n' = let n = fromIntegral n'
  18. bound x = x `mod` 128
  19. in PixelRGB8 (bound n * 53) (bound n * 71) (bound n * 28)
  20. -- main!
  21. main = do args <- getArgs
  22. putStrLn "How many cells do you want?"
  23. numCells <- getLine
  24. putStrLn "How many pixels across?"
  25. numPixels <- getLine
  26. let pixels = read numPixels
  27. n = read numCells
  28. seed = getSeed args
  29. ls = randomList seed (fromIntegral pixels) :: [Double]
  30. v = voronoi $ zip (take n ls) (take n . drop n $ ls)
  31. saveBmpImage "test_voronoi.bmp" $ image v pixels
  32. getSeed [] = 42
  33. getSeed (n:_) = read n
/Voronoi.hs 1.2 KB (text/plain)
12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. module Voronoi where
  2. -- Clearer type name (preference)
  3. type List a = [a]
  4. -- A point is an x and a y co-ordinate
  5. type Point = (Double, Double)
  6. -- a cell in a voronoi diagram is given a unique id
  7. type CellId = Int
  8. -- A voronoi space is just a collection of points arranged in cells
  9. type Voronoi = [(CellId, Point)]
  10. --- generates a voronoi space from a list of points
  11. voronoi :: List Point -> Voronoi
  12. voronoi list = voronoi' list 0
  13. where
  14. voronoi' [] _ = []
  15. voronoi' (p:ps) n = (n, p) : voronoi' ps (succ n)
  16. -- finds what cell a particular point should be in in a voronoi space
  17. findCell :: Voronoi -> Point -> CellId
  18. findCell [] _ = 0
  19. findCell v p = findCell' v p Nothing
  20. where
  21. findCell' [] _ (Just acc) = fst acc
  22. findCell' (cell:rest) point previousClosest
  23. = case previousClosest of
  24. Nothing -> findCell' rest point (Just cell)
  25. Just closest -> if distance point (snd cell) < distance point (snd closest)
  26. then findCell' rest point (Just cell)
  27. else findCell' rest point previousClosest
  28. -- the distance between 2 points
  29. distance :: Point -> Point -> Double
  30. distance (a, b) (c, d) = sqrt ((a - c)^2 + (b - d)^2)
© 2017-2018 git.txt - version: 0.5.2 - b28934a7ddecd31f2e40cb7058fa1fb5e9a1acc8 - page: 11ms - template: 2ms
Gitxts: 42, managed: 86
Sources - Go1.11.5