1
0
Fork 0
mirror of https://github.com/luanti-org/luanti.git synced 2025-07-02 16:38:41 +00:00

Add API for restoring PseudoRandom and PcgRandom state (#14123)

This commit is contained in:
sfence 2024-01-16 23:20:52 +01:00 committed by GitHub
parent 8093044f07
commit ceaa7e2fb0
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
9 changed files with 155 additions and 29 deletions

View file

@ -65,32 +65,39 @@ void TestRandom::testPseudoRandom()
for (u32 i = 0; i != 256; i++)
UASSERTEQ(s32, pr.next(), expected_pseudorandom_results[i]);
PseudoRandom pr2(0);
UASSERTEQ(int, pr2.next(), 0);
UASSERTEQ(int, pr2.next(), 21469);
UASSERTEQ(int, pr2.next(), 9989);
s32 state = pr.getState();
PseudoRandom pr2(state);
PseudoRandom pr3(-101);
UASSERTEQ(int, pr3.next(), 3267);
UASSERTEQ(int, pr3.next(), 2485);
UASSERTEQ(int, pr3.next(), 30057);
for (u32 i = 0; i != 256; i++) {
UASSERTEQ(s32, pr.next(), pr2.next());
}
PseudoRandom pr3(0);
UASSERTEQ(s32, pr3.next(), 0);
UASSERTEQ(s32, pr3.next(), 21469);
UASSERTEQ(s32, pr3.next(), 9989);
PseudoRandom pr4(-101);
UASSERTEQ(s32, pr4.next(), 3267);
UASSERTEQ(s32, pr4.next(), 2485);
UASSERTEQ(s32, pr4.next(), 30057);
}
void TestRandom::testPseudoRandomRange()
{
PseudoRandom pr((int)time(NULL));
PseudoRandom pr((s32)time(NULL));
EXCEPTION_CHECK(PrngException, pr.range(2000, 8600));
EXCEPTION_CHECK(PrngException, pr.range(5, 1));
for (u32 i = 0; i != 32768; i++) {
int min = (pr.next() % 3000) - 500;
int max = (pr.next() % 3000) - 500;
s32 min = (pr.next() % 3000) - 500;
s32 max = (pr.next() % 3000) - 500;
if (min > max)
SWAP(int, min, max);
SWAP(s32, min, max);
int randval = pr.range(min, max);
s32 randval = pr.range(min, max);
UASSERT(randval >= min);
UASSERT(randval <= max);
}
@ -103,12 +110,21 @@ void TestRandom::testPcgRandom()
for (u32 i = 0; i != 256; i++)
UASSERTEQ(u32, pr.next(), expected_pcgrandom_results[i]);
PcgRandom pr2(0, 0);
u64 state[2];
pr.getState(state);
pr2.setState(state);
for (u32 i = 0; i != 256; i++) {
UASSERTEQ(u32, pr.next(), pr2.next());
}
}
void TestRandom::testPcgRandomRange()
{
PcgRandom pr((int)time(NULL));
PcgRandom pr((u64)time(NULL));
EXCEPTION_CHECK(PrngException, pr.range(5, 1));
@ -116,12 +132,12 @@ void TestRandom::testPcgRandomRange()
pr.range(pr.RANDOM_MIN, pr.RANDOM_MAX);
for (u32 i = 0; i != 32768; i++) {
int min = (pr.next() % 3000) - 500;
int max = (pr.next() % 3000) - 500;
s32 min = (pr.next() % 3000) - 500;
s32 max = (pr.next() % 3000) - 500;
if (min > max)
SWAP(int, min, max);
SWAP(s32, min, max);
int randval = pr.range(min, max);
s32 randval = pr.range(min, max);
UASSERT(randval >= min);
UASSERT(randval <= max);
}
@ -147,8 +163,8 @@ void TestRandom::testPcgRandomBytes()
void TestRandom::testPcgRandomNormalDist()
{
static const int max = 120;
static const int min = -120;
static const s32 max = 120;
static const s32 min = -120;
static const int num_trials = 20;
static const u32 num_samples = 61000;
s32 bins[max - min + 1];