CRandomGenerator.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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. if (lower <= upper)
  34. return std::bind(TIntDist(lower, upper), std::ref(rand));
  35. throw std::runtime_error("Invalid range provided: " + std::to_string(lower) + " ... " + std::to_string(upper));
  36. }
  37. vstd::TRandI64 CRandomGenerator::getInt64Range(int64_t lower, int64_t upper)
  38. {
  39. if(lower <= upper)
  40. return std::bind(TInt64Dist(lower, upper), std::ref(rand));
  41. throw std::runtime_error("Invalid range provided: " + std::to_string(lower) + " ... " + std::to_string(upper));
  42. }
  43. int CRandomGenerator::nextInt(int upper)
  44. {
  45. return getIntRange(0, upper)();
  46. }
  47. int CRandomGenerator::nextInt(int lower, int upper)
  48. {
  49. return getIntRange(lower, upper)();
  50. }
  51. int CRandomGenerator::nextInt()
  52. {
  53. return TIntDist()(rand);
  54. }
  55. vstd::TRand CRandomGenerator::getDoubleRange(double lower, double upper)
  56. {
  57. if(lower <= upper)
  58. return std::bind(TRealDist(lower, upper), std::ref(rand));
  59. throw std::runtime_error("Invalid range provided: " + std::to_string(lower) + " ... " + std::to_string(upper));
  60. }
  61. double CRandomGenerator::nextDouble(double upper)
  62. {
  63. return getDoubleRange(0, upper)();
  64. }
  65. double CRandomGenerator::nextDouble(double lower, double upper)
  66. {
  67. return getDoubleRange(lower, upper)();
  68. }
  69. double CRandomGenerator::nextDouble()
  70. {
  71. return TRealDist()(rand);
  72. }
  73. CRandomGenerator & CRandomGenerator::getDefault()
  74. {
  75. static thread_local CRandomGenerator defaultRand;
  76. return defaultRand;
  77. }
  78. TGenerator & CRandomGenerator::getStdGenerator()
  79. {
  80. return rand;
  81. }
  82. VCMI_LIB_NAMESPACE_END