random.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // The reason we use our own random instead of Math.random() is because
  2. // we can seed this, and thus get the same L-System each time we view.
  3. // Otherwise, when you view the same L-System with the same parameters,
  4. // using Math.random(), it'll change each time.
  5. //
  6. // Code from https://stackoverflow.com/questions/521295/
  7. export const random = (function() {
  8. function xmur3(str) {
  9. for(var i = 0, h = 1779033703 ^ str.length; i < str.length; i++)
  10. h = Math.imul(h ^ str.charCodeAt(i), 3432918353),
  11. h = h << 13 | h >>> 19;
  12. return function() {
  13. h = Math.imul(h ^ h >>> 16, 2246822507);
  14. h = Math.imul(h ^ h >>> 13, 3266489909);
  15. return (h ^= h >>> 16) >>> 0;
  16. }
  17. }
  18. function sfc32(a, b, c, d) {
  19. return function() {
  20. a >>>= 0; b >>>= 0; c >>>= 0; d >>>= 0;
  21. var t = (a + b) | 0;
  22. a = b ^ b >>> 9;
  23. b = c + (c << 3) | 0;
  24. c = (c << 21 | c >>> 11);
  25. d = d + 1 | 0;
  26. t = t + d | 0;
  27. c = c + t | 0;
  28. return (t >>> 0) / 4294967296;
  29. }
  30. }
  31. let _SeededRandom = null;
  32. function _Random() {
  33. if (!_SeededRandom) {
  34. _Seed('abc');
  35. }
  36. return _SeededRandom();
  37. }
  38. function _RandomRange(a, b) {
  39. return _Random() * (b - a) + a;
  40. }
  41. function _Seed(s) {
  42. const seed = xmur3(s + '');
  43. _SeededRandom = sfc32(seed(), seed(), seed(), seed());
  44. }
  45. return {
  46. Seed: _Seed,
  47. Random: _Random,
  48. RandomRange: _RandomRange,
  49. }
  50. })();