1use crate::device::workgroup_grid;
4use crate::spatial::{vec4, GpuKdTree, KD_TREE_WGSL, MAX_K};
5use crate::GpuContext;
6use bytemuck::{Pod, Zeroable};
7use rayon::prelude::*;
8use threecrate_algorithms::KdTree;
9use threecrate_core::{NormalPoint3f, Point3f, PointCloud, Result};
10
11fn normals_shader() -> String {
16 format!(
17 "{}{}",
18 KD_TREE_WGSL,
19 r#"
20struct NormalParams {
21 num_points: u32,
22 k: u32,
23 consistent_orientation: u32,
24 _pad: u32,
25 viewpoint: vec4<f32>,
26}
27
28@group(0) @binding(2) var<storage, read_write> output_normals: array<vec4<f32>>;
29@group(0) @binding(3) var<uniform> params: NormalParams;
30
31// Eigenvector for the smallest eigenvalue of the symmetric matrix
32// [[a00 a01 a02] [a01 a11 a12] [a02 a12 a22]], via the closed-form
33// (trigonometric) eigenvalues and a cross product of two rows of A - lambda*I.
34fn smallest_eigenvector(c00: f32, c01: f32, c02: f32, c11: f32, c12: f32, c22: f32) -> vec3<f32> {
35 // Scale to unit size so f32 keeps its precision for tiny or huge clouds.
36 let scale = max(max(max(abs(c00), abs(c01)), max(abs(c02), abs(c11))), max(abs(c12), abs(c22)));
37 if (scale <= 0.0) {
38 return vec3<f32>(0.0, 0.0, 1.0);
39 }
40 let a00 = c00 / scale;
41 let a01 = c01 / scale;
42 let a02 = c02 / scale;
43 let a11 = c11 / scale;
44 let a12 = c12 / scale;
45 let a22 = c22 / scale;
46
47 let p1 = a01 * a01 + a02 * a02 + a12 * a12;
48 let q = (a00 + a11 + a22) / 3.0;
49 let b00 = a00 - q;
50 let b11 = a11 - q;
51 let b22 = a22 - q;
52 let p2 = b00 * b00 + b11 * b11 + b22 * b22 + 2.0 * p1;
53 if (p2 < 1e-12) {
54 // All eigenvalues equal: no preferred direction.
55 return vec3<f32>(0.0, 0.0, 1.0);
56 }
57 let p = sqrt(p2 / 6.0);
58 let det_b = b00 * (b11 * b22 - a12 * a12) - a01 * (a01 * b22 - a12 * a02) + a02 * (a01 * a12 - b11 * a02);
59 let r = clamp(det_b / (2.0 * p * p * p), -1.0, 1.0);
60 let phi = acos(r) / 3.0;
61 // Eigenvalues are q + 2p cos(phi + 2 pi j / 3); j = 1 gives the smallest.
62 let lambda = q + 2.0 * p * cos(phi + 2.0943951);
63
64 let r0 = vec3<f32>(a00 - lambda, a01, a02);
65 let r1 = vec3<f32>(a01, a11 - lambda, a12);
66 let r2 = vec3<f32>(a02, a12, a22 - lambda);
67 let x01 = cross(r0, r1);
68 let x02 = cross(r0, r2);
69 let x12 = cross(r1, r2);
70 let d01 = dot(x01, x01);
71 let d02 = dot(x02, x02);
72 let d12 = dot(x12, x12);
73 var best = x01;
74 var best_len = d01;
75 if (d02 > best_len) {
76 best = x02;
77 best_len = d02;
78 }
79 if (d12 > best_len) {
80 best = x12;
81 best_len = d12;
82 }
83 if (best_len < 1e-20) {
84 // Two smallest eigenvalues equal (points on a line): any perpendicular works.
85 return vec3<f32>(0.0, 0.0, 1.0);
86 }
87 return best / sqrt(best_len);
88}
89
90@compute @workgroup_size(64)
91fn normals(@builtin(global_invocation_id) gid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {
92 // One thread per tree node rather than per input point: nodes are stored
93 // in tree order, so neighboring threads search neighboring parts of the
94 // cloud, which keeps them in step and their memory reads cached.
95 let node_id = gid.x + gid.y * nwg.x * 64u;
96 if (node_id >= arrayLength(&nodes) || node_id >= params.num_points) {
97 return;
98 }
99 let index = nodes[node_id].index;
100 let center = nodes[node_id].pos;
101
102 // k + 1 so the point itself (distance 0) can be dropped and still leave k.
103 find_k_nearest(center, params.k + 1u, 3.4e38);
104
105 // Neighborhood = up to k neighbors other than the point, plus the point.
106 var sum = center;
107 var count = 1u;
108 for (var i = 0u; i < knn_count; i++) {
109 let node = nodes[knn_node[i]];
110 if (node.index != index && count <= params.k) {
111 sum += node.pos;
112 count += 1u;
113 }
114 }
115 if (count < 4u) {
116 output_normals[index] = vec4<f32>(0.0, 0.0, 1.0, 0.0);
117 return;
118 }
119 let centroid = sum / f32(count);
120
121 let dc = center - centroid;
122 var c00 = dc.x * dc.x;
123 var c01 = dc.x * dc.y;
124 var c02 = dc.x * dc.z;
125 var c11 = dc.y * dc.y;
126 var c12 = dc.y * dc.z;
127 var c22 = dc.z * dc.z;
128 var used = 1u;
129 for (var i = 0u; i < knn_count; i++) {
130 let node = nodes[knn_node[i]];
131 if (node.index != index && used <= params.k) {
132 let d = node.pos - centroid;
133 c00 += d.x * d.x;
134 c01 += d.x * d.y;
135 c02 += d.x * d.z;
136 c11 += d.y * d.y;
137 c12 += d.y * d.z;
138 c22 += d.z * d.z;
139 used += 1u;
140 }
141 }
142
143 var normal = smallest_eigenvector(c00, c01, c02, c11, c12, c22);
144 if (params.consistent_orientation == 1u) {
145 let to_view = params.viewpoint.xyz - center;
146 if (dot(normal, to_view) < 0.0) {
147 normal = -normal;
148 }
149 }
150 output_normals[index] = vec4<f32>(normal, 0.0);
151}
152"#
153 )
154}
155
156#[repr(C)]
158#[derive(Copy, Clone, Pod, Zeroable)]
159struct NormalParams {
160 num_points: u32,
161 k: u32,
162 consistent_orientation: u32,
163 _pad: u32,
164 viewpoint: [f32; 4],
165}
166
167impl GpuContext {
168 pub async fn compute_normals_with_options(
175 &self,
176 points: &[Point3f],
177 k_neighbors: usize,
178 consistent_orientation: bool,
179 viewpoint: Option<[f32; 3]>,
180 ) -> Result<Vec<nalgebra::Vector3<f32>>> {
181 if points.is_empty() {
182 return Ok(Vec::new());
183 }
184 let k = k_neighbors.clamp(3, MAX_K - 1);
185
186 let tree = GpuKdTree::new(self, points)?;
187 if tree.is_empty() {
188 return Ok(vec![nalgebra::Vector3::z(); points.len()]);
189 }
190 let frame = tree.frame;
191
192 let viewpoint = viewpoint.unwrap_or_else(|| {
195 let (min, max) =
196 points
197 .iter()
198 .fold(([f32::MAX; 3], [f32::MIN; 3]), |(mut lo, mut hi), p| {
199 for i in 0..3 {
200 lo[i] = lo[i].min(p[i]);
201 hi[i] = hi[i].max(p[i]);
202 }
203 (lo, hi)
204 });
205 let extent =
206 ((max[0] - min[0]).powi(2) + (max[1] - min[1]).powi(2) + (max[2] - min[2]).powi(2))
207 .sqrt();
208 [
209 (min[0] + max[0]) * 0.5,
210 (min[1] + max[1]) * 0.5,
211 (min[2] + max[2]) * 0.5 + extent,
212 ]
213 });
214
215 let output = self.create_buffer_init(
218 "Normals Output",
219 &vec![[0.0f32, 0.0, 1.0, 0.0]; points.len()],
220 wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
221 );
222 let params = NormalParams {
223 num_points: tree.node_to_index.len() as u32,
225 k: k as u32,
226 consistent_orientation: consistent_orientation as u32,
227 _pad: 0,
228 viewpoint: vec4(&frame.point_to_local(&Point3f::from(viewpoint))),
229 };
230 let params_buffer =
231 self.create_buffer_init("Normals Params", &[params], wgpu::BufferUsages::UNIFORM);
232
233 let pipeline = self.cached_pipeline(
234 &self.pipelines.normals,
235 "Normals",
236 normals_shader,
237 "normals",
238 );
239 let bind_group = self.create_bind_group(
240 "Normals",
241 &pipeline.get_bind_group_layout(0),
242 &[
243 wgpu::BindGroupEntry {
244 binding: 0,
245 resource: tree.nodes.as_entire_binding(),
246 },
247 wgpu::BindGroupEntry {
248 binding: 2,
249 resource: output.as_entire_binding(),
250 },
251 wgpu::BindGroupEntry {
252 binding: 3,
253 resource: params_buffer.as_entire_binding(),
254 },
255 ],
256 );
257
258 let mut encoder = self
259 .device
260 .create_command_encoder(&wgpu::CommandEncoderDescriptor {
261 label: Some("Normals"),
262 });
263 {
264 let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
265 label: Some("Normals"),
266 timestamp_writes: None,
267 });
268 pass.set_pipeline(pipeline);
269 pass.set_bind_group(0, &bind_group, &[]);
270 let (x, y) = workgroup_grid(tree.node_to_index.len().div_ceil(64));
271 pass.dispatch_workgroups(x, y, 1);
272 }
273 self.queue.submit(std::iter::once(encoder.finish()));
274
275 let normals: Vec<[f32; 4]> = self.read_buffer(&output)?;
276 Ok(normals
277 .into_iter()
278 .map(|n| nalgebra::Vector3::new(n[0], n[1], n[2]))
279 .collect())
280 }
281
282 pub async fn compute_normals(
284 &self,
285 points: &[Point3f],
286 k_neighbors: usize,
287 ) -> Result<Vec<nalgebra::Vector3<f32>>> {
288 self.compute_normals_with_options(points, k_neighbors, true, None)
289 .await
290 }
291
292 pub fn compute_neighbors_simple(&self, points: &[[f32; 3]], k: usize) -> Vec<[u32; 64]> {
296 let k = k.min(64).min(points.len().saturating_sub(1));
297 if points.is_empty() {
298 return Vec::new();
299 }
300 let cloud: Vec<Point3f> = points
301 .iter()
302 .map(|p| Point3f::new(p[0], p[1], p[2]))
303 .collect();
304 let Ok(tree) = KdTree::new(&cloud) else {
305 return vec![[0; 64]; points.len()];
306 };
307
308 cloud
309 .par_iter()
310 .enumerate()
311 .map_init(Vec::new, |knn, (i, point)| {
312 tree.find_k_nearest_into(point, k + 1, knn);
313 let mut neighbors = [i as u32; 64];
314 let mut count = 0;
315 for &(index, _) in knn.iter() {
316 if index != i && count < k {
317 neighbors[count] = index as u32;
318 count += 1;
319 }
320 }
321 if count > 0 {
322 let last = neighbors[count - 1];
323 neighbors[count..].fill(last);
324 }
325 neighbors
326 })
327 .collect()
328 }
329
330 pub fn compute_neighbors_simple_points3(
332 &self,
333 points: &[[f32; 3]],
334 k: usize,
335 ) -> Vec<[u32; 64]> {
336 self.compute_neighbors_simple(points, k)
337 }
338}
339
340pub async fn gpu_estimate_normals(
342 gpu_context: &GpuContext,
343 cloud: &mut PointCloud<Point3f>,
344 k: usize,
345) -> Result<PointCloud<NormalPoint3f>> {
346 let normals = gpu_context.compute_normals(&cloud.points, k).await?;
347
348 let normal_points: Vec<NormalPoint3f> = cloud
349 .points
350 .iter()
351 .zip(normals.iter())
352 .map(|(point, normal)| NormalPoint3f {
353 position: *point,
354 normal: *normal,
355 })
356 .collect();
357
358 Ok(PointCloud::from_points(normal_points))
359}
360
361#[cfg(test)]
362mod tests {
363 use super::*;
364 use threecrate_core::{Point3f, PointCloud};
365
366 async fn try_create_gpu_context() -> Option<crate::GpuContext> {
368 match crate::GpuContext::new().await {
369 Ok(gpu) => Some(gpu),
370 Err(_) => {
371 println!("⚠️ GPU not available, skipping GPU-dependent test");
372 None
373 }
374 }
375 }
376
377 #[tokio::test]
378 async fn test_gpu_normals_plane() {
379 let Some(gpu) = try_create_gpu_context().await else {
380 return;
381 };
382
383 let mut cloud = PointCloud::new();
384 for i in 0..15 {
386 for j in 0..15 {
387 cloud.push(Point3f::new(i as f32 * 0.1, j as f32 * 0.1, 0.0));
388 }
389 }
390 let result = gpu_estimate_normals(&gpu, &mut cloud, 8).await.unwrap();
391 assert_eq!(result.len(), 225);
392 let mut z_count = 0;
393 for p in result.iter() {
394 if p.normal.z.abs() > 0.8 {
395 z_count += 1;
396 }
397 }
398 let pct = (z_count as f32 / result.len() as f32) * 100.0;
399 assert!(pct > 80.0, "Only {:.1}% normals in Z direction", pct);
400 }
401
402 #[tokio::test]
403 async fn test_gpu_normals_compare_cpu_plane() {
404 use threecrate_algorithms::estimate_normals as cpu_estimate_normals;
405 let Some(gpu) = try_create_gpu_context().await else {
406 return;
407 };
408
409 let mut cloud = PointCloud::new();
410 for i in 0..10 {
411 for j in 0..10 {
412 cloud.push(Point3f::new(i as f32 * 0.1, j as f32 * 0.1, 0.0));
413 }
414 }
415 let gpu_cloud = gpu_estimate_normals(&gpu, &mut cloud.clone(), 8)
416 .await
417 .unwrap();
418 let cpu_cloud = cpu_estimate_normals(&cloud, 8).unwrap();
419 let mut agree = 0usize;
421 for (g, c) in gpu_cloud.iter().zip(cpu_cloud.iter()) {
422 let dot = g.normal.dot(&c.normal);
423 if dot.abs() > 0.7 {
424 agree += 1;
425 }
426 }
427 let pct = (agree as f32 / gpu_cloud.len() as f32) * 100.0;
428 assert!(pct > 70.0, "GPU-CPU normals agree only {:.1}%", pct);
429 }
430
431 #[tokio::test]
432 async fn test_gpu_normals_non_finite_point_gets_unit_normal() {
433 let Some(gpu) = try_create_gpu_context().await else {
434 return;
435 };
436 let mut cloud = PointCloud::new();
437 for i in 0..10 {
438 for j in 0..10 {
439 cloud.push(Point3f::new(i as f32 * 0.1, j as f32 * 0.1, 0.0));
440 }
441 }
442 cloud.push(Point3f::new(f32::NAN, 0.0, 0.0));
443 let normals = gpu_estimate_normals(&gpu, &mut cloud, 8).await.unwrap();
444 assert_eq!(
445 normals.points[100].normal,
446 nalgebra::Vector3::new(0.0, 0.0, 1.0)
447 );
448 assert!(normals.points[..100]
449 .iter()
450 .all(|p| (p.normal.norm() - 1.0).abs() < 1e-4));
451 }
452
453 #[tokio::test]
454 async fn test_gpu_normals_match_cpu_on_curved_surface() {
455 use threecrate_algorithms::estimate_normals as cpu_estimate_normals;
456 let Some(gpu) = try_create_gpu_context().await else {
457 return;
458 };
459
460 let mut cloud = PointCloud::new();
462 for i in 0..120 {
463 for j in 0..120 {
464 let x = i as f32 * 0.05 + 0.013 * ((i * 7 + j * 3) % 5) as f32;
465 let y = j as f32 * 0.05 + 0.011 * ((i * 3 + j * 5) % 7) as f32;
466 let z = 0.5 * (x * 1.3).sin() * (y * 0.9).cos();
467 cloud.push(Point3f::new(x + 1000.0, y - 500.0, z + 20.0));
468 }
469 }
470
471 let gpu_cloud = gpu_estimate_normals(&gpu, &mut cloud.clone(), 10)
472 .await
473 .unwrap();
474 let cpu_cloud = cpu_estimate_normals(&cloud, 10).unwrap();
475
476 let agree = gpu_cloud
478 .iter()
479 .zip(cpu_cloud.iter())
480 .filter(|(g, c)| g.normal.dot(&c.normal) > 0.999)
481 .count();
482 let pct = 100.0 * agree as f32 / gpu_cloud.len() as f32;
483 assert!(
484 pct > 99.0,
485 "GPU and CPU normals agree on only {pct:.2}% of points"
486 );
487 }
488}