threecrate-gpu 0.12.1

GPU-accelerated algorithms for threecrate using wgpu
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
//! GPU-accelerated point cloud segmentation.

use nalgebra::{Vector3, Vector4};
use threecrate_core::{Error, Point3f, PointCloud, Result};

use crate::device::workgroup_grid;
use crate::GpuContext;

const RANSAC_SCORE_SHADER: &str = r#"
@group(0) @binding(0) var<storage, read> points: array<vec4<f32>>;
@group(0) @binding(1) var<storage, read> samples: array<vec4<u32>>;
@group(0) @binding(2) var<storage, read_write> candidates: array<PlaneCandidate>;
@group(0) @binding(3) var<uniform> params: RansacParams;

struct PlaneCandidate {
    coefficients: vec4<f32>,
    inlier_count: u32,
    _pad0: u32,
    _pad1: u32,
    _pad2: u32,
}

struct RansacParams {
    num_points: u32,
    num_samples: u32,
    threshold: f32,
    _pad: u32,
}

@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) global_id: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {
    let sample_idx = global_id.x + global_id.y * nwg.x * 64u;
    if (sample_idx >= params.num_samples) {
        return;
    }

    let sample = samples[sample_idx];
    let p1 = points[sample.x].xyz;
    let p2 = points[sample.y].xyz;
    let p3 = points[sample.z].xyz;

    let normal_raw = cross(p2 - p1, p3 - p1);
    let normal_len = length(normal_raw);
    if (normal_len < 1e-8) {
        candidates[sample_idx].coefficients = vec4<f32>(0.0);
        candidates[sample_idx].inlier_count = 0u;
        return;
    }

    let normal = normal_raw / normal_len;
    let d = -dot(normal, p1);
    var count = 0u;

    for (var i = 0u; i < params.num_points; i++) {
        let distance = abs(dot(normal, points[i].xyz) + d);
        if (distance <= params.threshold) {
            count++;
        }
    }

    candidates[sample_idx].coefficients = vec4<f32>(normal, d);
    candidates[sample_idx].inlier_count = count;
}
"#;

const RANSAC_INLIER_SHADER: &str = r#"
@group(0) @binding(0) var<storage, read> points: array<vec4<f32>>;
@group(0) @binding(1) var<storage, read_write> flags: array<u32>;
@group(0) @binding(2) var<uniform> params: InlierParams;

struct InlierParams {
    num_points: u32,
    threshold: f32,
    _pad0: u32,
    _pad1: u32,
    plane: vec4<f32>,
}

@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) global_id: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {
    let index = global_id.x + global_id.y * nwg.x * 64u;
    if (index >= params.num_points) {
        return;
    }

    let normal_len = length(params.plane.xyz);
    if (normal_len < 1e-8) {
        flags[index] = 0u;
        return;
    }

    let distance = abs(dot(params.plane.xyz, points[index].xyz) + params.plane.w) / normal_len;
    flags[index] = select(0u, 1u, distance <= params.threshold);
}
"#;

/// A 3D plane model defined by `ax + by + cz + d = 0`.
#[derive(Debug, Clone, PartialEq)]
pub struct GpuPlaneModel {
    /// Plane coefficients `[a, b, c, d]`.
    pub coefficients: Vector4<f32>,
}

impl GpuPlaneModel {
    /// Create a model from normalized coefficients.
    pub fn new(coefficients: Vector4<f32>) -> Self {
        Self { coefficients }
    }

    /// Return the plane normal.
    pub fn normal(&self) -> Vector3<f32> {
        Vector3::new(
            self.coefficients.x,
            self.coefficients.y,
            self.coefficients.z,
        )
    }

    /// Distance from `point` to this plane.
    pub fn distance_to_point(&self, point: &Point3f) -> f32 {
        let normal = self.normal();
        let normal_len = normal.magnitude();
        if normal_len < 1e-8 {
            return f32::INFINITY;
        }

        (normal.dot(&point.coords) + self.coefficients.w).abs() / normal_len
    }
}

/// Result of GPU RANSAC plane segmentation.
#[derive(Debug, Clone)]
pub struct GpuPlaneSegmentationResult {
    /// Best-scoring plane model.
    pub plane: GpuPlaneModel,
    /// Best-scoring plane model.
    pub model: GpuPlaneModel,
    /// Indices of points within the distance threshold.
    pub inliers: Vec<u32>,
    /// Number of RANSAC candidates evaluated.
    pub iterations: usize,
}

/// Configuration for GPU RANSAC plane segmentation.
#[derive(Debug, Clone, Copy)]
pub struct GpuPlaneSegmentationConfig {
    /// Maximum RANSAC candidates to evaluate.
    pub max_iterations: usize,
    /// Maximum point-to-plane distance for an inlier.
    pub distance_threshold: f32,
    /// Minimum inliers required for a valid result.
    pub min_inliers: usize,
}

impl Default for GpuPlaneSegmentationConfig {
    fn default() -> Self {
        Self {
            max_iterations: 1_000,
            distance_threshold: 0.02,
            min_inliers: 1,
        }
    }
}

/// Configuration for GPU Euclidean cluster extraction.
#[derive(Debug, Clone)]
pub struct GpuEuclideanClusterConfig {
    /// Maximum distance between neighboring points in the same cluster.
    pub tolerance: f32,
    /// Minimum number of points for a valid cluster.
    pub min_cluster_size: usize,
    /// Maximum number of points allowed in a valid cluster.
    pub max_cluster_size: usize,
    /// Maximum radius neighbors retained per point from the GPU adjacency pass.
    pub max_neighbors: usize,
}

impl Default for GpuEuclideanClusterConfig {
    fn default() -> Self {
        Self {
            tolerance: 0.02,
            min_cluster_size: 100,
            max_cluster_size: 25_000,
            max_neighbors: 64,
        }
    }
}

impl GpuEuclideanClusterConfig {
    /// Create a config using the default `max_neighbors` cap.
    pub fn new(tolerance: f32, min_cluster_size: usize, max_cluster_size: usize) -> Self {
        Self {
            tolerance,
            min_cluster_size,
            max_cluster_size,
            ..Self::default()
        }
    }

    /// Create a config with an explicit GPU neighbor cap.
    pub fn with_max_neighbors(
        tolerance: f32,
        min_cluster_size: usize,
        max_cluster_size: usize,
        max_neighbors: usize,
    ) -> Self {
        Self {
            tolerance,
            min_cluster_size,
            max_cluster_size,
            max_neighbors,
        }
    }
}

/// Issue-compatible alias for GPU Euclidean cluster extraction config.
pub type GpuClusterConfig = GpuEuclideanClusterConfig;

/// Result of GPU-accelerated Euclidean cluster extraction.
#[derive(Debug, Clone)]
pub struct GpuClusterExtractionResult {
    /// Each inner vector contains point indices for one cluster, largest first.
    pub clusters: Vec<Vec<usize>>,
}

impl GpuClusterExtractionResult {
    /// Number of clusters found.
    pub fn num_clusters(&self) -> usize {
        self.clusters.len()
    }

    /// Extract a sub-cloud for the cluster at `index`.
    pub fn get_cluster_cloud(
        &self,
        cloud: &PointCloud<Point3f>,
        index: usize,
    ) -> Option<PointCloud<Point3f>> {
        self.clusters.get(index).map(|indices| {
            PointCloud::from_points(indices.iter().map(|&i| cloud.points[i]).collect())
        })
    }
}

#[repr(C)]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
struct PlaneCandidate {
    coefficients: [f32; 4],
    inlier_count: u32,
    _padding: [u32; 3],
}

impl GpuContext {
    /// Segment the dominant plane using GPU-scored RANSAC candidates.
    pub async fn segment_plane(
        &self,
        points: &[Point3f],
        config: GpuPlaneSegmentationConfig,
    ) -> Result<GpuPlaneSegmentationResult> {
        validate_ransac_config(points, config)?;

        let mut result = self
            .segment_plane_ransac(points, config.distance_threshold, config.max_iterations)
            .await?;
        if result.inliers.len() < config.min_inliers {
            return Err(Error::Algorithm(format!(
                "Plane model has {} inliers, below required minimum {}",
                result.inliers.len(),
                config.min_inliers
            )));
        }

        result.plane = result.model.clone();
        Ok(result)
    }

    /// Segment the dominant plane using GPU-scored RANSAC candidates.
    pub async fn segment_plane_ransac(
        &self,
        points: &[Point3f],
        threshold: f32,
        max_iters: usize,
    ) -> Result<GpuPlaneSegmentationResult> {
        validate_ransac_inputs(points, threshold, max_iters)?;

        let point_data = points_to_vec4(points);
        let sample_count = max_iters.min(u32::MAX as usize);
        let samples = generate_ransac_samples(points.len(), sample_count);

        let input_buffer =
            self.create_buffer_init("RANSAC Points", &point_data, wgpu::BufferUsages::STORAGE);
        let samples_buffer =
            self.create_buffer_init("RANSAC Samples", &samples, wgpu::BufferUsages::STORAGE);
        let candidates_buffer = self.create_buffer(
            "RANSAC Candidates",
            (sample_count * std::mem::size_of::<PlaneCandidate>()) as u64,
            wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
        );

        #[repr(C)]
        #[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
        struct RansacParams {
            num_points: u32,
            num_samples: u32,
            threshold: f32,
            _padding: u32,
        }

        let params = RansacParams {
            num_points: points.len() as u32,
            num_samples: sample_count as u32,
            threshold,
            _padding: 0,
        };
        let params_buffer =
            self.create_buffer_init("RANSAC Params", &[params], wgpu::BufferUsages::UNIFORM);

        let shader = self.create_shader_module("RANSAC Score Shader", RANSAC_SCORE_SHADER);
        let layout = self.create_bind_group_layout(
            "RANSAC Score Layout",
            &[
                storage_entry(0, true),
                storage_entry(1, true),
                storage_entry(2, false),
                uniform_entry(3),
            ],
        );
        let pipeline = self.create_pipeline_with_layout("RANSAC Score Pipeline", &shader, &layout);
        let bind_group = self.create_bind_group(
            "RANSAC Score Bind Group",
            &layout,
            &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: input_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: samples_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: candidates_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 3,
                    resource: params_buffer.as_entire_binding(),
                },
            ],
        );

        let mut encoder = self
            .device
            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("RANSAC Score Encoder"),
            });
        {
            let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                label: Some("RANSAC Score Pass"),
                timestamp_writes: None,
            });
            pass.set_pipeline(&pipeline);
            pass.set_bind_group(0, &bind_group, &[]);
            let (x, y) = workgroup_grid(div_ceil(sample_count, 64));
            pass.dispatch_workgroups(x, y, 1);
        }

        let candidates = self
            .read_storage_buffer::<PlaneCandidate>(
                encoder,
                &candidates_buffer,
                sample_count,
                "RANSAC Candidate Staging",
            )
            .await?;

        let best = candidates
            .iter()
            .max_by_key(|candidate| candidate.inlier_count)
            .ok_or_else(|| Error::Algorithm("Failed to evaluate RANSAC candidates".to_string()))?;

        if best.inlier_count == 0 {
            return Err(Error::Algorithm(
                "Failed to find valid plane model".to_string(),
            ));
        }

        let coefficients = Vector4::new(
            best.coefficients[0],
            best.coefficients[1],
            best.coefficients[2],
            best.coefficients[3],
        );
        let inliers = self
            .plane_inlier_indices(points, coefficients, threshold)
            .await?;

        Ok(GpuPlaneSegmentationResult {
            plane: GpuPlaneModel::new(coefficients),
            model: GpuPlaneModel::new(coefficients),
            inliers,
            iterations: sample_count,
        })
    }

    /// Extract Euclidean clusters as point-cloud values.
    pub async fn extract_clusters(
        &self,
        cloud: &PointCloud<Point3f>,
        config: GpuClusterConfig,
    ) -> Result<Vec<PointCloud<Point3f>>> {
        let result = self
            .extract_euclidean_clusters(&cloud.points, &config)
            .await?;
        Ok(result
            .clusters
            .iter()
            .map(|indices| {
                PointCloud::from_points(indices.iter().map(|&i| cloud.points[i]).collect())
            })
            .collect())
    }

    /// Extract Euclidean clusters. Runs on the CPU (`threecrate_algorithms`)
    /// with a kd-tree radius search: the old GPU path capped each point's
    /// candidates before checking distance, so it split real clusters, and it
    /// ran out of buffer space above 65,536 points (#217). `max_neighbors` is
    /// no longer used.
    pub async fn extract_euclidean_clusters(
        &self,
        points: &[Point3f],
        config: &GpuEuclideanClusterConfig,
    ) -> Result<GpuClusterExtractionResult> {
        validate_cluster_inputs(points, config)?;
        let cpu_config = threecrate_algorithms::EuclideanClusterConfig::new(
            config.tolerance,
            config.min_cluster_size,
            config.max_cluster_size,
        );
        let cloud = PointCloud::from_points(points.to_vec());
        let result = threecrate_algorithms::extract_euclidean_clusters(&cloud, &cpu_config)?;
        Ok(GpuClusterExtractionResult {
            clusters: result.clusters,
        })
    }

    async fn plane_inlier_indices(
        &self,
        points: &[Point3f],
        coefficients: Vector4<f32>,
        threshold: f32,
    ) -> Result<Vec<u32>> {
        let point_data = points_to_vec4(points);
        let input_buffer = self.create_buffer_init(
            "Plane Inlier Points",
            &point_data,
            wgpu::BufferUsages::STORAGE,
        );
        let flags_buffer = self.create_buffer(
            "Plane Inlier Flags",
            (points.len() * std::mem::size_of::<u32>()) as u64,
            wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
        );

        #[repr(C)]
        #[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
        struct InlierParams {
            num_points: u32,
            threshold: f32,
            _padding: [u32; 2],
            plane: [f32; 4],
        }

        let params = InlierParams {
            num_points: points.len() as u32,
            threshold,
            _padding: [0; 2],
            plane: [
                coefficients.x,
                coefficients.y,
                coefficients.z,
                coefficients.w,
            ],
        };
        let params_buffer = self.create_buffer_init(
            "Plane Inlier Params",
            &[params],
            wgpu::BufferUsages::UNIFORM,
        );
        let shader = self.create_shader_module("Plane Inlier Shader", RANSAC_INLIER_SHADER);
        let layout = self.create_bind_group_layout(
            "Plane Inlier Layout",
            &[
                storage_entry(0, true),
                storage_entry(1, false),
                uniform_entry(2),
            ],
        );
        let pipeline = self.create_pipeline_with_layout("Plane Inlier Pipeline", &shader, &layout);
        let bind_group = self.create_bind_group(
            "Plane Inlier Bind Group",
            &layout,
            &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: input_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: flags_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: params_buffer.as_entire_binding(),
                },
            ],
        );

        let mut encoder = self
            .device
            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("Plane Inlier Encoder"),
            });
        {
            let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                label: Some("Plane Inlier Pass"),
                timestamp_writes: None,
            });
            pass.set_pipeline(&pipeline);
            pass.set_bind_group(0, &bind_group, &[]);
            let (x, y) = workgroup_grid(div_ceil(points.len(), 64));
            pass.dispatch_workgroups(x, y, 1);
        }

        let flags = self
            .read_storage_buffer::<u32>(
                encoder,
                &flags_buffer,
                points.len(),
                "Plane Inlier Staging",
            )
            .await?;
        Ok(flags
            .iter()
            .enumerate()
            .filter_map(|(idx, flag)| (*flag == 1).then_some(idx as u32))
            .collect())
    }

    fn create_pipeline_with_layout(
        &self,
        label: &str,
        shader: &wgpu::ShaderModule,
        layout: &wgpu::BindGroupLayout,
    ) -> wgpu::ComputePipeline {
        self.device
            .create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
                label: Some(label),
                layout: Some(&self.device.create_pipeline_layout(
                    &wgpu::PipelineLayoutDescriptor {
                        label: Some(label),
                        bind_group_layouts: &[Some(layout)],
                        immediate_size: 0,
                    },
                )),
                module: shader,
                entry_point: Some("main"),
                compilation_options: wgpu::PipelineCompilationOptions::default(),
                cache: None,
            })
    }

    async fn read_storage_buffer<T: bytemuck::Pod>(
        &self,
        mut encoder: wgpu::CommandEncoder,
        source: &wgpu::Buffer,
        len: usize,
        label: &str,
    ) -> Result<Vec<T>> {
        let size = (len * std::mem::size_of::<T>()) as u64;
        let staging = self.create_buffer(
            label,
            size,
            wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
        );
        encoder.copy_buffer_to_buffer(source, 0, &staging, 0, size);
        self.queue.submit(std::iter::once(encoder.finish()));

        let slice = staging.slice(..);
        let (sender, receiver) = futures_intrusive::channel::shared::oneshot_channel();
        slice.map_async(wgpu::MapMode::Read, move |result| {
            sender.send(result).unwrap()
        });
        let _ = self.device.poll(wgpu::PollType::Wait {
            submission_index: None,
            timeout: None,
        });

        if let Some(Ok(())) = receiver.receive().await {
            let data = slice.get_mapped_range();
            let result = bytemuck::cast_slice(&data).to_vec();
            drop(data);
            staging.unmap();
            Ok(result)
        } else {
            Err(Error::Gpu(
                "Failed to read GPU segmentation results".to_string(),
            ))
        }
    }
}

/// GPU-accelerated RANSAC plane segmentation for a point cloud.
pub async fn gpu_segment_plane(
    gpu_context: &GpuContext,
    cloud: &PointCloud<Point3f>,
    config: GpuPlaneSegmentationConfig,
) -> Result<GpuPlaneSegmentationResult> {
    gpu_context.segment_plane(&cloud.points, config).await
}

/// GPU-accelerated RANSAC plane segmentation for a point cloud.
pub async fn gpu_segment_plane_ransac(
    gpu_context: &GpuContext,
    cloud: &PointCloud<Point3f>,
    threshold: f32,
    max_iters: usize,
) -> Result<GpuPlaneSegmentationResult> {
    gpu_context
        .segment_plane_ransac(&cloud.points, threshold, max_iters)
        .await
}

/// GPU-accelerated Euclidean cluster extraction for a point cloud.
pub async fn gpu_extract_clusters(
    gpu_context: &GpuContext,
    cloud: &PointCloud<Point3f>,
    config: GpuClusterConfig,
) -> Result<Vec<PointCloud<Point3f>>> {
    gpu_context.extract_clusters(cloud, config).await
}

/// GPU-accelerated Euclidean cluster extraction for a point cloud.
pub async fn gpu_extract_euclidean_clusters(
    gpu_context: &GpuContext,
    cloud: &PointCloud<Point3f>,
    config: &GpuEuclideanClusterConfig,
) -> Result<GpuClusterExtractionResult> {
    gpu_context
        .extract_euclidean_clusters(&cloud.points, config)
        .await
}

fn validate_ransac_config(points: &[Point3f], config: GpuPlaneSegmentationConfig) -> Result<()> {
    validate_ransac_inputs(points, config.distance_threshold, config.max_iterations)?;
    if config.min_inliers == 0 {
        return Err(Error::InvalidData(
            "min_inliers must be at least 1".to_string(),
        ));
    }
    Ok(())
}

fn validate_ransac_inputs(points: &[Point3f], threshold: f32, max_iters: usize) -> Result<()> {
    if points.len() < 3 {
        return Err(Error::InvalidData(
            "Need at least 3 points for plane segmentation".to_string(),
        ));
    }
    if threshold <= 0.0 {
        return Err(Error::InvalidData("Threshold must be positive".to_string()));
    }
    if max_iters == 0 {
        return Err(Error::InvalidData(
            "Max iterations must be positive".to_string(),
        ));
    }
    if points.len() > u32::MAX as usize {
        return Err(Error::InvalidData(
            "Point cloud is too large for GPU segmentation".to_string(),
        ));
    }
    Ok(())
}

fn validate_cluster_inputs(points: &[Point3f], config: &GpuEuclideanClusterConfig) -> Result<()> {
    if points.is_empty() {
        return Err(Error::InvalidData("Point cloud is empty".to_string()));
    }
    if config.tolerance <= 0.0 {
        return Err(Error::InvalidData("Tolerance must be positive".to_string()));
    }
    if config.min_cluster_size == 0 {
        return Err(Error::InvalidData(
            "min_cluster_size must be at least 1".to_string(),
        ));
    }
    if config.min_cluster_size > config.max_cluster_size {
        return Err(Error::InvalidData(
            "min_cluster_size must not exceed max_cluster_size".to_string(),
        ));
    }
    if config.max_neighbors == 0 {
        return Err(Error::InvalidData(
            "max_neighbors must be at least 1".to_string(),
        ));
    }
    if points.len() > u32::MAX as usize {
        return Err(Error::InvalidData(
            "Point cloud is too large for GPU clustering".to_string(),
        ));
    }
    Ok(())
}

fn points_to_vec4(points: &[Point3f]) -> Vec<[f32; 4]> {
    points.iter().map(|p| [p.x, p.y, p.z, 0.0]).collect()
}

fn generate_ransac_samples(num_points: usize, sample_count: usize) -> Vec<[u32; 4]> {
    let mut state = ((num_points as u64) << 32) ^ sample_count as u64 ^ 0x9E37_79B9_7F4A_7C15;
    let mut samples = Vec::with_capacity(sample_count);

    for iteration in 0..sample_count {
        let mut a = next_index(&mut state, num_points);
        let mut b = next_index(&mut state, num_points);
        let mut c = next_index(&mut state, num_points);

        if a == b || a == c || b == c {
            a = iteration % num_points;
            b = (iteration.wrapping_mul(37) + 1) % num_points;
            c = (iteration.wrapping_mul(101) + 2) % num_points;
            while b == a {
                b = (b + 1) % num_points;
            }
            while c == a || c == b {
                c = (c + 1) % num_points;
            }
        }

        samples.push([a as u32, b as u32, c as u32, 0]);
    }

    samples
}

fn next_index(state: &mut u64, len: usize) -> usize {
    *state = state
        .wrapping_mul(6_364_136_223_846_793_005)
        .wrapping_add(1_442_695_040_888_963_407);
    ((*state >> 32) as usize) % len
}

fn storage_entry(binding: u32, read_only: bool) -> wgpu::BindGroupLayoutEntry {
    wgpu::BindGroupLayoutEntry {
        binding,
        visibility: wgpu::ShaderStages::COMPUTE,
        ty: wgpu::BindingType::Buffer {
            ty: wgpu::BufferBindingType::Storage { read_only },
            has_dynamic_offset: false,
            min_binding_size: None,
        },
        count: None,
    }
}

fn uniform_entry(binding: u32) -> wgpu::BindGroupLayoutEntry {
    wgpu::BindGroupLayoutEntry {
        binding,
        visibility: wgpu::ShaderStages::COMPUTE,
        ty: wgpu::BindingType::Buffer {
            ty: wgpu::BufferBindingType::Uniform,
            has_dynamic_offset: false,
            min_binding_size: None,
        },
        count: None,
    }
}

fn div_ceil(value: usize, divisor: usize) -> usize {
    value.div_ceil(divisor)
}

#[cfg(test)]
mod tests {
    use super::*;

    async fn try_create_gpu_context() -> Option<GpuContext> {
        match GpuContext::new().await {
            Ok(gpu) => Some(gpu),
            Err(_) => {
                println!("GPU not available, skipping GPU-dependent test");
                None
            }
        }
    }

    fn planar_cloud() -> PointCloud<Point3f> {
        let mut cloud = PointCloud::new();
        for x in 0..12 {
            for y in 0..12 {
                cloud.push(Point3f::new(x as f32 * 0.1, y as f32 * 0.1, 0.0));
            }
        }
        cloud.push(Point3f::new(0.0, 0.0, 3.0));
        cloud.push(Point3f::new(1.0, 1.0, -3.0));
        cloud
    }

    fn clustered_cloud() -> PointCloud<Point3f> {
        let mut cloud = PointCloud::new();
        for i in 0..30 {
            let x = (i % 5) as f32 * 0.04;
            let y = (i / 5) as f32 * 0.04;
            cloud.push(Point3f::new(x, y, 0.0));
        }
        for i in 0..20 {
            let x = 5.0 + (i % 5) as f32 * 0.04;
            let y = (i / 5) as f32 * 0.04;
            cloud.push(Point3f::new(x, y, 0.0));
        }
        cloud
    }

    #[test]
    fn test_gpu_ransac_plane() {
        pollster::block_on(async {
            let Some(gpu) = try_create_gpu_context().await else {
                return;
            };

            let cloud = planar_cloud();
            let config = GpuPlaneSegmentationConfig {
                max_iterations: 256,
                distance_threshold: 0.01,
                min_inliers: 140,
            };
            let result = gpu_segment_plane(&gpu, &cloud, config).await.unwrap();

            assert!(result.inliers.len() >= 140);
            assert!(result.plane.normal().z.abs() > 0.9);
            assert_eq!(result.model, result.plane);
            assert_eq!(result.iterations, 256);
        });
    }

    /// The cases from #217: the old GPU path split two dense blobs into single
    /// points and separated a pair 0.02 apart, and it ran out of buffer space
    /// above 65,536 points.
    #[test]
    fn test_gpu_clusters_match_cpu_and_handle_large_clouds() {
        pollster::block_on(async {
            let Some(gpu) = try_create_gpu_context().await else {
                return;
            };
            let blob = |cx: f32, cy: f32, cz: f32| {
                (0..600).map(move |i| {
                    let (a, b, c) = ((i % 10) as f32, ((i / 10) % 10) as f32, (i / 100) as f32);
                    Point3f::new(cx + a * 0.02, cy + b * 0.02, cz + c * 0.02)
                })
            };
            let mut points: Vec<Point3f> =
                blob(0.25, 0.5, 0.5).chain(blob(1.05, -0.9, -0.9)).collect();
            points.push(Point3f::new(1.99, 0.5, 0.5));
            points.push(Point3f::new(2.01, 0.5, 0.5));
            let cloud = PointCloud::from_points(points);
            let config = GpuEuclideanClusterConfig::new(1.0, 1, 10_000);
            let gpu_result = gpu_extract_euclidean_clusters(&gpu, &cloud, &config)
                .await
                .unwrap();
            let sizes: Vec<usize> = gpu_result.clusters.iter().map(Vec::len).collect();
            let cpu = threecrate_algorithms::extract_euclidean_clusters(
                &cloud,
                &threecrate_algorithms::EuclideanClusterConfig::new(1.0, 1, 10_000),
            )
            .unwrap();
            assert_eq!(gpu_result.clusters, cpu.clusters);
            assert_eq!(sizes.iter().sum::<usize>(), 1202);
            assert!(sizes.len() <= 3, "clusters were split: {sizes:?}");

            // 70,000 points in two well-separated sheets.
            let big = PointCloud::from_points(
                (0..70_000)
                    .map(|i| {
                        let x = (i % 350) as f32 * 0.01 + if i < 35_000 { 0.0 } else { 100.0 };
                        Point3f::new(x, (i / 350 % 100) as f32 * 0.01, 0.0)
                    })
                    .collect(),
            );
            let config = GpuEuclideanClusterConfig::new(0.02, 100, 100_000);
            let result = gpu_extract_euclidean_clusters(&gpu, &big, &config)
                .await
                .unwrap();
            assert_eq!(result.num_clusters(), 2);
        });
    }

    #[test]
    fn test_gpu_clusters() {
        pollster::block_on(async {
            let Some(gpu) = try_create_gpu_context().await else {
                return;
            };

            let cloud = clustered_cloud();
            let config = GpuEuclideanClusterConfig::with_max_neighbors(0.09, 5, 100, 16);
            let result = gpu_extract_euclidean_clusters(&gpu, &cloud, &config)
                .await
                .unwrap();
            let cluster_clouds = gpu_extract_clusters(&gpu, &cloud, config).await.unwrap();

            assert_eq!(result.num_clusters(), 2);
            assert_eq!(result.clusters[0].len(), 30);
            assert_eq!(result.clusters[1].len(), 20);
            assert_eq!(cluster_clouds.len(), 2);
            assert_eq!(cluster_clouds[0].len(), 30);
            assert_eq!(cluster_clouds[1].len(), 20);
        });
    }

    #[test]
    fn test_invalid_inputs() {
        let cloud = PointCloud::from_points(vec![Point3f::new(0.0, 0.0, 0.0)]);
        assert!(validate_ransac_inputs(&cloud.points, 0.1, 10).is_err());
        assert!(validate_ransac_inputs(&planar_cloud().points, -0.1, 10).is_err());
        assert!(validate_ransac_inputs(&planar_cloud().points, 0.1, 0).is_err());
        assert!(validate_ransac_config(
            &planar_cloud().points,
            GpuPlaneSegmentationConfig {
                min_inliers: 0,
                ..GpuPlaneSegmentationConfig::default()
            }
        )
        .is_err());

        let config = GpuEuclideanClusterConfig::new(-1.0, 1, 10);
        assert!(validate_cluster_inputs(&clustered_cloud().points, &config).is_err());
    }
}