Skip to main content

quick_noise/noise/generators/cellular/
batch_2d.rs

1use simply_simd::{Arch, Simd};
2
3use crate::api::batch::interface::BatchGenerator;
4use crate::noise::generators::Cellular;
5use crate::noise::util::constants::{BYTE_SHUFFLE, CELLULAR_EXP_MASK, HASH_MASK, HASH_PRIME};
6
7impl BatchGenerator<2> for Cellular {
8    #[inline(always)]
9    fn sample_batch<A: Arch>(
10        seed: u32,
11        input: [Simd<f32, A>; 2],
12        freq: [Simd<f32, A>; 2],
13    ) -> Simd<f32, A> {
14        // Constants.
15        let three_halves: Simd<f32, A> = Simd::splat(1.5);
16        let one: Simd<f32, A> = Simd::splat(1.0);
17
18        let hash_mask: Simd<u32, A> = Simd::splat(HASH_MASK);
19        let exp_bits: Simd<u32, A> = Simd::splat(CELLULAR_EXP_MASK);
20
21        // Hash constants.
22        let shuffle_indices = Simd::<u8, A>::from_slice(&BYTE_SHUFFLE[..]);
23        let channel_seed = Simd::splat(seed);
24        let prime = Simd::splat(HASH_PRIME);
25
26        // Scale: 2
27        let x_scaled = input[0] * freq[0];
28        let y_scaled = input[1] * freq[1];
29
30        // Gridpoints and distances: 8
31        let x_grid_lo = x_scaled.floor();
32        let y_grid_lo = y_scaled.floor();
33
34        let x_dist_lo = x_scaled - x_grid_lo - three_halves;
35        let y_dist_lo = y_scaled - y_grid_lo - three_halves;
36        let x_dist_hi = one - x_dist_lo;
37        let y_dist_hi = one - y_dist_lo;
38
39        // Threshold: 6
40        let close_edge_lo = x_dist_lo.min(y_dist_lo) + Simd::splat(2.0);
41        let close_edge_hi = x_dist_hi.min(y_dist_hi) - one;
42        let closest_edge_dist = close_edge_lo.min(close_edge_hi);
43        let threshold = closest_edge_dist * closest_edge_dist;
44
45        // Hash: 22
46        let x1: Simd<u32, A> = x_grid_lo.cast_int_trunc().raw_cast() * channel_seed;
47        let y1: Simd<u32, A> = y_grid_lo.cast_int_trunc().raw_cast() * channel_seed;
48        let x2 = x1 + channel_seed;
49        let y2 = y1 + channel_seed;
50
51        let x1_shuf = x1.permute_8(shuffle_indices) ^ prime;
52        let y1_shuf = y1.permute_8(shuffle_indices) ^ prime;
53        let x2_shuf = x2.permute_8(shuffle_indices) ^ prime;
54        let y2_shuf = y2.permute_8(shuffle_indices) ^ prime;
55
56        let hash_tl = (x1_shuf * y1_shuf) ^ x1_shuf;
57        let hash_tr = (x1_shuf * y2_shuf) ^ x1_shuf;
58        let hash_bl = (x2_shuf * y1_shuf) ^ x2_shuf;
59        let hash_br = (x2_shuf * y2_shuf) ^ x2_shuf;
60
61        // Distance Calc: 35
62        let x_dist_tl = ((hash_tl & hash_mask) | exp_bits).raw_cast::<f32>() + x_dist_lo;
63        let x_dist_tr = ((hash_tr & hash_mask) | exp_bits).raw_cast::<f32>() + x_dist_lo;
64        let x_dist_bl = ((hash_bl & hash_mask) | exp_bits).raw_cast::<f32>() - x_dist_hi;
65        let x_dist_br = ((hash_br & hash_mask) | exp_bits).raw_cast::<f32>() - x_dist_hi;
66
67        let y_dist_tl = ((hash_tl >> 9) | exp_bits).raw_cast::<f32>() + y_dist_lo;
68        let y_dist_tr = ((hash_tr >> 9) | exp_bits).raw_cast::<f32>() - y_dist_hi;
69        let y_dist_bl = ((hash_bl >> 9) | exp_bits).raw_cast::<f32>() + y_dist_lo;
70        let y_dist_br = ((hash_br >> 9) | exp_bits).raw_cast::<f32>() - y_dist_hi;
71
72        let dist_tl = x_dist_tl.mul_add(x_dist_tl, y_dist_tl * y_dist_tl);
73        let dist_tr = x_dist_tr.mul_add(x_dist_tr, y_dist_tr * y_dist_tr);
74        let dist_bl = x_dist_bl.mul_add(x_dist_bl, y_dist_bl * y_dist_bl);
75        let dist_br = x_dist_br.mul_add(x_dist_br, y_dist_br * y_dist_br);
76
77        let mut min_dist = dist_tl.min(dist_tr).min(dist_bl).min(dist_br);
78
79        // Branch: 2 + Branch prediction.
80        let is_far = min_dist.simd_gt(threshold);
81
82        // Only triggers 2-3% of the time. -25% Throughput despite this.
83        if !is_far.all_false() {
84            let x0 = x1 - channel_seed;
85            let y0 = y1 - channel_seed;
86            let x3 = x2 + channel_seed;
87            let y3 = y2 + channel_seed;
88
89            let x0_shuf = x0.permute_8(shuffle_indices) ^ prime;
90            let y0_shuf = y0.permute_8(shuffle_indices) ^ prime;
91            let x3_shuf = x3.permute_8(shuffle_indices) ^ prime;
92            let y3_shuf = y3.permute_8(shuffle_indices) ^ prime;
93
94            let hash_ttl = (x0_shuf * y1_shuf) ^ x0_shuf;
95            let hash_tll = (x1_shuf * y0_shuf) ^ x1_shuf;
96            let hash_ttr = (x0_shuf * y2_shuf) ^ x0_shuf;
97            let hash_trr = (x1_shuf * y3_shuf) ^ x1_shuf;
98
99            let hash_bbl = (x3_shuf * y1_shuf) ^ x3_shuf;
100            let hash_bll = (x2_shuf * y0_shuf) ^ x2_shuf;
101            let hash_bbr = (x3_shuf * y2_shuf) ^ x3_shuf;
102            let hash_brr = (x2_shuf * y3_shuf) ^ x2_shuf;
103
104            let x_dist_ttl =
105                ((hash_ttl & hash_mask) | exp_bits).raw_cast::<f32>() + x_dist_lo + one;
106            let x_dist_tll = ((hash_tll & hash_mask) | exp_bits).raw_cast::<f32>() + x_dist_lo;
107            let x_dist_ttr =
108                ((hash_ttr & hash_mask) | exp_bits).raw_cast::<f32>() + x_dist_lo + one;
109            let x_dist_trr = ((hash_trr & hash_mask) | exp_bits).raw_cast::<f32>() + x_dist_lo;
110            let x_dist_bbl =
111                ((hash_bbl & hash_mask) | exp_bits).raw_cast::<f32>() - x_dist_hi - one;
112            let x_dist_bll = ((hash_bll & hash_mask) | exp_bits).raw_cast::<f32>() - x_dist_hi;
113            let x_dist_bbr =
114                ((hash_bbr & hash_mask) | exp_bits).raw_cast::<f32>() - x_dist_hi - one;
115            let x_dist_brr = ((hash_brr & hash_mask) | exp_bits).raw_cast::<f32>() - x_dist_hi;
116
117            let y_dist_ttl = ((hash_ttl >> 9) | exp_bits).raw_cast::<f32>() + y_dist_lo;
118            let y_dist_tll = ((hash_tll >> 9) | exp_bits).raw_cast::<f32>() + y_dist_lo + one;
119            let y_dist_ttr = ((hash_ttr >> 9) | exp_bits).raw_cast::<f32>() - y_dist_hi;
120            let y_dist_trr = ((hash_trr >> 9) | exp_bits).raw_cast::<f32>() - y_dist_hi - one;
121            let y_dist_bbl = ((hash_bbl >> 9) | exp_bits).raw_cast::<f32>() + y_dist_lo;
122            let y_dist_bll = ((hash_bll >> 9) | exp_bits).raw_cast::<f32>() + y_dist_lo + one;
123            let y_dist_bbr = ((hash_bbr >> 9) | exp_bits).raw_cast::<f32>() - y_dist_hi;
124            let y_dist_brr = ((hash_brr >> 9) | exp_bits).raw_cast::<f32>() - y_dist_hi - one;
125
126            let dist_ttl = x_dist_ttl.mul_add(x_dist_ttl, y_dist_ttl * y_dist_ttl);
127            let dist_tll = x_dist_tll.mul_add(x_dist_tll, y_dist_tll * y_dist_tll);
128            let dist_ttr = x_dist_ttr.mul_add(x_dist_ttr, y_dist_ttr * y_dist_ttr);
129            let dist_trr = x_dist_trr.mul_add(x_dist_trr, y_dist_trr * y_dist_trr);
130            let dist_bbl = x_dist_bbl.mul_add(x_dist_bbl, y_dist_bbl * y_dist_bbl);
131            let dist_bll = x_dist_bll.mul_add(x_dist_bll, y_dist_bll * y_dist_bll);
132            let dist_bbr = x_dist_bbr.mul_add(x_dist_bbr, y_dist_bbr * y_dist_bbr);
133            let dist_brr = x_dist_brr.mul_add(x_dist_brr, y_dist_brr * y_dist_brr);
134
135            let outer_min = dist_ttl
136                .min(dist_tll)
137                .min(dist_ttr)
138                .min(dist_trr)
139                .min(dist_bbl)
140                .min(dist_bll)
141                .min(dist_bbr)
142                .min(dist_brr);
143
144            min_dist = min_dist.min(outer_min);
145        }
146
147        // Sqrt: 1
148        min_dist.sqrt()
149    }
150}
151
152#[cfg(test)]
153mod tests {
154    use super::*;
155    use crate::api::seed::gen_octave_seed;
156    use crate::math::random::Random;
157    use crate::noise::generators::cellular::grid_2d::{hash_cell, split_hash};
158    use crate::simd::StaticArch;
159
160    #[test]
161    fn cellular_batch_2d_reference() {
162        const W: usize = 64;
163        const H: usize = 64;
164        const FREQ: f32 = 1.0 / 32.0;
165        let seed = 123456789i64;
166
167        let grid_seed = Random::mix_u64(seed as u64);
168        let base_seed = Random::mix_u64_pair(grid_seed, 0xD5E7B3C94F8A1E6B);
169        let octave_seed = gen_octave_seed([FREQ, FREQ], base_seed);
170
171        let max_diff = compare_batch(octave_seed, FREQ, W, H, (-5, 3));
172        assert!(
173            max_diff < 1e-4,
174            "Batch cellular diverges from the brute-force Cellular by {max_diff}"
175        );
176
177        let max_diff = compare_batch(octave_seed, FREQ, 32, 96, (-5, 3));
178        assert!(
179            max_diff < 1e-4,
180            "Tall batch cellular diverges from the brute-force Cellular by {max_diff}"
181        );
182    }
183
184    fn compare_batch(octave_seed: u32, freq: f32, w: usize, h: usize, pos: (i32, i32)) -> f32 {
185        let lanes = Simd::<f32, StaticArch>::LANES;
186
187        // Same sample coordinates as the grid: `position + index` scaled by freq.
188        let xs: Vec<f32> = (0..w * h).map(|i| pos.0 as f32 + (i % w) as f32).collect();
189        let ys: Vec<f32> = (0..w * h).map(|i| pos.1 as f32 + (i / w) as f32).collect();
190
191        let mut max_diff = 0.0f32;
192        for (block, (x_block, y_block)) in xs
193            .chunks_exact(lanes)
194            .zip(ys.chunks_exact(lanes))
195            .enumerate()
196        {
197            let input = [
198                Simd::<f32, StaticArch>::from_slice(x_block),
199                Simd::<f32, StaticArch>::from_slice(y_block),
200            ];
201            let freq_simd = [Simd::<f32, StaticArch>::splat(freq); 2];
202
203            let actual =
204                Cellular::sample_batch::<StaticArch>(octave_seed, input, freq_simd).to_array();
205
206            for (lane, actual) in actual.iter().enumerate().take(lanes) {
207                let i = block * lanes + lane;
208                let px = xs[i] * freq;
209                let py = ys[i] * freq;
210                let reference = reference_cellular(octave_seed, px, py);
211                max_diff = max_diff.max((actual - reference).abs());
212            }
213        }
214        max_diff
215    }
216
217    fn reference_cellular(seed: u32, px: f32, py: f32) -> f32 {
218        let cell_x = px.floor() as i32;
219        let cell_y = py.floor() as i32;
220        let sx = px - px.floor();
221        let sy = py - py.floor();
222
223        let mut min_dist = f32::MAX;
224        for ox in -3..=3 {
225            for oy in -3..=3 {
226                let (jx, jy) = split_hash(hash_cell::<StaticArch>(
227                    (cell_x + ox) as u32,
228                    (cell_y + oy) as u32,
229                    seed,
230                ));
231                let dx = sx - (ox as f32 + jx);
232                let dy = sy - (oy as f32 + jy);
233                min_dist = min_dist.min(dx * dx + dy * dy);
234            }
235        }
236        min_dist.sqrt()
237    }
238}