CRandomGenerator.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. boost::thread_specific_ptr<CRandomGenerator> CRandomGenerator::defaultRand;
  13. CRandomGenerator::CRandomGenerator()
  14. {
  15. resetSeed();
  16. }
  17. void CRandomGenerator::setSeed(int seed)
  18. {
  19. rand.seed(seed);
  20. }
  21. void CRandomGenerator::resetSeed()
  22. {
  23. boost::hash<std::string> stringHash;
  24. auto threadIdHash = stringHash(boost::lexical_cast<std::string>(boost::this_thread::get_id()));
  25. setSeed(threadIdHash * std::time(nullptr));
  26. }
  27. TRandI CRandomGenerator::getIntRange(int lower, int upper)
  28. {
  29. return boost::bind(TIntDist(lower, upper), boost::ref(rand));
  30. }
  31. int CRandomGenerator::nextInt(int upper)
  32. {
  33. return getIntRange(0, upper)();
  34. }
  35. int CRandomGenerator::nextInt(int lower, int upper)
  36. {
  37. return getIntRange(lower, upper)();
  38. }
  39. int CRandomGenerator::nextInt()
  40. {
  41. return TIntDist()(rand);
  42. }
  43. TRand CRandomGenerator::getDoubleRange(double lower, double upper)
  44. {
  45. return boost::bind(TRealDist(lower, upper), boost::ref(rand));
  46. }
  47. double CRandomGenerator::nextDouble(double upper)
  48. {
  49. return getDoubleRange(0, upper)();
  50. }
  51. double CRandomGenerator::nextDouble(double lower, double upper)
  52. {
  53. return getDoubleRange(lower, upper)();
  54. }
  55. double CRandomGenerator::nextDouble()
  56. {
  57. return TRealDist()(rand);
  58. }
  59. CRandomGenerator & CRandomGenerator::getDefault()
  60. {
  61. if(!defaultRand.get())
  62. {
  63. defaultRand.reset(new CRandomGenerator());
  64. }
  65. return *defaultRand.get();
  66. }
  67. TGenerator & CRandomGenerator::getStdGenerator()
  68. {
  69. return rand;
  70. }