SDL_random.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2024 Sam Lantinga <[email protected]>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include "SDL_internal.h"
  19. /* This file contains portable random functions for SDL */
  20. static Uint64 SDL_rand_state;
  21. static SDL_bool SDL_rand_initialized = SDL_FALSE;
  22. void SDL_srand(Uint64 seed)
  23. {
  24. if (!seed) {
  25. seed = SDL_GetPerformanceCounter();
  26. }
  27. SDL_rand_state = seed;
  28. SDL_rand_initialized = SDL_TRUE;
  29. }
  30. Uint32 SDL_rand(void)
  31. {
  32. if(!SDL_rand_initialized) {
  33. SDL_srand(0);
  34. }
  35. return SDL_rand_r(&SDL_rand_state);
  36. }
  37. Uint32 SDL_rand_n(Uint32 n)
  38. {
  39. // On 32-bit arch, the compiler will optimize to a single 32-bit multiply
  40. Uint64 val = (Uint64)SDL_rand() * n;
  41. return (Uint32)(val >> 32);
  42. }
  43. float SDL_rand_float(void)
  44. {
  45. return (SDL_rand() >> (32-24)) * 0x1p-24f;
  46. }
  47. /* A fast psuedo-random number generator.
  48. * Not suitable for cryptography or gambling
  49. */
  50. Uint32 SDL_rand_r(Uint64 *state)
  51. {
  52. if (!state) {
  53. return 0;
  54. }
  55. // Multiplier from Table 6 of
  56. // Steele GL, Vigna S. Computationally easy, spectrally good multipliers
  57. // for congruential pseudorandom number generators.
  58. // Softw Pract Exper. 2022;52(2):443-458. doi: 10.1002/spe.3030
  59. // 32-bit 'a' improves performance on 32-bit architectures
  60. // 'c' can be any odd number, but < 256 generates smaller code on some arch
  61. *state = *state * 0xf9b25d65ul + 0xFD;
  62. // Only return top 32 bits because they have a longer period
  63. return (Uint32)(*state >> 32);
  64. }