Skip to main content

spatialrust_gpu/kernels/
normals.rs

1use bytemuck::{Pod, Zeroable};
2use spatialrust_core::{SpatialError, SpatialResult};
3
4use super::point_estimators::{self, Kind};
5use crate::runtime::WgpuRuntime;
6
7#[repr(C)]
8#[derive(Clone, Copy, Debug, Pod, Zeroable)]
9struct NormalsUniform {
10    point_count: u32,
11    k: u32,
12    _pad0: u32,
13    _pad1: u32,
14}
15
16/// Per-point normal estimation output: `(nx, ny, nz, curvature)`.
17#[derive(Clone, Copy, Debug, Default)]
18pub struct GpuNormal {
19    /// Unit normal x/y/z.
20    pub normal: [f32; 3],
21    /// Surface variation curvature in `[0, 1/3]`.
22    pub curvature: f32,
23}
24
25pub(crate) const NORMALS_WGSL: &str = r#"
26struct Params { point_count: u32, k: u32, pad0: u32, pad1: u32, };
27
28@group(0) @binding(0) var<uniform> params: Params;
29@group(0) @binding(1) var<storage, read> xs: array<f32>;
30@group(0) @binding(2) var<storage, read> ys: array<f32>;
31@group(0) @binding(3) var<storage, read> zs: array<f32>;
32@group(0) @binding(4) var<storage, read> neighbors: array<u32>;
33@group(0) @binding(5) var<storage, read_write> out_normals: array<vec4<f32>>;
34
35fn rotate(a: ptr<function, array<vec3<f32>, 3>>,
36          v: ptr<function, array<vec3<f32>, 3>>,
37          p: u32, q: u32) {
38    let apq = (*a)[p][q];
39    if (abs(apq) < 1e-20) {
40        return;
41    }
42    let app = (*a)[p][p];
43    let aqq = (*a)[q][q];
44    let phi = 0.5 * (aqq - app) / apq;
45    var t: f32;
46    if (phi >= 0.0) {
47        t = 1.0 / (phi + sqrt(1.0 + phi * phi));
48    } else {
49        t = -1.0 / (-phi + sqrt(1.0 + phi * phi));
50    }
51    let c = 1.0 / sqrt(1.0 + t * t);
52    let s = t * c;
53
54    // Apply the Jacobi rotation to columns/rows p and q of the symmetric matrix.
55    for (var r: u32 = 0u; r < 3u; r = r + 1u) {
56        let arp = (*a)[r][p];
57        let arq = (*a)[r][q];
58        (*a)[r][p] = c * arp - s * arq;
59        (*a)[r][q] = s * arp + c * arq;
60    }
61    for (var r: u32 = 0u; r < 3u; r = r + 1u) {
62        let apr = (*a)[p][r];
63        let aqr = (*a)[q][r];
64        (*a)[p][r] = c * apr - s * aqr;
65        (*a)[q][r] = s * apr + c * aqr;
66    }
67    for (var r: u32 = 0u; r < 3u; r = r + 1u) {
68        let vrp = (*v)[r][p];
69        let vrq = (*v)[r][q];
70        (*v)[r][p] = c * vrp - s * vrq;
71        (*v)[r][q] = s * vrp + c * vrq;
72    }
73}
74
75@compute @workgroup_size(256)
76fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
77    let i = gid.x;
78    if (i >= params.point_count) {
79        return;
80    }
81    let k = params.k;
82    let base = i * k;
83
84    var mean = vec3<f32>(0.0, 0.0, 0.0);
85    var count = 0.0;
86    for (var j: u32 = 0u; j < k; j = j + 1u) {
87        let idx = neighbors[base + j];
88        mean = mean + vec3<f32>(xs[idx], ys[idx], zs[idx]);
89        count = count + 1.0;
90    }
91    if (count < 3.0) {
92        out_normals[i] = vec4<f32>(0.0, 0.0, 1.0, 0.0);
93        return;
94    }
95    mean = mean / count;
96
97    var c00 = 0.0; var c11 = 0.0; var c22 = 0.0;
98    var c01 = 0.0; var c02 = 0.0; var c12 = 0.0;
99    for (var j: u32 = 0u; j < k; j = j + 1u) {
100        let idx = neighbors[base + j];
101        let d = vec3<f32>(xs[idx], ys[idx], zs[idx]) - mean;
102        c00 = c00 + d.x * d.x;
103        c11 = c11 + d.y * d.y;
104        c22 = c22 + d.z * d.z;
105        c01 = c01 + d.x * d.y;
106        c02 = c02 + d.x * d.z;
107        c12 = c12 + d.y * d.z;
108    }
109
110    var a = array<vec3<f32>, 3>(
111        vec3<f32>(c00, c01, c02),
112        vec3<f32>(c01, c11, c12),
113        vec3<f32>(c02, c12, c22),
114    );
115    var v = array<vec3<f32>, 3>(
116        vec3<f32>(1.0, 0.0, 0.0),
117        vec3<f32>(0.0, 1.0, 0.0),
118        vec3<f32>(0.0, 0.0, 1.0),
119    );
120
121    for (var sweep: u32 = 0u; sweep < 16u; sweep = sweep + 1u) {
122        rotate(&a, &v, 0u, 1u);
123        rotate(&a, &v, 0u, 2u);
124        rotate(&a, &v, 1u, 2u);
125    }
126
127    let eig = vec3<f32>(a[0][0], a[1][1], a[2][2]);
128    var min_idx = 0u;
129    if (eig[1] < eig[min_idx]) { min_idx = 1u; }
130    if (eig[2] < eig[min_idx]) { min_idx = 2u; }
131
132    let normal = vec3<f32>(v[0][min_idx], v[1][min_idx], v[2][min_idx]);
133    let length = max(sqrt(dot(normal, normal)), 1e-20);
134    let unit = normal / length;
135
136    let trace = eig[0] + eig[1] + eig[2];
137    var curvature = 0.0;
138    if (trace > 0.0) {
139        curvature = eig[min_idx] / trace;
140    }
141
142    out_normals[i] = vec4<f32>(unit.x, unit.y, unit.z, curvature);
143}
144"#;
145
146/// Estimates per-point normals and curvature on the GPU.
147///
148/// `neighbors` is a flattened `point_count * k` array of indices into the point
149/// arrays, where row `i` lists the neighbors of point `i` (pad short rows by
150/// repeating the point's own index). Normal orientation is arbitrary (sign is
151/// not disambiguated); callers can flip toward a viewpoint on the CPU.
152pub fn estimate_normals_gpu(
153    runtime: &WgpuRuntime,
154    x: &[f32],
155    y: &[f32],
156    z: &[f32],
157    neighbors: &[u32],
158    k: u32,
159) -> SpatialResult<Vec<GpuNormal>> {
160    let point_count = x.len();
161    if y.len() != point_count {
162        return Err(SpatialError::BufferLengthMismatch { expected: point_count, found: y.len() });
163    }
164    if z.len() != point_count {
165        return Err(SpatialError::BufferLengthMismatch { expected: point_count, found: z.len() });
166    }
167    if point_count == 0 {
168        return Ok(Vec::new());
169    }
170    point_estimators::validate_knn(runtime, point_count, neighbors, k)?;
171    let params = NormalsUniform { point_count: point_count as u32, k, _pad0: 0, _pad1: 0 };
172    point_estimators::run(
173        runtime,
174        Kind::KnnNormals,
175        point_count,
176        bytemuck::bytes_of(&params),
177        &[
178            bytemuck::cast_slice(x),
179            bytemuck::cast_slice(y),
180            bytemuck::cast_slice(z),
181            bytemuck::cast_slice(neighbors),
182        ],
183        |rows| {
184            rows.iter().map(|r| GpuNormal { normal: [r[0], r[1], r[2]], curvature: r[3] }).collect()
185        },
186    )
187}
188
189#[cfg(test)]
190mod tests {
191    use super::estimate_normals_gpu;
192    use crate::runtime::WgpuRuntime;
193
194    #[test]
195    fn planar_patch_has_vertical_normal() {
196        let runtime = WgpuRuntime::new_headless().expect("wgpu runtime");
197        // 5x5 grid on the z=0 plane.
198        let mut x: Vec<f32> = Vec::new();
199        let mut y: Vec<f32> = Vec::new();
200        let mut z: Vec<f32> = Vec::new();
201        for i in 0..5 {
202            for j in 0..5 {
203                x.push(i as f32 * 0.1);
204                y.push(j as f32 * 0.1);
205                z.push(0.0);
206            }
207        }
208        let n = x.len();
209        let k = 8u32;
210
211        // Brute-force k nearest neighbors per point (CPU).
212        let mut neighbors = Vec::with_capacity(n * k as usize);
213        for i in 0..n {
214            let mut order: Vec<usize> = (0..n).collect();
215            order.sort_by(|&a, &b| {
216                let da = (x[a] - x[i]).powi(2) + (y[a] - y[i]).powi(2) + (z[a] - z[i]).powi(2);
217                let db = (x[b] - x[i]).powi(2) + (y[b] - y[i]).powi(2) + (z[b] - z[i]).powi(2);
218                da.total_cmp(&db)
219            });
220            for &idx in order.iter().take(k as usize) {
221                neighbors.push(idx as u32);
222            }
223        }
224
225        let normals =
226            estimate_normals_gpu(&runtime, &x, &y, &z, &neighbors, k).expect("gpu normals");
227        assert_eq!(normals.len(), n);
228        for normal in &normals {
229            // Normal should point along Z (up or down) and curvature ~0 on a plane.
230            assert!(normal.normal[2].abs() > 0.99, "normal not vertical: {:?}", normal.normal);
231            assert!(normal.curvature < 1e-3, "curvature too high: {}", normal.curvature);
232        }
233    }
234}