mirror of
https://github.com/mlepage/heightmap.git
synced 2024-11-19 04:44:23 +00:00
Simple heightmap module for Lua. Uses the diamond-square algorithm to generate realistic terrain. MIT license.
COPYRIGHT | ||
heightmap.lua | ||
README |
Heightmap module by Marc Lepage OVERVIEW The heightmap module uses the diamond-square algorithm to generate cloud or plasma fractal heightmaps which can be used for terrain. USAGE -- import module require "heightmap" -- create 256x256 heightmap map = heightmap.create(256, 256) -- examine each height value for x = 0, map.w do for y = 0, map.y do print(map[x][y]) end end -- define a custom height function (reusing the default but scaling it) function f(map, x, y, d, h) return 2 * heightmap.defaultf(map, x, y, d, h) end -- use it to create a new heightmap map = heightmap.create(256, 256, f) HOW IT WORKS The heightmap must be a square the size of a power of two, plus one, so that it can be evenly divided. For example, 4x4 cells will require 5x5 vertices. First the four corners are seeded with a random value (C). Then each square is used to set the value of its center (S) based on the average of its four corners (plus some randomness). Then each diamond is used to set the value of its center (D) based on the average of its four points (plus some randomness). The square and diamond steps continue until all values have been set: 4 S 2 D 2 S 1 D 1 C...C c...c c.D.c c.d.c cDdDc ..... ..... ..... .S.S. DsDsD ..... ..S.. D.s.D d.S.d dDsDd ..... ..... ..... .S.S. DsDsD C...C c...c c.D.c c.d.c cDdDc The default height function randomly displaces values by up to +/- 0.5 of the step size. So above, the corners will be from -2 to +2, the center will be the mean of the corners randomly displaced from -1 to +1, and so on. RESOURCES http://en.wikipedia.org/wiki/Diamond-square_algorithm http://en.wikipedia.org/wiki/Heightmap http://en.wikipedia.org/wiki/Fractal_landscape