Skip to main content

lactea_render/
rng.rs

1// SPDX-FileCopyrightText: 2026 Gianluca Boiano
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! Tiny deterministic PRNG (SplitMix64). Every random decision the renderer makes
5//! (noise textures, preset rotation parameters, per-frame random rotations, hue-shader
6//! phases) is derived from `RenderConfig::seed` through this generator.
7
8/// The SplitMix64 output mixer: a bijective scramble of `z`, usable on its own to hash a value into 64 random bits.
9pub fn mix64(mut z: u64) -> u64 {
10    z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
11    z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
12    z ^ (z >> 31)
13}
14
15/// The renderer's deterministic generator (SplitMix64).
16#[derive(Clone, Debug)]
17pub struct Rng(u64);
18
19impl Rng {
20    /// A generator starting at `seed`.
21    pub fn new(seed: u64) -> Self {
22        Rng(seed)
23    }
24
25    /// Derive an independent stream: `Rng::new(seed).fork(tag)`.
26    pub fn fork(&self, tag: u64) -> Rng {
27        let mut r = Rng(self.0 ^ tag.wrapping_mul(0xD6E8_FEB8_6659_FD93));
28        r.next_u64();
29        r
30    }
31
32    /// Next 64 random bits.
33    pub fn next_u64(&mut self) -> u64 {
34        self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
35        mix64(self.0)
36    }
37
38    /// Uniform in `[0, 1)`; MD2's `FRAND` (plugin.cpp: `uniform_real_distribution<float>(0,1)`).
39    pub fn frand(&mut self) -> f32 {
40        (self.next_u64() >> 40) as f32 / 16_777_216.0
41    }
42
43    /// Uniform integer in `[0, n)`.
44    pub fn below(&mut self, n: u32) -> u32 {
45        if n == 0 {
46            return 0;
47        }
48        (((self.next_u64() >> 32) * n as u64) >> 32) as u32
49    }
50}
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55
56    #[test]
57    fn deterministic_and_in_range() {
58        let mut a = Rng::new(1);
59        let mut b = Rng::new(1);
60        for _ in 0..1000 {
61            let x = a.frand();
62            assert_eq!(x, b.frand());
63            assert!((0.0..1.0).contains(&x));
64        }
65        let mut c = Rng::new(2);
66        assert_ne!(Rng::new(1).next_u64(), c.next_u64());
67        for _ in 0..1000 {
68            assert!(a.below(7) < 7);
69        }
70    }
71}