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.

102 lines
2.2 KiB

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