hexyz is tower defense game, and a lua library for dealing with hexagonal grids
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

93 lines
2.1 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. -- https://stackoverflow.com/a/32387452/12464892
  2. local function bitwise_and(a, b)
  3. local result = 0
  4. local bit = 1
  5. while a > 0 and b > 0 do
  6. if a % 2 == 1 and b % 2 == 1 then
  7. result = result + bit
  8. end
  9. bit = bit * 2 -- shift left
  10. a = math.floor(a/2) -- shift-right
  11. b = math.floor(b/2)
  12. end
  13. return result
  14. end
  15. -- https://stackoverflow.com/a/20177466/12464892
  16. local A1, A2 = 727595, 798405 -- 5^17=D20*A1+A2
  17. local D20, D40 = 1048576, 1099511627776 -- 2^20, 2^40
  18. local X1, X2 = 0, 1
  19. local function rand()
  20. local U = X2*A2
  21. local V = (X1*A2 + X2*A1) % D20
  22. V = (V*D20 + U) % D40
  23. X1 = math.floor(V/D20)
  24. X2 = V - X1*D20
  25. return V/D40
  26. end
  27. local SEED_BOUNDS = 2^20 - 1
  28. math.randomseed = function(seed)
  29. RANDOM_CALLS_COUNT = 0
  30. -- 0 <= X1 <= 2^20-1, 1 <= X2 <= 2^20-1 (must be odd!)
  31. -- ensure the number is odd, and within the bounds of
  32. local seed = bitwise_and(seed, 1)
  33. local v = math.clamp(math.abs(seed), 0, SEED_BOUNDS)
  34. X1 = v
  35. X2 = v + 1
  36. end
  37. RANDOM_CALLS_COUNT = 0
  38. local R = math.random
  39. local function random(n, m)
  40. RANDOM_CALLS_COUNT = RANDOM_CALLS_COUNT + 1
  41. if n then
  42. if m then
  43. return (rand() + n) * m
  44. else
  45. return rand() * n
  46. end
  47. else
  48. return rand()
  49. end
  50. end
  51. -- whenever we refer to math.random, actually use the function 'random' above
  52. math.random = random
  53. function g_octave_noise(x, y, num_octaves, seed)
  54. local seed = seed or os.clock()
  55. local noise = 0
  56. for oct = 1, num_octaves do
  57. local f = 1/4^oct
  58. local l = 2^oct
  59. local pos = vec2(x + seed, y + seed)
  60. noise = noise + f * math.simplex(pos * l)
  61. end
  62. return noise
  63. end
  64. ---- @TODO test, fix
  65. --function poisson_knuth(lambda)
  66. -- local e = 2.71828
  67. --
  68. -- local L = e^-lambda
  69. -- local k = 0
  70. -- local p = 1
  71. --
  72. -- while p > L do
  73. -- k = k + 1
  74. -- p = p * math.random()
  75. -- end
  76. --
  77. -- return k - 1
  78. --end
  79. -- seed the random number generator with the current time
  80. -- os.clock() is better if the program has been running for a little bit.
  81. math.randomseed(os.time())