Skip to main content

spatialrust_gpu/kernels/
point_to_plane_reduction.rs

1use crate::{scratch::ScratchBuffers, GpuIcpInput, 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
9#[path = "point_to_plane_normal_preparation.rs"]
10mod normal_preparation;
11
12const RESULT_BYTES: u64 = 256;
13
14#[repr(C)]
15#[derive(Clone, Copy, Pod, Zeroable)]
16struct Params {
17    rows: [[f32; 4]; 3],
18    anchor: [f32; 4],
19    count: u32,
20    targets: u32,
21    groups: u32,
22    unused: u32,
23    bound: f32,
24    max_distance: f32,
25    scale: f32,
26    normal_scale: f32,
27}
28
29fn invalid() -> SpatialError {
30    SpatialError::InvalidArgument("GPU point-to-plane ICP reduction requires finite raw target normals, matching counts/runtime, supported finite geometry/normal scales, a finite unit pose, positive finite nonzero distance square and supported device limits".to_owned())
31}
32
33fn plan(source: u64, normal_count: u64, limits: &wgpu::Limits) -> SpatialResult<u32> {
34    let groups = source.div_ceil(64).min(256);
35    let bound = limits.max_buffer_size.min(u64::from(limits.max_storage_buffer_binding_size));
36    for (count, stride) in [(source, 16), (normal_count, 16), (groups, 240)] {
37        if count > u64::from(u32::MAX)
38            || count
39                .checked_mul(stride)
40                .map_or(true, |bytes| bytes > bound || bytes > isize::MAX as u64)
41        {
42            return Err(invalid());
43        }
44    }
45    if bound < RESULT_BYTES
46        || limits.max_compute_workgroups_per_dimension < 28
47        || source.div_ceil(64) > u64::from(limits.max_compute_workgroups_per_dimension)
48        || limits.max_compute_workgroup_size_x < 64
49        || limits.max_compute_workgroup_size_y == 0
50        || limits.max_compute_workgroup_size_z == 0
51        || limits.max_compute_invocations_per_workgroup < 64
52        || limits.max_compute_workgroup_storage_size < 1024
53        || limits.max_storage_buffers_per_shader_stage < 8
54        || limits.max_bindings_per_bind_group < 9
55        || limits.max_bind_groups == 0
56        || limits.max_uniform_buffers_per_shader_stage == 0
57        || limits.max_uniform_buffer_binding_size < 96
58    {
59        return Err(invalid());
60    }
61    Ok(groups as u32)
62}
63
64// The transformed queries become rotation Jacobian/residual rows after the
65// nearest-search pass. Only the normal/count half of each pair needs a separate
66// buffer; both halves are fully written before the reductions read them.
67fn acquire_working_buffers(
68    scratch: &mut ScratchBuffers<'_>,
69    count: u32,
70    groups: u32,
71) -> [wgpu::Buffer; 4] {
72    [
73        scratch.acquire("point_to_plane-queries-rotation", u64::from(count) * 16),
74        scratch.acquire("point_to_plane-matches", u64::from(count) * 8),
75        scratch.acquire("point_to_plane-pair-normals", u64::from(count) * 16),
76        scratch.acquire("point_to_plane-partials", u64::from(groups) * 240),
77    ]
78}
79
80/// Reusable explicitly uploaded positions/tree and original-order target normals.
81/// A single common normal scale preserves relative raw-normal weights; normals
82/// are never normalized individually. Source positions remain immutable.
83pub struct GpuPointToPlaneInput {
84    positions: GpuIcpInput,
85    normals: wgpu::Buffer,
86    normal_scale: f32,
87    transfers: TransferStats,
88}
89
90impl GpuPointToPlaneInput {
91    /// Uploads original source positions, target tree and original-order raw
92    /// target normals. Normals must be finite; zero rows retain their zero weight.
93    /// Nonzero components must remain normal f32 after common scaling. H2D
94    /// payload is 16*S + 48*T + 32*M bytes (M = target tree nodes).
95    pub fn upload(
96        runtime: &WgpuRuntime,
97        source: &[[f32; 3]],
98        target: &KdTree,
99        target_normals: &[[f32; 3]],
100    ) -> SpatialResult<Self> {
101        Self::upload_impl(runtime, source, target, target_normals, false)
102    }
103
104    /// Explicitly uses shared GPU gathering for target tree points/queries.
105    /// Host payload is 16*S + 32*T + 32*M bytes, compared with 16*S + 48*T + 32*M
106    /// for `upload`; device output bytes are 32*T. Raw-normal validation/packing and common normal scale are unchanged.
107    /// Source/geometry preparation remains on CPU. Two transient inputs add
108    /// 16*T GPU bytes; host target packing totaling 32*T payload bytes over
109    /// construction is removed. No readback or completion wait is added.
110    /// Placement is explicit; small inputs may be slower and existing device
111    /// requirements apply. See `GpuIcpInput::upload_with_gpu_gather`.
112    pub fn upload_with_gpu_gather(
113        runtime: &WgpuRuntime,
114        source: &[[f32; 3]],
115        target: &KdTree,
116        target_normals: &[[f32; 3]],
117    ) -> SpatialResult<Self> {
118        Self::upload_impl(runtime, source, target, target_normals, true)
119    }
120
121    fn upload_impl(
122        runtime: &WgpuRuntime,
123        source: &[[f32; 3]],
124        target: &KdTree,
125        target_normals: &[[f32; 3]],
126        gpu_gather: bool,
127    ) -> SpatialResult<Self> {
128        if target.layout().positions().0.len() != target_normals.len() {
129            return Err(invalid());
130        }
131        plan(source.len() as u64, target_normals.len() as u64, &runtime.device().limits())?;
132        let (packed, normal_scale) = normal_preparation::prepare(target_normals)?;
133        let positions = if gpu_gather {
134            GpuIcpInput::upload_with_gpu_gather(runtime, source, target)?
135        } else {
136            GpuIcpInput::upload(runtime, source, target)?
137        };
138        let normals = runtime.device().create_buffer_init(&wgpu::util::BufferInitDescriptor {
139            label: Some("point-to-plane-normals"),
140            contents: bytemuck::cast_slice(&packed),
141            usage: wgpu::BufferUsages::STORAGE,
142        });
143        let mut transfers = positions.upload_transfers();
144        transfers.record(TransferDirection::HostToDevice, target_normals.len() as u64 * 16);
145        Ok(Self { positions, normals, normal_scale, transfers })
146    }
147
148    /// All position/tree/normal payload uploaded at construction.
149    #[must_use]
150    pub const fn upload_transfers(&self) -> TransferStats {
151        self.transfers
152    }
153
154    /// Original source count.
155    #[must_use]
156    pub fn source_count(&self) -> u32 {
157        self.positions.source_count()
158    }
159
160    /// Transforms originals, runs unbounded nearest matching then an inclusive
161    /// Euclidean distance gate, and reduces centered/scaled Hessian/gradient and
162    /// raw-normal point-to-plane squared fitness. Five passes share a submission;
163    /// no payload transfer or host wait occurs. Transformed query storage is
164    /// reused for rotation/residual rows after matching. Private scratch is
165    /// 40*S + 240*min(ceil(S/64),256) bytes.
166    /// f32 operations can change matches, weights, solutions and stopping
167    /// relative to the existing CPU f64 path.
168    pub fn equations_resident(
169        &self,
170        runtime: &WgpuRuntime,
171        transform: Isometry3<f32>,
172        max_distance: f32,
173    ) -> SpatialResult<GpuPointToPlaneNormalEquations> {
174        let q = transform.rotation();
175        let t = transform.translation();
176        let norm = f64::from(q.x).hypot(f64::from(q.y)).hypot(f64::from(q.z)).hypot(f64::from(q.w));
177        let bound = max_distance * max_distance;
178        if !Arc::ptr_eq(&self.positions.identity, &runtime.profiling_identity())
179            || !norm.is_finite()
180            || (norm - 1.0).abs() > 1e-4
181            || !t.x.is_finite()
182            || !t.y.is_finite()
183            || !t.z.is_finite()
184            || !max_distance.is_finite()
185            || max_distance <= 0.0
186            || !bound.is_finite()
187            || bound == 0.0
188        {
189            return Err(invalid());
190        }
191        let count = self.source_count();
192        let groups = plan(
193            u64::from(count),
194            u64::from(self.positions.target.query_count()),
195            &runtime.device().limits(),
196        )?;
197        let output = GpuPointToPlaneNormalEquations {
198            buffer: runtime.device().create_buffer(&wgpu::BufferDescriptor {
199                label: Some("point_to_plane-equations"),
200                size: RESULT_BYTES,
201                usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
202                mapped_at_creation: false,
203            }),
204            source_count: count,
205            coordinate_scale: self.positions.scale,
206            max_distance,
207            normal_scale: self.normal_scale,
208            identity: Arc::clone(&self.positions.identity),
209        };
210        if count == 0 {
211            return Ok(output);
212        }
213        let r = q.to_mat3();
214        let params = Params {
215            rows: [
216                [r.m[0][0], r.m[0][1], r.m[0][2], t.x],
217                [r.m[1][0], r.m[1][1], r.m[1][2], t.y],
218                [r.m[2][0], r.m[2][1], r.m[2][2], t.z],
219            ],
220            anchor: self.positions.source_anchor,
221            count,
222            targets: self.positions.target.query_count(),
223            groups,
224            unused: 0,
225            bound,
226            max_distance,
227            scale: self.positions.scale,
228            normal_scale: self.normal_scale,
229        };
230        let uniform = runtime.device().create_buffer_init(&wgpu::util::BufferInitDescriptor {
231            label: Some("point_to_plane-params"),
232            contents: bytemuck::bytes_of(&params),
233            usage: wgpu::BufferUsages::UNIFORM,
234        });
235        let mut scratch = ScratchBuffers::new(runtime);
236        let [queries, matches, pair_normals, partials] =
237            acquire_working_buffers(&mut scratch, count, groups);
238        let cache = runtime
239            .point_to_plane_reduction_pipelines
240            .get_or_init(|| PointToPlaneReductionPipelines::new(runtime.device()));
241        let buffers = [
242            &uniform,
243            self.positions.source.buffer().unwrap(),
244            self.positions.target.buffer().unwrap(),
245            &queries,
246            &matches,
247            &self.normals,
248            &pair_normals,
249            &partials,
250            &output.buffer,
251        ];
252        let entries: Vec<_> = buffers
253            .iter()
254            .enumerate()
255            .map(|(binding, buffer)| wgpu::BindGroupEntry {
256                binding: binding as u32,
257                resource: buffer.as_entire_binding(),
258            })
259            .collect();
260        let group = runtime.device().create_bind_group(&wgpu::BindGroupDescriptor {
261            label: Some("point_to_plane-bindings"),
262            layout: &cache.layout,
263            entries: &entries,
264        });
265        let mut encoder = runtime.device().create_command_encoder(&Default::default());
266        dispatch(&mut encoder, &cache.pipelines[0], &group, count.div_ceil(64), 1);
267        self.positions.tree.encode_nearest(
268            runtime,
269            &mut encoder,
270            &queries,
271            count,
272            f32::INFINITY,
273            &matches,
274        )?;
275        for (index, x, y) in [(1, count.div_ceil(64), 1), (2, groups, 28), (3, 1, 1)] {
276            dispatch(&mut encoder, &cache.pipelines[index], &group, x, y);
277        }
278        scratch.submit_and_recycle(encoder);
279        Ok(output)
280    }
281}
282
283fn dispatch(
284    encoder: &mut wgpu::CommandEncoder,
285    pipeline: &wgpu::ComputePipeline,
286    group: &wgpu::BindGroup,
287    x: u32,
288    y: u32,
289) {
290    let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
291        label: Some("point_to_plane-reduction"),
292        timestamp_writes: None,
293    });
294    pass.set_pipeline(pipeline);
295    pass.set_bind_group(0, group, &[]);
296    pass.dispatch_workgroups(x, y, 1);
297}
298
299/// Downloaded point-to-plane ICP normal equations in the documented normalized parameter basis.
300#[derive(Clone, Debug, PartialEq)]
301pub struct GpuPointToPlaneEquations {
302    /// Gated pairs contributing to supported normal equations.
303    pub correspondences: u32,
304    /// Gated pairs contributing to raw-normal squared plane residuals.
305    pub fitness_correspondences: u32,
306    /// Symmetric normalized 6x6 Hessian (not world-coordinate coefficients).
307    pub hessian: [[f64; 6]; 6],
308    /// Normalized gradient; solve H*u=-g before converting with world_step.
309    pub gradient: [f64; 6],
310    /// Actual device-transformed bounding-box anchor in world coordinates.
311    pub anchor: [f64; 3],
312    /// Rotation scale converting solved normalized coordinates to radians.
313    pub rotation_step_scale: f64,
314    /// Translation scale converting solved local coordinates to physical units.
315    pub translation_step_scale: f64,
316    /// Common raw-normal component scale divided out of H/g.
317    pub normal_scale: f64,
318    /// Physical raw-normal point-to-plane squared-error sum (not mean).
319    pub squared_error_sum: f64,
320    /// Payload copied during this explicit download.
321    pub transfers: TransferStats,
322}
323impl GpuPointToPlaneEquations {
324    /// Converts the solved normalized step to the world [-skew(p)|I] basis:
325    /// omega=u_rotation*distance/coordinate_scale, local_t=u_translation*distance,
326    /// world_t=local_t-omega cross anchor. This is a LINEARIZED basis conversion;
327    /// the caller's existing finite rotation/update policy remains separate.
328    pub fn world_step(&self, solution: [f64; 6]) -> SpatialResult<[f64; 6]> {
329        let omega: [f64; 3] = std::array::from_fn(|i| solution[i] * self.rotation_step_scale);
330        let [x, y, z] = self.anchor;
331        let cross =
332            [omega[1] * z - omega[2] * y, omega[2] * x - omega[0] * z, omega[0] * y - omega[1] * x];
333        let step = std::array::from_fn(|i| {
334            if i < 3 {
335                omega[i]
336            } else {
337                solution[i] * self.translation_step_scale - cross[i - 3]
338            }
339        });
340        if step.iter().any(|v| !v.is_finite()) {
341            return Err(invalid());
342        }
343        Ok(step)
344    }
345}
346
347/// Owned resident fixed-size normal equations/status, independent of input/pools.
348pub struct GpuPointToPlaneNormalEquations {
349    buffer: wgpu::Buffer,
350    source_count: u32,
351    coordinate_scale: f32,
352    max_distance: f32,
353    normal_scale: f32,
354    identity: Arc<()>,
355}
356impl GpuPointToPlaneNormalEquations {
357    /// 256-byte storage: u32 status/H-count/fitness-count/reserved-zero, one
358    /// vec4<f32> actual anchor, then 28 compensated vec2<f32> sums. Terms 0..20
359    /// are Hessian upper triangle by row, 21..26 gradient and 27 raw-normal plane error
360    /// normalized by distance squared and normal scale squared. Status bits 1/2/4/8 indicate transform,
361    /// match, nonfinite arithmetic and reserved future conditions.
362    /// Any nonzero status invalidates ALL payload, which is zeroed on device.
363    /// GPU consumers must check status and preserve immutable application data.
364    #[must_use]
365    pub fn buffer(&self) -> &wgpu::Buffer {
366        &self.buffer
367    }
368
369    /// Metadata required to decode the resident normalized parameter basis.
370    #[must_use]
371    pub fn parameter_scales(&self) -> (f64, f64, f64) {
372        (
373            f64::from(self.max_distance) / f64::from(self.coordinate_scale),
374            f64::from(self.max_distance),
375            f64::from(self.normal_scale),
376        )
377    }
378
379    /// Explicit readback size, zero for empty source and otherwise 256 bytes.
380    #[must_use]
381    pub const fn readback_bytes(&self) -> u64 {
382        if self.source_count == 0 {
383            0
384        } else {
385            RESULT_BYTES
386        }
387    }
388
389    /// Copies and waits for fixed-size equations/status, validates them before
390    /// decoding hi/lo f32 sums in f64. No query/pair/neighbor readback occurs.
391    pub fn download(&self, runtime: &WgpuRuntime) -> SpatialResult<GpuPointToPlaneEquations> {
392        if !Arc::ptr_eq(&self.identity, &runtime.profiling_identity()) {
393            return Err(invalid());
394        }
395        let mut words = vec![0u32; 64];
396        let mut transfers = TransferStats::default();
397        if self.source_count > 0 {
398            let staging = runtime.device().create_buffer(&wgpu::BufferDescriptor {
399                label: Some("point_to_plane-readback"),
400                size: RESULT_BYTES,
401                usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
402                mapped_at_creation: false,
403            });
404            let mut encoder = runtime.device().create_command_encoder(&Default::default());
405            encoder.copy_buffer_to_buffer(&self.buffer, 0, &staging, 0, RESULT_BYTES);
406            runtime.queue().submit(Some(encoder.finish()));
407            let slice = staging.slice(..);
408            let (tx, rx) = std::sync::mpsc::channel();
409            slice.map_async(wgpu::MapMode::Read, move |r| {
410                let _ = tx.send(r);
411            });
412            runtime.device().poll(wgpu::Maintain::Wait);
413            rx.recv()
414                .map_err(|e| SpatialError::InvalidArgument(e.to_string()))?
415                .map_err(|e| SpatialError::InvalidArgument(e.to_string()))?;
416            let mapped = slice.get_mapped_range();
417            words.copy_from_slice(bytemuck::cast_slice(&mapped));
418            drop(mapped);
419            staging.unmap();
420            transfers.record(TransferDirection::DeviceToHost, RESULT_BYTES);
421        }
422        if words[0] != 0
423            || words[1] != words[2]
424            || words[2] > self.source_count
425            || words[3] != 0
426            || (words[2] == 0 && words[4..].iter().any(|&v| v != 0))
427        {
428            return Err(SpatialError::InvalidArgument(format!(
429                "GPU point-to-plane ICP reduction invalid status/counts: {:?}",
430                &words[..4]
431            )));
432        }
433        let values: Vec<_> = words[4..].iter().map(|&v| f64::from(f32::from_bits(v))).collect();
434        if values.iter().any(|v| !v.is_finite()) || values[3] != 0.0 {
435            return Err(invalid());
436        }
437        let sum = |i: usize| values[4 + i * 2] + values[5 + i * 2];
438        // Row prefixes of the upper triangle are 0, 6, 11, 15, 18, 20.
439        let hessian = std::array::from_fn(|a: usize| {
440            std::array::from_fn(|b: usize| {
441                let (lo, hi) = (a.min(b), a.max(b));
442                sum(lo * (13 - lo) / 2 + hi - lo)
443            })
444        });
445        let gradient = std::array::from_fn(|i| sum(21 + i));
446        let squared_error_sum =
447            sum(27) * f64::from(self.max_distance).powi(2) * f64::from(self.normal_scale).powi(2);
448        if squared_error_sum < 0.0 || (0..6).any(|i| hessian[i][i] < 0.0) {
449            return Err(invalid());
450        }
451        let (rotation_step_scale, translation_step_scale, normal_scale) = self.parameter_scales();
452        Ok(GpuPointToPlaneEquations {
453            correspondences: words[1],
454            fitness_correspondences: words[2],
455            hessian,
456            gradient,
457            anchor: [values[0], values[1], values[2]],
458            rotation_step_scale,
459            translation_step_scale,
460            normal_scale,
461            squared_error_sum,
462            transfers,
463        })
464    }
465}
466
467pub(crate) struct PointToPlaneReductionPipelines {
468    layout: wgpu::BindGroupLayout,
469    pipelines: [wgpu::ComputePipeline; 4],
470}
471impl PointToPlaneReductionPipelines {
472    fn new(device: &wgpu::Device) -> Self {
473        let entries: Vec<_> = (0..9)
474            .map(|binding| wgpu::BindGroupLayoutEntry {
475                binding,
476                visibility: wgpu::ShaderStages::COMPUTE,
477                ty: wgpu::BindingType::Buffer {
478                    ty: if binding == 0 {
479                        wgpu::BufferBindingType::Uniform
480                    } else {
481                        wgpu::BufferBindingType::Storage {
482                            read_only: matches!(binding, 1 | 2 | 4 | 5),
483                        }
484                    },
485                    has_dynamic_offset: false,
486                    min_binding_size: None,
487                },
488                count: None,
489            })
490            .collect();
491        let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
492            label: Some("point_to_plane-layout"),
493            entries: &entries,
494        });
495        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
496            label: Some("point_to_plane-layout"),
497            bind_group_layouts: &[&layout],
498            push_constant_ranges: &[],
499        });
500        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
501            label: Some("point_to_plane-reduction"),
502            source: wgpu::ShaderSource::Wgsl(
503                include_str!("../shaders/point_to_plane_reduction.wgsl").into(),
504            ),
505        });
506        let pipelines =
507            ["transform_source", "prepare_pairs", "reduce_partials", "finalize"].map(|entry| {
508                device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
509                    label: Some("point_to_plane-pipeline"),
510                    layout: Some(&pipeline_layout),
511                    module: &shader,
512                    entry_point: Some(entry),
513                    compilation_options: Default::default(),
514                    cache: None,
515                })
516            });
517        Self { layout, pipelines }
518    }
519}
520
521#[cfg(all(test, not(target_arch = "wasm32")))]
522#[path = "point_to_plane_reduction_tests.rs"]
523mod tests;
524
525#[cfg(all(test, not(target_arch = "wasm32")))]
526#[path = "point_to_plane_reduction_gather_reference.rs"]
527pub(crate) mod gather_reference;
528
529#[cfg(all(test, not(target_arch = "wasm32")))]
530#[path = "point_to_plane_preparation_reference.rs"]
531pub(crate) mod preparation_reference;
532
533#[cfg(all(test, not(target_arch = "wasm32")))]
534#[path = "point_to_plane_normal_upload_tests.rs"]
535mod normal_upload_tests;