Skip to main content

threecrate_gpu/
segmentation.rs

1//! GPU-accelerated point cloud segmentation.
2
3use nalgebra::{Vector3, Vector4};
4use threecrate_core::{Error, Point3f, PointCloud, Result};
5
6use crate::device::workgroup_grid;
7use crate::GpuContext;
8
9const RANSAC_SCORE_SHADER: &str = r#"
10@group(0) @binding(0) var<storage, read> points: array<vec4<f32>>;
11@group(0) @binding(1) var<storage, read> samples: array<vec4<u32>>;
12@group(0) @binding(2) var<storage, read_write> candidates: array<PlaneCandidate>;
13@group(0) @binding(3) var<uniform> params: RansacParams;
14
15struct PlaneCandidate {
16    coefficients: vec4<f32>,
17    inlier_count: u32,
18    _pad0: u32,
19    _pad1: u32,
20    _pad2: u32,
21}
22
23struct RansacParams {
24    num_points: u32,
25    num_samples: u32,
26    threshold: f32,
27    _pad: u32,
28}
29
30@compute @workgroup_size(64)
31fn main(@builtin(global_invocation_id) global_id: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {
32    let sample_idx = global_id.x + global_id.y * nwg.x * 64u;
33    if (sample_idx >= params.num_samples) {
34        return;
35    }
36
37    let sample = samples[sample_idx];
38    let p1 = points[sample.x].xyz;
39    let p2 = points[sample.y].xyz;
40    let p3 = points[sample.z].xyz;
41
42    let normal_raw = cross(p2 - p1, p3 - p1);
43    let normal_len = length(normal_raw);
44    if (normal_len < 1e-8) {
45        candidates[sample_idx].coefficients = vec4<f32>(0.0);
46        candidates[sample_idx].inlier_count = 0u;
47        return;
48    }
49
50    let normal = normal_raw / normal_len;
51    let d = -dot(normal, p1);
52    var count = 0u;
53
54    for (var i = 0u; i < params.num_points; i++) {
55        let distance = abs(dot(normal, points[i].xyz) + d);
56        if (distance <= params.threshold) {
57            count++;
58        }
59    }
60
61    candidates[sample_idx].coefficients = vec4<f32>(normal, d);
62    candidates[sample_idx].inlier_count = count;
63}
64"#;
65
66const RANSAC_INLIER_SHADER: &str = r#"
67@group(0) @binding(0) var<storage, read> points: array<vec4<f32>>;
68@group(0) @binding(1) var<storage, read_write> flags: array<u32>;
69@group(0) @binding(2) var<uniform> params: InlierParams;
70
71struct InlierParams {
72    num_points: u32,
73    threshold: f32,
74    _pad0: u32,
75    _pad1: u32,
76    plane: vec4<f32>,
77}
78
79@compute @workgroup_size(64)
80fn main(@builtin(global_invocation_id) global_id: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {
81    let index = global_id.x + global_id.y * nwg.x * 64u;
82    if (index >= params.num_points) {
83        return;
84    }
85
86    let normal_len = length(params.plane.xyz);
87    if (normal_len < 1e-8) {
88        flags[index] = 0u;
89        return;
90    }
91
92    let distance = abs(dot(params.plane.xyz, points[index].xyz) + params.plane.w) / normal_len;
93    flags[index] = select(0u, 1u, distance <= params.threshold);
94}
95"#;
96
97/// A 3D plane model defined by `ax + by + cz + d = 0`.
98#[derive(Debug, Clone, PartialEq)]
99pub struct GpuPlaneModel {
100    /// Plane coefficients `[a, b, c, d]`.
101    pub coefficients: Vector4<f32>,
102}
103
104impl GpuPlaneModel {
105    /// Create a model from normalized coefficients.
106    pub fn new(coefficients: Vector4<f32>) -> Self {
107        Self { coefficients }
108    }
109
110    /// Return the plane normal.
111    pub fn normal(&self) -> Vector3<f32> {
112        Vector3::new(
113            self.coefficients.x,
114            self.coefficients.y,
115            self.coefficients.z,
116        )
117    }
118
119    /// Distance from `point` to this plane.
120    pub fn distance_to_point(&self, point: &Point3f) -> f32 {
121        let normal = self.normal();
122        let normal_len = normal.magnitude();
123        if normal_len < 1e-8 {
124            return f32::INFINITY;
125        }
126
127        (normal.dot(&point.coords) + self.coefficients.w).abs() / normal_len
128    }
129}
130
131/// Result of GPU RANSAC plane segmentation.
132#[derive(Debug, Clone)]
133pub struct GpuPlaneSegmentationResult {
134    /// Best-scoring plane model.
135    pub plane: GpuPlaneModel,
136    /// Best-scoring plane model.
137    pub model: GpuPlaneModel,
138    /// Indices of points within the distance threshold.
139    pub inliers: Vec<u32>,
140    /// Number of RANSAC candidates evaluated.
141    pub iterations: usize,
142}
143
144/// Configuration for GPU RANSAC plane segmentation.
145#[derive(Debug, Clone, Copy)]
146pub struct GpuPlaneSegmentationConfig {
147    /// Maximum RANSAC candidates to evaluate.
148    pub max_iterations: usize,
149    /// Maximum point-to-plane distance for an inlier.
150    pub distance_threshold: f32,
151    /// Minimum inliers required for a valid result.
152    pub min_inliers: usize,
153}
154
155impl Default for GpuPlaneSegmentationConfig {
156    fn default() -> Self {
157        Self {
158            max_iterations: 1_000,
159            distance_threshold: 0.02,
160            min_inliers: 1,
161        }
162    }
163}
164
165/// Configuration for GPU Euclidean cluster extraction.
166#[derive(Debug, Clone)]
167pub struct GpuEuclideanClusterConfig {
168    /// Maximum distance between neighboring points in the same cluster.
169    pub tolerance: f32,
170    /// Minimum number of points for a valid cluster.
171    pub min_cluster_size: usize,
172    /// Maximum number of points allowed in a valid cluster.
173    pub max_cluster_size: usize,
174    /// Maximum radius neighbors retained per point from the GPU adjacency pass.
175    pub max_neighbors: usize,
176}
177
178impl Default for GpuEuclideanClusterConfig {
179    fn default() -> Self {
180        Self {
181            tolerance: 0.02,
182            min_cluster_size: 100,
183            max_cluster_size: 25_000,
184            max_neighbors: 64,
185        }
186    }
187}
188
189impl GpuEuclideanClusterConfig {
190    /// Create a config using the default `max_neighbors` cap.
191    pub fn new(tolerance: f32, min_cluster_size: usize, max_cluster_size: usize) -> Self {
192        Self {
193            tolerance,
194            min_cluster_size,
195            max_cluster_size,
196            ..Self::default()
197        }
198    }
199
200    /// Create a config with an explicit GPU neighbor cap.
201    pub fn with_max_neighbors(
202        tolerance: f32,
203        min_cluster_size: usize,
204        max_cluster_size: usize,
205        max_neighbors: usize,
206    ) -> Self {
207        Self {
208            tolerance,
209            min_cluster_size,
210            max_cluster_size,
211            max_neighbors,
212        }
213    }
214}
215
216/// Issue-compatible alias for GPU Euclidean cluster extraction config.
217pub type GpuClusterConfig = GpuEuclideanClusterConfig;
218
219/// Result of GPU-accelerated Euclidean cluster extraction.
220#[derive(Debug, Clone)]
221pub struct GpuClusterExtractionResult {
222    /// Each inner vector contains point indices for one cluster, largest first.
223    pub clusters: Vec<Vec<usize>>,
224}
225
226impl GpuClusterExtractionResult {
227    /// Number of clusters found.
228    pub fn num_clusters(&self) -> usize {
229        self.clusters.len()
230    }
231
232    /// Extract a sub-cloud for the cluster at `index`.
233    pub fn get_cluster_cloud(
234        &self,
235        cloud: &PointCloud<Point3f>,
236        index: usize,
237    ) -> Option<PointCloud<Point3f>> {
238        self.clusters.get(index).map(|indices| {
239            PointCloud::from_points(indices.iter().map(|&i| cloud.points[i]).collect())
240        })
241    }
242}
243
244#[repr(C)]
245#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
246struct PlaneCandidate {
247    coefficients: [f32; 4],
248    inlier_count: u32,
249    _padding: [u32; 3],
250}
251
252impl GpuContext {
253    /// Segment the dominant plane using GPU-scored RANSAC candidates.
254    pub async fn segment_plane(
255        &self,
256        points: &[Point3f],
257        config: GpuPlaneSegmentationConfig,
258    ) -> Result<GpuPlaneSegmentationResult> {
259        validate_ransac_config(points, config)?;
260
261        let mut result = self
262            .segment_plane_ransac(points, config.distance_threshold, config.max_iterations)
263            .await?;
264        if result.inliers.len() < config.min_inliers {
265            return Err(Error::Algorithm(format!(
266                "Plane model has {} inliers, below required minimum {}",
267                result.inliers.len(),
268                config.min_inliers
269            )));
270        }
271
272        result.plane = result.model.clone();
273        Ok(result)
274    }
275
276    /// Segment the dominant plane using GPU-scored RANSAC candidates.
277    pub async fn segment_plane_ransac(
278        &self,
279        points: &[Point3f],
280        threshold: f32,
281        max_iters: usize,
282    ) -> Result<GpuPlaneSegmentationResult> {
283        validate_ransac_inputs(points, threshold, max_iters)?;
284
285        let point_data = points_to_vec4(points);
286        let sample_count = max_iters.min(u32::MAX as usize);
287        let samples = generate_ransac_samples(points.len(), sample_count);
288
289        let input_buffer =
290            self.create_buffer_init("RANSAC Points", &point_data, wgpu::BufferUsages::STORAGE);
291        let samples_buffer =
292            self.create_buffer_init("RANSAC Samples", &samples, wgpu::BufferUsages::STORAGE);
293        let candidates_buffer = self.create_buffer(
294            "RANSAC Candidates",
295            (sample_count * std::mem::size_of::<PlaneCandidate>()) as u64,
296            wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
297        );
298
299        #[repr(C)]
300        #[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
301        struct RansacParams {
302            num_points: u32,
303            num_samples: u32,
304            threshold: f32,
305            _padding: u32,
306        }
307
308        let params = RansacParams {
309            num_points: points.len() as u32,
310            num_samples: sample_count as u32,
311            threshold,
312            _padding: 0,
313        };
314        let params_buffer =
315            self.create_buffer_init("RANSAC Params", &[params], wgpu::BufferUsages::UNIFORM);
316
317        let shader = self.create_shader_module("RANSAC Score Shader", RANSAC_SCORE_SHADER);
318        let layout = self.create_bind_group_layout(
319            "RANSAC Score Layout",
320            &[
321                storage_entry(0, true),
322                storage_entry(1, true),
323                storage_entry(2, false),
324                uniform_entry(3),
325            ],
326        );
327        let pipeline = self.create_pipeline_with_layout("RANSAC Score Pipeline", &shader, &layout);
328        let bind_group = self.create_bind_group(
329            "RANSAC Score Bind Group",
330            &layout,
331            &[
332                wgpu::BindGroupEntry {
333                    binding: 0,
334                    resource: input_buffer.as_entire_binding(),
335                },
336                wgpu::BindGroupEntry {
337                    binding: 1,
338                    resource: samples_buffer.as_entire_binding(),
339                },
340                wgpu::BindGroupEntry {
341                    binding: 2,
342                    resource: candidates_buffer.as_entire_binding(),
343                },
344                wgpu::BindGroupEntry {
345                    binding: 3,
346                    resource: params_buffer.as_entire_binding(),
347                },
348            ],
349        );
350
351        let mut encoder = self
352            .device
353            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
354                label: Some("RANSAC Score Encoder"),
355            });
356        {
357            let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
358                label: Some("RANSAC Score Pass"),
359                timestamp_writes: None,
360            });
361            pass.set_pipeline(&pipeline);
362            pass.set_bind_group(0, &bind_group, &[]);
363            let (x, y) = workgroup_grid(div_ceil(sample_count, 64));
364            pass.dispatch_workgroups(x, y, 1);
365        }
366
367        let candidates = self
368            .read_storage_buffer::<PlaneCandidate>(
369                encoder,
370                &candidates_buffer,
371                sample_count,
372                "RANSAC Candidate Staging",
373            )
374            .await?;
375
376        let best = candidates
377            .iter()
378            .max_by_key(|candidate| candidate.inlier_count)
379            .ok_or_else(|| Error::Algorithm("Failed to evaluate RANSAC candidates".to_string()))?;
380
381        if best.inlier_count == 0 {
382            return Err(Error::Algorithm(
383                "Failed to find valid plane model".to_string(),
384            ));
385        }
386
387        let coefficients = Vector4::new(
388            best.coefficients[0],
389            best.coefficients[1],
390            best.coefficients[2],
391            best.coefficients[3],
392        );
393        let inliers = self
394            .plane_inlier_indices(points, coefficients, threshold)
395            .await?;
396
397        Ok(GpuPlaneSegmentationResult {
398            plane: GpuPlaneModel::new(coefficients),
399            model: GpuPlaneModel::new(coefficients),
400            inliers,
401            iterations: sample_count,
402        })
403    }
404
405    /// Extract Euclidean clusters as point-cloud values.
406    pub async fn extract_clusters(
407        &self,
408        cloud: &PointCloud<Point3f>,
409        config: GpuClusterConfig,
410    ) -> Result<Vec<PointCloud<Point3f>>> {
411        let result = self
412            .extract_euclidean_clusters(&cloud.points, &config)
413            .await?;
414        Ok(result
415            .clusters
416            .iter()
417            .map(|indices| {
418                PointCloud::from_points(indices.iter().map(|&i| cloud.points[i]).collect())
419            })
420            .collect())
421    }
422
423    /// Extract Euclidean clusters. Runs on the CPU (`threecrate_algorithms`)
424    /// with a kd-tree radius search: the old GPU path capped each point's
425    /// candidates before checking distance, so it split real clusters, and it
426    /// ran out of buffer space above 65,536 points (#217). `max_neighbors` is
427    /// no longer used.
428    pub async fn extract_euclidean_clusters(
429        &self,
430        points: &[Point3f],
431        config: &GpuEuclideanClusterConfig,
432    ) -> Result<GpuClusterExtractionResult> {
433        validate_cluster_inputs(points, config)?;
434        let cpu_config = threecrate_algorithms::EuclideanClusterConfig::new(
435            config.tolerance,
436            config.min_cluster_size,
437            config.max_cluster_size,
438        );
439        let cloud = PointCloud::from_points(points.to_vec());
440        let result = threecrate_algorithms::extract_euclidean_clusters(&cloud, &cpu_config)?;
441        Ok(GpuClusterExtractionResult {
442            clusters: result.clusters,
443        })
444    }
445
446    async fn plane_inlier_indices(
447        &self,
448        points: &[Point3f],
449        coefficients: Vector4<f32>,
450        threshold: f32,
451    ) -> Result<Vec<u32>> {
452        let point_data = points_to_vec4(points);
453        let input_buffer = self.create_buffer_init(
454            "Plane Inlier Points",
455            &point_data,
456            wgpu::BufferUsages::STORAGE,
457        );
458        let flags_buffer = self.create_buffer(
459            "Plane Inlier Flags",
460            (points.len() * std::mem::size_of::<u32>()) as u64,
461            wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
462        );
463
464        #[repr(C)]
465        #[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
466        struct InlierParams {
467            num_points: u32,
468            threshold: f32,
469            _padding: [u32; 2],
470            plane: [f32; 4],
471        }
472
473        let params = InlierParams {
474            num_points: points.len() as u32,
475            threshold,
476            _padding: [0; 2],
477            plane: [
478                coefficients.x,
479                coefficients.y,
480                coefficients.z,
481                coefficients.w,
482            ],
483        };
484        let params_buffer = self.create_buffer_init(
485            "Plane Inlier Params",
486            &[params],
487            wgpu::BufferUsages::UNIFORM,
488        );
489        let shader = self.create_shader_module("Plane Inlier Shader", RANSAC_INLIER_SHADER);
490        let layout = self.create_bind_group_layout(
491            "Plane Inlier Layout",
492            &[
493                storage_entry(0, true),
494                storage_entry(1, false),
495                uniform_entry(2),
496            ],
497        );
498        let pipeline = self.create_pipeline_with_layout("Plane Inlier Pipeline", &shader, &layout);
499        let bind_group = self.create_bind_group(
500            "Plane Inlier Bind Group",
501            &layout,
502            &[
503                wgpu::BindGroupEntry {
504                    binding: 0,
505                    resource: input_buffer.as_entire_binding(),
506                },
507                wgpu::BindGroupEntry {
508                    binding: 1,
509                    resource: flags_buffer.as_entire_binding(),
510                },
511                wgpu::BindGroupEntry {
512                    binding: 2,
513                    resource: params_buffer.as_entire_binding(),
514                },
515            ],
516        );
517
518        let mut encoder = self
519            .device
520            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
521                label: Some("Plane Inlier Encoder"),
522            });
523        {
524            let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
525                label: Some("Plane Inlier Pass"),
526                timestamp_writes: None,
527            });
528            pass.set_pipeline(&pipeline);
529            pass.set_bind_group(0, &bind_group, &[]);
530            let (x, y) = workgroup_grid(div_ceil(points.len(), 64));
531            pass.dispatch_workgroups(x, y, 1);
532        }
533
534        let flags = self
535            .read_storage_buffer::<u32>(
536                encoder,
537                &flags_buffer,
538                points.len(),
539                "Plane Inlier Staging",
540            )
541            .await?;
542        Ok(flags
543            .iter()
544            .enumerate()
545            .filter_map(|(idx, flag)| (*flag == 1).then_some(idx as u32))
546            .collect())
547    }
548
549    fn create_pipeline_with_layout(
550        &self,
551        label: &str,
552        shader: &wgpu::ShaderModule,
553        layout: &wgpu::BindGroupLayout,
554    ) -> wgpu::ComputePipeline {
555        self.device
556            .create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
557                label: Some(label),
558                layout: Some(&self.device.create_pipeline_layout(
559                    &wgpu::PipelineLayoutDescriptor {
560                        label: Some(label),
561                        bind_group_layouts: &[Some(layout)],
562                        immediate_size: 0,
563                    },
564                )),
565                module: shader,
566                entry_point: Some("main"),
567                compilation_options: wgpu::PipelineCompilationOptions::default(),
568                cache: None,
569            })
570    }
571
572    async fn read_storage_buffer<T: bytemuck::Pod>(
573        &self,
574        mut encoder: wgpu::CommandEncoder,
575        source: &wgpu::Buffer,
576        len: usize,
577        label: &str,
578    ) -> Result<Vec<T>> {
579        let size = (len * std::mem::size_of::<T>()) as u64;
580        let staging = self.create_buffer(
581            label,
582            size,
583            wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
584        );
585        encoder.copy_buffer_to_buffer(source, 0, &staging, 0, size);
586        self.queue.submit(std::iter::once(encoder.finish()));
587
588        let slice = staging.slice(..);
589        let (sender, receiver) = futures_intrusive::channel::shared::oneshot_channel();
590        slice.map_async(wgpu::MapMode::Read, move |result| {
591            sender.send(result).unwrap()
592        });
593        let _ = self.device.poll(wgpu::PollType::Wait {
594            submission_index: None,
595            timeout: None,
596        });
597
598        if let Some(Ok(())) = receiver.receive().await {
599            let data = slice.get_mapped_range();
600            let result = bytemuck::cast_slice(&data).to_vec();
601            drop(data);
602            staging.unmap();
603            Ok(result)
604        } else {
605            Err(Error::Gpu(
606                "Failed to read GPU segmentation results".to_string(),
607            ))
608        }
609    }
610}
611
612/// GPU-accelerated RANSAC plane segmentation for a point cloud.
613pub async fn gpu_segment_plane(
614    gpu_context: &GpuContext,
615    cloud: &PointCloud<Point3f>,
616    config: GpuPlaneSegmentationConfig,
617) -> Result<GpuPlaneSegmentationResult> {
618    gpu_context.segment_plane(&cloud.points, config).await
619}
620
621/// GPU-accelerated RANSAC plane segmentation for a point cloud.
622pub async fn gpu_segment_plane_ransac(
623    gpu_context: &GpuContext,
624    cloud: &PointCloud<Point3f>,
625    threshold: f32,
626    max_iters: usize,
627) -> Result<GpuPlaneSegmentationResult> {
628    gpu_context
629        .segment_plane_ransac(&cloud.points, threshold, max_iters)
630        .await
631}
632
633/// GPU-accelerated Euclidean cluster extraction for a point cloud.
634pub async fn gpu_extract_clusters(
635    gpu_context: &GpuContext,
636    cloud: &PointCloud<Point3f>,
637    config: GpuClusterConfig,
638) -> Result<Vec<PointCloud<Point3f>>> {
639    gpu_context.extract_clusters(cloud, config).await
640}
641
642/// GPU-accelerated Euclidean cluster extraction for a point cloud.
643pub async fn gpu_extract_euclidean_clusters(
644    gpu_context: &GpuContext,
645    cloud: &PointCloud<Point3f>,
646    config: &GpuEuclideanClusterConfig,
647) -> Result<GpuClusterExtractionResult> {
648    gpu_context
649        .extract_euclidean_clusters(&cloud.points, config)
650        .await
651}
652
653fn validate_ransac_config(points: &[Point3f], config: GpuPlaneSegmentationConfig) -> Result<()> {
654    validate_ransac_inputs(points, config.distance_threshold, config.max_iterations)?;
655    if config.min_inliers == 0 {
656        return Err(Error::InvalidData(
657            "min_inliers must be at least 1".to_string(),
658        ));
659    }
660    Ok(())
661}
662
663fn validate_ransac_inputs(points: &[Point3f], threshold: f32, max_iters: usize) -> Result<()> {
664    if points.len() < 3 {
665        return Err(Error::InvalidData(
666            "Need at least 3 points for plane segmentation".to_string(),
667        ));
668    }
669    if threshold <= 0.0 {
670        return Err(Error::InvalidData("Threshold must be positive".to_string()));
671    }
672    if max_iters == 0 {
673        return Err(Error::InvalidData(
674            "Max iterations must be positive".to_string(),
675        ));
676    }
677    if points.len() > u32::MAX as usize {
678        return Err(Error::InvalidData(
679            "Point cloud is too large for GPU segmentation".to_string(),
680        ));
681    }
682    Ok(())
683}
684
685fn validate_cluster_inputs(points: &[Point3f], config: &GpuEuclideanClusterConfig) -> Result<()> {
686    if points.is_empty() {
687        return Err(Error::InvalidData("Point cloud is empty".to_string()));
688    }
689    if config.tolerance <= 0.0 {
690        return Err(Error::InvalidData("Tolerance must be positive".to_string()));
691    }
692    if config.min_cluster_size == 0 {
693        return Err(Error::InvalidData(
694            "min_cluster_size must be at least 1".to_string(),
695        ));
696    }
697    if config.min_cluster_size > config.max_cluster_size {
698        return Err(Error::InvalidData(
699            "min_cluster_size must not exceed max_cluster_size".to_string(),
700        ));
701    }
702    if config.max_neighbors == 0 {
703        return Err(Error::InvalidData(
704            "max_neighbors must be at least 1".to_string(),
705        ));
706    }
707    if points.len() > u32::MAX as usize {
708        return Err(Error::InvalidData(
709            "Point cloud is too large for GPU clustering".to_string(),
710        ));
711    }
712    Ok(())
713}
714
715fn points_to_vec4(points: &[Point3f]) -> Vec<[f32; 4]> {
716    points.iter().map(|p| [p.x, p.y, p.z, 0.0]).collect()
717}
718
719fn generate_ransac_samples(num_points: usize, sample_count: usize) -> Vec<[u32; 4]> {
720    let mut state = ((num_points as u64) << 32) ^ sample_count as u64 ^ 0x9E37_79B9_7F4A_7C15;
721    let mut samples = Vec::with_capacity(sample_count);
722
723    for iteration in 0..sample_count {
724        let mut a = next_index(&mut state, num_points);
725        let mut b = next_index(&mut state, num_points);
726        let mut c = next_index(&mut state, num_points);
727
728        if a == b || a == c || b == c {
729            a = iteration % num_points;
730            b = (iteration.wrapping_mul(37) + 1) % num_points;
731            c = (iteration.wrapping_mul(101) + 2) % num_points;
732            while b == a {
733                b = (b + 1) % num_points;
734            }
735            while c == a || c == b {
736                c = (c + 1) % num_points;
737            }
738        }
739
740        samples.push([a as u32, b as u32, c as u32, 0]);
741    }
742
743    samples
744}
745
746fn next_index(state: &mut u64, len: usize) -> usize {
747    *state = state
748        .wrapping_mul(6_364_136_223_846_793_005)
749        .wrapping_add(1_442_695_040_888_963_407);
750    ((*state >> 32) as usize) % len
751}
752
753fn storage_entry(binding: u32, read_only: bool) -> wgpu::BindGroupLayoutEntry {
754    wgpu::BindGroupLayoutEntry {
755        binding,
756        visibility: wgpu::ShaderStages::COMPUTE,
757        ty: wgpu::BindingType::Buffer {
758            ty: wgpu::BufferBindingType::Storage { read_only },
759            has_dynamic_offset: false,
760            min_binding_size: None,
761        },
762        count: None,
763    }
764}
765
766fn uniform_entry(binding: u32) -> wgpu::BindGroupLayoutEntry {
767    wgpu::BindGroupLayoutEntry {
768        binding,
769        visibility: wgpu::ShaderStages::COMPUTE,
770        ty: wgpu::BindingType::Buffer {
771            ty: wgpu::BufferBindingType::Uniform,
772            has_dynamic_offset: false,
773            min_binding_size: None,
774        },
775        count: None,
776    }
777}
778
779fn div_ceil(value: usize, divisor: usize) -> usize {
780    value.div_ceil(divisor)
781}
782
783#[cfg(test)]
784mod tests {
785    use super::*;
786
787    async fn try_create_gpu_context() -> Option<GpuContext> {
788        match GpuContext::new().await {
789            Ok(gpu) => Some(gpu),
790            Err(_) => {
791                println!("GPU not available, skipping GPU-dependent test");
792                None
793            }
794        }
795    }
796
797    fn planar_cloud() -> PointCloud<Point3f> {
798        let mut cloud = PointCloud::new();
799        for x in 0..12 {
800            for y in 0..12 {
801                cloud.push(Point3f::new(x as f32 * 0.1, y as f32 * 0.1, 0.0));
802            }
803        }
804        cloud.push(Point3f::new(0.0, 0.0, 3.0));
805        cloud.push(Point3f::new(1.0, 1.0, -3.0));
806        cloud
807    }
808
809    fn clustered_cloud() -> PointCloud<Point3f> {
810        let mut cloud = PointCloud::new();
811        for i in 0..30 {
812            let x = (i % 5) as f32 * 0.04;
813            let y = (i / 5) as f32 * 0.04;
814            cloud.push(Point3f::new(x, y, 0.0));
815        }
816        for i in 0..20 {
817            let x = 5.0 + (i % 5) as f32 * 0.04;
818            let y = (i / 5) as f32 * 0.04;
819            cloud.push(Point3f::new(x, y, 0.0));
820        }
821        cloud
822    }
823
824    #[test]
825    fn test_gpu_ransac_plane() {
826        pollster::block_on(async {
827            let Some(gpu) = try_create_gpu_context().await else {
828                return;
829            };
830
831            let cloud = planar_cloud();
832            let config = GpuPlaneSegmentationConfig {
833                max_iterations: 256,
834                distance_threshold: 0.01,
835                min_inliers: 140,
836            };
837            let result = gpu_segment_plane(&gpu, &cloud, config).await.unwrap();
838
839            assert!(result.inliers.len() >= 140);
840            assert!(result.plane.normal().z.abs() > 0.9);
841            assert_eq!(result.model, result.plane);
842            assert_eq!(result.iterations, 256);
843        });
844    }
845
846    /// The cases from #217: the old GPU path split two dense blobs into single
847    /// points and separated a pair 0.02 apart, and it ran out of buffer space
848    /// above 65,536 points.
849    #[test]
850    fn test_gpu_clusters_match_cpu_and_handle_large_clouds() {
851        pollster::block_on(async {
852            let Some(gpu) = try_create_gpu_context().await else {
853                return;
854            };
855            let blob = |cx: f32, cy: f32, cz: f32| {
856                (0..600).map(move |i| {
857                    let (a, b, c) = ((i % 10) as f32, ((i / 10) % 10) as f32, (i / 100) as f32);
858                    Point3f::new(cx + a * 0.02, cy + b * 0.02, cz + c * 0.02)
859                })
860            };
861            let mut points: Vec<Point3f> =
862                blob(0.25, 0.5, 0.5).chain(blob(1.05, -0.9, -0.9)).collect();
863            points.push(Point3f::new(1.99, 0.5, 0.5));
864            points.push(Point3f::new(2.01, 0.5, 0.5));
865            let cloud = PointCloud::from_points(points);
866            let config = GpuEuclideanClusterConfig::new(1.0, 1, 10_000);
867            let gpu_result = gpu_extract_euclidean_clusters(&gpu, &cloud, &config)
868                .await
869                .unwrap();
870            let sizes: Vec<usize> = gpu_result.clusters.iter().map(Vec::len).collect();
871            let cpu = threecrate_algorithms::extract_euclidean_clusters(
872                &cloud,
873                &threecrate_algorithms::EuclideanClusterConfig::new(1.0, 1, 10_000),
874            )
875            .unwrap();
876            assert_eq!(gpu_result.clusters, cpu.clusters);
877            assert_eq!(sizes.iter().sum::<usize>(), 1202);
878            assert!(sizes.len() <= 3, "clusters were split: {sizes:?}");
879
880            // 70,000 points in two well-separated sheets.
881            let big = PointCloud::from_points(
882                (0..70_000)
883                    .map(|i| {
884                        let x = (i % 350) as f32 * 0.01 + if i < 35_000 { 0.0 } else { 100.0 };
885                        Point3f::new(x, (i / 350 % 100) as f32 * 0.01, 0.0)
886                    })
887                    .collect(),
888            );
889            let config = GpuEuclideanClusterConfig::new(0.02, 100, 100_000);
890            let result = gpu_extract_euclidean_clusters(&gpu, &big, &config)
891                .await
892                .unwrap();
893            assert_eq!(result.num_clusters(), 2);
894        });
895    }
896
897    #[test]
898    fn test_gpu_clusters() {
899        pollster::block_on(async {
900            let Some(gpu) = try_create_gpu_context().await else {
901                return;
902            };
903
904            let cloud = clustered_cloud();
905            let config = GpuEuclideanClusterConfig::with_max_neighbors(0.09, 5, 100, 16);
906            let result = gpu_extract_euclidean_clusters(&gpu, &cloud, &config)
907                .await
908                .unwrap();
909            let cluster_clouds = gpu_extract_clusters(&gpu, &cloud, config).await.unwrap();
910
911            assert_eq!(result.num_clusters(), 2);
912            assert_eq!(result.clusters[0].len(), 30);
913            assert_eq!(result.clusters[1].len(), 20);
914            assert_eq!(cluster_clouds.len(), 2);
915            assert_eq!(cluster_clouds[0].len(), 30);
916            assert_eq!(cluster_clouds[1].len(), 20);
917        });
918    }
919
920    #[test]
921    fn test_invalid_inputs() {
922        let cloud = PointCloud::from_points(vec![Point3f::new(0.0, 0.0, 0.0)]);
923        assert!(validate_ransac_inputs(&cloud.points, 0.1, 10).is_err());
924        assert!(validate_ransac_inputs(&planar_cloud().points, -0.1, 10).is_err());
925        assert!(validate_ransac_inputs(&planar_cloud().points, 0.1, 0).is_err());
926        assert!(validate_ransac_config(
927            &planar_cloud().points,
928            GpuPlaneSegmentationConfig {
929                min_inliers: 0,
930                ..GpuPlaneSegmentationConfig::default()
931            }
932        )
933        .is_err());
934
935        let config = GpuEuclideanClusterConfig::new(-1.0, 1, 10);
936        assert!(validate_cluster_inputs(&clustered_cloud().points, &config).is_err());
937    }
938}