Advertisement
LPGhatguy

Perlin Noise!

Jan 9th, 2013
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.99 KB | None | 0 0
  1. local random, randomseed = math.random, math.randomseed
  2. local floor = math.floor
  3. local max, min = math.max, math.min
  4.  
  5. local octaves = 3
  6. local persistence = 0.8
  7.  
  8. function cos_interpolate(a, b, x)
  9.     local ft = x * math.pi
  10.     local f = (1 - math.cos(ft)) * .5
  11.  
  12.     return  a * (1 - f) + b * f
  13. end
  14.  
  15. function noise_2d(x, y, i, seed)
  16.     randomseed((x * seed + y * i ^ 1.1 + 14) / 789221 + 33 * x + 15731 * y * seed)
  17.  
  18.     random()
  19.  
  20.     return random(-1000, 1000) / 1000
  21. end
  22.  
  23. function smooth_noise_2d(x, y, i, seed)
  24.     local corners = (noise_2d(x - 1, y - 1, i, seed) + noise_2d(x + 1, y - 1, i, seed) + noise_2d(x - 1, y + 1, i, seed) + noise_2d(x + 1, y + 1, i, seed)) / 16
  25.     local sides = (noise_2d(x - 1, y, i, seed) + noise_2d(x + 1, y, i, seed) + noise_2d(x, y - 1, i, seed) + noise_2d(x, y + 1, i, seed)) / 8
  26.     local center = noise_2d(x, y, i, seed) / 4
  27.     return corners + sides + center
  28. end
  29.  
  30. function interpolate_noise_2d(x, y, i, seed)
  31.     local int_x = floor(x)
  32.     local frac_x = x - int_x
  33.  
  34.     local int_y = floor(y)
  35.     local frac_y = y - int_y
  36.  
  37.     local v1 = smooth_noise_2d(int_x, int_y, i, seed)
  38.     local v2 = smooth_noise_2d(int_x + 1, int_y, i, seed)
  39.     local v3 = smooth_noise_2d(int_x, int_y + 1, i, seed)
  40.     local v4 = smooth_noise_2d(int_x + 1, int_y + 1, i, seed)
  41.  
  42.     local i1 = cos_interpolate(v1, v2, frac_x)
  43.     local i2 = cos_interpolate(v3, v4, frac_x)
  44.  
  45.     return cos_interpolate(i1, i2, frac_y)
  46. end
  47.  
  48. function perlin_2d(x, y, seed)
  49.     local total = 0
  50.     local p = persistence
  51.     local n = octaves - 1
  52.  
  53.     for i = 0, n do
  54.         local frequency = 2 ^ i
  55.         local amplitude = p ^ i
  56.  
  57.         total = total + interpolate_noise_2d(x * frequency, y * frequency, i, seed) * amplitude
  58.     end
  59.  
  60.     return total
  61. end
  62.  
  63. --[[
  64. USAGE (generate a two-dimensional array of points):
  65. local size = 50 --number of samples
  66. local smoothiness = 8
  67. local points = {}
  68.  
  69. for x = -size, size do
  70.     points[x] = {}
  71.     local ax = points[x]
  72.     for y = -size, size do
  73.         ax[y] = min(max(perlin_2d(x / smoothiness, y / smoothiness, 4923), -1), 1)
  74.     end
  75. end
  76. ]]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement