sciart_core/rng.rs
1//! A tiny generator for hot inner loops (SPEC-001 CORE-R57), and stateless hashes on its
2//! finaliser (CORE-R70).
3//!
4//! `ctx.rng` (ChaCha8) is the scene's one source of randomness (GEN-R7, ADR-0008), but
5//! it is a 136-byte state with block buffering behind `&mut`. A Monte-Carlo sweep over a
6//! lattice (Ising, stochastic automata) draws millions of numbers per second and wants
7//! an 8-byte state in a register: seed a [`SplitMix64`] from `ctx.rng` once, then draw
8//! from it. Determinism is preserved because the seed itself came from `ctx.rng`.
9
10use rand::{Rng, RngCore};
11
12/// Steele, Lea & Flood's SplitMix64 (the `java.util.SplittableRandom` mixer): a Weyl
13/// sequence through a 64-bit avalanche finaliser (CORE-R57). Passes BigCrush; period
14/// 2⁶⁴. Not cryptographic, which art does not need.
15///
16/// Implements [`RngCore`], so `rand`'s [`Rng`] methods and the `particles` samplers
17/// accept it too.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct SplitMix64 {
20 state: u64,
21}
22
23impl SplitMix64 {
24 const GAMMA: u64 = 0x9E37_79B9_7F4A_7C15;
25
26 /// A generator seeded with `seed`.
27 pub const fn new(seed: u64) -> Self {
28 Self { state: seed }
29 }
30
31 /// A generator seeded from `rng` (normally `ctx.rng`), consuming one `u64` of it.
32 pub fn from_rng(rng: &mut impl Rng) -> Self {
33 Self::new(rng.next_u64())
34 }
35
36 /// The SplitMix64 finaliser: a bijective 64-bit avalanche, so neighbouring keys give
37 /// independent-looking outputs (CORE-R70).
38 #[inline]
39 pub const fn mix(mut z: u64) -> u64 {
40 z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
41 z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
42 z ^ (z >> 31)
43 }
44
45 /// The next 64 random bits. Seed 0 yields `0xE220A8397B1DCDAF` first.
46 #[inline]
47 pub fn next_u64(&mut self) -> u64 {
48 self.state = self.state.wrapping_add(Self::GAMMA);
49 Self::mix(self.state)
50 }
51
52 /// Uniform in `[0, 1)` from the top 53 bits: every value is a multiple of 2⁻⁵³.
53 #[inline]
54 pub fn next_f64(&mut self) -> f64 {
55 unit(self.next_u64())
56 }
57
58 /// Uniform in `0..n` (`0` for `n = 0`), by Lemire's multiply-shift on the top 32
59 /// bits: branch-free, with a bias below `n / 2³²`, invisible at art scale.
60 #[inline]
61 pub fn below(&mut self, n: u32) -> u32 {
62 // (r · n) >> 32 < n for r < 2³², so the narrowing cast is lossless.
63 (((self.next_u64() >> 32) * u64::from(n)) >> 32) as u32
64 }
65}
66
67/// `[0, 1)` from the top 53 bits of `z`: every value is a multiple of 2⁻⁵³.
68#[inline]
69fn unit(z: u64) -> f64 {
70 const SCALE: f64 = 1.0 / (1u64 << 53) as f64;
71 (z >> 11) as f64 * SCALE
72}
73
74/// A stateless uniform in `[0, 1)` keyed by `key`: the top 53 bits of
75/// [`SplitMix64::mix`]`(key)` (CORE-R70). For per-cell dither and speckle that must hold
76/// still from frame to frame, e.g. `hash01(salt ^ cell_key(x, y))`.
77#[inline]
78pub fn hash01(key: u64) -> f64 {
79 unit(SplitMix64::mix(key))
80}
81
82/// A cell's coordinates packed into one hash key, `x` in the high and `y` in the low 32
83/// bits (two's complement), so distinct cells get distinct keys (CORE-R70).
84#[inline]
85pub const fn cell_key(x: i32, y: i32) -> u64 {
86 ((x as u32 as u64) << 32) | y as u32 as u64
87}
88
89/// Smooth 2-D value noise in `[0, 1]` (CORE-R97): lattice corners every `cell` units carry
90/// `hash01(salt ^ cell_key(i, j))`, blended bilinearly with smoothstep weights. Stateless,
91/// so a cloud or clump texture holds still between frames without a stored field.
92pub fn value_noise(salt: u64, x: f64, y: f64, cell: f64) -> f64 {
93 use crate::timeline::ease;
94 let (u, v) = (x / cell, y / cell);
95 let (i, j) = (u.floor(), v.floor());
96 // Saturating float→int casts: far-off or NaN coordinates stay finite, never panic.
97 let corner = |di: i32, dj: i32| {
98 hash01(salt ^ cell_key((i as i32).wrapping_add(di), (j as i32).wrapping_add(dj)))
99 };
100 let (fu, fv) = (ease::smoothstep(u - i), ease::smoothstep(v - j));
101 ease::lerp(
102 ease::lerp(corner(0, 0), corner(1, 0), fu),
103 ease::lerp(corner(0, 1), corner(1, 1), fu),
104 fv,
105 )
106}
107
108impl RngCore for SplitMix64 {
109 #[inline]
110 fn next_u32(&mut self) -> u32 {
111 (self.next_u64() >> 32) as u32
112 }
113
114 #[inline]
115 fn next_u64(&mut self) -> u64 {
116 SplitMix64::next_u64(self)
117 }
118
119 fn fill_bytes(&mut self, dst: &mut [u8]) {
120 for chunk in dst.chunks_mut(8) {
121 let bytes = SplitMix64::next_u64(self).to_le_bytes();
122 chunk.copy_from_slice(&bytes[..chunk.len()]);
123 }
124 }
125}