Skip to main content

openqmc/
sampler.rs

1//! Port of `oqmc/sampler.h` — the public, static-polymorphic sampler interface.
2//!
3//! Upstream `SamplerInterface<Impl>` composes an internal implementation and
4//! exposes a uniform domain-tree API. We model that with the [`SamplerImpl`]
5//! trait plus the generic [`Sampler`] wrapper. Each impl computes a full
6//! 4-dimensional block; the wrapper's const-generic `draw_*::<N>` methods
7//! return the first `N` values, which is identical to computing `N` directly in
8//! every upstream draw path (each output dimension is independent of the
9//! requested depth).
10//!
11//! Divergence from the C++ headers: upstream takes a caller-allocated `void*`
12//! cache, a design driven by GPU memory management (see `sampler.h`). This CPU
13//! port instead builds any required tables in lazily-initialised process
14//! globals, so every `Sampler<T>` stays a small `Copy + Send + 'static` value.
15
16use crate::float::uint_to_float;
17use crate::pcg;
18use crate::range::uint_to_range;
19
20/// Internal sampler implementation. Not called directly — use [`Sampler`].
21pub trait SamplerImpl: Copy {
22    /// Construct from pixel/frame/sample indices (index must be `>= 0`).
23    fn from_pixel(x: i32, y: i32, frame: i32, index: i32) -> Self;
24    /// Derive a child domain (independent 4D pattern).
25    fn new_domain(&self, key: i32) -> Self;
26    /// Derive a fixed-rate split domain.
27    fn new_domain_split(&self, key: i32, size: i32, index: i32) -> Self;
28    /// Derive an adaptive-rate (local) split domain.
29    fn new_domain_distrib(&self, key: i32, index: i32) -> Self;
30    /// Compute the 4D high-quality sample block for this domain.
31    fn draw_block(&self) -> [u32; 4];
32    /// Compute the 4D low-quality pseudo-random block for this domain.
33    fn draw_rnd_block(&self) -> [u32; 4];
34    /// A sequential PRNG stream for this domain (for unbounded draws).
35    fn rng(&self) -> pcg::Rng;
36    /// Force any lazily-built cache to initialise. Optional; draws trigger it
37    /// anyway. Default no-op for cache-free samplers.
38    fn warm_cache() {}
39}
40
41#[inline]
42fn take<const N: usize>(block: [u32; 4]) -> [u32; N] {
43    const { assert!(N >= 1 && N <= 4, "Draw size must be within [1, 4]") };
44    let mut out = [0u32; N];
45    out.copy_from_slice(&block[..N]);
46    out
47}
48
49/// The public sampler. Different `Impl`s are interchangeable at every call site.
50///
51/// A sampler is immutable: derive children with `new_domain*`, draw values with
52/// `draw_*`. Deriving a domain is cheap (an LCG state transition); drawing is
53/// where the sequence work happens.
54#[derive(Clone, Copy, Debug)]
55pub struct Sampler<T: SamplerImpl> {
56    imp: T,
57}
58
59impl<T: SamplerImpl> Sampler<T> {
60    /// Eagerly initialise any lazily-built cache for this sampler type.
61    #[inline]
62    pub fn warm_cache() {
63        T::warm_cache();
64    }
65
66    /// Construct from pixel coordinate, frame and sample index (`index >= 0`).
67    #[inline]
68    pub fn new(x: i32, y: i32, frame: i32, index: i32) -> Self {
69        debug_assert!(index >= 0);
70        Self {
71            imp: T::from_pixel(x, y, frame, index),
72        }
73    }
74
75    /// Derive a child domain with an independent 4D pattern.
76    #[inline]
77    pub fn new_domain(&self, key: i32) -> Self {
78        Self {
79            imp: self.imp.new_domain(key),
80        }
81    }
82
83    /// Derive a split domain with a fixed sample-rate multiplier.
84    #[inline]
85    pub fn new_domain_split(&self, key: i32, size: i32, index: i32) -> Self {
86        debug_assert!(size > 0 && index >= 0);
87        Self {
88            imp: self.imp.new_domain_split(key, size, index),
89        }
90    }
91
92    /// Derive a split domain with a local (adaptive) distribution.
93    #[inline]
94    pub fn new_domain_distrib(&self, key: i32, index: i32) -> Self {
95        debug_assert!(index >= 0);
96        Self {
97            imp: self.imp.new_domain_distrib(key, index),
98        }
99    }
100
101    /// Derive a split domain with a global (adaptive) distribution
102    /// (`new_domain(key).new_domain(index)`).
103    #[inline]
104    pub fn new_domain_chain(&self, key: i32, index: i32) -> Self {
105        debug_assert!(index >= 0);
106        self.new_domain(key).new_domain(index)
107    }
108
109    /// Draw `N` (1..=4) high-quality integer sample values, each in `[0, 2^32)`.
110    #[inline]
111    pub fn draw_sample<const N: usize>(&self) -> [u32; N] {
112        take(self.imp.draw_block())
113    }
114
115    /// Draw `N` high-quality sample values within `[0, range)`.
116    #[inline]
117    pub fn draw_sample_range<const N: usize>(&self, range: u32) -> [u32; N] {
118        debug_assert!(range > 0);
119        let block = self.draw_sample::<N>();
120        let mut out = [0u32; N];
121        for i in 0..N {
122            out[i] = uint_to_range(block[i], range);
123        }
124        out
125    }
126
127    /// Draw `N` high-quality sample values within `[0, 1)`.
128    #[inline]
129    pub fn draw_sample_f32<const N: usize>(&self) -> [f32; N] {
130        let block = self.draw_sample::<N>();
131        let mut out = [0.0f32; N];
132        for i in 0..N {
133            out[i] = uint_to_float(block[i]);
134        }
135        out
136    }
137
138    /// Draw `N` low-quality pseudo-random integer values, each in `[0, 2^32)`.
139    #[inline]
140    pub fn draw_rnd<const N: usize>(&self) -> [u32; N] {
141        take(self.imp.draw_rnd_block())
142    }
143
144    /// Draw `N` low-quality pseudo-random values within `[0, range)`.
145    #[inline]
146    pub fn draw_rnd_range<const N: usize>(&self, range: u32) -> [u32; N] {
147        debug_assert!(range > 0);
148        let block = self.draw_rnd::<N>();
149        let mut out = [0u32; N];
150        for i in 0..N {
151            out[i] = uint_to_range(block[i], range);
152        }
153        out
154    }
155
156    /// Draw `N` low-quality pseudo-random values within `[0, 1)`.
157    #[inline]
158    pub fn draw_rnd_f32<const N: usize>(&self) -> [f32; N] {
159        let block = self.draw_rnd::<N>();
160        let mut out = [0.0f32; N];
161        for i in 0..N {
162            out[i] = uint_to_float(block[i]);
163        }
164        out
165    }
166
167    /// A sequential PRNG stream seeded from this domain, for unbounded random
168    /// draws (Russian roulette, delta tracking) where QMC stratification does not
169    /// apply.
170    #[inline]
171    pub fn rng(&self) -> pcg::Rng {
172        self.imp.rng()
173    }
174}
175
176#[cfg(test)]
177mod tests {
178    use super::*;
179
180    use crate::state::State64Bit;
181
182    /// A minimal deterministic implementation to exercise the wrapper alone.
183    #[derive(Clone, Copy, Debug)]
184    struct Dummy {
185        state: State64Bit,
186    }
187
188    impl SamplerImpl for Dummy {
189        fn from_pixel(x: i32, y: i32, frame: i32, index: i32) -> Self {
190            Self {
191                state: State64Bit::new(x, y, frame, index),
192            }
193        }
194        fn new_domain(&self, key: i32) -> Self {
195            Self {
196                state: self.state.new_domain(key),
197            }
198        }
199        fn new_domain_split(&self, key: i32, size: i32, index: i32) -> Self {
200            Self {
201                state: self.state.new_domain_split(key, size, index),
202            }
203        }
204        fn new_domain_distrib(&self, key: i32, index: i32) -> Self {
205            Self {
206                state: self.state.new_domain_distrib(key, index),
207            }
208        }
209        fn draw_block(&self) -> [u32; 4] {
210            let p = self.state.pattern_id;
211            [p, p ^ 1, p ^ 2, p ^ 3]
212        }
213        fn draw_rnd_block(&self) -> [u32; 4] {
214            self.state.draw_rnd::<4>()
215        }
216        fn rng(&self) -> pcg::Rng {
217            self.state.rng()
218        }
219    }
220
221    type DummySampler = Sampler<Dummy>;
222
223    #[test]
224    fn take_returns_the_prefix() {
225        let block = [10u32, 20, 30, 40];
226        assert_eq!(take::<1>(block), [10]);
227        assert_eq!(take::<2>(block), [10, 20]);
228        assert_eq!(take::<3>(block), [10, 20, 30]);
229        assert_eq!(take::<4>(block), block);
230    }
231
232    #[test]
233    fn default_warm_cache_is_a_no_op() {
234        Dummy::warm_cache();
235        DummySampler::warm_cache();
236    }
237
238    #[test]
239    fn draw_sample_is_take_of_draw_block() {
240        let s = DummySampler::new(1, 2, 3, 4).new_domain(5);
241        let block = s.imp.draw_block();
242        assert_eq!(s.draw_sample::<4>(), block);
243        assert_eq!(s.draw_sample::<2>(), [block[0], block[1]]);
244        assert_eq!(s.draw_sample::<1>(), [block[0]]);
245    }
246
247    #[test]
248    fn draw_rnd_is_take_of_draw_rnd_block() {
249        let s = DummySampler::new(1, 2, 3, 4).new_domain(5);
250        let block = s.imp.draw_rnd_block();
251        assert_eq!(s.draw_rnd::<4>(), block);
252        assert_eq!(s.draw_rnd::<3>(), [block[0], block[1], block[2]]);
253    }
254
255    #[test]
256    fn conversions_apply_per_element() {
257        let s = DummySampler::new(1, 2, 3, 4).new_domain(5);
258        let block = s.draw_sample::<4>();
259        let f = s.draw_sample_f32::<4>();
260        let r = s.draw_sample_range::<4>(1000);
261        for k in 0..4 {
262            assert_eq!(f[k], uint_to_float(block[k]));
263            assert_eq!(r[k], uint_to_range(block[k], 1000));
264        }
265        let block = s.draw_rnd::<4>();
266        let f = s.draw_rnd_f32::<4>();
267        let r = s.draw_rnd_range::<4>(7);
268        for k in 0..4 {
269            assert_eq!(f[k], uint_to_float(block[k]));
270            assert_eq!(r[k], uint_to_range(block[k], 7));
271        }
272    }
273
274    #[test]
275    fn domain_methods_forward_to_the_impl() {
276        let s = DummySampler::new(1, 2, 3, 4);
277        assert_eq!(s.new_domain(7).imp.state, s.imp.state.new_domain(7));
278        assert_eq!(
279            s.new_domain_split(7, 4, 1).imp.state,
280            s.imp.state.new_domain_split(7, 4, 1)
281        );
282        assert_eq!(
283            s.new_domain_distrib(7, 1).imp.state,
284            s.imp.state.new_domain_distrib(7, 1)
285        );
286        assert_eq!(
287            s.new_domain_chain(7, 1).imp.state,
288            s.imp.state.new_domain(7).new_domain(1)
289        );
290    }
291
292    #[test]
293    fn rng_forwards_to_the_impl() {
294        let s = DummySampler::new(1, 2, 3, 4);
295        assert_eq!(s.rng().next_u32(), s.imp.rng().next_u32());
296        assert_eq!(s.rng().next_u32(), s.draw_rnd::<1>()[0]);
297    }
298
299    #[test]
300    fn wrapper_is_copy_and_debug() {
301        let s = DummySampler::new(1, 2, 3, 4);
302        let t = s;
303        assert_eq!(s.draw_sample::<4>(), t.draw_sample::<4>());
304        assert!(format!("{s:?}").contains("Sampler"));
305    }
306
307    #[cfg(debug_assertions)]
308    #[test]
309    #[should_panic]
310    fn negative_index_is_rejected_in_debug() {
311        let _ = DummySampler::new(0, 0, 0, -1);
312    }
313
314    #[cfg(debug_assertions)]
315    #[test]
316    #[should_panic]
317    fn zero_split_size_is_rejected_in_debug() {
318        let _ = DummySampler::new(0, 0, 0, 0).new_domain_split(0, 0, 0);
319    }
320
321    #[cfg(debug_assertions)]
322    #[test]
323    #[should_panic]
324    fn negative_split_index_is_rejected_in_debug() {
325        let _ = DummySampler::new(0, 0, 0, 0).new_domain_split(0, 2, -1);
326    }
327
328    #[cfg(debug_assertions)]
329    #[test]
330    #[should_panic]
331    fn negative_distrib_index_is_rejected_in_debug() {
332        let _ = DummySampler::new(0, 0, 0, 0).new_domain_distrib(0, -1);
333    }
334
335    #[cfg(debug_assertions)]
336    #[test]
337    #[should_panic]
338    fn negative_chain_index_is_rejected_in_debug() {
339        let _ = DummySampler::new(0, 0, 0, 0).new_domain_chain(0, -1);
340    }
341
342    #[cfg(debug_assertions)]
343    #[test]
344    #[should_panic]
345    fn zero_range_is_rejected_in_debug() {
346        let _ = DummySampler::new(0, 0, 0, 0).draw_sample_range::<1>(0);
347    }
348
349    #[cfg(debug_assertions)]
350    #[test]
351    #[should_panic]
352    fn zero_rnd_range_is_rejected_in_debug() {
353        let _ = DummySampler::new(0, 0, 0, 0).draw_rnd_range::<1>(0);
354    }
355}