Merge pull request #44089 from Xrayez/rng-state

Add ability to restore `RandomNumberGenerator` state
This commit is contained in:
Rémi Verschelde 2020-12-08 21:40:38 +01:00 committed by GitHub
commit 2034a1cca0
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 145 additions and 11 deletions

View file

@ -34,6 +34,9 @@ void RandomNumberGenerator::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_seed", "seed"), &RandomNumberGenerator::set_seed);
ClassDB::bind_method(D_METHOD("get_seed"), &RandomNumberGenerator::get_seed);
ClassDB::bind_method(D_METHOD("set_state", "state"), &RandomNumberGenerator::set_state);
ClassDB::bind_method(D_METHOD("get_state"), &RandomNumberGenerator::get_state);
ClassDB::bind_method(D_METHOD("randi"), &RandomNumberGenerator::randi);
ClassDB::bind_method(D_METHOD("randf"), &RandomNumberGenerator::randf);
ClassDB::bind_method(D_METHOD("randfn", "mean", "deviation"), &RandomNumberGenerator::randfn, DEFVAL(0.0), DEFVAL(1.0));
@ -42,6 +45,8 @@ void RandomNumberGenerator::_bind_methods() {
ClassDB::bind_method(D_METHOD("randomize"), &RandomNumberGenerator::randomize);
ADD_PROPERTY(PropertyInfo(Variant::INT, "seed"), "set_seed", "get_seed");
// Default value is non-deterministic, override it for doc generation purposes.
ADD_PROPERTY(PropertyInfo(Variant::INT, "state"), "set_state", "get_state");
// Default values are non-deterministic, override for doc generation purposes.
ADD_PROPERTY_DEFAULT("seed", 0);
ADD_PROPERTY_DEFAULT("state", 0);
}

View file

@ -44,19 +44,17 @@ protected:
public:
_FORCE_INLINE_ void set_seed(uint64_t p_seed) { randbase.seed(p_seed); }
_FORCE_INLINE_ uint64_t get_seed() { return randbase.get_seed(); }
_FORCE_INLINE_ void set_state(uint64_t p_state) { randbase.set_state(p_state); }
_FORCE_INLINE_ uint64_t get_state() const { return randbase.get_state(); }
_FORCE_INLINE_ void randomize() { randbase.randomize(); }
_FORCE_INLINE_ uint32_t randi() { return randbase.rand(); }
_FORCE_INLINE_ real_t randf() { return randbase.randf(); }
_FORCE_INLINE_ real_t randf_range(real_t p_from, real_t p_to) { return randbase.random(p_from, p_to); }
_FORCE_INLINE_ real_t randfn(real_t p_mean = 0.0, real_t p_deviation = 1.0) { return randbase.randfn(p_mean, p_deviation); }
_FORCE_INLINE_ int randi_range(int p_from, int p_to) { return randbase.random(p_from, p_to); }
RandomNumberGenerator() {}

View file

@ -61,7 +61,7 @@ static int __bsr_clz32(uint32_t x) {
class RandomPCG {
pcg32_random_t pcg;
uint64_t current_seed; // seed with this to get the same state
uint64_t current_seed; // The seed the current generator state started from.
uint64_t current_inc;
public:
@ -76,13 +76,14 @@ public:
}
_FORCE_INLINE_ uint64_t get_seed() { return current_seed; }
_FORCE_INLINE_ void set_state(uint64_t p_state) { pcg.state = p_state; }
_FORCE_INLINE_ uint64_t get_state() const { return pcg.state; }
void randomize();
_FORCE_INLINE_ uint32_t rand() {
current_seed = pcg.state;
return pcg32_random_r(&pcg);
}
_FORCE_INLINE_ uint32_t rand(uint32_t bounds) {
current_seed = pcg.state;
return pcg32_boundedrand_r(&pcg, bounds);
}

View file

@ -13,6 +13,7 @@
rng.randomize()
var my_random_number = rng.randf_range(-10.0, 10.0)
[/codeblock]
[b]Note:[/b] The default values of [member seed] and [member state] properties are pseudo-random, and changes when calling [method randomize]. The [code]0[/code] value documented here is a placeholder, and not the actual default seed.
</description>
<tutorials>
<link title="Random number generation">https://docs.godotengine.org/en/latest/tutorials/math/random_number_generation.html</link>
@ -75,9 +76,26 @@
</methods>
<members>
<member name="seed" type="int" setter="set_seed" getter="get_seed" default="0">
The seed used by the random number generator. A given seed will give a reproducible sequence of pseudo-random numbers.
Initializes the random number generator state based on the given seed value. A given seed will give a reproducible sequence of pseudo-random numbers.
[b]Note:[/b] The RNG does not have an avalanche effect, and can output similar random streams given similar seeds. Consider using a hash function to improve your seed quality if they're sourced externally.
[b]Note:[/b] The default value of this property is pseudo-random, and changes when calling [method randomize]. The [code]0[/code] value documented here is a placeholder, and not the actual default seed.
[b]Note:[/b] Setting this property produces a side effect of changing the internal [member state], so make sure to initialize the seed [i]before[/i] modifying the [member state]:
[codeblock]
var rng = RandomNumberGenerator.new()
rng.seed = hash("Godot")
rng.state = 100 # Restore to some previously saved state.
[/codeblock]
</member>
<member name="state" type="int" setter="set_state" getter="get_state" default="0">
The current state of the random number generator. Save and restore this property to restore the generator to a previous state:
[codeblock]
var rng = RandomNumberGenerator.new()
print(rng.randf())
var saved_state = rng.state # Store current state.
print(rng.randf()) # Advance internal state.
rng.state = saved_state # Restore the state.
print(rng.randf()) # Prints the same value as in previous.
[/codeblock]
[b]Note:[/b] Do not set state to arbitrary values, since the random number generator requires the state to have certain qualities to behave properly. It should only be set to values that came from the state property itself. To initialize the random number generator with arbitrary input, use [member seed] instead.
</member>
</members>
<constants>

View file

@ -56,6 +56,7 @@
#include "test_pck_packer.h"
#include "test_physics_2d.h"
#include "test_physics_3d.h"
#include "test_random_number_generator.h"
#include "test_rect2.h"
#include "test_render.h"
#include "test_shader_lang.h"

View file

@ -0,0 +1,111 @@
/*************************************************************************/
/* test_random_number_generator.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#ifndef TEST_RANDOM_NUMBER_GENERATOR_H
#define TEST_RANDOM_NUMBER_GENERATOR_H
#include "core/math/random_number_generator.h"
#include "tests/test_macros.h"
namespace TestRandomNumberGenerator {
TEST_CASE("[RandomNumberGenerator] Zero for first number immediately after seeding") {
Ref<RandomNumberGenerator> rng = memnew(RandomNumberGenerator);
rng->set_seed(0);
uint32_t n1 = rng->randi();
uint32_t n2 = rng->randi();
INFO("Initial random values: " << n1 << " " << n2);
CHECK(n1 != 0);
rng->set_seed(1);
uint32_t n3 = rng->randi();
uint32_t n4 = rng->randi();
INFO("Values after changing the seed: " << n3 << " " << n4);
CHECK(n3 != 0);
}
TEST_CASE("[RandomNumberGenerator] Restore state") {
Ref<RandomNumberGenerator> rng = memnew(RandomNumberGenerator);
rng->randomize();
uint64_t last_seed = rng->get_seed();
INFO("Current seed: " << last_seed);
rng->randi();
rng->randi();
CHECK_MESSAGE(rng->get_seed() == last_seed,
"The seed should remain the same after generating some numbers");
uint64_t saved_state = rng->get_state();
INFO("Current state: " << saved_state);
real_t f1_before = rng->randf();
real_t f2_before = rng->randf();
INFO("This seed produces: " << f1_before << " " << f2_before);
// Restore now.
rng->set_state(saved_state);
real_t f1_after = rng->randf();
real_t f2_after = rng->randf();
INFO("Resetting the state produces: " << f1_after << " " << f2_after);
String msg = "Should restore the sequence of numbers after resetting the state";
CHECK_MESSAGE(f1_before == f1_after, msg);
CHECK_MESSAGE(f2_before == f2_after, msg);
}
TEST_CASE("[RandomNumberGenerator] Restore from seed") {
Ref<RandomNumberGenerator> rng = memnew(RandomNumberGenerator);
rng->set_seed(0);
INFO("Current seed: " << rng->get_seed());
uint32_t s0_1_before = rng->randi();
uint32_t s0_2_before = rng->randi();
INFO("This seed produces: " << s0_1_before << " " << s0_2_before);
rng->set_seed(9000);
INFO("Current seed: " << rng->get_seed());
uint32_t s9000_1 = rng->randi();
uint32_t s9000_2 = rng->randi();
INFO("This seed produces: " << s9000_1 << " " << s9000_2);
rng->set_seed(0);
INFO("Current seed: " << rng->get_seed());
uint32_t s0_1_after = rng->randi();
uint32_t s0_2_after = rng->randi();
INFO("This seed produces: " << s0_1_after << " " << s0_2_after);
String msg = "Should restore the sequence of numbers after resetting the seed";
CHECK_MESSAGE(s0_1_before == s0_1_after, msg);
CHECK_MESSAGE(s0_2_before == s0_2_after, msg);
}
} // namespace TestRandomNumberGenerator
#endif // TEST_RANDOM_NUMBER_GENERATOR_H