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
9const RESULT_BYTES: u64 = 256;
10
11#[path = "gicp_upload_preparation.rs"]
12mod upload_preparation;
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 weight_scale: f32,
27}
28
29fn invalid() -> SpatialError {
30 SpatialError::InvalidArgument("GPU GICP reduction requires finite SPD covariance rows, matching counts/runtime, supported finite geometry/weight scales, a finite unit pose, positive finite nonzero distance square and supported device limits".to_owned())
31}
32
33fn plan(source: u64, covariance_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, 48), (covariance_count, 32), (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
64fn acquire_working_buffers(
67 scratch: &mut ScratchBuffers<'_>,
68 count: u32,
69 groups: u32,
70) -> [wgpu::Buffer; 4] {
71 [
72 scratch.acquire("gicp-queries-centered", u64::from(count) * 16),
73 scratch.acquire("gicp-matches", u64::from(count) * 8),
74 scratch.acquire("gicp-weights-residual", u64::from(count) * 48),
75 scratch.acquire("gicp-partials", u64::from(groups) * 240),
76 ]
77}
78
79fn inverse_trace(c: &[f32; 6]) -> SpatialResult<f64> {
82 if c.iter().any(|v| !v.is_finite()) || c[0] <= 0.0 {
83 return Err(invalid());
84 }
85 let [xx, yy, zz, xy, xz, yz] = c.map(f64::from);
86 let a = xx.sqrt();
87 let b = xy / a;
88 let d = xz / a;
89 let pivot1 = yy - b * b;
90 if pivot1 <= 0.0 {
91 return Err(invalid());
92 }
93 let e = pivot1.sqrt();
94 let f = (yz - d * b) / e;
95 let pivot2 = zz - d * d - f * f;
96 if pivot2 <= 0.0 {
97 return Err(invalid());
98 }
99 let g = pivot2.sqrt();
100 let trace = (1.0 / a).powi(2)
101 + (-b / (a * e)).powi(2)
102 + (1.0 / e).powi(2)
103 + ((b * f / e - d) / (a * g)).powi(2)
104 + (-f / (e * g)).powi(2)
105 + (1.0 / g).powi(2);
106 if !trace.is_finite() || trace <= 0.0 {
107 return Err(invalid());
108 }
109 Ok(trace)
110}
111
112pub struct GpuGicpInput {
116 positions: GpuIcpInput,
117 covariances: wgpu::Buffer,
118 weight_scale: f32,
119 covariance_offset: u32,
120 transfers: TransferStats,
121}
122
123impl GpuGicpInput {
124 pub fn upload(
132 runtime: &WgpuRuntime,
133 source: &[[f32; 3]],
134 source_covariances: &[[f32; 6]],
135 target: &KdTree,
136 target_covariances: &[[f32; 6]],
137 ) -> SpatialResult<Self> {
138 Self::upload_impl(runtime, source, source_covariances, target, target_covariances, false)
139 }
140
141 pub fn upload_with_gpu_gather(
150 runtime: &WgpuRuntime,
151 source: &[[f32; 3]],
152 source_covariances: &[[f32; 6]],
153 target: &KdTree,
154 target_covariances: &[[f32; 6]],
155 ) -> SpatialResult<Self> {
156 Self::upload_impl(runtime, source, source_covariances, target, target_covariances, true)
157 }
158
159 fn upload_impl(
160 runtime: &WgpuRuntime,
161 source: &[[f32; 3]],
162 source_covariances: &[[f32; 6]],
163 target: &KdTree,
164 target_covariances: &[[f32; 6]],
165 gpu_gather: bool,
166 ) -> SpatialResult<Self> {
167 if source.len() != source_covariances.len()
168 || target.layout().positions().0.len() != target_covariances.len()
169 {
170 return Err(invalid());
171 }
172 let total = (source.len() as u64)
173 .checked_add(target_covariances.len() as u64)
174 .ok_or_else(invalid)?;
175 plan(source.len() as u64, total, &runtime.device().limits())?;
176 let (packed, weight_scale) =
177 upload_preparation::prepare(source_covariances, target_covariances)?;
178 let positions = if gpu_gather {
179 GpuIcpInput::upload_with_gpu_gather(runtime, source, target)?
180 } else {
181 GpuIcpInput::upload(runtime, source, target)?
182 };
183 let covariances = runtime.device().create_buffer_init(&wgpu::util::BufferInitDescriptor {
184 label: Some("gicp-covariances"),
185 contents: bytemuck::cast_slice(&packed),
186 usage: wgpu::BufferUsages::STORAGE,
187 });
188 let mut transfers = positions.upload_transfers();
189 transfers.record(TransferDirection::HostToDevice, total * 32);
190 Ok(Self { positions, covariances, weight_scale, covariance_offset: 0, transfers })
191 }
192
193 #[must_use]
195 pub const fn upload_transfers(&self) -> TransferStats {
196 self.transfers
197 }
198
199 #[must_use]
201 pub fn source_count(&self) -> u32 {
202 self.positions.source_count()
203 }
204
205 pub fn equations_resident(
215 &self,
216 runtime: &WgpuRuntime,
217 transform: Isometry3<f32>,
218 max_distance: f32,
219 ) -> SpatialResult<GpuGicpNormalEquations> {
220 let q = transform.rotation();
221 let t = transform.translation();
222 let norm = f64::from(q.x).hypot(f64::from(q.y)).hypot(f64::from(q.z)).hypot(f64::from(q.w));
223 let bound = max_distance * max_distance;
224 if !Arc::ptr_eq(&self.positions.identity, &runtime.profiling_identity())
225 || !norm.is_finite()
226 || (norm - 1.0).abs() > 1e-4
227 || !t.x.is_finite()
228 || !t.y.is_finite()
229 || !t.z.is_finite()
230 || !max_distance.is_finite()
231 || max_distance <= 0.0
232 || !bound.is_finite()
233 || bound == 0.0
234 {
235 return Err(invalid());
236 }
237 let count = self.source_count();
238 let groups = plan(
239 u64::from(count),
240 u64::from(count) + u64::from(self.positions.target.query_count()),
241 &runtime.device().limits(),
242 )?;
243 let output = GpuGicpNormalEquations {
244 buffer: runtime.device().create_buffer(&wgpu::BufferDescriptor {
245 label: Some("gicp-equations"),
246 size: RESULT_BYTES,
247 usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
248 mapped_at_creation: false,
249 }),
250 source_count: count,
251 coordinate_scale: self.positions.scale,
252 max_distance,
253 weight_scale: self.weight_scale,
254 identity: Arc::clone(&self.positions.identity),
255 };
256 if count == 0 {
257 return Ok(output);
258 }
259 let r = q.to_mat3();
260 let params = Params {
261 rows: [
262 [r.m[0][0], r.m[0][1], r.m[0][2], t.x],
263 [r.m[1][0], r.m[1][1], r.m[1][2], t.y],
264 [r.m[2][0], r.m[2][1], r.m[2][2], t.z],
265 ],
266 anchor: self.positions.source_anchor,
267 count,
268 targets: self.positions.target.query_count(),
269 groups,
270 unused: self.covariance_offset,
271 bound,
272 max_distance,
273 scale: self.positions.scale,
274 weight_scale: self.weight_scale,
275 };
276 let uniform = runtime.device().create_buffer_init(&wgpu::util::BufferInitDescriptor {
277 label: Some("gicp-params"),
278 contents: bytemuck::bytes_of(¶ms),
279 usage: wgpu::BufferUsages::UNIFORM,
280 });
281 let mut scratch = ScratchBuffers::new(runtime);
282 let [queries, matches, pairs, partials] =
283 acquire_working_buffers(&mut scratch, count, groups);
284 let cache = runtime
285 .gicp_reduction_pipelines
286 .get_or_init(|| GicpReductionPipelines::new(runtime.device()));
287 let buffers = [
288 &uniform,
289 self.positions.source.buffer().unwrap(),
290 self.positions.target.buffer().unwrap(),
291 &queries,
292 &matches,
293 &self.covariances,
294 &pairs,
295 &partials,
296 &output.buffer,
297 ];
298 let entries: Vec<_> = buffers
299 .iter()
300 .enumerate()
301 .map(|(binding, buffer)| wgpu::BindGroupEntry {
302 binding: binding as u32,
303 resource: buffer.as_entire_binding(),
304 })
305 .collect();
306 let group = runtime.device().create_bind_group(&wgpu::BindGroupDescriptor {
307 label: Some("gicp-bindings"),
308 layout: &cache.layout,
309 entries: &entries,
310 });
311 let mut encoder = runtime.device().create_command_encoder(&Default::default());
312 dispatch(&mut encoder, &cache.pipelines[0], &group, count.div_ceil(64), 1);
313 self.positions.tree.encode_nearest(
314 runtime,
315 &mut encoder,
316 &queries,
317 count,
318 f32::INFINITY,
319 &matches,
320 )?;
321 for (index, x, y) in [(1, count.div_ceil(64), 1), (2, groups, 28), (3, 1, 1)] {
322 dispatch(&mut encoder, &cache.pipelines[index], &group, x, y);
323 }
324 scratch.submit_and_recycle(encoder);
325 Ok(output)
326 }
327}
328
329fn dispatch(
330 encoder: &mut wgpu::CommandEncoder,
331 pipeline: &wgpu::ComputePipeline,
332 group: &wgpu::BindGroup,
333 x: u32,
334 y: u32,
335) {
336 let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
337 label: Some("gicp-reduction"),
338 timestamp_writes: None,
339 });
340 pass.set_pipeline(pipeline);
341 pass.set_bind_group(0, group, &[]);
342 pass.dispatch_workgroups(x, y, 1);
343}
344
345#[derive(Clone, Debug, PartialEq)]
347pub struct GpuGicpEquations {
348 pub correspondences: u32,
350 pub fitness_correspondences: u32,
352 pub hessian: [[f64; 6]; 6],
354 pub gradient: [f64; 6],
356 pub anchor: [f64; 3],
358 pub rotation_step_scale: f64,
360 pub translation_step_scale: f64,
362 pub weight_scale: f64,
364 pub squared_error_sum: f64,
366 pub transfers: TransferStats,
368}
369impl GpuGicpEquations {
370 pub fn world_step(&self, solution: [f64; 6]) -> SpatialResult<[f64; 6]> {
375 let omega: [f64; 3] = std::array::from_fn(|i| solution[i] * self.rotation_step_scale);
376 let [x, y, z] = self.anchor;
377 let cross =
378 [omega[1] * z - omega[2] * y, omega[2] * x - omega[0] * z, omega[0] * y - omega[1] * x];
379 let step = std::array::from_fn(|i| {
380 if i < 3 {
381 omega[i]
382 } else {
383 solution[i] * self.translation_step_scale - cross[i - 3]
384 }
385 });
386 if step.iter().any(|v| !v.is_finite()) {
387 return Err(invalid());
388 }
389 Ok(step)
390 }
391}
392
393pub struct GpuGicpNormalEquations {
395 buffer: wgpu::Buffer,
396 source_count: u32,
397 coordinate_scale: f32,
398 max_distance: f32,
399 weight_scale: f32,
400 identity: Arc<()>,
401}
402impl GpuGicpNormalEquations {
403 #[must_use]
413 pub fn buffer(&self) -> &wgpu::Buffer {
414 &self.buffer
415 }
416
417 #[must_use]
419 pub fn parameter_scales(&self) -> (f64, f64, f64) {
420 (
421 f64::from(self.max_distance) / f64::from(self.coordinate_scale),
422 f64::from(self.max_distance),
423 f64::from(self.weight_scale),
424 )
425 }
426
427 #[must_use]
429 pub const fn readback_bytes(&self) -> u64 {
430 if self.source_count == 0 {
431 0
432 } else {
433 RESULT_BYTES
434 }
435 }
436
437 pub fn download(&self, runtime: &WgpuRuntime) -> SpatialResult<GpuGicpEquations> {
440 if !Arc::ptr_eq(&self.identity, &runtime.profiling_identity()) {
441 return Err(invalid());
442 }
443 let mut words = vec![0u32; 64];
444 let mut transfers = TransferStats::default();
445 if self.source_count > 0 {
446 let staging = runtime.device().create_buffer(&wgpu::BufferDescriptor {
447 label: Some("gicp-readback"),
448 size: RESULT_BYTES,
449 usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
450 mapped_at_creation: false,
451 });
452 let mut encoder = runtime.device().create_command_encoder(&Default::default());
453 encoder.copy_buffer_to_buffer(&self.buffer, 0, &staging, 0, RESULT_BYTES);
454 runtime.queue().submit(Some(encoder.finish()));
455 let slice = staging.slice(..);
456 let (tx, rx) = std::sync::mpsc::channel();
457 slice.map_async(wgpu::MapMode::Read, move |r| {
458 let _ = tx.send(r);
459 });
460 runtime.device().poll(wgpu::Maintain::Wait);
461 rx.recv()
462 .map_err(|e| SpatialError::InvalidArgument(e.to_string()))?
463 .map_err(|e| SpatialError::InvalidArgument(e.to_string()))?;
464 let mapped = slice.get_mapped_range();
465 words.copy_from_slice(bytemuck::cast_slice(&mapped));
466 drop(mapped);
467 staging.unmap();
468 transfers.record(TransferDirection::DeviceToHost, RESULT_BYTES);
469 }
470 if words[0] != 0
471 || words[1] != words[2]
472 || words[2] > self.source_count
473 || words[3] != 0
474 || (words[2] == 0 && words[4..].iter().any(|&v| v != 0))
475 {
476 return Err(SpatialError::InvalidArgument(format!(
477 "GPU GICP reduction invalid status/counts: {:?}",
478 &words[..4]
479 )));
480 }
481 let values: Vec<_> = words[4..].iter().map(|&v| f64::from(f32::from_bits(v))).collect();
482 if values.iter().any(|v| !v.is_finite()) || values[3] != 0.0 {
483 return Err(invalid());
484 }
485 let sum = |i: usize| values[4 + i * 2] + values[5 + i * 2];
486 let hessian = std::array::from_fn(|a: usize| {
488 std::array::from_fn(|b: usize| {
489 let (lo, hi) = (a.min(b), a.max(b));
490 sum(lo * (13 - lo) / 2 + hi - lo)
491 })
492 });
493 let gradient = std::array::from_fn(|i| sum(21 + i));
494 let squared_error_sum = sum(27) * f64::from(self.max_distance * self.max_distance);
495 if squared_error_sum < 0.0 || (0..6).any(|i| hessian[i][i] < 0.0) {
496 return Err(invalid());
497 }
498 let (rotation_step_scale, translation_step_scale, weight_scale) = self.parameter_scales();
499 Ok(GpuGicpEquations {
500 correspondences: words[1],
501 fitness_correspondences: words[2],
502 hessian,
503 gradient,
504 anchor: [values[0], values[1], values[2]],
505 rotation_step_scale,
506 translation_step_scale,
507 weight_scale,
508 squared_error_sum,
509 transfers,
510 })
511 }
512}
513
514pub(crate) struct GicpReductionPipelines {
515 layout: wgpu::BindGroupLayout,
516 pipelines: [wgpu::ComputePipeline; 4],
517}
518impl GicpReductionPipelines {
519 fn new(device: &wgpu::Device) -> Self {
520 let entries: Vec<_> = (0..9)
521 .map(|binding| wgpu::BindGroupLayoutEntry {
522 binding,
523 visibility: wgpu::ShaderStages::COMPUTE,
524 ty: wgpu::BindingType::Buffer {
525 ty: if binding == 0 {
526 wgpu::BufferBindingType::Uniform
527 } else {
528 wgpu::BufferBindingType::Storage {
529 read_only: matches!(binding, 1 | 2 | 4 | 5),
530 }
531 },
532 has_dynamic_offset: false,
533 min_binding_size: None,
534 },
535 count: None,
536 })
537 .collect();
538 let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
539 label: Some("gicp-layout"),
540 entries: &entries,
541 });
542 let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
543 label: Some("gicp-layout"),
544 bind_group_layouts: &[&layout],
545 push_constant_ranges: &[],
546 });
547 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
548 label: Some("gicp-reduction"),
549 source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/gicp_reduction.wgsl").into()),
550 });
551 let pipelines =
552 ["transform_source", "prepare_pairs", "reduce_partials", "finalize"].map(|entry| {
553 device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
554 label: Some("gicp-pipeline"),
555 layout: Some(&pipeline_layout),
556 module: &shader,
557 entry_point: Some(entry),
558 compilation_options: Default::default(),
559 cache: None,
560 })
561 });
562 Self { layout, pipelines }
563 }
564}
565
566#[path = "gicp_covariances.rs"]
567pub(crate) mod resident_covariances;
568
569#[path = "gicp_grid_covariances.rs"]
570pub(crate) mod resident_grid_covariances;
571
572#[cfg(all(test, not(target_arch = "wasm32")))]
573#[path = "gicp_reduction_tests.rs"]
574mod tests;
575
576#[cfg(all(test, not(target_arch = "wasm32")))]
577#[path = "gicp_reduction_gather_reference.rs"]
578pub(crate) mod gather_reference;