Skip to main content

spatialrust_gpu/aoso_staging/
voxel.rs

1use super::*;
2
3/// Computes voxel keys directly from uploaded interleaved XYZ chunks.
4///
5/// The returned outer vector preserves chunk boundaries and order. Positions
6/// stay in their existing GPU buffers; only the computed keys are read back.
7/// All chunks must use the same `origin` and `inv_leaf` so keys are globally
8/// comparable across chunk boundaries.
9pub fn compute_voxel_keys_aoso_chunks(
10    runtime: &WgpuRuntime,
11    chunks: &[GpuAoSoXyzChunk],
12    origin: [f32; 3],
13    inv_leaf: f32,
14) -> SpatialResult<Vec<Vec<(i64, i64, i64)>>> {
15    if !inv_leaf.is_finite() || inv_leaf <= 0.0 {
16        return Err(SpatialError::InvalidArgument(
17            "inverse voxel leaf size must be finite and positive".to_owned(),
18        ));
19    }
20
21    chunks
22        .iter()
23        .map(|chunk| compute_voxel_keys_aoso_chunk(runtime, chunk, origin, inv_leaf))
24        .collect()
25}
26
27/// Runs global voxel centroid downsampling from uploaded AoSoA chunks.
28///
29/// Chunk buffers are concatenated with GPU-to-GPU copies. Key generation,
30/// sorting, segmentation, and centroid reduction then operate on that combined
31/// GPU buffer, so voxels spanning chunk boundaries are merged correctly. The
32/// scalar cell count and final centroids are read back.
33pub fn downsample_voxel_centroid_aoso_chunks(
34    runtime: &WgpuRuntime,
35    chunks: &[GpuAoSoXyzChunk],
36    origin: [f32; 3],
37    inv_leaf: f32,
38) -> SpatialResult<AoSoAVoxelCentroidResult> {
39    let (positions, segments) =
40        build_voxel_segments_aoso_chunks(runtime, chunks, origin, inv_leaf)?;
41    let (out_x, out_y, out_z) =
42        reduce_voxel_centroids_aoso(runtime, positions.buffer(), &segments)?;
43    Ok(AoSoAVoxelCentroidResult { out_x, out_y, out_z, segments, positions })
44}
45
46/// Combines source positions and partitions them without reducing centroids.
47///
48/// Only the scalar cell count is read back; point and segment arrays stay on
49/// the device. The returned positions still represent every source point.
50pub(crate) fn build_voxel_segments_aoso_chunks(
51    runtime: &WgpuRuntime,
52    chunks: &[GpuAoSoXyzChunk],
53    origin: [f32; 3],
54    inv_leaf: f32,
55) -> SpatialResult<(GpuAoSoXyzBuffer, GpuVoxelSegments)> {
56    build_voxel_segments_aoso_chunks_with_profiler(runtime, chunks, origin, inv_leaf, None)
57}
58
59pub(crate) fn build_voxel_segments_aoso_chunks_with_profiler(
60    runtime: &WgpuRuntime,
61    chunks: &[GpuAoSoXyzChunk],
62    origin: [f32; 3],
63    inv_leaf: f32,
64    mut profiler: Option<&mut crate::GpuStageProfiler>,
65) -> SpatialResult<(GpuAoSoXyzBuffer, GpuVoxelSegments)> {
66    if !inv_leaf.is_finite() || inv_leaf <= 0.0 {
67        return Err(SpatialError::InvalidArgument(
68            "inverse voxel leaf size must be finite and positive".to_owned(),
69        ));
70    }
71    let total_points = chunks.iter().try_fold(0usize, |total, chunk| {
72        total
73            .checked_add(chunk.point_count)
74            .ok_or_else(|| SpatialError::InvalidArgument("AoSoA point count overflow".to_owned()))
75    })?;
76    if total_points == 0 {
77        return Ok((
78            empty_aoso_buffer(runtime),
79            build_voxel_segments_gpu_from_keys_buffer(
80                runtime,
81                &empty_storage_buffer(runtime),
82                0,
83                1,
84            )?,
85        ));
86    }
87    let point_count = u32::try_from(total_points).map_err(|_| {
88        SpatialError::InvalidArgument("AoSoA chunks exceed the GPU point limit".to_owned())
89    })?;
90    let positions = combine_aoso_chunks(runtime, chunks, total_points);
91    let keys = dispatch_voxel_keys_aoso_with_profiler(
92        runtime,
93        positions.buffer(),
94        point_count,
95        origin,
96        inv_leaf,
97        profiler.as_deref_mut(),
98    )?;
99    let segments = crate::kernels::build_voxel_segments_with_profiler(
100        runtime,
101        &keys,
102        point_count,
103        point_count,
104        profiler,
105    )?;
106    Ok((positions, segments))
107}
108
109fn empty_aoso_buffer(runtime: &WgpuRuntime) -> GpuAoSoXyzBuffer {
110    GpuAoSoXyzBuffer {
111        buffer: runtime.device().create_buffer(&wgpu::BufferDescriptor {
112            label: Some("aoso-empty-positions"),
113            size: 4,
114            usage: wgpu::BufferUsages::STORAGE
115                | wgpu::BufferUsages::COPY_DST
116                | wgpu::BufferUsages::COPY_SRC,
117            mapped_at_creation: false,
118        }),
119        point_count: 0,
120        device_key: runtime_device_key(runtime),
121    }
122}
123
124pub(super) fn empty_storage_buffer(runtime: &WgpuRuntime) -> Buffer {
125    runtime.device().create_buffer(&wgpu::BufferDescriptor {
126        label: Some("aoso-empty-storage"),
127        size: 4,
128        usage: wgpu::BufferUsages::STORAGE,
129        mapped_at_creation: false,
130    })
131}
132
133fn combine_aoso_chunks(
134    runtime: &WgpuRuntime,
135    chunks: &[GpuAoSoXyzChunk],
136    total_points: usize,
137) -> GpuAoSoXyzBuffer {
138    let device = runtime.device();
139    let combined = device.create_buffer(&wgpu::BufferDescriptor {
140        label: Some("aoso-xyz-combined"),
141        size: (total_points * 3 * std::mem::size_of::<f32>()) as u64,
142        usage: wgpu::BufferUsages::STORAGE
143            | wgpu::BufferUsages::COPY_DST
144            | wgpu::BufferUsages::COPY_SRC,
145        mapped_at_creation: false,
146    });
147    let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
148        label: Some("aoso-combine-encoder"),
149    });
150    let mut offset = 0;
151    for chunk in chunks {
152        let bytes = (chunk.point_count * 3 * std::mem::size_of::<f32>()) as u64;
153        if bytes > 0 {
154            encoder.copy_buffer_to_buffer(&chunk.buffer, 0, &combined, offset, bytes);
155            offset += bytes;
156        }
157    }
158    runtime.queue().submit(Some(encoder.finish()));
159    GpuAoSoXyzBuffer {
160        buffer: combined,
161        point_count: total_points,
162        device_key: runtime_device_key(runtime),
163    }
164}
165
166pub(crate) fn dispatch_voxel_keys_aoso_with_profiler(
167    runtime: &WgpuRuntime,
168    positions: &Buffer,
169    point_count: u32,
170    origin: [f32; 3],
171    inv_leaf: f32,
172    mut profiler: Option<&mut crate::GpuStageProfiler>,
173) -> SpatialResult<Buffer> {
174    let device = runtime.device();
175    let uniform = VoxelKeyUniform {
176        origin: [origin[0], origin[1], origin[2], 0.0],
177        inv_leaf,
178        point_count,
179        _pad0: 0,
180        _pad1: 0,
181    };
182    let uniform_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
183        label: Some("voxel-key-aoso-uniform"),
184        contents: bytemuck::bytes_of(&uniform),
185        usage: wgpu::BufferUsages::UNIFORM,
186    });
187    let output = device.create_buffer(&wgpu::BufferDescriptor {
188        label: Some("voxel-key-aoso-output"),
189        size: u64::from(point_count) * std::mem::size_of::<VoxelKeyOutput>() as u64,
190        usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
191        mapped_at_creation: false,
192    });
193    let pipelines = runtime.pipelines();
194    let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
195        label: Some("voxel-key-aoso-bind-group"),
196        layout: &pipelines.voxel_keys_aoso.bind_group_layout,
197        entries: &[
198            wgpu::BindGroupEntry { binding: 0, resource: uniform_buffer.as_entire_binding() },
199            wgpu::BindGroupEntry { binding: 1, resource: positions.as_entire_binding() },
200            wgpu::BindGroupEntry { binding: 2, resource: output.as_entire_binding() },
201        ],
202    });
203    let mut encoder = device
204        .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("voxel-key-aoso") });
205    {
206        let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
207            label: Some("voxel-key-aoso-pass"),
208            timestamp_writes: crate::profiling::timestamp_writes(&mut profiler, "voxel-keys"),
209        });
210        pass.set_pipeline(&pipelines.voxel_keys_aoso.pipeline);
211        pass.set_bind_group(0, &bind_group, &[]);
212        pass.dispatch_workgroups(point_count.div_ceil(WORKGROUP_SIZE), 1, 1);
213    }
214    runtime.queue().submit(Some(encoder.finish()));
215    Ok(output)
216}
217
218fn reduce_voxel_centroids_aoso(
219    runtime: &WgpuRuntime,
220    positions: &Buffer,
221    segments: &GpuVoxelSegments,
222) -> SpatialResult<(Vec<f32>, Vec<f32>, Vec<f32>)> {
223    let cell_count = segments.cell_count();
224    if cell_count == 0 {
225        return Ok((Vec::new(), Vec::new(), Vec::new()));
226    }
227    let device = runtime.device();
228    let output_len = u64::from(cell_count) * std::mem::size_of::<[f32; 4]>() as u64;
229    let output = device.create_buffer(&wgpu::BufferDescriptor {
230        label: Some("voxel-reduce-aoso-output"),
231        size: output_len,
232        usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
233        mapped_at_creation: false,
234    });
235    let staging = device.create_buffer(&wgpu::BufferDescriptor {
236        label: Some("voxel-reduce-aoso-staging"),
237        size: output_len,
238        usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
239        mapped_at_creation: false,
240    });
241    let uniform =
242        VoxelReduceUniform { cell_count, point_count: segments.point_count(), _pad0: 0, _pad1: 0 };
243    let uniform_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
244        label: Some("voxel-reduce-aoso-uniform"),
245        contents: bytemuck::bytes_of(&uniform),
246        usage: wgpu::BufferUsages::UNIFORM,
247    });
248    let pipelines = runtime.pipelines();
249    let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
250        label: Some("voxel-reduce-aoso-bind-group"),
251        layout: &pipelines.voxel_reduce_aoso.bind_group_layout,
252        entries: &[
253            wgpu::BindGroupEntry { binding: 0, resource: uniform_buffer.as_entire_binding() },
254            wgpu::BindGroupEntry {
255                binding: 1,
256                resource: segments.point_indices_buffer().as_entire_binding(),
257            },
258            wgpu::BindGroupEntry {
259                binding: 2,
260                resource: segments.cell_starts_buffer().as_entire_binding(),
261            },
262            wgpu::BindGroupEntry { binding: 3, resource: positions.as_entire_binding() },
263            wgpu::BindGroupEntry { binding: 4, resource: output.as_entire_binding() },
264        ],
265    });
266    let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
267        label: Some("voxel-reduce-aoso-encoder"),
268    });
269    {
270        let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
271            label: Some("voxel-reduce-aoso-pass"),
272            timestamp_writes: None,
273        });
274        pass.set_pipeline(&pipelines.voxel_reduce_aoso.pipeline);
275        pass.set_bind_group(0, &bind_group, &[]);
276        pass.dispatch_workgroups(cell_count.div_ceil(WORKGROUP_SIZE), 1, 1);
277    }
278    encoder.copy_buffer_to_buffer(&output, 0, &staging, 0, output_len);
279    runtime.queue().submit(Some(encoder.finish()));
280    let slice = staging.slice(..);
281    let (sender, receiver) = std::sync::mpsc::channel();
282    slice.map_async(wgpu::MapMode::Read, move |result| {
283        let _ = sender.send(result);
284    });
285    device.poll(wgpu::Maintain::Wait);
286    receiver
287        .recv()
288        .map_err(|_| SpatialError::InvalidArgument("failed to receive wgpu map result".to_owned()))?
289        .map_err(|error| {
290            SpatialError::InvalidArgument(format!("failed to map wgpu buffer: {error}"))
291        })?;
292    let data = slice.get_mapped_range();
293    let centroids: &[[f32; 4]] = bytemuck::cast_slice(&data);
294    let mut out_x = Vec::with_capacity(centroids.len());
295    let mut out_y = Vec::with_capacity(centroids.len());
296    let mut out_z = Vec::with_capacity(centroids.len());
297    for centroid in centroids {
298        out_x.push(centroid[0]);
299        out_y.push(centroid[1]);
300        out_z.push(centroid[2]);
301    }
302    drop(data);
303    staging.unmap();
304    Ok((out_x, out_y, out_z))
305}
306
307fn compute_voxel_keys_aoso_chunk(
308    runtime: &WgpuRuntime,
309    chunk: &GpuAoSoXyzChunk,
310    origin: [f32; 3],
311    inv_leaf: f32,
312) -> SpatialResult<Vec<(i64, i64, i64)>> {
313    if chunk.point_count == 0 {
314        return Ok(Vec::new());
315    }
316    let point_count = u32::try_from(chunk.point_count).map_err(|_| {
317        SpatialError::InvalidArgument("AoSoA chunk exceeds the GPU point limit".to_owned())
318    })?;
319    let device = runtime.device();
320    let queue = runtime.queue();
321    let uniform = VoxelKeyUniform {
322        origin: [origin[0], origin[1], origin[2], 0.0],
323        inv_leaf,
324        point_count,
325        _pad0: 0,
326        _pad1: 0,
327    };
328    let uniform_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
329        label: Some("voxel-key-aoso-uniform"),
330        contents: bytemuck::bytes_of(&uniform),
331        usage: wgpu::BufferUsages::UNIFORM,
332    });
333    let output_len = chunk.point_count * std::mem::size_of::<VoxelKeyOutput>();
334    let output_buffer = device.create_buffer(&wgpu::BufferDescriptor {
335        label: Some("voxel-key-aoso-output"),
336        size: output_len as u64,
337        usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
338        mapped_at_creation: false,
339    });
340    let staging_buffer = device.create_buffer(&wgpu::BufferDescriptor {
341        label: Some("voxel-key-aoso-staging"),
342        size: output_len as u64,
343        usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
344        mapped_at_creation: false,
345    });
346    let pipelines = runtime.pipelines();
347    let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
348        label: Some("voxel-key-aoso-bind-group"),
349        layout: &pipelines.voxel_keys_aoso.bind_group_layout,
350        entries: &[
351            wgpu::BindGroupEntry { binding: 0, resource: uniform_buffer.as_entire_binding() },
352            wgpu::BindGroupEntry { binding: 1, resource: chunk.buffer.as_entire_binding() },
353            wgpu::BindGroupEntry { binding: 2, resource: output_buffer.as_entire_binding() },
354        ],
355    });
356    let mut encoder = device
357        .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("voxel-key-aoso") });
358    {
359        let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
360            label: Some("voxel-key-aoso-pass"),
361            timestamp_writes: None,
362        });
363        pass.set_pipeline(&pipelines.voxel_keys_aoso.pipeline);
364        pass.set_bind_group(0, &bind_group, &[]);
365        pass.dispatch_workgroups(point_count.div_ceil(WORKGROUP_SIZE), 1, 1);
366    }
367    encoder.copy_buffer_to_buffer(&output_buffer, 0, &staging_buffer, 0, output_len as u64);
368    queue.submit(Some(encoder.finish()));
369
370    let slice = staging_buffer.slice(..);
371    let (sender, receiver) = std::sync::mpsc::channel();
372    slice.map_async(wgpu::MapMode::Read, move |result| {
373        let _ = sender.send(result);
374    });
375    device.poll(wgpu::Maintain::Wait);
376    receiver
377        .recv()
378        .map_err(|_| SpatialError::InvalidArgument("failed to receive wgpu map result".to_owned()))?
379        .map_err(|error| {
380            SpatialError::InvalidArgument(format!("failed to map wgpu buffer: {error}"))
381        })?;
382    let data = slice.get_mapped_range();
383    let keys = bytemuck::cast_slice::<u8, VoxelKeyOutput>(&data)
384        .iter()
385        .map(|key| (i64::from(key.ix), i64::from(key.iy), i64::from(key.iz)))
386        .collect();
387    drop(data);
388    staging_buffer.unmap();
389    Ok(keys)
390}