1use std::sync::Arc;
2
3use bytemuck::{Pod, Zeroable};
4use spatialrust_core::{SpatialError, SpatialResult, TransferDirection, TransferStats};
5use spatialrust_search::KdTree;
6use wgpu::util::DeviceExt;
7
8use crate::{GpuKdTree, GpuNeighborhoods, GpuQueryBatch, WgpuRuntime};
9
10#[repr(C)]
11#[derive(Clone, Copy, Pod, Zeroable)]
12struct Params {
13 count: u32,
14 salient_capacity: u32,
15 non_max_capacity: u32,
16 min_neighbors: u32,
17 gamma_21: f32,
18 gamma_32: f32,
19 radius: f32,
20 non_max_radius_squared: f32,
21}
22
23fn invalid() -> SpatialError {
24 SpatialError::InvalidArgument("GPU ISS requires matching input/runtime ownership, finite XYZ/extents, positive finite nonzero radius squares, finite gamma values in [0,1] and supported buffers/dispatch".to_owned())
25}
26
27fn valid_radius(radius: f32) -> bool {
28 radius.is_finite() && radius > 0.0 && (radius * radius).is_finite() && radius * radius > 0.0
29}
30
31fn plan(points: u64, limits: &wgpu::Limits) -> SpatialResult<u32> {
32 let bytes = points.checked_mul(16).ok_or_else(invalid)?;
33 let bound = limits.max_buffer_size.min(u64::from(limits.max_storage_buffer_binding_size));
34 if points > u64::from(u32::MAX)
35 || bytes > bound
36 || bytes > isize::MAX as u64
37 || bound < 32
38 || limits.max_compute_workgroup_size_x < 64
39 || limits.max_compute_workgroup_size_y == 0
40 || limits.max_compute_workgroup_size_z == 0
41 || limits.max_compute_invocations_per_workgroup < 64
42 || points.div_ceil(64) > u64::from(limits.max_compute_workgroups_per_dimension)
43 || limits.max_storage_buffers_per_shader_stage < 6
44 || limits.max_bindings_per_bind_group < 7
45 || limits.max_bind_groups == 0
46 || limits.max_uniform_buffers_per_shader_stage == 0
47 || limits.max_uniform_buffer_binding_size < 32
48 || points
49 .checked_mul(16)
50 .and_then(|n| n.checked_add(32))
51 .map_or(true, |n| n > limits.max_buffer_size || n > isize::MAX as u64)
52 {
53 return Err(invalid());
54 }
55 Ok(points as u32)
56}
57
58pub struct GpuIssInput {
61 tree: GpuKdTree,
62 queries: GpuQueryBatch,
63 count: u32,
64 identity: Arc<()>,
65 input_identity: Arc<()>,
66 transfers: TransferStats,
67}
68
69impl GpuIssInput {
70 pub fn upload(runtime: &WgpuRuntime, tree: &KdTree) -> SpatialResult<Self> {
74 Self::upload_impl(runtime, tree, false)
75 }
76
77 pub fn upload_with_gpu_gather(runtime: &WgpuRuntime, tree: &KdTree) -> SpatialResult<Self> {
85 Self::upload_impl(runtime, tree, true)
86 }
87
88 fn upload_impl(runtime: &WgpuRuntime, tree: &KdTree, gpu_gather: bool) -> SpatialResult<Self> {
89 let layout = tree.layout();
90 let (x, y, z) = layout.positions();
91 let count = plan(x.len() as u64, &runtime.device().limits())?;
92 if !super::feature_validation::valid([x, y, z], None) {
93 return Err(invalid());
94 }
95 let (tree, queries) = if gpu_gather {
96 GpuKdTree::upload_and_queries_with_gpu_gather(runtime, tree)?
97 } else {
98 (GpuKdTree::upload(runtime, tree)?, GpuQueryBatch::upload_soa(runtime, [x, y, z])?)
99 };
100 let mut transfers = tree.upload_transfers();
101 transfers.record(
102 TransferDirection::HostToDevice,
103 queries.upload_transfers().host_to_device_bytes(),
104 );
105 transfers.record(
106 TransferDirection::DeviceToDevice,
107 queries.upload_transfers().device_to_device_bytes(),
108 );
109 Ok(Self {
110 tree,
111 queries,
112 count,
113 identity: runtime.profiling_identity(),
114 input_identity: Arc::new(()),
115 transfers,
116 })
117 }
118
119 #[must_use]
121 pub const fn point_count(&self) -> u32 {
122 self.count
123 }
124
125 #[must_use]
128 pub const fn upload_transfers(&self) -> TransferStats {
129 self.transfers
130 }
131
132 pub fn neighborhoods_resident(
135 &self,
136 runtime: &WgpuRuntime,
137 salient_radius: f32,
138 non_max_radius: f32,
139 salient_capacity: u32,
140 non_max_capacity: u32,
141 ) -> SpatialResult<GpuIssNeighborhoods> {
142 if !Arc::ptr_eq(&self.identity, &runtime.profiling_identity())
143 || !valid_radius(salient_radius)
144 || !valid_radius(non_max_radius)
145 {
146 return Err(invalid());
147 }
148 let salient = self.tree.radius_neighbors_resident(
149 runtime,
150 &self.queries,
151 salient_radius,
152 salient_capacity,
153 )?;
154 let non_max = self.tree.radius_neighbors_resident(
155 runtime,
156 &self.queries,
157 non_max_radius,
158 non_max_capacity,
159 )?;
160 Ok(GpuIssNeighborhoods {
161 salient,
162 non_max,
163 salient_radius,
164 non_max_radius,
165 input_identity: Arc::clone(&self.input_identity),
166 })
167 }
168
169 pub fn keypoints_resident(
179 &self,
180 runtime: &WgpuRuntime,
181 neighbors: &GpuIssNeighborhoods,
182 gamma_21: f32,
183 gamma_32: f32,
184 min_neighbors: u32,
185 ) -> SpatialResult<GpuIssKeypoints> {
186 if !Arc::ptr_eq(&self.identity, &runtime.profiling_identity())
187 || !Arc::ptr_eq(&self.input_identity, &neighbors.input_identity)
188 || [gamma_21, gamma_32].iter().any(|g| !g.is_finite() || !(0.0..=1.0).contains(g))
189 {
190 return Err(invalid());
191 }
192 plan(u64::from(self.count), &runtime.device().limits())?;
193 let create = |label, size| {
194 runtime.device().create_buffer(&wgpu::BufferDescriptor {
195 label: Some(label),
196 size,
197 usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
198 mapped_at_creation: false,
199 })
200 };
201 let result = GpuIssKeypoints {
202 scores: create("iss-eigenvalues", (u64::from(self.count) * 16).max(16)),
203 flags: create("iss-selection", (u64::from(self.count) * 4).max(4)),
204 status: create("iss-status", 32),
205 count: self.count,
206 identity: Arc::clone(&self.identity),
207 };
208 if self.count == 0 {
209 return Ok(result);
210 }
211 let cache = runtime.iss_pipelines.get_or_init(|| IssPipelines::new(runtime.device()));
212 let params = Params {
213 count: self.count,
214 salient_capacity: neighbors.salient.capacity(),
215 non_max_capacity: neighbors.non_max.capacity(),
216 min_neighbors,
217 gamma_21,
218 gamma_32,
219 radius: neighbors.salient_radius,
220 non_max_radius_squared: neighbors.non_max_radius * neighbors.non_max_radius,
221 };
222 let uniform = runtime.device().create_buffer_init(&wgpu::util::BufferInitDescriptor {
223 label: Some("iss-params"),
224 contents: bytemuck::bytes_of(¶ms),
225 usage: wgpu::BufferUsages::UNIFORM,
226 });
227 let buffers = [
228 &uniform,
229 self.queries.buffer().unwrap(),
230 neighbors.salient.buffer(),
231 neighbors.non_max.buffer(),
232 &result.scores,
233 &result.flags,
234 &result.status,
235 ];
236 let entries: Vec<_> = buffers
237 .iter()
238 .enumerate()
239 .map(|(binding, buffer)| wgpu::BindGroupEntry {
240 binding: binding as u32,
241 resource: buffer.as_entire_binding(),
242 })
243 .collect();
244 let group = runtime.device().create_bind_group(&wgpu::BindGroupDescriptor {
245 label: Some("iss-bindings"),
246 layout: &cache.layout,
247 entries: &entries,
248 });
249 let mut encoder = runtime.device().create_command_encoder(&Default::default());
250 for pipeline in [&cache.saliency, &cache.selection] {
251 let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
252 label: Some("iss-compute"),
253 timestamp_writes: None,
254 });
255 pass.set_pipeline(pipeline);
256 pass.set_bind_group(0, &group, &[]);
257 pass.dispatch_workgroups(self.count.div_ceil(64), 1, 1);
258 }
259 runtime.queue().submit(Some(encoder.finish()));
260 Ok(result)
261 }
262}
263
264pub struct GpuIssNeighborhoods {
266 salient: GpuNeighborhoods,
267 non_max: GpuNeighborhoods,
268 salient_radius: f32,
269 non_max_radius: f32,
270 input_identity: Arc<()>,
271}
272impl GpuIssNeighborhoods {
273 #[must_use]
275 pub fn salient_rows(&self) -> &GpuNeighborhoods {
276 &self.salient
277 }
278 #[must_use]
280 pub fn non_max_rows(&self) -> &GpuNeighborhoods {
281 &self.non_max
282 }
283}
284
285pub struct GpuIssKeypoints {
288 scores: wgpu::Buffer,
289 flags: wgpu::Buffer,
290 status: wgpu::Buffer,
291 count: u32,
292 identity: Arc<()>,
293}
294impl GpuIssKeypoints {
295 #[must_use]
297 pub fn buffer(&self) -> &wgpu::Buffer {
298 &self.flags
299 }
300 #[must_use]
304 pub fn scores_buffer(&self) -> &wgpu::Buffer {
305 &self.scores
306 }
307 #[must_use]
311 pub fn status_buffer(&self) -> &wgpu::Buffer {
312 &self.status
313 }
314 #[must_use]
316 pub const fn point_count(&self) -> u32 {
317 self.count
318 }
319 #[must_use]
321 pub const fn readback_bytes(&self) -> u64 {
322 if self.count == 0 {
323 0
324 } else {
325 self.count as u64 * 4 + 32
326 }
327 }
328 pub fn download(&self, runtime: &WgpuRuntime) -> SpatialResult<(Vec<u32>, TransferStats)> {
333 self.readback(runtime, false, |words| {
334 if words.iter().any(|&v| v > 1) {
335 return Err(invalid());
336 }
337 Ok(words
338 .iter()
339 .enumerate()
340 .filter_map(|(i, &flag)| (flag == 1).then_some(i as u32))
341 .collect())
342 })
343 }
344
345 pub fn download_scores(
350 &self,
351 runtime: &WgpuRuntime,
352 ) -> SpatialResult<(Vec<[f32; 4]>, TransferStats)> {
353 self.readback(runtime, true, |words| {
354 let mut rows = Vec::with_capacity(self.count as usize);
355 for row in words.chunks_exact(4) {
356 let values: [f32; 4] = std::array::from_fn(|i| f32::from_bits(row[i]));
357 if values.iter().any(|v| !v.is_finite())
358 || values[0] > values[1]
359 || values[1] > values[2]
360 || (values[3] != 0.0 && values[3] != 1.0)
361 {
362 return Err(invalid());
363 }
364 rows.push(values);
365 }
366 Ok(rows)
367 })
368 }
369
370 fn readback<T: Default>(
371 &self,
372 runtime: &WgpuRuntime,
373 scores: bool,
374 decode: impl FnOnce(&[u32]) -> SpatialResult<T>,
375 ) -> SpatialResult<(T, TransferStats)> {
376 if !Arc::ptr_eq(&self.identity, &runtime.profiling_identity()) {
377 return Err(invalid());
378 }
379 if self.count == 0 {
380 return Ok((T::default(), TransferStats::default()));
381 }
382 let bytes = u64::from(self.count) * if scores { 16 } else { 4 };
383 let staging = runtime.device().create_buffer(&wgpu::BufferDescriptor {
384 label: Some("iss-readback"),
385 size: bytes + 32,
386 usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
387 mapped_at_creation: false,
388 });
389 let mut encoder = runtime.device().create_command_encoder(&Default::default());
390 encoder.copy_buffer_to_buffer(
391 if scores { &self.scores } else { &self.flags },
392 0,
393 &staging,
394 0,
395 bytes,
396 );
397 encoder.copy_buffer_to_buffer(&self.status, 0, &staging, bytes, 32);
398 runtime.queue().submit(Some(encoder.finish()));
399 let slice = staging.slice(..);
400 let (sender, receiver) = std::sync::mpsc::channel();
401 slice.map_async(wgpu::MapMode::Read, move |r| {
402 let _ = sender.send(r);
403 });
404 runtime.device().poll(wgpu::Maintain::Wait);
405 receiver
406 .recv()
407 .map_err(|e| SpatialError::InvalidArgument(e.to_string()))?
408 .map_err(|e| SpatialError::InvalidArgument(e.to_string()))?;
409 let mapped = slice.get_mapped_range();
410 let words: &[u32] = bytemuck::cast_slice(&mapped);
411 let payload_words = bytes as usize / 4;
412 let status = &words[payload_words..];
413 let decoded = if status.iter().any(|&v| v != 0) {
414 Err(SpatialError::InvalidArgument(format!("GPU ISS rejected incomplete/malformed neighborhoods or numerical output; status={status:?}")))
415 } else {
416 decode(&words[..payload_words])
417 };
418 drop(mapped);
419 staging.unmap();
420 let mut transfers = TransferStats::default();
421 transfers.record(TransferDirection::DeviceToHost, bytes + 32);
422 Ok((decoded?, transfers))
423 }
424}
425
426pub(crate) struct IssPipelines {
427 layout: wgpu::BindGroupLayout,
428 saliency: wgpu::ComputePipeline,
429 selection: wgpu::ComputePipeline,
430}
431impl IssPipelines {
432 fn new(device: &wgpu::Device) -> Self {
433 let entries: Vec<_> = (0..7)
434 .map(|binding| wgpu::BindGroupLayoutEntry {
435 binding,
436 visibility: wgpu::ShaderStages::COMPUTE,
437 ty: wgpu::BindingType::Buffer {
438 ty: if binding == 0 {
439 wgpu::BufferBindingType::Uniform
440 } else {
441 wgpu::BufferBindingType::Storage { read_only: binding < 4 }
442 },
443 has_dynamic_offset: false,
444 min_binding_size: None,
445 },
446 count: None,
447 })
448 .collect();
449 let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
450 label: Some("iss-layout"),
451 entries: &entries,
452 });
453 let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
454 label: Some("iss-layout"),
455 bind_group_layouts: &[&layout],
456 push_constant_ranges: &[],
457 });
458 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
459 label: Some("iss-shader"),
460 source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/iss.wgsl").into()),
461 });
462 let create = |entry| {
463 device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
464 label: Some("iss-pipeline"),
465 layout: Some(&pipeline_layout),
466 module: &shader,
467 entry_point: Some(entry),
468 compilation_options: Default::default(),
469 cache: None,
470 })
471 };
472 Self { saliency: create("build_saliency"), selection: create("select_keypoints"), layout }
473 }
474}
475
476#[cfg(all(test, not(target_arch = "wasm32")))]
477#[path = "iss_tests.rs"]
478mod tests;
479
480#[cfg(all(test, not(target_arch = "wasm32")))]
481#[path = "iss_soa_upload_reference.rs"]
482pub(crate) mod soa_upload_reference;
483
484#[cfg(all(test, not(target_arch = "wasm32")))]
485#[path = "iss_validation_reference.rs"]
486pub(crate) mod validation_reference;