Skip to main content

openqmc/
pmj.rs

1//! Port of `oqmc/pmj.h` — the progressive multi-jittered (0,2) sampler.
2//!
3//! A base 4D pattern for all 2^16 sample indices is pre-computed once (see
4//! [`crate::stochastic`]), then looked up and XOR-scrambled at runtime. The
5//! first pair of dimensions integrates as well as the Sobol sampler; the second
6//! pair is a randomisation of the first (the (0,2) table only produces two
7//! dimensions).
8//!
9//! Upstream requires a caller-allocated cache; this port builds it lazily in a
10//! process global (see [`crate::sampler`] for the rationale).
11
12use std::sync::OnceLock;
13
14use crate::lookup::shuffled_scrambled_lookup;
15use crate::pcg;
16use crate::sampler::{Sampler, SamplerImpl};
17use crate::state::{MAX_INDEX_SIZE, State64Bit};
18use crate::stochastic::stochastic_pmj_init;
19
20/// The pre-computed 4D PMJ pattern table (one entry per sample index). Shared
21/// with the blue-noise PMJ variant.
22pub(crate) fn pmj_cache() -> &'static [[u32; 4]] {
23    static CACHE: OnceLock<Box<[[u32; 4]]>> = OnceLock::new();
24    CACHE.get_or_init(|| {
25        let mut table = vec![[0u32; 4]; MAX_INDEX_SIZE];
26        stochastic_pmj_init(MAX_INDEX_SIZE, &mut table);
27        table.into_boxed_slice()
28    })
29}
30
31/// Implementation behind [`PmjSampler`]. Use it through [`Sampler`].
32#[derive(Clone, Copy, Debug)]
33pub struct PmjImpl {
34    state: State64Bit,
35    cache: &'static [[u32; 4]],
36}
37
38impl SamplerImpl for PmjImpl {
39    #[inline]
40    fn from_pixel(x: i32, y: i32, frame: i32, index: i32) -> Self {
41        Self {
42            state: State64Bit::new(x, y, frame, index).pixel_decorrelate(),
43            cache: pmj_cache(),
44        }
45    }
46
47    #[inline]
48    fn new_domain(&self, key: i32) -> Self {
49        Self {
50            state: self.state.new_domain(key),
51            cache: self.cache,
52        }
53    }
54
55    #[inline]
56    fn new_domain_split(&self, key: i32, size: i32, index: i32) -> Self {
57        Self {
58            state: self.state.new_domain_split(key, size, index),
59            cache: self.cache,
60        }
61    }
62
63    #[inline]
64    fn new_domain_distrib(&self, key: i32, index: i32) -> Self {
65        Self {
66            state: self.state.new_domain_distrib(key, index),
67            cache: self.cache,
68        }
69    }
70
71    #[inline]
72    fn draw_block(&self) -> [u32; 4] {
73        shuffled_scrambled_lookup::<4, 4>(
74            self.state.sample_id as u32,
75            pcg::output(self.state.pattern_id),
76            self.cache,
77        )
78    }
79
80    #[inline]
81    fn draw_rnd_block(&self) -> [u32; 4] {
82        self.state.draw_rnd::<4>()
83    }
84
85    #[inline]
86    fn rng(&self) -> pcg::Rng {
87        self.state.rng()
88    }
89
90    fn warm_cache() {
91        pmj_cache();
92    }
93}
94
95/// Progressive multi-jittered (0,2) sampler (Helmer et al.).
96///
97/// Draws from a lazily-built 2^16-entry 4D table, so per-draw cost is a cheap
98/// lookup. The first dimension pair integrates like Sobol; the second pair is a
99/// randomisation of the first. Call `PmjSampler::warm_cache()` to build the
100/// table up front instead of on first draw. See
101/// [`PmjBnSampler`](crate::PmjBnSampler) for the blue-noise variant.
102///
103/// ```
104/// use openqmc::PmjSampler;
105///
106/// PmjSampler::warm_cache();
107/// let root = PmjSampler::new(12, 34, 0, 7);
108/// let [u, v] = root.new_domain(0).draw_sample_f32::<2>();
109/// assert!((0.0..1.0).contains(&u) && (0.0..1.0).contains(&v));
110/// ```
111pub type PmjSampler = Sampler<PmjImpl>;
112
113#[cfg(test)]
114mod tests {
115    use super::*;
116
117    #[test]
118    fn cache_is_built_once_and_full_length() {
119        let a = pmj_cache();
120        let b = pmj_cache();
121        assert!(std::ptr::eq(a, b));
122        assert_eq!(a.len(), MAX_INDEX_SIZE);
123    }
124
125    #[test]
126    fn cache_matches_a_fresh_stochastic_init() {
127        let mut fresh = vec![[0u32; 4]; MAX_INDEX_SIZE];
128        stochastic_pmj_init(MAX_INDEX_SIZE, &mut fresh);
129        assert_eq!(pmj_cache(), &fresh[..]);
130    }
131
132    #[test]
133    fn from_pixel_decorrelates_the_state_and_holds_the_cache() {
134        let imp = PmjImpl::from_pixel(3, 4, 5, 6);
135        assert_eq!(imp.state, State64Bit::new(3, 4, 5, 6).pixel_decorrelate());
136        assert!(std::ptr::eq(imp.cache, pmj_cache()));
137        assert!(std::ptr::eq(imp.new_domain(1).cache, pmj_cache()));
138        assert!(std::ptr::eq(
139            imp.new_domain_split(1, 2, 0).cache,
140            pmj_cache()
141        ));
142        assert!(std::ptr::eq(
143            imp.new_domain_distrib(1, 2).cache,
144            pmj_cache()
145        ));
146    }
147
148    #[test]
149    fn draw_block_is_a_lookup_seeded_with_output_of_pattern() {
150        let imp = PmjImpl::from_pixel(3, 4, 5, 6).new_domain(2);
151        assert_eq!(
152            imp.draw_block(),
153            shuffled_scrambled_lookup::<4, 4>(
154                imp.state.sample_id as u32,
155                pcg::output(imp.state.pattern_id),
156                pmj_cache()
157            )
158        );
159        assert_eq!(imp.draw_rnd_block(), imp.state.draw_rnd::<4>());
160    }
161
162    #[test]
163    fn warm_cache_builds_the_table() {
164        PmjImpl::warm_cache();
165        assert_eq!(pmj_cache().len(), MAX_INDEX_SIZE);
166    }
167}