Skip to main content

spatialrust_gpu/aoso_staging/
normals.rs

1use super::voxel::empty_storage_buffer;
2use super::*;
3
4/// Estimates normals directly from a retained interleaved XYZ GPU buffer.
5///
6/// `neighbors` is a global flattened `point_count * k` index array. Position
7/// data remains GPU-resident; only neighbor indices are uploaded. The returned
8/// normal buffer stays on the GPU until [`GpuAoSoNormals::readback`] is called.
9pub fn estimate_normals_aoso_gpu(
10    runtime: &WgpuRuntime,
11    positions: &GpuAoSoXyzBuffer,
12    neighbors: &[u32],
13    k: u32,
14) -> SpatialResult<GpuAoSoNormals> {
15    let point_count = positions.point_count;
16    if k == 0 || neighbors.len() != point_count * k as usize {
17        return Err(SpatialError::InvalidArgument(format!(
18            "neighbors must have point_count*k = {} entries, got {}",
19            point_count * k as usize,
20            neighbors.len()
21        )));
22    }
23    let device = runtime.device();
24    if point_count == 0 {
25        return Ok(GpuAoSoNormals {
26            buffer: device.create_buffer(&wgpu::BufferDescriptor {
27                label: Some("normals-aoso-empty"),
28                size: 4,
29                usage: wgpu::BufferUsages::STORAGE
30                    | wgpu::BufferUsages::COPY_SRC
31                    | wgpu::BufferUsages::COPY_DST,
32                mapped_at_creation: false,
33            }),
34            point_count: 0,
35            device_key: runtime_device_key(runtime),
36        });
37    }
38    let point_count_u32 = u32::try_from(point_count).map_err(|_| {
39        SpatialError::InvalidArgument("AoSoA positions exceed the GPU point limit".to_owned())
40    })?;
41    let neighbor_buffer = runtime.upload_u32_storage("normals-aoso-neighbors", neighbors)?;
42    let uniform = AoSoANormalsUniform { point_count: point_count_u32, k, _pad0: 0, _pad1: 0 };
43    let uniform_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
44        label: Some("normals-aoso-uniform"),
45        contents: bytemuck::bytes_of(&uniform),
46        usage: wgpu::BufferUsages::UNIFORM,
47    });
48    let output = device.create_buffer(&wgpu::BufferDescriptor {
49        label: Some("normals-aoso-output"),
50        size: (point_count * std::mem::size_of::<[f32; 4]>()) as u64,
51        usage: wgpu::BufferUsages::STORAGE
52            | wgpu::BufferUsages::COPY_SRC
53            | wgpu::BufferUsages::COPY_DST,
54        mapped_at_creation: false,
55    });
56    let shader_source = crate::kernels::NORMALS_WGSL
57        .replace(
58            "@group(0) @binding(1) var<storage, read> xs: array<f32>;\n@group(0) @binding(2) var<storage, read> ys: array<f32>;\n@group(0) @binding(3) var<storage, read> zs: array<f32>;",
59            "@group(0) @binding(1) var<storage, read> positions: array<f32>;",
60        )
61        .replace("xs[idx]", "positions[idx * 3u]")
62        .replace("ys[idx]", "positions[idx * 3u + 1u]")
63        .replace("zs[idx]", "positions[idx * 3u + 2u]");
64    let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
65        label: Some("normals-aoso-shader"),
66        source: wgpu::ShaderSource::Wgsl(shader_source.into()),
67    });
68    let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
69        label: Some("normals-aoso-pipeline"),
70        layout: None,
71        module: &module,
72        entry_point: Some("main"),
73        compilation_options: wgpu::PipelineCompilationOptions::default(),
74        cache: None,
75    });
76    let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
77        label: Some("normals-aoso-bind-group"),
78        layout: &pipeline.get_bind_group_layout(0),
79        entries: &[
80            wgpu::BindGroupEntry { binding: 0, resource: uniform_buffer.as_entire_binding() },
81            wgpu::BindGroupEntry { binding: 1, resource: positions.buffer.as_entire_binding() },
82            wgpu::BindGroupEntry { binding: 4, resource: neighbor_buffer.as_entire_binding() },
83            wgpu::BindGroupEntry { binding: 5, resource: output.as_entire_binding() },
84        ],
85    });
86    let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
87        label: Some("normals-aoso-encoder"),
88    });
89    {
90        let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
91            label: Some("normals-aoso-pass"),
92            timestamp_writes: None,
93        });
94        pass.set_pipeline(&pipeline);
95        pass.set_bind_group(0, &bind_group, &[]);
96        pass.dispatch_workgroups(point_count_u32.div_ceil(WORKGROUP_SIZE), 1, 1);
97    }
98    runtime.queue().submit(Some(encoder.finish()));
99    Ok(GpuAoSoNormals { buffer: output, point_count, device_key: runtime_device_key(runtime) })
100}
101
102/// Builds a sparse uniform radius grid directly from retained AoSoA positions.
103///
104/// Cell keys, sorting, and segment compaction stay on the GPU. Grid keys use a
105/// zero origin and `floor(position / radius)`; negative coordinates therefore
106/// remain valid without requiring CPU-side bounds discovery.
107pub fn build_radius_grid_aoso_gpu(
108    runtime: &WgpuRuntime,
109    positions: &GpuAoSoXyzBuffer,
110    radius: f32,
111) -> SpatialResult<GpuAoSoRadiusGrid> {
112    build_radius_grid_aoso_gpu_with_profiler(runtime, positions, radius, None)
113}
114
115pub(crate) fn build_radius_grid_aoso_gpu_with_profiler(
116    runtime: &WgpuRuntime,
117    positions: &GpuAoSoXyzBuffer,
118    radius: f32,
119    mut profiler: Option<&mut crate::GpuStageProfiler>,
120) -> SpatialResult<GpuAoSoRadiusGrid> {
121    if !radius.is_finite() || radius <= 0.0 {
122        return Err(SpatialError::InvalidArgument(
123            "grid radius must be finite and positive".to_owned(),
124        ));
125    }
126    let point_count = u32::try_from(positions.point_count).map_err(|_| {
127        SpatialError::InvalidArgument("AoSoA positions exceed the GPU point limit".to_owned())
128    })?;
129    let empty = empty_storage_buffer(runtime);
130    let segments = if point_count == 0 {
131        build_voxel_segments_gpu_from_keys_buffer(runtime, &empty, 0, 1)?
132    } else {
133        let keys = super::voxel::dispatch_voxel_keys_aoso_with_profiler(
134            runtime,
135            positions.buffer(),
136            point_count,
137            [0.0; 3],
138            1.0 / radius,
139            profiler.as_deref_mut(),
140        )?;
141        crate::kernels::build_voxel_segments_with_profiler(
142            runtime,
143            &keys,
144            point_count,
145            point_count.next_power_of_two(),
146            profiler,
147        )?
148    };
149    Ok(GpuAoSoRadiusGrid { radius, segments })
150}
151
152/// Estimates radius normals directly from a GPU-resident sparse AoSoA grid.
153pub fn estimate_normals_radius_grid_aoso_gpu(
154    runtime: &WgpuRuntime,
155    positions: &GpuAoSoXyzBuffer,
156    grid: &GpuAoSoRadiusGrid,
157) -> SpatialResult<GpuAoSoNormals> {
158    estimate_normals_radius_grid_aoso_gpu_with_profiler(runtime, positions, grid, None)
159}
160
161pub(crate) fn estimate_normals_radius_grid_aoso_gpu_with_profiler(
162    runtime: &WgpuRuntime,
163    positions: &GpuAoSoXyzBuffer,
164    grid: &GpuAoSoRadiusGrid,
165    mut profiler: Option<&mut crate::GpuStageProfiler>,
166) -> SpatialResult<GpuAoSoNormals> {
167    let point_count = u32::try_from(positions.point_count).map_err(|_| {
168        SpatialError::InvalidArgument("AoSoA positions exceed the GPU point limit".to_owned())
169    })?;
170    if grid.segments.point_count() != point_count {
171        return Err(SpatialError::BufferLengthMismatch {
172            expected: point_count as usize,
173            found: grid.segments.point_count() as usize,
174        });
175    }
176    if point_count == 0 {
177        return estimate_normals_aoso_gpu(runtime, positions, &[], 1);
178    }
179    let device = runtime.device();
180    let uniform = SparseGridNormalsUniform {
181        origin: [0.0; 4],
182        dims: [grid.segments.cell_count(), 0, 0, point_count],
183        inv_cell: 1.0 / grid.radius,
184        radius_sq: grid.radius * grid.radius,
185        _pad0: 0.0,
186        _pad1: 0.0,
187    };
188    let uniform_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
189        label: Some("normals-radius-aoso-uniform"),
190        contents: bytemuck::bytes_of(&uniform),
191        usage: wgpu::BufferUsages::UNIFORM,
192    });
193    let output = device.create_buffer(&wgpu::BufferDescriptor {
194        label: Some("normals-radius-aoso-output"),
195        size: u64::from(point_count) * std::mem::size_of::<[f32; 4]>() as u64,
196        usage: wgpu::BufferUsages::STORAGE
197            | wgpu::BufferUsages::COPY_SRC
198            | wgpu::BufferUsages::COPY_DST,
199        mapped_at_creation: false,
200    });
201    let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
202        label: Some("normals-radius-aoso-shader"),
203        source: wgpu::ShaderSource::Wgsl(sparse_grid_normals_shader().into()),
204    });
205    let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
206        label: Some("normals-radius-aoso-pipeline"),
207        layout: None,
208        module: &module,
209        entry_point: Some("main"),
210        compilation_options: wgpu::PipelineCompilationOptions::default(),
211        cache: None,
212    });
213    let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
214        label: Some("normals-radius-aoso-bind-group"),
215        layout: &pipeline.get_bind_group_layout(0),
216        entries: &[
217            wgpu::BindGroupEntry { binding: 0, resource: uniform_buffer.as_entire_binding() },
218            wgpu::BindGroupEntry { binding: 1, resource: positions.buffer.as_entire_binding() },
219            wgpu::BindGroupEntry {
220                binding: 2,
221                resource: grid.segments.keys_buffer().as_entire_binding(),
222            },
223            wgpu::BindGroupEntry {
224                binding: 3,
225                resource: grid.segments.point_indices_buffer().as_entire_binding(),
226            },
227            wgpu::BindGroupEntry {
228                binding: 4,
229                resource: grid.segments.cell_starts_buffer().as_entire_binding(),
230            },
231            wgpu::BindGroupEntry { binding: 5, resource: output.as_entire_binding() },
232        ],
233    });
234    let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
235        label: Some("normals-radius-aoso-encoder"),
236    });
237    {
238        let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
239            label: Some("normals-radius-aoso-pass"),
240            timestamp_writes: crate::profiling::timestamp_writes(&mut profiler, "radius-normals"),
241        });
242        pass.set_pipeline(&pipeline);
243        pass.set_bind_group(0, &bind_group, &[]);
244        pass.dispatch_workgroups(point_count.div_ceil(WORKGROUP_SIZE), 1, 1);
245    }
246    runtime.queue().submit(Some(encoder.finish()));
247    Ok(GpuAoSoNormals {
248        buffer: output,
249        point_count: point_count as usize,
250        device_key: runtime_device_key(runtime),
251    })
252}
253
254// Sparse keys use a different ordering and lookup than dense CSR cell rows.
255// Keep this shader independent of dense traversal changes.
256fn sparse_grid_normals_shader() -> &'static str {
257    include_str!("sparse_radius_normals.wgsl")
258}
259
260#[cfg(all(test, not(target_arch = "wasm32")))]
261#[path = "sparse_radius_shader_tests.rs"]
262mod shader_tests;