CRandomGenerator.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. * CRandomGenerator.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CRandomGenerator.h"
  12. VCMI_LIB_NAMESPACE_BEGIN
  13. CRandomGenerator::CRandomGenerator()
  14. {
  15. resetSeed();
  16. }
  17. CRandomGenerator::CRandomGenerator(int seed)
  18. {
  19. setSeed(seed);
  20. }
  21. void CRandomGenerator::setSeed(int seed)
  22. {
  23. rand.seed(seed);
  24. }
  25. void CRandomGenerator::resetSeed()
  26. {
  27. boost::hash<std::string> stringHash;
  28. auto threadIdHash = stringHash(boost::lexical_cast<std::string>(boost::this_thread::get_id()));
  29. setSeed(static_cast<int>(threadIdHash * std::time(nullptr)));
  30. }
  31. TRandI CRandomGenerator::getIntRange(int lower, int upper)
  32. {
  33. return std::bind(TIntDist(lower, upper), std::ref(rand));
  34. }
  35. vstd::TRandI64 CRandomGenerator::getInt64Range(int64_t lower, int64_t upper)
  36. {
  37. return std::bind(TInt64Dist(lower, upper), std::ref(rand));
  38. }
  39. int CRandomGenerator::nextInt(int upper)
  40. {
  41. return getIntRange(0, upper)();
  42. }
  43. int CRandomGenerator::nextInt(int lower, int upper)
  44. {
  45. return getIntRange(lower, upper)();
  46. }
  47. int CRandomGenerator::nextInt()
  48. {
  49. return TIntDist()(rand);
  50. }
  51. vstd::TRand CRandomGenerator::getDoubleRange(double lower, double upper)
  52. {
  53. return std::bind(TRealDist(lower, upper), std::ref(rand));
  54. }
  55. double CRandomGenerator::nextDouble(double upper)
  56. {
  57. return getDoubleRange(0, upper)();
  58. }
  59. double CRandomGenerator::nextDouble(double lower, double upper)
  60. {
  61. return getDoubleRange(lower, upper)();
  62. }
  63. double CRandomGenerator::nextDouble()
  64. {
  65. return TRealDist()(rand);
  66. }
  67. CRandomGenerator & CRandomGenerator::getDefault()
  68. {
  69. static thread_local CRandomGenerator defaultRand;
  70. return defaultRand;
  71. }
  72. TGenerator & CRandomGenerator::getStdGenerator()
  73. {
  74. return rand;
  75. }
  76. VCMI_LIB_NAMESPACE_END