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 renderer's deterministic generator (SplitMix64).
9#[derive(Clone, Debug)]
10pub struct Rng(u64);
11
12impl Rng {
13    /// A generator starting at `seed`.
14    pub fn new(seed: u64) -> Self {
15        Rng(seed)
16    }
17
18    /// Derive an independent stream: `Rng::new(seed).fork(tag)`.
19    pub fn fork(&self, tag: u64) -> Rng {
20        let mut r = Rng(self.0 ^ tag.wrapping_mul(0xD6E8_FEB8_6659_FD93));
21        r.next_u64();
22        r
23    }
24
25    /// Next 64 random bits.
26    pub fn next_u64(&mut self) -> u64 {
27        self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
28        let mut z = self.0;
29        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
30        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
31        z ^ (z >> 31)
32    }
33
34    /// Uniform in `[0, 1)`; MD2's `FRAND` (plugin.cpp: `uniform_real_distribution<float>(0,1)`).
35    pub fn frand(&mut self) -> f32 {
36        (self.next_u64() >> 40) as f32 / 16_777_216.0
37    }
38
39    /// Uniform integer in `[0, n)`.
40    pub fn below(&mut self, n: u32) -> u32 {
41        if n == 0 {
42            return 0;
43        }
44        (((self.next_u64() >> 32) * n as u64) >> 32) as u32
45    }
46}
47
48#[cfg(test)]
49mod tests {
50    use super::*;
51
52    #[test]
53    fn deterministic_and_in_range() {
54        let mut a = Rng::new(1);
55        let mut b = Rng::new(1);
56        for _ in 0..1000 {
57            let x = a.frand();
58            assert_eq!(x, b.frand());
59            assert!((0.0..1.0).contains(&x));
60        }
61        let mut c = Rng::new(2);
62        assert_ne!(Rng::new(1).next_u64(), c.next_u64());
63        for _ in 0..1000 {
64            assert!(a.below(7) < 7);
65        }
66    }
67}