Skip to main content

spatialrust_gpu/kernels/
icp_reduction.rs

1use crate::{scratch::ScratchBuffers, GpuKdTree, GpuQueryBatch, WgpuRuntime};
2use bytemuck::{Pod, Zeroable};
3use spatialrust_core::{SpatialError, SpatialResult, TransferDirection, TransferStats};
4use spatialrust_math::Isometry3;
5use spatialrust_search::KdTree;
6use std::sync::Arc;
7use wgpu::util::DeviceExt;
8
9const RESULT_BYTES: u64 = 176;
10
11#[path = "icp_geometry_preparation.rs"]
12mod geometry_preparation;
13
14#[path = "icp_trim.rs"]
15pub(crate) mod trim;
16
17#[repr(C)]
18#[derive(Clone, Copy, Pod, Zeroable)]
19struct Params {
20    rows: [[f32; 4]; 3],
21    source_anchor: [f32; 4],
22    target_anchor: [f32; 4],
23    count: u32,
24    targets: u32,
25    groups: u32,
26    unused: u32,
27    bound: f32,
28    max_distance: f32,
29    scale: f32,
30    padding: f32,
31}
32
33fn invalid() -> SpatialError {
34    SpatialError::InvalidArgument("GPU ICP reduction requires matching runtime, finite XYZ/extents, a finite unit-quaternion transform, a positive finite nonzero distance square, nonempty target and supported limits".to_owned())
35}
36
37fn plan(count: u64, limits: &wgpu::Limits) -> SpatialResult<u32> {
38    let groups = count.div_ceil(64).min(256);
39    let bound = limits.max_buffer_size.min(u64::from(limits.max_storage_buffer_binding_size));
40    if count > u64::from(u32::MAX)
41        || count.checked_mul(16).map_or(true, |n| n > bound || n > isize::MAX as u64)
42        || groups * 144 > bound
43        || bound < RESULT_BYTES
44        || limits.max_compute_workgroups_per_dimension < 9
45        || count.div_ceil(64) > u64::from(limits.max_compute_workgroups_per_dimension)
46        || limits.max_compute_workgroup_size_x < 64
47        || limits.max_compute_workgroup_size_y == 0
48        || limits.max_compute_workgroup_size_z == 0
49        || limits.max_compute_invocations_per_workgroup < 64
50        || limits.max_compute_workgroup_storage_size < 768
51        || limits.max_storage_buffers_per_shader_stage < 6
52        || limits.max_bindings_per_bind_group < 7
53        || limits.max_bind_groups == 0
54        || limits.max_uniform_buffers_per_shader_stage == 0
55        || limits.max_uniform_buffer_binding_size < 112
56    {
57        return Err(invalid());
58    }
59    Ok(groups as u32)
60}
61
62fn geometry(points: &[[f32; 3]]) -> SpatialResult<([f32; 4], f64)> {
63    geometry_preparation::prepare(points)
64}
65
66/// Explicitly uploaded source and target for reusable device ICP moments.
67/// CPU target-tree construction is external. Original source points remain
68/// immutable; every evaluation applies the absolute pose to those originals.
69pub struct GpuIcpInput {
70    pub(super) source: GpuQueryBatch,
71    pub(super) target: GpuQueryBatch,
72    pub(super) tree: GpuKdTree,
73    pub(super) source_anchor: [f32; 4],
74    target_anchor: [f32; 4],
75    pub(super) scale: f32,
76    pub(super) identity: Arc<()>,
77    transfers: TransferStats,
78}
79
80impl GpuIcpInput {
81    /// Uploads source XYZ and a nonempty finite target tree. Payload is 16*S
82    /// source bytes, 32*T target bytes (tree order plus original order), and
83    /// 32*M tree-node bytes. The combined normalization extent must have a normal
84    /// finite f32 square; coincident source/target sets use scale 1.
85    /// Derived zero frame anchors use +0 consistently; uploaded original XYZ
86    /// bits, including signed zeros, are preserved. Nonzero anchors and scales
87    /// retain their f64 preparation arithmetic.
88    pub fn upload(
89        runtime: &WgpuRuntime,
90        source: &[[f32; 3]],
91        target: &KdTree,
92    ) -> SpatialResult<Self> {
93        Self::upload_impl(runtime, source, target, false)
94    }
95
96    /// Explicitly gathers target tree points and original-order target queries
97    /// together on GPU. Host payload is 16*S + 16*T + 32*M bytes, compared
98    /// with 16*S + 32*T + 32*M for `upload`; device output bytes are 32*T.
99    /// Source packing, CPU geometry validation/partitioning and node staging
100    /// remain. Integer copies preserve input bits, anchors, scale and ordering.
101    /// Two transient inputs add 16*T GPU bytes beside owned outputs; host
102    /// target point/query packing vectors totaling 32*T payload bytes over
103    /// construction are removed. This is not a peak-memory reduction claim.
104    /// There is no readback or completion wait. Placement is explicit;
105    /// small inputs may be slower and existing device requirements apply.
106    pub fn upload_with_gpu_gather(
107        runtime: &WgpuRuntime,
108        source: &[[f32; 3]],
109        target: &KdTree,
110    ) -> SpatialResult<Self> {
111        Self::upload_impl(runtime, source, target, true)
112    }
113
114    fn upload_impl(
115        runtime: &WgpuRuntime,
116        source: &[[f32; 3]],
117        target: &KdTree,
118        gpu_gather: bool,
119    ) -> SpatialResult<Self> {
120        plan(source.len() as u64, &runtime.device().limits())?;
121        let layout = target.layout();
122        let (x, y, z) = layout.positions();
123        plan(x.len() as u64, &runtime.device().limits())?;
124        if x.is_empty() {
125            return Err(invalid());
126        }
127        let (source_anchor, source_extent) = geometry(source)?;
128        let (target_anchor, target_extent) = geometry_preparation::prepare_soa([x, y, z])?;
129        let extent = source_extent.max(target_extent);
130        if extent > 0.0 && (extent as f32) < f32::MIN_POSITIVE {
131            return Err(invalid());
132        }
133        let scale = if extent == 0.0 { 1.0 } else { extent.sqrt() as f32 };
134        let (tree, gathered_target) = if gpu_gather {
135            let (tree, queries) = GpuKdTree::upload_and_queries_with_gpu_gather(runtime, target)?;
136            (tree, Some(queries))
137        } else {
138            (GpuKdTree::upload(runtime, target)?, None)
139        };
140        let source = GpuQueryBatch::upload(runtime, source)?;
141        let target = match gathered_target {
142            Some(queries) => queries,
143            None => GpuQueryBatch::upload_soa(runtime, [x, y, z])?,
144        };
145        let mut transfers = tree.upload_transfers();
146        transfers.record(
147            TransferDirection::HostToDevice,
148            source.upload_transfers().host_to_device_bytes(),
149        );
150        transfers.record(
151            TransferDirection::HostToDevice,
152            target.upload_transfers().host_to_device_bytes(),
153        );
154        transfers.record(
155            TransferDirection::DeviceToDevice,
156            target.upload_transfers().device_to_device_bytes(),
157        );
158        Ok(Self {
159            source,
160            target,
161            tree,
162            source_anchor,
163            target_anchor,
164            scale,
165            identity: runtime.profiling_identity(),
166            transfers,
167        })
168    }
169
170    /// Payload transferred during explicit input upload.
171    #[must_use]
172    pub const fn upload_transfers(&self) -> TransferStats {
173        self.transfers
174    }
175
176    /// Original source point count.
177    #[must_use]
178    pub fn source_count(&self) -> u32 {
179        self.source.query_count()
180    }
181
182    /// Submits source transformation, bounded nearest search, compensated
183    /// centroid/fitness and centered cross-covariance reductions in six passes.
184    /// No payload copy/readback or host wait occurs. The fixed-size owned result
185    /// can outlive inputs; consumers must check status before using its moments.
186    /// GPU f32 transforms/reductions can differ from CPU f64 accumulation near
187    /// match gates, degenerate geometry and convergence thresholds. No trimming
188    /// or pose solve is performed here. Overflow invalidates ALL result payload.
189    pub fn moments_resident(
190        &self,
191        runtime: &WgpuRuntime,
192        transform: Isometry3<f32>,
193        max_distance: f32,
194    ) -> SpatialResult<GpuIcpMoments> {
195        self.moments_impl(
196            runtime,
197            transform,
198            max_distance,
199            None,
200            trim::GpuIcpTrimPrecision::DoubleSingle,
201        )
202    }
203
204    /// Submits stable GPU selection of the lowest-distance floor(fraction*N)
205    /// gated pairs, breaking distance ties by original source index. Moments
206    /// use retained pairs with DoubleSingle normalized arithmetic; fitness
207    /// uses ALL gated pairs. Binary64 fraction
208    /// multiplication/floor is emulated with integer limbs on the device.
209    /// No match/point payload readback or host wait occurs. A fraction of one
210    /// delegates to the canonical untrimmed kernels; no CPU fallback occurs.
211    pub fn trimmed_moments_resident(
212        &self,
213        runtime: &WgpuRuntime,
214        transform: Isometry3<f32>,
215        max_distance: f32,
216        fraction: f64,
217    ) -> SpatialResult<GpuIcpTrimmedMoments> {
218        self.trimmed_moments_resident_with_precision(
219            runtime,
220            transform,
221            max_distance,
222            fraction,
223            trim::GpuIcpTrimPrecision::DoubleSingle,
224        )
225    }
226
227    /// Explicit choice of retained-moment arithmetic. DoubleSingle carries
228    /// two f32 words through normalized offsets, division and products; f32
229    /// transforms/search stay unchanged. CompensatedF32 retains the earlier
230    /// coordinate/product precision. Fraction one uses canonical ordinary
231    /// moments for either choice. Transfers/ownership/status rules are identical.
232    pub fn trimmed_moments_resident_with_precision(
233        &self,
234        runtime: &WgpuRuntime,
235        transform: Isometry3<f32>,
236        max_distance: f32,
237        fraction: f64,
238        precision: trim::GpuIcpTrimPrecision,
239    ) -> SpatialResult<GpuIcpTrimmedMoments> {
240        if !fraction.is_finite() || fraction <= 0.0 || fraction > 1.0 {
241            return Err(SpatialError::InvalidArgument(
242                "trim_fraction must be finite and in (0, 1]".to_owned(),
243            ));
244        }
245        let trimmed = fraction < 1.0;
246        let inner = self.moments_impl(
247            runtime,
248            transform,
249            max_distance,
250            trimmed.then_some(fraction),
251            precision,
252        )?;
253        Ok(GpuIcpTrimmedMoments { inner, trimmed })
254    }
255
256    fn moments_impl(
257        &self,
258        runtime: &WgpuRuntime,
259        transform: Isometry3<f32>,
260        max_distance: f32,
261        fraction: Option<f64>,
262        precision: trim::GpuIcpTrimPrecision,
263    ) -> SpatialResult<GpuIcpMoments> {
264        let q = transform.rotation();
265        let t = transform.translation();
266        let norm = f64::from(q.x).hypot(f64::from(q.y)).hypot(f64::from(q.z)).hypot(f64::from(q.w));
267        let bound = max_distance * max_distance;
268        if !Arc::ptr_eq(&self.identity, &runtime.profiling_identity())
269            || !norm.is_finite()
270            || (norm - 1.0).abs() > 1e-4
271            || !t.x.is_finite()
272            || !t.y.is_finite()
273            || !t.z.is_finite()
274            || !max_distance.is_finite()
275            || max_distance <= 0.0
276            || !bound.is_finite()
277            || bound == 0.0
278        {
279            return Err(invalid());
280        }
281        let count = self.source_count();
282        let groups = if fraction.is_some() {
283            trim::plan_trim(u64::from(count), &runtime.device().limits())?
284        } else {
285            plan(u64::from(count), &runtime.device().limits())?
286        };
287        let output = GpuIcpMoments {
288            buffer: runtime.device().create_buffer(&wgpu::BufferDescriptor {
289                label: Some("icp-moments"),
290                size: RESULT_BYTES,
291                usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
292                mapped_at_creation: false,
293            }),
294            count,
295            scale: self.scale,
296            bound,
297            identity: Arc::clone(&self.identity),
298        };
299        if count == 0 {
300            return Ok(output);
301        }
302        let r = transform.rotation().to_mat3();
303        let params = Params {
304            rows: [
305                [r.m[0][0], r.m[0][1], r.m[0][2], t.x],
306                [r.m[1][0], r.m[1][1], r.m[1][2], t.y],
307                [r.m[2][0], r.m[2][1], r.m[2][2], t.z],
308            ],
309            source_anchor: self.source_anchor,
310            target_anchor: self.target_anchor,
311            count,
312            targets: self.target.query_count(),
313            groups,
314            unused: 0,
315            bound,
316            max_distance,
317            scale: self.scale,
318            padding: 0.0,
319        };
320        let uniform = runtime.device().create_buffer_init(&wgpu::util::BufferInitDescriptor {
321            label: Some("icp-reduction-params"),
322            contents: bytemuck::bytes_of(&params),
323            usage: wgpu::BufferUsages::UNIFORM,
324        });
325        let mut scratch = ScratchBuffers::new(runtime);
326        let queries = scratch.acquire("icp-transformed", u64::from(count) * 16);
327        let matches = scratch.acquire("icp-matches", u64::from(count) * 8);
328        let partials = scratch.acquire("icp-partials", u64::from(groups) * 144);
329        let selection = fraction.map(|_| scratch.acquire("icp-trim-selection", 32));
330        let cache = if fraction.is_some() {
331            runtime
332                .icp_trim_pipelines
333                .get_or_init(|| trim::TrimPipelines::new(runtime.device()))
334                .reduction(runtime.device(), precision)
335        } else {
336            runtime
337                .icp_reduction_pipelines
338                .get_or_init(|| IcpReductionPipelines::new(runtime.device()))
339        };
340        let mut buffers = vec![
341            &uniform,
342            self.source.buffer().unwrap(),
343            self.target.buffer().unwrap(),
344            &queries,
345            &matches,
346            &partials,
347            &output.buffer,
348        ];
349        if let Some(selection) = &selection {
350            buffers.push(selection);
351        }
352        let entries: Vec<_> = buffers
353            .iter()
354            .enumerate()
355            .map(|(binding, buffer)| wgpu::BindGroupEntry {
356                binding: binding as u32,
357                resource: buffer.as_entire_binding(),
358            })
359            .collect();
360        let group = runtime.device().create_bind_group(&wgpu::BindGroupDescriptor {
361            label: Some("icp-reduction-bindings"),
362            layout: &cache.layout,
363            entries: &entries,
364        });
365        let mut encoder = runtime.device().create_command_encoder(&Default::default());
366        dispatch(&mut encoder, &cache.pipelines[0], &group, count.div_ceil(64), 1);
367        self.tree.encode_nearest(runtime, &mut encoder, &queries, count, bound, &matches)?;
368        if let Some(fraction) = fraction {
369            trim::encode_selection(
370                runtime,
371                &mut encoder,
372                &mut scratch,
373                &params,
374                fraction,
375                &matches,
376                selection.as_ref().unwrap(),
377            );
378        }
379        for (index, x, y) in [(1, groups, 7), (2, 1, 1), (3, groups, 9), (4, 1, 1)] {
380            dispatch(&mut encoder, &cache.pipelines[index], &group, x, y);
381        }
382        scratch.submit_and_recycle(encoder);
383        Ok(output)
384    }
385}
386
387fn dispatch(
388    encoder: &mut wgpu::CommandEncoder,
389    pipeline: &wgpu::ComputePipeline,
390    group: &wgpu::BindGroup,
391    x: u32,
392    y: u32,
393) {
394    let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
395        label: Some("icp-reduction"),
396        timestamp_writes: None,
397    });
398    pass.set_pipeline(pipeline);
399    pass.set_bind_group(0, group, &[]);
400    pass.dispatch_workgroups(x, y, 1);
401}
402
403/// Decoded device ICP moments in physical units, with explicit transfer receipt.
404#[derive(Clone, Debug, PartialEq)]
405pub struct GpuIcpStatistics {
406    /// Pairs contributing to centroids/covariance; ordinary moments use every
407    /// gated match. Zero yields zero centroids/covariance.
408    pub correspondences: u32,
409    /// Arithmetic source centroid after applying the requested transform.
410    pub source_centroid: [f64; 3],
411    /// Corresponding target centroid.
412    pub target_centroid: [f64; 3],
413    /// Unnormalized centered sum of source[i] * target[j], row-major.
414    pub cross_covariance: [[f64; 3]; 3],
415    /// Sum of squared matched residual lengths (not a mean). In the containing
416    /// trimmed statistics, use its all-gated count as the fitness denominator.
417    pub squared_error_sum: f64,
418    /// Payload copied by this explicit download, independent of input upload.
419    pub transfers: TransferStats,
420}
421
422/// Owned fixed-size device ICP moments. No buffer is pooled or input-borrowed.
423pub struct GpuIcpMoments {
424    buffer: wgpu::Buffer,
425    count: u32,
426    scale: f32,
427    bound: f32,
428    identity: Arc<()>,
429}
430impl GpuIcpMoments {
431    /// Physical coordinate scale for the normalized centroid/covariance words.
432    #[must_use]
433    pub const fn normalization_scale(&self) -> f32 {
434        self.scale
435    }
436
437    /// Physical squared-distance scale for normalized residual sum word 15.
438    #[must_use]
439    pub const fn squared_distance_scale(&self) -> f32 {
440        self.bound
441    }
442
443    /// 176-byte storage: u32 status/count/two reserved zeros, two vec4<f32>
444    /// anchors, then 16 vec2<f32> compensated sums. Status bits 1/2/4 denote
445    /// transform overflow, malformed matches, nonfinite moments. Status must be
446    /// zero. Terms 0..5 are normalized source/target centroid offsets; 6..14
447    /// normalized centered cross-covariance; 15 normalized squared-error sum.
448    /// Scale is the input bounding-box diagonal; fitness scale is distance^2.
449    /// Upload geometry canonicalizes derived zero anchors to +0. Earlier
450    /// builds could expose either signed zero from CPU min/max preparation;
451    /// the arithmetic value is unchanged. Transformed anchors follow the
452    /// requested GPU pose arithmetic.
453    /// Invalid or zero-match results have all-zero payload (status retained).
454    #[must_use]
455    pub fn buffer(&self) -> &wgpu::Buffer {
456        &self.buffer
457    }
458
459    /// Explicit readback size; zero for an empty source, otherwise 176 bytes.
460    #[must_use]
461    pub const fn readback_bytes(&self) -> u64 {
462        if self.count == 0 {
463            0
464        } else {
465            RESULT_BYTES
466        }
467    }
468
469    /// Copies the fixed-size moments/status, waits, then validates and decodes
470    /// compensated f32 sums in f64. No point/query/match payload is downloaded.
471    pub fn download(&self, runtime: &WgpuRuntime) -> SpatialResult<GpuIcpStatistics> {
472        self.download_impl(runtime, false).map(|(statistics, _)| statistics)
473    }
474
475    fn download_impl(
476        &self,
477        runtime: &WgpuRuntime,
478        trimmed: bool,
479    ) -> SpatialResult<(GpuIcpStatistics, u32)> {
480        if !Arc::ptr_eq(&self.identity, &runtime.profiling_identity()) {
481            return Err(invalid());
482        }
483        let mut transfers = TransferStats::default();
484        let mut words = vec![0u32; RESULT_BYTES as usize / 4];
485        if self.count > 0 {
486            let staging = runtime.device().create_buffer(&wgpu::BufferDescriptor {
487                label: Some("icp-moments-readback"),
488                size: RESULT_BYTES,
489                usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
490                mapped_at_creation: false,
491            });
492            let mut encoder = runtime.device().create_command_encoder(&Default::default());
493            encoder.copy_buffer_to_buffer(&self.buffer, 0, &staging, 0, RESULT_BYTES);
494            runtime.queue().submit(Some(encoder.finish()));
495            let slice = staging.slice(..);
496            let (sender, receiver) = std::sync::mpsc::channel();
497            slice.map_async(wgpu::MapMode::Read, move |r| {
498                let _ = sender.send(r);
499            });
500            runtime.device().poll(wgpu::Maintain::Wait);
501            receiver
502                .recv()
503                .map_err(|e| SpatialError::InvalidArgument(e.to_string()))?
504                .map_err(|e| SpatialError::InvalidArgument(e.to_string()))?;
505            let mapped = slice.get_mapped_range();
506            words.copy_from_slice(bytemuck::cast_slice(&mapped));
507            drop(mapped);
508            staging.unmap();
509            transfers.record(TransferDirection::DeviceToHost, RESULT_BYTES);
510        }
511        let evaluated = if trimmed { words[2] } else { words[1] };
512        if words[0] != 0
513            || words[1] > evaluated
514            || evaluated > self.count
515            || words[3] != 0
516            || (!trimmed && words[2] != 0)
517            || (evaluated == 0 && words[4..].iter().any(|&v| v != 0))
518            || (words[1] == 0 && words[4..42].iter().any(|&v| v != 0))
519        {
520            return Err(SpatialError::InvalidArgument(format!(
521                "GPU ICP reduction invalid status/count: {:?}",
522                &words[..4]
523            )));
524        }
525        let values: Vec<_> = words[4..].iter().map(|&v| f64::from(f32::from_bits(v))).collect();
526        if values.iter().any(|v| !v.is_finite()) {
527            return Err(invalid());
528        }
529        let sum = |term: usize| values[8 + term * 2] + values[9 + term * 2];
530        let scale = f64::from(self.scale);
531        let source_centroid =
532            std::array::from_fn(|i| if words[1] == 0 { 0.0 } else { values[i] + sum(i) * scale });
533        let target_centroid = std::array::from_fn(|i| {
534            if words[1] == 0 {
535                0.0
536            } else {
537                values[4 + i] + sum(3 + i) * scale
538            }
539        });
540        let cross_covariance =
541            std::array::from_fn(|i| std::array::from_fn(|j| sum(6 + i * 3 + j) * scale * scale));
542        let squared_error_sum = sum(15) * f64::from(self.bound);
543        if squared_error_sum < 0.0 {
544            return Err(invalid());
545        }
546        Ok((
547            GpuIcpStatistics {
548                correspondences: words[1],
549                source_centroid,
550                target_centroid,
551                cross_covariance,
552                squared_error_sum,
553                transfers,
554            },
555            evaluated,
556        ))
557    }
558}
559
560/// Fixed-size selected moments plus the all-gated fitness denominator.
561#[derive(Clone, Debug, PartialEq)]
562pub struct GpuIcpTrimmedStatistics {
563    /// Retained-pair centroids/covariance, ALL-gated residual sum, and readback receipt.
564    pub moments: GpuIcpStatistics,
565    /// Number of all gated matches used for fitness (before trimming).
566    pub evaluated_correspondences: u32,
567}
568
569/// Owned 176-byte trimmed moments/status; no point or match readback is implicit.
570pub struct GpuIcpTrimmedMoments {
571    inner: GpuIcpMoments,
572    trimmed: bool,
573}
574
575impl GpuIcpTrimmedMoments {
576    /// Device storage layout matches ordinary moments, except word 2 is the
577    /// all-gated count. Word 1 is retained count. Terms 0..14 use retained pairs;
578    /// term 15 uses every gated pair. Zero retained count zeros terms 0..14 and
579    /// anchors but preserves all-gated fitness. Any invalid status zeros payload.
580    /// Fraction one retains ordinary moments' two reserved zeros.
581    #[must_use]
582    pub fn buffer(&self) -> &wgpu::Buffer {
583        self.inner.buffer()
584    }
585
586    /// Explicit fixed readback size, zero for empty source and 176 otherwise.
587    #[must_use]
588    pub const fn readback_bytes(&self) -> u64 {
589        self.inner.readback_bytes()
590    }
591
592    /// Physical coordinate scale for normalized centroid/covariance words.
593    #[must_use]
594    pub const fn normalization_scale(&self) -> f32 {
595        self.inner.normalization_scale()
596    }
597
598    /// Physical squared-distance scale for normalized all-gated residual sum.
599    #[must_use]
600    pub const fn squared_distance_scale(&self) -> f32 {
601        self.inner.squared_distance_scale()
602    }
603
604    /// Explicitly copies/waits/validates only the fixed-size moments and counts.
605    pub fn download(&self, runtime: &WgpuRuntime) -> SpatialResult<GpuIcpTrimmedStatistics> {
606        let (moments, evaluated_correspondences) =
607            self.inner.download_impl(runtime, self.trimmed)?;
608        Ok(GpuIcpTrimmedStatistics { moments, evaluated_correspondences })
609    }
610}
611
612pub(crate) struct IcpReductionPipelines {
613    layout: wgpu::BindGroupLayout,
614    pipelines: [wgpu::ComputePipeline; 5],
615}
616impl IcpReductionPipelines {
617    fn new(device: &wgpu::Device) -> Self {
618        Self::with_shader(device, include_str!("../shaders/icp_reduction.wgsl"), false)
619    }
620
621    fn with_shader(device: &wgpu::Device, shader_source: &str, trimmed: bool) -> Self {
622        let entries: Vec<_> = (0..if trimmed { 8 } else { 7 })
623            .map(|binding| wgpu::BindGroupLayoutEntry {
624                binding,
625                visibility: wgpu::ShaderStages::COMPUTE,
626                ty: wgpu::BindingType::Buffer {
627                    ty: if binding == 0 {
628                        wgpu::BufferBindingType::Uniform
629                    } else {
630                        wgpu::BufferBindingType::Storage {
631                            read_only: matches!(binding, 1 | 2 | 4 | 7),
632                        }
633                    },
634                    has_dynamic_offset: false,
635                    min_binding_size: None,
636                },
637                count: None,
638            })
639            .collect();
640        let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
641            label: Some("icp-reduction-layout"),
642            entries: &entries,
643        });
644        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
645            label: Some("icp-reduction-layout"),
646            bind_group_layouts: &[&layout],
647            push_constant_ranges: &[],
648        });
649        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
650            label: Some("icp-reduction-shader"),
651            source: wgpu::ShaderSource::Wgsl(shader_source.into()),
652        });
653        let pipelines = [
654            "transform_source",
655            "centroid_partials",
656            "finish_centroids",
657            "covariance_partials",
658            "finish_covariance",
659        ]
660        .map(|entry| {
661            device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
662                label: Some("icp-reduction-pipeline"),
663                layout: Some(&pipeline_layout),
664                module: &shader,
665                entry_point: Some(entry),
666                compilation_options: Default::default(),
667                cache: None,
668            })
669        });
670        Self { layout, pipelines }
671    }
672}
673
674#[cfg(all(test, not(target_arch = "wasm32")))]
675#[path = "icp_reduction_tests.rs"]
676mod tests;
677
678#[cfg(all(test, not(target_arch = "wasm32")))]
679#[path = "icp_reduction_gather_reference.rs"]
680pub(crate) mod gather_reference;