Skip to content

Commit 35f1af5

Browse files
authored
Reuse seeded rng in tilemap_chunk for more determinism (#19812)
# Objective This example uses a seeded RNG for the initial setup, but new unseeded RNGs during each timed update. This is causing the example to produce different output each time in the [example report](https://bevyengine.github.io/bevy-example-runner/). <img width="838" alt="image" src="https://github.com/user-attachments/assets/05d78083-97d0-4bcf-aebc-f645b570d144" /> ## Solution Store and reuse the RNG, following the pattern used in other examples. ## Testing `cargo run --example tilemap_chunk`
1 parent dd4479e commit 35f1af5

File tree

1 file changed

+14
-3
lines changed

1 file changed

+14
-3
lines changed

examples/2d/tilemap_chunk.rs

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ use rand_chacha::ChaCha8Rng;
99

1010
fn main() {
1111
App::new()
12-
.add_plugins((DefaultPlugins.set(ImagePlugin::default_nearest()),))
12+
.add_plugins(DefaultPlugins.set(ImagePlugin::default_nearest()))
1313
.add_systems(Startup, setup)
1414
.add_systems(Update, (update_tileset_image, update_tilemap))
1515
.run();
@@ -18,8 +18,14 @@ fn main() {
1818
#[derive(Component, Deref, DerefMut)]
1919
struct UpdateTimer(Timer);
2020

21+
#[derive(Resource, Deref, DerefMut)]
22+
struct SeededRng(ChaCha8Rng);
23+
2124
fn setup(mut commands: Commands, assets: Res<AssetServer>) {
25+
// We're seeding the PRNG here to make this example deterministic for testing purposes.
26+
// This isn't strictly required in practical use unless you need your app to be deterministic.
2227
let mut rng = ChaCha8Rng::seed_from_u64(42);
28+
2329
let chunk_size = UVec2::splat(64);
2430
let tile_display_size = UVec2::splat(8);
2531
let indices: Vec<Option<u16>> = (0..chunk_size.element_product())
@@ -39,6 +45,8 @@ fn setup(mut commands: Commands, assets: Res<AssetServer>) {
3945
));
4046

4147
commands.spawn(Camera2d);
48+
49+
commands.insert_resource(SeededRng(rng));
4250
}
4351

4452
fn update_tileset_image(
@@ -55,12 +63,15 @@ fn update_tileset_image(
5563
}
5664
}
5765

58-
fn update_tilemap(time: Res<Time>, mut query: Query<(&mut TilemapChunkIndices, &mut UpdateTimer)>) {
66+
fn update_tilemap(
67+
time: Res<Time>,
68+
mut query: Query<(&mut TilemapChunkIndices, &mut UpdateTimer)>,
69+
mut rng: ResMut<SeededRng>,
70+
) {
5971
for (mut indices, mut timer) in query.iter_mut() {
6072
timer.tick(time.delta());
6173

6274
if timer.just_finished() {
63-
let mut rng = ChaCha8Rng::from_entropy();
6475
for _ in 0..50 {
6576
let index = rng.gen_range(0..indices.len());
6677
indices[index] = Some(rng.gen_range(0..5));

0 commit comments

Comments
 (0)