random_pcg.h 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. /**************************************************************************/
  2. /* random_pcg.h */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #ifndef RANDOM_PCG_H
  31. #define RANDOM_PCG_H
  32. #include <math.h>
  33. #include "core/math/math_defs.h"
  34. #include "thirdparty/misc/pcg.h"
  35. #if defined(__GNUC__) || (_llvm_has_builtin(__builtin_clz))
  36. #define CLZ32(x) __builtin_clz(x)
  37. #elif defined(_MSC_VER)
  38. #include "intrin.h"
  39. static int __bsr_clz32(uint32_t x) {
  40. unsigned long index;
  41. _BitScanReverse(&index, x);
  42. return 31 - index;
  43. }
  44. #define CLZ32(x) __bsr_clz32(x)
  45. #else
  46. #endif
  47. #if defined(__GNUC__) || (_llvm_has_builtin(__builtin_ldexp) && _llvm_has_builtin(__builtin_ldexpf))
  48. #define LDEXP(s, e) __builtin_ldexp(s, e)
  49. #define LDEXPF(s, e) __builtin_ldexpf(s, e)
  50. #else
  51. #include "math.h"
  52. #define LDEXP(s, e) ldexp(s, e)
  53. #define LDEXPF(s, e) ldexp(s, e)
  54. #endif
  55. class RandomPCG {
  56. pcg32_random_t pcg;
  57. uint64_t current_seed; // The seed the current generator state started from.
  58. uint64_t current_inc;
  59. public:
  60. static const uint64_t DEFAULT_SEED = 12047754176567800795U;
  61. static const uint64_t DEFAULT_INC = PCG_DEFAULT_INC_64;
  62. RandomPCG(uint64_t p_seed = DEFAULT_SEED, uint64_t p_inc = DEFAULT_INC);
  63. _FORCE_INLINE_ void seed(uint64_t p_seed) {
  64. current_seed = p_seed;
  65. pcg32_srandom_r(&pcg, current_seed, current_inc);
  66. }
  67. _FORCE_INLINE_ uint64_t get_seed() { return current_seed; }
  68. _FORCE_INLINE_ void set_state(uint64_t p_state) { pcg.state = p_state; }
  69. _FORCE_INLINE_ uint64_t get_state() const { return pcg.state; }
  70. void randomize();
  71. _FORCE_INLINE_ uint32_t rand() {
  72. current_seed = pcg.state;
  73. return pcg32_random_r(&pcg);
  74. }
  75. // Obtaining floating point numbers in [0, 1] range with "good enough" uniformity.
  76. // These functions sample the output of rand() as the fraction part of an infinite binary number,
  77. // with some tricks applied to reduce ops and branching:
  78. // 1. Instead of shifting to the first 1 and connecting random bits, we simply set the MSB and LSB to 1.
  79. // Provided that the RNG is actually uniform bit by bit, this should have the exact same effect.
  80. // 2. In order to compensate for exponent info loss, we count zeros from another random number,
  81. // and just add that to the initial offset.
  82. // This has the same probability as counting and shifting an actual bit stream: 2^-n for n zeroes.
  83. // For all numbers above 2^-96 (2^-64 for floats), the functions should be uniform.
  84. // However, all numbers below that threshold are floored to 0.
  85. // The thresholds are chosen to minimize rand() calls while keeping the numbers within a totally subjective quality standard.
  86. // If clz or ldexp isn't available, fall back to bit truncation for performance, sacrificing uniformity.
  87. _FORCE_INLINE_ double randd() {
  88. #if defined(CLZ32)
  89. uint32_t proto_exp_offset = rand();
  90. if (unlikely(proto_exp_offset == 0)) {
  91. return 0;
  92. }
  93. uint64_t significand = (((uint64_t)rand()) << 32) | rand() | 0x8000000000000001U;
  94. return LDEXP((double)significand, -64 - CLZ32(proto_exp_offset));
  95. #else
  96. #pragma message("RandomPCG::randd - intrinsic clz is not available, falling back to bit truncation")
  97. return (double)(((((uint64_t)rand()) << 32) | rand()) & 0x1FFFFFFFFFFFFFU) / (double)0x1FFFFFFFFFFFFFU;
  98. #endif
  99. }
  100. _FORCE_INLINE_ float randf() {
  101. #if defined(CLZ32)
  102. uint32_t proto_exp_offset = rand();
  103. if (unlikely(proto_exp_offset == 0)) {
  104. return 0;
  105. }
  106. return LDEXPF((float)(rand() | 0x80000001), -32 - CLZ32(proto_exp_offset));
  107. #else
  108. #pragma message("RandomPCG::randf - intrinsic clz is not available, falling back to bit truncation")
  109. return (float)(rand() & 0xFFFFFF) / (float)0xFFFFFF;
  110. #endif
  111. }
  112. _FORCE_INLINE_ double randfn(double p_mean, double p_deviation) {
  113. return p_mean + p_deviation * (cos(Math_TAU * randd()) * sqrt(-2.0 * log(randd()))); // Box-Muller transform
  114. }
  115. _FORCE_INLINE_ float randfn(float p_mean, float p_deviation) {
  116. return p_mean + p_deviation * (cos(Math_TAU * randf()) * sqrt(-2.0 * log(randf()))); // Box-Muller transform
  117. }
  118. double random(double p_from, double p_to);
  119. float random(float p_from, float p_to);
  120. real_t random(int p_from, int p_to) { return (real_t)random((real_t)p_from, (real_t)p_to); }
  121. };
  122. #endif // RANDOM_PCG_H