Skip to main content

spatialrust_gpu/kernels/
nearest.rs

1use std::sync::Arc;
2
3use bytemuck::{Pod, Zeroable};
4use spatialrust_core::{SpatialError, SpatialResult, TransferDirection, TransferStats};
5use spatialrust_search::{KdTree, KdTreeNode, Neighbor};
6use wgpu::util::DeviceExt;
7
8use crate::{scratch::ScratchBuffers, WgpuRuntime};
9
10#[path = "tree_staging.rs"]
11mod tree_staging;
12
13#[path = "tree_gpu_gather.rs"]
14pub(crate) mod tree_gpu_gather;
15
16#[cfg(all(test, not(target_arch = "wasm32")))]
17#[path = "registration_gather_upload_tests.rs"]
18mod registration_gather_tests;
19
20#[path = "neighborhoods.rs"]
21mod neighborhoods;
22pub(crate) use neighborhoods::NeighborhoodPipelines;
23pub use neighborhoods::{
24    GpuNeighborhoodKind, GpuNeighborhoodReadback, GpuNeighborhoods, GpuQueryBatch,
25    MAX_GPU_K_NEIGHBORS,
26};
27
28#[repr(C)]
29#[derive(Clone, Copy, Pod, Zeroable)]
30struct Node {
31    split: f32,
32    axis: u32,
33    left: u32,
34    right: u32,
35    start: u32,
36    end: u32,
37    padding: [u32; 2],
38}
39
40#[repr(C)]
41#[derive(Clone, Copy, Pod, Zeroable)]
42struct Point {
43    xyz: [f32; 3],
44    index: u32,
45}
46
47#[repr(C)]
48#[derive(Clone, Copy, Pod, Zeroable)]
49struct Params {
50    count: u32,
51    root: u32,
52    bound: f32,
53    unused: u32,
54}
55
56pub(crate) struct NearestPipeline {
57    layout: wgpu::BindGroupLayout,
58    pipeline: wgpu::ComputePipeline,
59}
60
61impl NearestPipeline {
62    fn new(device: &wgpu::Device) -> Self {
63        let entries: Vec<_> = (0..5)
64            .map(|binding| wgpu::BindGroupLayoutEntry {
65                binding,
66                visibility: wgpu::ShaderStages::COMPUTE,
67                ty: wgpu::BindingType::Buffer {
68                    ty: if binding == 0 {
69                        wgpu::BufferBindingType::Uniform
70                    } else {
71                        wgpu::BufferBindingType::Storage { read_only: binding != 4 }
72                    },
73                    has_dynamic_offset: false,
74                    min_binding_size: None,
75                },
76                count: None,
77            })
78            .collect();
79        let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
80            label: Some("nearest-layout"),
81            entries: &entries,
82        });
83        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
84            label: Some("nearest-pipeline-layout"),
85            bind_group_layouts: &[&layout],
86            push_constant_ranges: &[],
87        });
88        let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
89            label: Some("nearest-shader"),
90            source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/nearest.wgsl").into()),
91        });
92        let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
93            label: Some("nearest-pipeline"),
94            layout: Some(&pipeline_layout),
95            module: &module,
96            entry_point: Some("nearest"),
97            compilation_options: Default::default(),
98            cache: None,
99        });
100        Self { layout, pipeline }
101    }
102}
103
104fn invalid() -> SpatialError {
105    SpatialError::InvalidArgument("GPU nearest search requires a matching runtime, finite target and supported buffer/dispatch limits".to_owned())
106}
107
108fn buffer_bytes(count: u64, stride: u64, limits: &wgpu::Limits) -> SpatialResult<u64> {
109    let bytes = count.checked_mul(stride).ok_or_else(invalid)?;
110    if count > u64::from(u32::MAX)
111        || bytes > limits.max_buffer_size
112        || bytes > u64::from(limits.max_storage_buffer_binding_size)
113        || bytes > isize::MAX as u64
114    {
115        return Err(invalid());
116    }
117    Ok(bytes)
118}
119
120fn check_compute(limits: &wgpu::Limits, queries: u64) -> SpatialResult<()> {
121    if queries.div_ceil(64) > u64::from(limits.max_compute_workgroups_per_dimension)
122        || limits.max_compute_workgroup_size_x < 64
123        || limits.max_compute_workgroup_size_y == 0
124        || limits.max_compute_workgroup_size_z == 0
125        || limits.max_compute_invocations_per_workgroup < 64
126        || limits.max_storage_buffers_per_shader_stage < 4
127        || limits.max_bindings_per_bind_group < 5
128        || limits.max_bind_groups == 0
129        || limits.max_uniform_buffers_per_shader_stage == 0
130        || limits.max_uniform_buffer_binding_size < 16
131        || limits.max_buffer_size < 32
132        || limits.max_storage_buffer_binding_size < 32
133    {
134        return Err(invalid());
135    }
136    Ok(())
137}
138
139/// Immutable runtime-owned KD-tree uploaded explicitly and reused across batches.
140/// Construction/partitioning is on CPU; nearest-point traversal is on GPU.
141/// No device-to-host transfer is performed by upload, and no CPU search fallback
142/// is used. Public methods validate device identity before resource use.
143pub struct GpuKdTree {
144    nodes: Option<wgpu::Buffer>,
145    points: Option<wgpu::Buffer>,
146    root: Option<u32>,
147    identity: Arc<()>,
148    upload_transfers: TransferStats,
149}
150
151impl GpuKdTree {
152    // Internal device consumer: queries/results remain private to its encoder.
153    // Reuses the ordinary bounded nearest shader and tie traversal exactly.
154    pub(crate) fn encode_nearest(
155        &self,
156        runtime: &WgpuRuntime,
157        encoder: &mut wgpu::CommandEncoder,
158        queries: &wgpu::Buffer,
159        count: u32,
160        bound: f32,
161        results: &wgpu::Buffer,
162    ) -> SpatialResult<()> {
163        if !Arc::ptr_eq(&self.identity, &runtime.profiling_identity()) || self.root.is_none() {
164            return Err(invalid());
165        }
166        check_compute(&runtime.device().limits(), u64::from(count))?;
167        let params = Params { count, root: self.root.unwrap(), bound, unused: 0 };
168        let uniform = runtime.device().create_buffer_init(&wgpu::util::BufferInitDescriptor {
169            label: Some("resident-nearest-params"),
170            contents: bytemuck::bytes_of(&params),
171            usage: wgpu::BufferUsages::UNIFORM,
172        });
173        let cache = runtime.nearest_pipeline.get_or_init(|| NearestPipeline::new(runtime.device()));
174        let buffers = [
175            &uniform,
176            self.nodes.as_ref().unwrap(),
177            self.points.as_ref().unwrap(),
178            queries,
179            results,
180        ];
181        let entries: Vec<_> = buffers
182            .iter()
183            .enumerate()
184            .map(|(binding, buffer)| wgpu::BindGroupEntry {
185                binding: binding as u32,
186                resource: buffer.as_entire_binding(),
187            })
188            .collect();
189        let group = runtime.device().create_bind_group(&wgpu::BindGroupDescriptor {
190            label: Some("resident-nearest-bindings"),
191            layout: &cache.layout,
192            entries: &entries,
193        });
194        let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
195            label: Some("resident-nearest"),
196            timestamp_writes: None,
197        });
198        pass.set_pipeline(&cache.pipeline);
199        pass.set_bind_group(0, &group, &[]);
200        pass.dispatch_workgroups(count.div_ceil(64), 1, 1);
201        Ok(())
202    }
203
204    /// Uploads a finite CPU KD-tree, preserving its leaf and tie traversal order.
205    /// The borrowed tree may be dropped afterwards. Upload accounting includes
206    /// 16 bytes per point and 32 per node, excluding uniform control data.
207    pub fn upload(runtime: &WgpuRuntime, tree: &KdTree) -> SpatialResult<Self> {
208        let layout = tree.layout();
209        let (x, y, z) = layout.positions();
210        let limits = runtime.device().limits();
211        let point_bytes = buffer_bytes(x.len() as u64, 16, &limits)?;
212        let node_bytes = buffer_bytes(layout.nodes().len() as u64, 32, &limits)?;
213        check_compute(&limits, 0)?;
214        let points = tree_staging::prepare([x, y, z], layout.point_order())?;
215        let mut target = Self {
216            nodes: None,
217            points: None,
218            root: layout.root(),
219            identity: runtime.profiling_identity(),
220            upload_transfers: TransferStats::default(),
221        };
222        if x.is_empty() {
223            return Ok(target);
224        }
225        let nodes: Vec<_> = layout
226            .nodes()
227            .map(|node| {
228                let mut output = Node::zeroed();
229                match node {
230                    KdTreeNode::Leaf { start, end } => {
231                        output.axis = u32::MAX;
232                        output.start = start;
233                        output.end = end;
234                    }
235                    KdTreeNode::Branch { axis, split, left, right } => {
236                        output.axis = u32::from(axis);
237                        output.split = split;
238                        output.left = left;
239                        output.right = right;
240                    }
241                }
242                output
243            })
244            .collect();
245        let upload = |label, data: &[u8]| {
246            runtime.device().create_buffer_init(&wgpu::util::BufferInitDescriptor {
247                label: Some(label),
248                contents: data,
249                usage: wgpu::BufferUsages::STORAGE,
250            })
251        };
252        target.nodes = Some(upload("nearest-nodes", bytemuck::cast_slice(&nodes)));
253        target.points = Some(upload("nearest-points", bytemuck::cast_slice(&points)));
254        target.upload_transfers.record(TransferDirection::HostToDevice, point_bytes + node_bytes);
255        Ok(target)
256    }
257
258    /// Explicitly uploads original SoA axes/indices and gathers point records on GPU.
259    /// CPU partitioning, finite validation and node packing remain. Existing
260    /// nearest-search device requirements apply; unsupported limits reject.
261    /// The pass copies integer words, preserving coordinate bits and leaf/tie order.
262    /// Host upload is 16*N + 32*M bytes; the gather records 16*N device-to-device
263    /// bytes. There is no download or host completion wait.
264    /// Two transient inputs use 16*N extra device bytes beside the owned output;
265    /// there is no 16*N host point-packing vector. Submission retains inputs until
266    /// completion, and later searches on this runtime follow queue ordering.
267    pub fn upload_with_gpu_gather(runtime: &WgpuRuntime, tree: &KdTree) -> SpatialResult<Self> {
268        Self::upload_gathered(runtime, tree, false).map(|(target, _)| target)
269    }
270
271    /// Uploads the tree and generates queries for every point in original input
272    /// order, sharing the same integer gather pass and uploaded SoA axes/indices.
273    /// Combined host upload is 16*N + 32*M bytes, compared with 32*N + 32*M
274    /// for separate tree/query uploads. Each returned object records 16*N
275    /// device-to-device output bytes; queries record zero host upload bytes.
276    /// CPU partitioning, finite validation and node packing remain. No readback
277    /// or completion wait occurs. Both outputs are owned and reusable; the CPU
278    /// tree may be dropped. Two transient inputs use 16*N extra device bytes;
279    /// no host point/query packing vectors are created. Device requirements
280    /// match nearest search, with an additional query dispatch-size check.
281    pub fn upload_and_queries_with_gpu_gather(
282        runtime: &WgpuRuntime,
283        tree: &KdTree,
284    ) -> SpatialResult<(Self, GpuQueryBatch)> {
285        let (target, queries) = Self::upload_gathered(runtime, tree, true)?;
286        Ok((target, queries.unwrap()))
287    }
288
289    fn upload_gathered(
290        runtime: &WgpuRuntime,
291        tree: &KdTree,
292        with_queries: bool,
293    ) -> SpatialResult<(Self, Option<GpuQueryBatch>)> {
294        Self::upload_gathered_impl(runtime, tree, with_queries, None)
295            .map(|(target, queries, _)| (target, queries))
296    }
297
298    // FPFH validates unit normals first, then records their 12*N host bytes and
299    // the 32*N sample output separately. Tree/query receipts keep their contract.
300    pub(crate) fn upload_with_gpu_samples(
301        runtime: &WgpuRuntime,
302        tree: &KdTree,
303        normals: &[[f32; 3]],
304    ) -> SpatialResult<(Self, GpuQueryBatch, Option<wgpu::Buffer>)> {
305        let (target, queries, samples) =
306            Self::upload_gathered_impl(runtime, tree, true, Some(normals))?;
307        Ok((target, queries.unwrap(), samples))
308    }
309
310    fn upload_gathered_impl(
311        runtime: &WgpuRuntime,
312        tree: &KdTree,
313        with_queries: bool,
314        normals: Option<&[[f32; 3]]>,
315    ) -> SpatialResult<(Self, Option<GpuQueryBatch>, Option<wgpu::Buffer>)> {
316        let layout = tree.layout();
317        let (x, y, z) = layout.positions();
318        let limits = runtime.device().limits();
319        let point_bytes = buffer_bytes(x.len() as u64, 16, &limits)?;
320        let node_bytes = buffer_bytes(layout.nodes().len() as u64, 32, &limits)?;
321        check_compute(&limits, 0)?;
322        tree_gpu_gather::check(x.len() as u64, &limits)?;
323        if with_queries {
324            check_compute(&limits, x.len() as u64)?;
325        }
326        if let Some(normals) = normals {
327            if normals.len() != x.len() {
328                return Err(invalid());
329            }
330            tree_gpu_gather::check_samples(x.len() as u64, &limits)?;
331        }
332        let mut target = Self {
333            nodes: None,
334            points: None,
335            root: layout.root(),
336            identity: runtime.profiling_identity(),
337            upload_transfers: TransferStats::default(),
338        };
339        if x.is_empty() {
340            return Ok((
341                target,
342                with_queries.then(|| GpuQueryBatch::from_gathered(runtime, None, 0)),
343                None,
344            ));
345        }
346        let (points, queries, samples) = if let Some(normals) = normals {
347            tree_gpu_gather::upload_with_samples(runtime, [x, y, z], layout.point_order(), normals)?
348        } else {
349            let (points, queries) =
350                tree_gpu_gather::upload(runtime, [x, y, z], layout.point_order(), with_queries)?;
351            (points, queries, None)
352        };
353        target.points = Some(points);
354        let queries = queries
355            .map(|buffer| GpuQueryBatch::from_gathered(runtime, Some(buffer), x.len() as u32));
356        let nodes: Vec<_> = layout
357            .nodes()
358            .map(|node| {
359                let mut output = Node::zeroed();
360                match node {
361                    KdTreeNode::Leaf { start, end } => {
362                        output.axis = u32::MAX;
363                        output.start = start;
364                        output.end = end;
365                    }
366                    KdTreeNode::Branch { axis, split, left, right } => {
367                        output.axis = u32::from(axis);
368                        output.split = split;
369                        output.left = left;
370                        output.right = right;
371                    }
372                }
373                output
374            })
375            .collect();
376        let upload = |label, data: &[u8]| {
377            runtime.device().create_buffer_init(&wgpu::util::BufferInitDescriptor {
378                label: Some(label),
379                contents: data,
380                usage: wgpu::BufferUsages::STORAGE,
381            })
382        };
383        target.nodes = Some(upload("nearest-nodes", bytemuck::cast_slice(&nodes)));
384        target.upload_transfers.record(TransferDirection::HostToDevice, point_bytes + node_bytes);
385        target.upload_transfers.record(TransferDirection::DeviceToDevice, point_bytes);
386        Ok((target, queries, samples))
387    }
388
389    /// Bytes transferred when this target was explicitly uploaded.
390    #[must_use]
391    pub fn upload_transfers(&self) -> TransferStats {
392        self.upload_transfers
393    }
394
395    /// Explicitly uploads queries and downloads one optional nearest result per
396    /// query, in input order, using an inclusive squared-distance gate.
397    /// Negative/NaN gates and nonfinite queries produce None as on CPU; positive
398    /// infinity is unbounded. Finite target coordinates are required at upload.
399    /// GPU f32 arithmetic can differ near rounding/underflow boundaries across
400    /// backends. Equal computed distances retain CPU near-first traversal ties.
401    /// Accounting is 16 query bytes uploaded and 8 result bytes downloaded per
402    /// query (uniform controls excluded); empty/invalid-gate calls copy no data.
403    /// This synchronous API waits for completion, including the readback.
404    pub fn nearest_one_within_download(
405        &self,
406        runtime: &WgpuRuntime,
407        queries: &[[f32; 3]],
408        bound: f32,
409    ) -> SpatialResult<(Vec<Option<Neighbor>>, TransferStats)> {
410        if !Arc::ptr_eq(&self.identity, &runtime.profiling_identity()) {
411            return Err(invalid());
412        }
413        let limits = runtime.device().limits();
414        let query_bytes = buffer_bytes(queries.len() as u64, 16, &limits)?;
415        let result_bytes = buffer_bytes(queries.len() as u64, 8, &limits)?;
416        check_compute(&limits, queries.len() as u64)?;
417        let mut transfers = TransferStats::default();
418        if queries.is_empty() || self.root.is_none() || bound.is_nan() || bound < 0.0 {
419            return Ok((vec![None; queries.len()], transfers));
420        }
421        let packed: Vec<[f32; 4]> = queries.iter().map(|p| [p[0], p[1], p[2], 0.0]).collect();
422        let mut scratch = ScratchBuffers::new(runtime);
423        let query_buffer = scratch.acquire("nearest-queries", query_bytes);
424        runtime.queue().write_buffer(&query_buffer, 0, bytemuck::cast_slice(&packed));
425        let output = scratch.acquire("nearest-output", result_bytes);
426        let params =
427            Params { count: queries.len() as u32, root: self.root.unwrap(), bound, unused: 0 };
428        let uniform = runtime.device().create_buffer_init(&wgpu::util::BufferInitDescriptor {
429            label: Some("nearest-params"),
430            contents: bytemuck::bytes_of(&params),
431            usage: wgpu::BufferUsages::UNIFORM,
432        });
433        let cache = runtime.nearest_pipeline.get_or_init(|| NearestPipeline::new(runtime.device()));
434        let buffers = [
435            &uniform,
436            self.nodes.as_ref().unwrap(),
437            self.points.as_ref().unwrap(),
438            &query_buffer,
439            &output,
440        ];
441        let entries: Vec<_> = buffers
442            .iter()
443            .enumerate()
444            .map(|(i, b)| wgpu::BindGroupEntry {
445                binding: i as u32,
446                resource: b.as_entire_binding(),
447            })
448            .collect();
449        let group = runtime.device().create_bind_group(&wgpu::BindGroupDescriptor {
450            label: Some("nearest-bindings"),
451            layout: &cache.layout,
452            entries: &entries,
453        });
454        let staging = runtime.device().create_buffer(&wgpu::BufferDescriptor {
455            label: Some("nearest-readback"),
456            size: result_bytes,
457            usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
458            mapped_at_creation: false,
459        });
460        let mut encoder = runtime.device().create_command_encoder(&Default::default());
461        {
462            let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
463                label: Some("nearest"),
464                timestamp_writes: None,
465            });
466            pass.set_pipeline(&cache.pipeline);
467            pass.set_bind_group(0, &group, &[]);
468            pass.dispatch_workgroups(params.count.div_ceil(64), 1, 1);
469        }
470        encoder.copy_buffer_to_buffer(&output, 0, &staging, 0, result_bytes);
471        scratch.submit_and_recycle(encoder);
472        let slice = staging.slice(..);
473        let (sender, receiver) = std::sync::mpsc::channel();
474        slice.map_async(wgpu::MapMode::Read, move |result| {
475            let _ = sender.send(result);
476        });
477        runtime.device().poll(wgpu::Maintain::Wait);
478        receiver
479            .recv()
480            .map_err(|e| SpatialError::InvalidArgument(e.to_string()))?
481            .map_err(|e| SpatialError::InvalidArgument(e.to_string()))?;
482        let mapped = slice.get_mapped_range();
483        let neighbors = bytemuck::cast_slice::<u8, [u32; 2]>(&mapped)
484            .iter()
485            .map(|word| {
486                (word[0] != u32::MAX).then(|| Neighbor {
487                    index: word[0] as usize,
488                    distance_squared: f32::from_bits(word[1]),
489                })
490            })
491            .collect();
492        drop(mapped);
493        staging.unmap();
494        transfers.record(TransferDirection::HostToDevice, query_bytes);
495        transfers.record(TransferDirection::DeviceToHost, result_bytes);
496        Ok((neighbors, transfers))
497    }
498}
499
500#[cfg(all(test, not(target_arch = "wasm32")))]
501#[path = "nearest_tests.rs"]
502mod tests;