1use super::{buffer_bytes, check_compute, invalid, Arc, GpuKdTree, Neighbor, Pod, Zeroable};
2use spatialrust_core::{SpatialError, SpatialResult, TransferDirection, TransferStats};
3use std::sync::OnceLock;
4use wgpu::util::DeviceExt;
5
6use crate::WgpuRuntime;
7
8pub const MAX_GPU_K_NEIGHBORS: u32 = 64;
10
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13pub enum GpuNeighborhoodKind {
14 NearestK,
16 Radius,
18}
19
20pub struct GpuQueryBatch {
23 buffer: Option<wgpu::Buffer>,
24 count: u32,
25 identity: Arc<()>,
26 transfers: TransferStats,
27}
28
29impl GpuQueryBatch {
30 pub(super) fn from_gathered(
31 runtime: &WgpuRuntime,
32 buffer: Option<wgpu::Buffer>,
33 count: u32,
34 ) -> Self {
35 let mut transfers = TransferStats::default();
36 transfers.record(TransferDirection::DeviceToDevice, u64::from(count) * 16);
37 Self { buffer, count, identity: runtime.profiling_identity(), transfers }
38 }
39
40 pub(crate) fn buffer(&self) -> Option<&wgpu::Buffer> {
41 self.buffer.as_ref()
42 }
43
44 pub fn upload(runtime: &WgpuRuntime, queries: &[[f32; 3]]) -> SpatialResult<Self> {
47 let limits = runtime.device().limits();
48 let bytes = buffer_bytes(queries.len() as u64, 16, &limits)?;
49 check_compute(&limits, queries.len() as u64)?;
50 let packed = aos_query_staging::prepare(queries)?;
51 let mut batch = Self {
52 buffer: None,
53 count: queries.len() as u32,
54 identity: runtime.profiling_identity(),
55 transfers: TransferStats::default(),
56 };
57 if !queries.is_empty() {
58 batch.buffer =
59 Some(runtime.device().create_buffer_init(&wgpu::util::BufferInitDescriptor {
60 label: Some("neighborhood-queries"),
61 contents: bytemuck::cast_slice(&packed),
62 usage: wgpu::BufferUsages::STORAGE,
63 }));
64 batch.transfers.record(TransferDirection::HostToDevice, bytes);
65 }
66 Ok(batch)
67 }
68
69 pub(crate) fn upload_soa(runtime: &WgpuRuntime, axes: [&[f32]; 3]) -> SpatialResult<Self> {
72 let count = axes[0].len();
73 if axes.iter().any(|axis| axis.len() != count) {
74 return Err(invalid());
75 }
76 let limits = runtime.device().limits();
77 let bytes = buffer_bytes(count as u64, 16, &limits)?;
78 check_compute(&limits, count as u64)?;
79 let packed = pack_soa(axes)?;
80 let mut batch = Self {
81 buffer: None,
82 count: count as u32,
83 identity: runtime.profiling_identity(),
84 transfers: TransferStats::default(),
85 };
86 if count != 0 {
87 batch.buffer =
88 Some(runtime.device().create_buffer_init(&wgpu::util::BufferInitDescriptor {
89 label: Some("neighborhood-queries"),
90 contents: bytemuck::cast_slice(&packed),
91 usage: wgpu::BufferUsages::STORAGE,
92 }));
93 batch.transfers.record(TransferDirection::HostToDevice, bytes);
94 }
95 Ok(batch)
96 }
97
98 #[must_use]
100 pub const fn query_count(&self) -> u32 {
101 self.count
102 }
103
104 #[must_use]
107 pub const fn upload_transfers(&self) -> TransferStats {
108 self.transfers
109 }
110}
111
112fn pack_soa(axes: [&[f32]; 3]) -> SpatialResult<Vec<[f32; 4]>> {
113 query_staging::prepare(axes)
114}
115
116#[path = "query_staging.rs"]
117mod query_staging;
118
119pub struct GpuNeighborhoods {
123 buffer: wgpu::Buffer,
124 queries: u32,
125 capacity: u32,
126 bytes: u64,
127 kind: GpuNeighborhoodKind,
128 identity: Arc<()>,
129}
130
131impl GpuNeighborhoods {
132 #[must_use]
139 pub fn buffer(&self) -> &wgpu::Buffer {
140 &self.buffer
141 }
142
143 #[must_use]
145 pub const fn query_count(&self) -> u32 {
146 self.queries
147 }
148
149 #[must_use]
151 pub const fn capacity(&self) -> u32 {
152 self.capacity
153 }
154
155 #[must_use]
157 pub const fn kind(&self) -> GpuNeighborhoodKind {
158 self.kind
159 }
160
161 #[must_use]
163 pub const fn readback_bytes(&self) -> u64 {
164 self.bytes
165 }
166
167 #[must_use]
170 pub fn execution_transfers(&self) -> TransferStats {
171 TransferStats::default()
172 }
173
174 pub fn download(&self, runtime: &WgpuRuntime) -> SpatialResult<GpuNeighborhoodReadback> {
178 if !Arc::ptr_eq(&self.identity, &runtime.profiling_identity()) {
179 return Err(invalid());
180 }
181 if self.queries == 0 {
182 return Ok(GpuNeighborhoodReadback {
183 rows: Vec::new(),
184 totals: Vec::new(),
185 transfers: TransferStats::default(),
186 });
187 }
188 let staging = runtime.device().create_buffer(&wgpu::BufferDescriptor {
189 label: Some("neighborhood-readback"),
190 size: self.bytes,
191 usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
192 mapped_at_creation: false,
193 });
194 let mut encoder = runtime.device().create_command_encoder(&Default::default());
195 encoder.copy_buffer_to_buffer(&self.buffer, 0, &staging, 0, self.bytes);
196 runtime.queue().submit(Some(encoder.finish()));
197 let slice = staging.slice(..);
198 let (sender, receiver) = std::sync::mpsc::channel();
199 slice.map_async(wgpu::MapMode::Read, move |r| {
200 let _ = sender.send(r);
201 });
202 runtime.device().poll(wgpu::Maintain::Wait);
203 receiver
204 .recv()
205 .map_err(|e| SpatialError::InvalidArgument(e.to_string()))?
206 .map_err(|e| SpatialError::InvalidArgument(e.to_string()))?;
207 let mapped = slice.get_mapped_range();
208 let words: &[u32] = bytemuck::cast_slice(&mapped);
209 let stride = 2 + 2 * self.capacity as usize;
210 let decoded = readback_decode::decode(words, stride, self.capacity, self.kind);
211 drop(mapped);
212 staging.unmap();
213 let (rows, totals) = decoded?;
214 let mut transfers = TransferStats::default();
215 transfers.record(TransferDirection::DeviceToHost, self.bytes);
216 Ok(GpuNeighborhoodReadback { rows, totals, transfers })
217 }
218}
219
220pub struct GpuNeighborhoodReadback {
223 rows: Vec<Vec<Neighbor>>,
224 totals: Vec<u32>,
225 transfers: TransferStats,
226}
227
228impl GpuNeighborhoodReadback {
229 #[must_use]
231 pub fn is_complete(&self) -> bool {
232 self.rows.iter().zip(&self.totals).all(|(row, &total)| row.len() == total as usize)
233 }
234
235 #[must_use]
237 pub fn total_counts(&self) -> &[u32] {
238 &self.totals
239 }
240
241 #[must_use]
244 pub fn truncated_rows(&self) -> &[Vec<Neighbor>] {
245 &self.rows
246 }
247
248 pub fn complete_rows(&self) -> SpatialResult<&[Vec<Neighbor>]> {
250 self.check_complete()?;
251 Ok(&self.rows)
252 }
253
254 pub fn into_complete_rows(self) -> SpatialResult<Vec<Vec<Neighbor>>> {
256 self.check_complete()?;
257 Ok(self.rows)
258 }
259
260 #[must_use]
262 pub const fn transfers(&self) -> TransferStats {
263 self.transfers
264 }
265
266 fn check_complete(&self) -> SpatialResult<()> {
267 if let Some((i, (row, &total))) = self
268 .rows
269 .iter()
270 .zip(&self.totals)
271 .enumerate()
272 .find(|(_, (row, total))| row.len() < **total as usize)
273 {
274 return Err(SpatialError::InvalidArgument(format!(
275 "radius neighborhood row {i} contains {total} matches but stores only {}; increase capacity before consuming complete neighborhoods", row.len()
276 )));
277 }
278 Ok(())
279 }
280}
281
282#[repr(C)]
283#[derive(Clone, Copy, Pod, Zeroable)]
284struct Params {
285 count: u32,
286 root: u32,
287 capacity: u32,
288 bound: f32,
289}
290
291const NEAREST_CAPACITIES: [u32; 4] = [1, 8, 16, 64];
292
293const MIN_SPECIALIZED_QUERIES: u32 = 1024;
294
295fn nearest_variant(capacity: u32, queries: u32) -> usize {
296 if queries < MIN_SPECIALIZED_QUERIES {
297 return 3;
298 }
299 match capacity {
300 0..=1 => 0,
301 2..=8 => 1,
302 9..=16 => 2,
303 _ => 3,
304 }
305}
306
307pub(crate) struct NeighborhoodPipelines {
308 layout: wgpu::BindGroupLayout,
309 nearest: [OnceLock<wgpu::ComputePipeline>; 4],
310 radius: OnceLock<wgpu::ComputePipeline>,
311}
312
313impl NeighborhoodPipelines {
314 fn new(device: &wgpu::Device) -> Self {
315 let entries: Vec<_> = (0..5)
316 .map(|binding| wgpu::BindGroupLayoutEntry {
317 binding,
318 visibility: wgpu::ShaderStages::COMPUTE,
319 ty: wgpu::BindingType::Buffer {
320 ty: if binding == 0 {
321 wgpu::BufferBindingType::Uniform
322 } else {
323 wgpu::BufferBindingType::Storage { read_only: binding != 4 }
324 },
325 has_dynamic_offset: false,
326 min_binding_size: None,
327 },
328 count: None,
329 })
330 .collect();
331 let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
332 label: Some("neighborhood-layout"),
333 entries: &entries,
334 });
335 Self { layout, nearest: std::array::from_fn(|_| OnceLock::new()), radius: OnceLock::new() }
336 }
337
338 fn pipeline(
339 &self,
340 device: &wgpu::Device,
341 kind: GpuNeighborhoodKind,
342 capacity: u32,
343 queries: u32,
344 ) -> &wgpu::ComputePipeline {
345 let (slot, entry, slots) = if kind == GpuNeighborhoodKind::NearestK {
346 let index = nearest_variant(capacity, queries);
347 (&self.nearest[index], "nearest_k", NEAREST_CAPACITIES[index])
348 } else {
349 (&self.radius, "radius_neighbors", MAX_GPU_K_NEIGHBORS)
350 };
351 slot.get_or_init(|| {
352 let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
353 label: Some("neighborhood-pipeline-layout"),
354 bind_group_layouts: &[&self.layout],
355 push_constant_ranges: &[],
356 });
357 let source = format!(
359 "const ACCUMULATOR_SIZE: u32 = {slots}u;\n{}",
360 include_str!("../shaders/neighborhoods.wgsl")
361 );
362 let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
363 label: Some("neighborhood-shader"),
364 source: wgpu::ShaderSource::Wgsl(source.into()),
365 });
366 device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
367 label: Some("neighborhood-pipeline"),
368 layout: Some(&pipeline_layout),
369 module: &module,
370 entry_point: Some(entry),
371 compilation_options: Default::default(),
372 cache: None,
373 })
374 })
375 }
376}
377
378fn plan(
379 queries: u64,
380 capacity: u64,
381 kind: GpuNeighborhoodKind,
382 limits: &wgpu::Limits,
383) -> SpatialResult<u64> {
384 if capacity > u64::from((u32::MAX - 2) / 2)
385 || (kind == GpuNeighborhoodKind::NearestK && capacity > u64::from(MAX_GPU_K_NEIGHBORS))
386 {
387 return Err(invalid());
388 }
389 check_compute(limits, queries)?;
390 buffer_bytes(queries, 16, limits)?;
391 let stride = capacity.checked_mul(8).and_then(|v| v.checked_add(8)).ok_or_else(invalid)?;
392 let bytes = buffer_bytes(queries, stride, limits)?;
393 let host_slots = queries
395 .checked_mul(capacity)
396 .and_then(|n| n.checked_mul(std::mem::size_of::<Neighbor>() as u64))
397 .ok_or_else(invalid)?;
398 let host_rows =
399 queries.checked_mul(std::mem::size_of::<Vec<Neighbor>>() as u64).ok_or_else(invalid)?;
400 if bytes / 4 > u64::from(u32::MAX)
401 || host_slots > isize::MAX as u64
402 || host_rows > isize::MAX as u64
403 {
404 return Err(invalid());
405 }
406 Ok(bytes)
407}
408
409impl GpuKdTree {
410 pub fn nearest_k_resident(
417 &self,
418 runtime: &WgpuRuntime,
419 queries: &GpuQueryBatch,
420 k: u32,
421 ) -> SpatialResult<GpuNeighborhoods> {
422 self.neighborhoods(runtime, queries, k, f32::INFINITY, GpuNeighborhoodKind::NearestK)
423 }
424
425 pub fn radius_neighbors_resident(
433 &self,
434 runtime: &WgpuRuntime,
435 queries: &GpuQueryBatch,
436 radius: f32,
437 capacity: u32,
438 ) -> SpatialResult<GpuNeighborhoods> {
439 self.neighborhoods(
440 runtime,
441 queries,
442 capacity,
443 if radius < 0.0 { f32::NAN } else { radius * radius },
444 GpuNeighborhoodKind::Radius,
445 )
446 }
447
448 fn neighborhoods(
449 &self,
450 runtime: &WgpuRuntime,
451 queries: &GpuQueryBatch,
452 capacity: u32,
453 bound: f32,
454 kind: GpuNeighborhoodKind,
455 ) -> SpatialResult<GpuNeighborhoods> {
456 let identity = runtime.profiling_identity();
457 if !Arc::ptr_eq(&self.identity, &identity) || !Arc::ptr_eq(&queries.identity, &identity) {
458 return Err(invalid());
459 }
460 let bytes =
461 plan(u64::from(queries.count), u64::from(capacity), kind, &runtime.device().limits())?;
462 let output = GpuNeighborhoods {
463 buffer: runtime.device().create_buffer(&wgpu::BufferDescriptor {
464 label: Some("neighborhood-results"),
465 size: bytes.max(8),
466 usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
467 mapped_at_creation: false,
468 }),
469 queries: queries.count,
470 capacity,
471 bytes,
472 kind,
473 identity,
474 };
475 if queries.count == 0
478 || self.root.is_none()
479 || bound.is_nan()
480 || (kind == GpuNeighborhoodKind::NearestK && capacity == 0)
481 {
482 return Ok(output);
483 }
484 let cache = runtime
485 .neighborhood_pipelines
486 .get_or_init(|| NeighborhoodPipelines::new(runtime.device()));
487 let params = Params { count: queries.count, root: self.root.unwrap(), capacity, bound };
488 let uniform = runtime.device().create_buffer_init(&wgpu::util::BufferInitDescriptor {
489 label: Some("neighborhood-params"),
490 contents: bytemuck::bytes_of(¶ms),
491 usage: wgpu::BufferUsages::UNIFORM,
492 });
493 let buffers = [
494 &uniform,
495 self.nodes.as_ref().unwrap(),
496 self.points.as_ref().unwrap(),
497 queries.buffer.as_ref().unwrap(),
498 &output.buffer,
499 ];
500 let entries: Vec<_> = buffers
501 .iter()
502 .enumerate()
503 .map(|(i, b)| wgpu::BindGroupEntry {
504 binding: i as u32,
505 resource: b.as_entire_binding(),
506 })
507 .collect();
508 let group = runtime.device().create_bind_group(&wgpu::BindGroupDescriptor {
509 label: Some("neighborhood-bindings"),
510 layout: &cache.layout,
511 entries: &entries,
512 });
513 let mut encoder = runtime.device().create_command_encoder(&Default::default());
514 {
515 let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
516 label: Some("neighborhood-search"),
517 timestamp_writes: None,
518 });
519 pass.set_pipeline(cache.pipeline(runtime.device(), kind, capacity, queries.count));
520 pass.set_bind_group(0, &group, &[]);
521 pass.dispatch_workgroups(queries.count.div_ceil(64), 1, 1);
522 }
523 runtime.queue().submit(Some(encoder.finish()));
524 Ok(output)
525 }
526}
527
528#[cfg(all(test, not(target_arch = "wasm32")))]
529#[path = "neighborhood_tests.rs"]
530mod tests;
531
532#[path = "aos_query_staging.rs"]
533mod aos_query_staging;
534
535#[cfg(all(test, not(target_arch = "wasm32")))]
536#[path = "aos_query_upload_reference.rs"]
537pub(crate) mod aos_upload_reference;
538
539#[cfg(all(test, not(target_arch = "wasm32")))]
540#[path = "aos_query_upload_tests.rs"]
541mod aos_upload_tests;
542
543#[cfg(all(test, not(target_arch = "wasm32")))]
544#[path = "neighborhood_capacity_tests.rs"]
545mod capacity_tests;
546
547#[path = "neighborhood_readback_decode.rs"]
548mod readback_decode;