Files
cuberite-2a/src/FastRandom.cpp
T

122 lines
1.9 KiB
C++
Raw Normal View History

2013-07-29 12:13:03 +01:00
// FastRandom.cpp
// Implements the cFastRandom class representing a fast random number generator
#include "Globals.h"
#include "FastRandom.h"
2015-05-17 10:53:16 +01:00
#include <random>
#if defined (__GNUC__)
#define ATTRIBUTE_TLS static __thread
#elif defined (_MSC_VER)
#define ATTRIBUTE_TLS static __declspec(thread)
#else
#error "Unknown thread local storage qualifier"
2015-03-14 21:52:13 +00:00
#endif
2015-05-17 10:53:16 +01:00
static unsigned int GetRandomSeed()
{
ATTRIBUTE_TLS bool SeedCounterInitialized = 0;
ATTRIBUTE_TLS unsigned int SeedCounter = 0;
2015-05-17 10:53:16 +01:00
if (!SeedCounterInitialized)
{
std::random_device rd;
std::uniform_int_distribution<unsigned int> dist;
SeedCounter = dist(rd);
SeedCounterInitialized = true;
}
return ++SeedCounter;
}
2013-07-29 12:13:03 +01:00
2014-10-19 14:10:18 +01:00
////////////////////////////////////////////////////////////////////////////////
// cFastRandom:
2013-07-29 12:13:03 +01:00
cFastRandom::cFastRandom(void) :
2015-05-17 10:53:16 +01:00
m_LinearRand(GetRandomSeed())
2013-07-29 12:13:03 +01:00
{
}
int cFastRandom::NextInt(int a_Range)
{
2014-12-07 15:46:27 +01:00
std::uniform_int_distribution<> distribution(0, a_Range - 1);
return distribution(m_LinearRand);
2013-07-29 12:13:03 +01:00
}
2014-10-19 14:10:18 +01:00
2013-07-29 12:13:03 +01:00
float cFastRandom::NextFloat(float a_Range)
{
2014-12-07 15:46:27 +01:00
std::uniform_real_distribution<float> distribution(0, a_Range);
return distribution(m_LinearRand);
2013-07-29 12:13:03 +01:00
}
2014-10-19 14:10:18 +01:00
2014-04-07 19:52:35 +02:00
int cFastRandom::GenerateRandomInteger(int a_Begin, int a_End)
{
2014-12-07 15:46:27 +01:00
std::uniform_int_distribution<> distribution(a_Begin, a_End);
return distribution(m_LinearRand);
2014-10-19 14:10:18 +01:00
}
////////////////////////////////////////////////////////////////////////////////
// MTRand:
MTRand::MTRand() :
2015-05-17 10:53:16 +01:00
m_MersenneRand(GetRandomSeed())
2014-10-19 14:10:18 +01:00
{
}
int MTRand::randInt(int a_Range)
{
2014-12-07 15:46:27 +01:00
std::uniform_int_distribution<> distribution(0, a_Range);
return distribution(m_MersenneRand);
2014-10-19 14:10:18 +01:00
}
int MTRand::randInt()
{
2014-12-07 15:46:27 +01:00
std::uniform_int_distribution<> distribution(0, std::numeric_limits<int>::max());
return distribution(m_MersenneRand);
2014-10-19 14:10:18 +01:00
}
double MTRand::rand(double a_Range)
{
2014-12-07 15:46:27 +01:00
std::uniform_real_distribution<> distribution(0, a_Range);
return distribution(m_MersenneRand);
2014-04-07 19:52:35 +02:00
}