meshopt 0.6.2

Rust ffi bindings and idiomatic wrapper for mesh optimizer
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
use crate::ffi;
use crate::{DecodePosition, VertexDataAdapter};
use std::mem;

pub type Bounds = ffi::meshopt_Bounds;

/// Internal helper to finalize meshlet data by truncating arrays and optimizing meshlets
fn finalize_meshlets(
    mut meshlets: Vec<ffi::meshopt_Meshlet>,
    mut meshlet_verts: Vec<u32>,
    mut meshlet_tris: Vec<u8>,
    count: usize,
) -> Meshlets {
    if count > 0 {
        let last_meshlet = meshlets[count - 1];
        meshlet_verts
            .truncate(last_meshlet.vertex_offset as usize + last_meshlet.vertex_count as usize);
        meshlet_tris.truncate(
            last_meshlet.triangle_offset as usize
                + ((last_meshlet.triangle_count as usize * 3 + 3) & !3),
        );
    }
    meshlets.truncate(count);

    // Optimize each meshlet
    for meshlet in meshlets.iter_mut().take(count) {
        unsafe {
            ffi::meshopt_optimizeMeshlet(
                &mut meshlet_verts[meshlet.vertex_offset as usize],
                &mut meshlet_tris[meshlet.triangle_offset as usize],
                meshlet.triangle_count as usize,
                meshlet.vertex_count as usize,
            );
        };
    }

    Meshlets {
        meshlets,
        vertices: meshlet_verts,
        triangles: meshlet_tris,
    }
}

#[derive(Copy, Clone)]
pub struct Meshlet<'data> {
    pub vertices: &'data [u32],
    pub triangles: &'data [u8],
}

pub struct Meshlets {
    pub meshlets: Vec<ffi::meshopt_Meshlet>,
    pub vertices: Vec<u32>,
    pub triangles: Vec<u8>,
}

impl Meshlets {
    #[inline]
    pub fn len(&self) -> usize {
        self.meshlets.len()
    }
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.meshlets.is_empty()
    }

    fn meshlet_from_ffi(&self, meshlet: &ffi::meshopt_Meshlet) -> Meshlet<'_> {
        Meshlet {
            vertices: &self.vertices[meshlet.vertex_offset as usize
                ..meshlet.vertex_offset as usize + meshlet.vertex_count as usize],
            triangles: &self.triangles[meshlet.triangle_offset as usize
                ..meshlet.triangle_offset as usize + meshlet.triangle_count as usize * 3],
        }
    }

    #[inline]
    pub fn get(&self, idx: usize) -> Meshlet<'_> {
        self.meshlet_from_ffi(&self.meshlets[idx])
    }

    pub fn iter(&self) -> impl Iterator<Item = Meshlet<'_>> {
        self.meshlets
            .iter()
            .map(|meshlet| self.meshlet_from_ffi(meshlet))
    }
}

/// Splits the mesh into a set of meshlets where each meshlet has a micro index buffer
/// indexing into meshlet vertices that refer to the original vertex buffer.
///
/// The resulting data can be used to render meshes using `NVidia programmable mesh shading`
/// pipeline, or in other cluster-based renderers.
///
/// Note: `max_vertices` must be <= 256 and `max_triangles` must be <= 512 and divisible by 4.
pub fn build_meshlets(
    indices: &[u32],
    vertices: &VertexDataAdapter<'_>,
    max_vertices: usize,
    max_triangles: usize,
    cone_weight: f32,
) -> Meshlets {
    let meshlet_count =
        unsafe { ffi::meshopt_buildMeshletsBound(indices.len(), max_vertices, max_triangles) };
    let mut meshlets: Vec<ffi::meshopt_Meshlet> =
        vec![unsafe { ::std::mem::zeroed() }; meshlet_count];

    let mut meshlet_verts: Vec<u32> = vec![0; meshlet_count * max_vertices];
    let mut meshlet_tris: Vec<u8> = vec![0; meshlet_count * max_triangles * 3];

    let count = unsafe {
        ffi::meshopt_buildMeshlets(
            meshlets.as_mut_ptr(),
            meshlet_verts.as_mut_ptr(),
            meshlet_tris.as_mut_ptr(),
            indices.as_ptr(),
            indices.len(),
            vertices.pos_ptr(),
            vertices.vertex_count,
            vertices.vertex_stride,
            max_vertices,
            max_triangles,
            cone_weight,
        )
    };

    finalize_meshlets(meshlets, meshlet_verts, meshlet_tris, count)
}

/// Experimental: Meshlet builder with flexible cluster sizes.
///
/// Splits the mesh into a set of meshlets, similarly to `build_meshlets`, but allows to specify minimum and maximum number of triangles per meshlet.
/// Clusters between min and max triangle counts are split when the cluster size would have exceeded the expected cluster size by more than `split_factor`.
/// Additionally, allows to switch to axis aligned clusters by setting `cone_weight` to a negative value.
///
/// * `max_vertices`, `min_triangles` and `max_triangles` must not exceed implementation limits (`max_vertices` <= 256, `max_triangles` <= 512; `min_triangles` <= `max_triangles`; both `min_triangles` and `max_triangles` must be divisible by 4)
/// * `cone_weight` should be set to 0 when cone culling is not used, and a value between 0 and 1 otherwise to balance between cluster size and cone culling efficiency; additionally, `cone_weight` can be set to a negative value to prioritize axis aligned clusters (for raytracing) instead
/// * `split_factor` should be set to a non-negative value; when greater than 0, clusters that have large bounds may be split unless they are under the `min_triangles` threshold
pub fn build_meshlets_flex(
    indices: &[u32],
    vertices: &VertexDataAdapter<'_>,
    max_vertices: usize,
    min_triangles: usize,
    max_triangles: usize,
    cone_weight: f32,
    split_factor: f32,
) -> Meshlets {
    let meshlet_count =
        unsafe { ffi::meshopt_buildMeshletsBound(indices.len(), max_vertices, min_triangles) };
    let mut meshlets: Vec<ffi::meshopt_Meshlet> = vec![unsafe { mem::zeroed() }; meshlet_count];

    let mut meshlet_verts: Vec<u32> = vec![0; meshlet_count * max_vertices];
    let mut meshlet_tris: Vec<u8> = vec![0; meshlet_count * max_triangles * 3];

    let count = unsafe {
        ffi::meshopt_buildMeshletsFlex(
            meshlets.as_mut_ptr(),
            meshlet_verts.as_mut_ptr(),
            meshlet_tris.as_mut_ptr(),
            indices.as_ptr(),
            indices.len(),
            vertices.pos_ptr(),
            vertices.vertex_count,
            vertices.vertex_stride,
            max_vertices,
            min_triangles,
            max_triangles,
            cone_weight,
            split_factor,
        )
    };

    finalize_meshlets(meshlets, meshlet_verts, meshlet_tris, count)
}

/// Experimental: Spatial meshlet builder with flexible cluster sizes.
///
/// Splits the mesh into a set of meshlets, similarly to `build_meshlets`, but allows to specify minimum and maximum number of triangles per meshlet.
/// Uses a spatial approach that optimizes for SAH (Surface Area Heuristic) quality while supporting flexible cluster sizes.
///
/// * `max_vertices`, `min_triangles` and `max_triangles` must not exceed implementation limits (`max_vertices` <= 256, `max_triangles` <= 512; `min_triangles` <= `max_triangles`; both `min_triangles` and `max_triangles` must be divisible by 4)
/// * `fill_weight` allows to prioritize clusters that are closer to maximum size at some cost to SAH quality; 0.5 is a safe default
pub fn build_meshlets_spatial(
    indices: &[u32],
    vertices: &VertexDataAdapter<'_>,
    max_vertices: usize,
    min_triangles: usize,
    max_triangles: usize,
    fill_weight: f32,
) -> Meshlets {
    let meshlet_count =
        unsafe { ffi::meshopt_buildMeshletsBound(indices.len(), max_vertices, min_triangles) };
    let mut meshlets: Vec<ffi::meshopt_Meshlet> = vec![unsafe { mem::zeroed() }; meshlet_count];

    let mut meshlet_verts: Vec<u32> = vec![0; meshlet_count * max_vertices];
    let mut meshlet_tris: Vec<u8> = vec![0; meshlet_count * max_triangles * 3];

    let count = unsafe {
        ffi::meshopt_buildMeshletsSpatial(
            meshlets.as_mut_ptr(),
            meshlet_verts.as_mut_ptr(),
            meshlet_tris.as_mut_ptr(),
            indices.as_ptr(),
            indices.len(),
            vertices.pos_ptr(),
            vertices.vertex_count,
            vertices.vertex_stride,
            max_vertices,
            min_triangles,
            max_triangles,
            fill_weight,
        )
    };

    finalize_meshlets(meshlets, meshlet_verts, meshlet_tris, count)
}

/// Cluster partitioner
/// Partitions clusters into groups of similar size, prioritizing grouping clusters that share vertices.
///
///  `destination` must contain enough space for the resulting partition data (`cluster_index_counts.len()` elements)
///  `destination[i]` will contain the partition id for cluster i, with the total number of partitions returned by the function.
///  `cluster_indices` should have the vertex indices referenced by each cluster, stored sequentially
///  `cluster_index_counts` should have the number of indices in each cluster; sum of all `cluster_index_counts` must be equal to `cluster_indices.len()`
///  `target_partition_size` is a target size for each partition, in clusters; the resulting partitions may be smaller or larger
///
/// The returned value is the number of partitions created. (`destination` can be sliced to the size of the returned value)
pub fn partition_clusters(
    destination: &mut [u32],
    cluster_indices: &[u32],
    cluster_index_counts: &[u32],
    vertex_count: usize,
    target_partition_size: usize,
) -> usize {
    assert_eq!(destination.len(), cluster_index_counts.len());
    debug_assert_eq!(
        cluster_indices.len(),
        cluster_index_counts.iter().sum::<u32>() as usize
    );
    unsafe {
        ffi::meshopt_partitionClusters(
            destination.as_mut_ptr(),
            cluster_indices.as_ptr(),
            cluster_indices.len(),
            cluster_index_counts.as_ptr(),
            cluster_index_counts.len(),
            std::ptr::null(),
            vertex_count,
            0,
            target_partition_size,
        )
    }
}

/// Cluster partitioner with vertex positions
/// Partitions clusters into groups of similar size, prioritizing grouping clusters that share vertices
/// and are spatially close based on vertex positions.
///
///  `destination` must contain enough space for the resulting partition data (`cluster_index_counts.len()` elements)
///  `destination[i]` will contain the partition id for cluster i, with the total number of partitions returned by the function.
///  `cluster_indices` should have the vertex indices referenced by each cluster, stored sequentially
///  `cluster_index_counts` should have the number of indices in each cluster; sum of all `cluster_index_counts` must be equal to `cluster_indices.len()`
///  `vertices` should contain vertex position data
///  `target_partition_size` is a target size for each partition, in clusters; the resulting partitions may be smaller or larger
///
/// The returned value is the number of partitions created. (`destination` can be sliced to the size of the returned value)
pub fn partition_clusters_with_positions(
    destination: &mut [u32],
    cluster_indices: &[u32],
    cluster_index_counts: &[u32],
    vertices: &VertexDataAdapter<'_>,
    target_partition_size: usize,
) -> usize {
    assert_eq!(destination.len(), cluster_index_counts.len());
    debug_assert_eq!(
        cluster_indices.len(),
        cluster_index_counts.iter().sum::<u32>() as usize
    );
    unsafe {
        ffi::meshopt_partitionClusters(
            destination.as_mut_ptr(),
            cluster_indices.as_ptr(),
            cluster_indices.len(),
            cluster_index_counts.as_ptr(),
            cluster_index_counts.len(),
            vertices.pos_ptr(),
            vertices.vertex_count,
            vertices.vertex_stride,
            target_partition_size,
        )
    }
}

/// Cluster partitioner with vertex positions (decoder version)
/// Partitions clusters into groups of similar size, prioritizing grouping clusters that share vertices
/// and are spatially close based on vertex positions.
///
///  `destination` must contain enough space for the resulting partition data (`cluster_index_counts.len()` elements)
///  `destination[i]` will contain the partition id for cluster i, with the total number of partitions returned by the function.
///  `cluster_indices` should have the vertex indices referenced by each cluster, stored sequentially
///  `cluster_index_counts` should have the number of indices in each cluster; sum of all `cluster_index_counts` must be equal to `cluster_indices.len()`
///  `vertices` should contain vertex data that can decode positions
///  `target_partition_size` is a target size for each partition, in clusters; the resulting partitions may be smaller or larger
///
/// The returned value is the number of partitions created. (`destination` can be sliced to the size of the returned value)
pub fn partition_clusters_with_decoder<T: DecodePosition>(
    destination: &mut [u32],
    cluster_indices: &[u32],
    cluster_index_counts: &[u32],
    vertices: &[T],
    target_partition_size: usize,
) -> usize {
    assert_eq!(destination.len(), cluster_index_counts.len());
    debug_assert_eq!(
        cluster_indices.len(),
        cluster_index_counts.iter().sum::<u32>() as usize
    );
    let positions = vertices
        .iter()
        .map(|vertex| vertex.decode_position())
        .collect::<Vec<[f32; 3]>>();
    unsafe {
        ffi::meshopt_partitionClusters(
            destination.as_mut_ptr(),
            cluster_indices.as_ptr(),
            cluster_indices.len(),
            cluster_index_counts.as_ptr(),
            cluster_index_counts.len(),
            positions.as_ptr().cast(),
            positions.len(),
            mem::size_of::<f32>() * 3,
            target_partition_size,
        )
    }
}

/// Creates bounding volumes that can be used for frustum, backface and occlusion culling.
///
/// For backface culling with orthographic projection, use the following formula to reject backfacing clusters:
///   `dot(view, cone_axis) >= cone_cutoff`
///
/// For perspective projection, use the following formula that needs cone apex in addition to axis & cutoff:
///   `dot(normalize(cone_apex - camera_position), cone_axis) >= cone_cutoff`
///
/// Alternatively, you can use the formula that doesn't need cone apex and uses bounding sphere instead:
///   `dot(normalize(center - camera_position), cone_axis) >= cone_cutoff + radius / length(center - camera_position)`
///
/// or an equivalent formula that doesn't have a singularity at `center = camera_position`:
///   `dot(center - camera_position, cone_axis) >= cone_cutoff * length(center - camera_position) + radius`
///
/// The formula that uses the apex is slightly more accurate but needs the apex; if you are already using bounding sphere
/// to do frustum/occlusion culling, the formula that doesn't use the apex may be preferable.
///
/// `index_count` should be <= 256*3 (the function assumes clusters of limited size)
pub fn compute_cluster_bounds(indices: &[u32], vertices: &VertexDataAdapter<'_>) -> Bounds {
    unsafe {
        ffi::meshopt_computeClusterBounds(
            indices.as_ptr(),
            indices.len(),
            vertices.pos_ptr(),
            vertices.vertex_count,
            vertices.vertex_stride,
        )
    }
}

/// Creates a view into data containing position-like information.
pub struct PositionDataAdapter<'a> {
    /// The data buffer containing position information.
    /// This should be a pointer to a buffer of size at least `position_count * position_stride`.
    pub data: &'a [u8],
    /// The number of positions in the buffer.
    pub position_count: usize,
    /// The size of each element in the buffer. can be as big as you want if indexing in some other struct
    pub position_stride: usize,
    /// The offset in bytes from the start of each element to the position data. it must contain 3xf32 of information.
    pub position_offset: usize,
}

/// Creates a view into data containing radius-like information. radius must be a non-negative f32.
/// You may use the same data for both position and radius, but the stride must be the same.
pub struct RadiusDataAdapter<'a> {
    /// The data buffer containing radius information.
    /// This should be a pointer to a buffer of size at least `radius_count * radius_stride`.
    pub data: &'a [u8],
    /// The number of radii in the buffer.
    pub radius_count: usize,
    /// The size of each element in the buffer. can be as big as you want if indexing in some other struct
    pub radius_stride: usize,
    /// The offset in bytes from the start of each element to the radius data.
    pub radius_offset: usize,
}

pub struct Sphere {
    pub center: [f32; 3],
    pub radius: f32,
}

/// Sphere bounds generator
/// Creates bounding sphere around a set of points or a set of spheres;
pub fn compute_sphere_bounds(
    positions: PositionDataAdapter<'_>,
    radius: Option<RadiusDataAdapter<'_>>,
) -> Sphere {
    if let Some(ref r) = radius {
        assert_eq!(positions.position_count, r.radius_count);
        assert!(r.data.len() >= r.radius_count * r.radius_stride);
        assert!(r.radius_offset + mem::size_of::<f32>() <= r.radius_stride);
    }
    assert!(positions.data.len() >= positions.position_count * positions.position_stride);
    assert!(positions.position_offset + mem::size_of::<f32>() * 3 <= positions.position_stride);
    unsafe {
        let (radius_ptr, radius_stride) = match radius {
            Some(r) => (r.data.as_ptr().add(r.radius_offset).cast(), r.radius_stride),
            None => (std::ptr::null(), 0),
        };
        let bounds = ffi::meshopt_computeSphereBounds(
            positions
                .data
                .as_ptr()
                .add(positions.position_offset)
                .cast(),
            positions.position_count,
            positions.position_stride,
            radius_ptr,
            radius_stride,
        );

        Sphere {
            center: [bounds.center[0], bounds.center[1], bounds.center[2]],
            radius: bounds.radius,
        }
    }
}

/// Creates bounding volumes that can be used for frustum, backface and occlusion culling.
///
/// For backface culling with orthographic projection, use the following formula to reject backfacing clusters:
///   `dot(view, cone_axis) >= cone_cutoff`
///
/// For perspective projection, use the following formula that needs cone apex in addition to axis & cutoff:
///   `dot(normalize(cone_apex - camera_position), cone_axis) >= cone_cutoff`
///
/// Alternatively, you can use the formula that doesn't need cone apex and uses bounding sphere instead:
///   `dot(normalize(center - camera_position), cone_axis) >= cone_cutoff + radius / length(center - camera_position)`
///
/// or an equivalent formula that doesn't have a singularity at `center = camera_position`:
///   `dot(center - camera_position, cone_axis) >= cone_cutoff * length(center - camera_position) + radius`
///
/// The formula that uses the apex is slightly more accurate but needs the apex; if you are already using bounding sphere
/// to do frustum/occlusion culling, the formula that doesn't use the apex may be preferable.
///
/// `index_count` should be <= 256*3 (the function assumes clusters of limited size)
pub fn compute_cluster_bounds_decoder<T: DecodePosition>(
    indices: &[u32],
    vertices: &[T],
) -> Bounds {
    let vertices = vertices
        .iter()
        .map(|vertex| vertex.decode_position())
        .collect::<Vec<[f32; 3]>>();
    unsafe {
        ffi::meshopt_computeClusterBounds(
            indices.as_ptr(),
            indices.len(),
            vertices.as_ptr().cast(),
            vertices.len() * 3,
            mem::size_of::<f32>() * 3,
        )
    }
}

pub fn compute_meshlet_bounds(meshlet: Meshlet<'_>, vertices: &VertexDataAdapter<'_>) -> Bounds {
    unsafe {
        ffi::meshopt_computeMeshletBounds(
            meshlet.vertices.as_ptr(),
            meshlet.triangles.as_ptr(),
            meshlet.triangles.len() / 3,
            vertices.pos_ptr(),
            vertices.vertex_count,
            vertices.vertex_stride,
        )
    }
}

pub fn compute_meshlet_bounds_decoder<T: DecodePosition>(
    meshlet: Meshlet<'_>,
    vertices: &[T],
) -> Bounds {
    let vertices = vertices
        .iter()
        .map(|vertex| vertex.decode_position())
        .collect::<Vec<[f32; 3]>>();
    unsafe {
        ffi::meshopt_computeMeshletBounds(
            meshlet.vertices.as_ptr(),
            meshlet.triangles.as_ptr(),
            meshlet.triangles.len() / 3,
            vertices.as_ptr().cast(),
            vertices.len() * 3,
            mem::size_of::<f32>() * 3,
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::typed_to_bytes;
    #[test]
    fn test_cluster_sphere_bounds() {
        let vbr: &[f32] = &[
            0.0, 0.0, 0.0, 0.0, //
            0.0, 1.0, 0.0, 1.0, //
            0.0, 0.0, 1.0, 2.0, //
            1.0, 0.0, 1.0, 3.0,
        ];

        let bounds = compute_sphere_bounds(
            PositionDataAdapter {
                data: typed_to_bytes(vbr),
                position_count: 4,
                position_stride: 4 * mem::size_of::<f32>(),
                position_offset: 0,
            },
            None,
        );

        assert!(bounds.radius < 0.97);

        let eps: &[f32] = &[1e-3, 2e-3, 3e-3, 4e-3];

        let bounds = compute_sphere_bounds(
            PositionDataAdapter {
                data: typed_to_bytes(vbr),
                position_count: 4,
                position_stride: 4 * mem::size_of::<f32>(),
                position_offset: 0,
            },
            Some(RadiusDataAdapter {
                data: typed_to_bytes(eps),
                radius_count: 4,
                radius_stride: mem::size_of::<f32>(),
                radius_offset: 0,
            }),
        );

        assert!(bounds.radius < 0.87);
        assert!((bounds.center[0] - 0.5).abs() < 1e-2);
        assert!((bounds.center[1] - 0.5).abs() < 1e-2);
        assert!((bounds.center[2] - 0.5).abs() < 1e-2);

        let bounds = compute_sphere_bounds(
            PositionDataAdapter {
                data: typed_to_bytes(vbr),
                position_count: 4,
                position_stride: 4 * mem::size_of::<f32>(),
                position_offset: 0,
            },
            Some(RadiusDataAdapter {
                data: typed_to_bytes(vbr),
                radius_count: 4,
                radius_stride: 4 * mem::size_of::<f32>(),
                radius_offset: 3 * mem::size_of::<f32>(),
            }),
        );

        assert!((bounds.radius - 3.0).abs() < 1e-2);
        assert!((bounds.center[0] - 1.0).abs() < 1e-2);
        assert!((bounds.center[1] - 0.0).abs() < 1e-2);
        assert!((bounds.center[2] - 1.0).abs() < 1e-2);
    }

    #[test]
    fn test_partition_basic() {
        // 0   1   2
        //     3
        // 4 5 6 7 8
        //     9
        // 10 11  12
        let cluster_indices: &[u32] = &[
            0, 1, 3, 4, 5, 6, //
            1, 2, 3, 6, 7, 8, //
            4, 5, 6, 9, 10, 11, //
            6, 7, 8, 9, 11, 12, //
        ];

        let cluster_index_counts: &[u32] = &[6, 6, 6, 6];
        let mut partitions = vec![0u32; cluster_index_counts.len()];

        assert_eq!(
            partition_clusters(
                &mut partitions,
                cluster_indices,
                cluster_index_counts,
                13,
                1
            ),
            4
        );
        assert_eq!(partitions, [0, 1, 2, 3]);

        assert_eq!(
            partition_clusters(
                &mut partitions,
                cluster_indices,
                cluster_index_counts,
                13,
                2
            ),
            2
        );
        assert_eq!(partitions, [0, 0, 1, 1]);

        assert_eq!(
            partition_clusters(
                &mut partitions,
                cluster_indices,
                cluster_index_counts,
                13,
                4
            ),
            1
        );
        assert_eq!(partitions, [0, 0, 0, 0]);
    }

    #[test]
    fn test_partition_with_positions() {
        // 0   1   2
        //     3
        // 4 5 6 7 8
        //     9
        // 10 11  12
        let cluster_indices: &[u32] = &[
            0, 1, 3, 4, 5, 6, //
            1, 2, 3, 6, 7, 8, //
            4, 5, 6, 9, 10, 11, //
            6, 7, 8, 9, 11, 12, //
        ];

        let cluster_index_counts: &[u32] = &[6, 6, 6, 6];
        let mut partitions = vec![0u32; cluster_index_counts.len()];

        // Vertex positions arranged in a 3x4 grid
        let vertices: &[f32] = &[
            0.0, 0.0, 0.0, // 0
            1.0, 0.0, 0.0, // 1
            2.0, 0.0, 0.0, // 2
            1.0, 1.0, 0.0, // 3
            0.0, 2.0, 0.0, // 4
            1.0, 2.0, 0.0, // 5
            2.0, 2.0, 0.0, // 6
            3.0, 2.0, 0.0, // 7
            4.0, 2.0, 0.0, // 8
            2.0, 3.0, 0.0, // 9
            0.0, 4.0, 0.0, // 10
            1.0, 4.0, 0.0, // 11
            2.0, 4.0, 0.0, // 12
        ];

        let vertex_adapter =
            VertexDataAdapter::new(typed_to_bytes(vertices), 3 * mem::size_of::<f32>(), 0).unwrap();

        // Test with positions - should produce better spatial partitioning
        let result = partition_clusters_with_positions(
            &mut partitions,
            cluster_indices,
            cluster_index_counts,
            &vertex_adapter,
            2,
        );

        assert_eq!(result, 2);
        assert_eq!(partitions, [0, 1, 0, 1]);
    }

    #[test]
    fn test_partition_with_decoder() {
        use crate::Vertex;

        // Same test as above but using decoder interface
        let cluster_indices: &[u32] = &[
            0, 1, 3, 4, 5, 6, 1, 2, 3, 6, 7, 8, 4, 5, 6, 9, 10, 11, 6, 7, 8, 9, 11, 12,
        ];

        let cluster_index_counts: &[u32] = &[6, 6, 6, 6];
        let mut partitions = vec![0u32; cluster_index_counts.len()];

        // Create vertices with position data
        let vertices: Vec<Vertex> = vec![
            Vertex {
                p: [0.0, 0.0, 0.0],
                ..Default::default()
            }, // 0
            Vertex {
                p: [1.0, 0.0, 0.0],
                ..Default::default()
            }, // 1
            Vertex {
                p: [2.0, 0.0, 0.0],
                ..Default::default()
            }, // 2
            Vertex {
                p: [1.0, 1.0, 0.0],
                ..Default::default()
            }, // 3
            Vertex {
                p: [0.0, 2.0, 0.0],
                ..Default::default()
            }, // 4
            Vertex {
                p: [1.0, 2.0, 0.0],
                ..Default::default()
            }, // 5
            Vertex {
                p: [2.0, 2.0, 0.0],
                ..Default::default()
            }, // 6
            Vertex {
                p: [3.0, 2.0, 0.0],
                ..Default::default()
            }, // 7
            Vertex {
                p: [4.0, 2.0, 0.0],
                ..Default::default()
            }, // 8
            Vertex {
                p: [2.0, 3.0, 0.0],
                ..Default::default()
            }, // 9
            Vertex {
                p: [0.0, 4.0, 0.0],
                ..Default::default()
            }, // 10
            Vertex {
                p: [1.0, 4.0, 0.0],
                ..Default::default()
            }, // 11
            Vertex {
                p: [2.0, 4.0, 0.0],
                ..Default::default()
            }, // 12
        ];

        let result = partition_clusters_with_decoder(
            &mut partitions,
            cluster_indices,
            cluster_index_counts,
            &vertices,
            2,
        );

        assert_eq!(result, 2);
        assert_eq!(partitions, [0, 1, 0, 1]);
    }

    #[test]
    fn test_meshlets_flex() {
        // Two tetrahedrons far apart
        let vb: &[f32] = &[
            0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, //
            10.0, 0.0, 0.0, 11.0, 0.0, 0.0, 10.0, 1.0, 0.0, 10.0, 0.0, 1.0,
        ];

        let ib: &[u32] = &[
            0, 1, 2, 0, 2, 3, 0, 3, 1, 1, 3, 2, //
            4, 5, 6, 4, 6, 7, 4, 7, 5, 5, 7, 6,
        ];

        let vertices =
            VertexDataAdapter::new(typed_to_bytes(vb), mem::size_of::<[f32; 3]>(), 0).unwrap();

        // Up to 2 meshlets with min_triangles = 4
        assert_eq!(
            unsafe { ffi::meshopt_buildMeshletsBound(ib.len(), 16, 4) },
            2
        );

        let meshlets = build_meshlets_flex(ib, &vertices, 16, 4, 8, 0.0, 0.0);
        assert_eq!(meshlets.len(), 1);
        assert_eq!(meshlets.meshlets[0].triangle_count, 8);
        assert_eq!(meshlets.meshlets[0].vertex_count, 8);

        let meshlets = build_meshlets_flex(ib, &vertices, 16, 4, 8, 0.0, 10.0);
        assert_eq!(meshlets.len(), 1);
        assert_eq!(meshlets.meshlets[0].triangle_count, 8);
        assert_eq!(meshlets.meshlets[0].vertex_count, 8);

        let meshlets = build_meshlets_flex(ib, &vertices, 16, 4, 8, 0.0, 1.0);
        assert_eq!(meshlets.len(), 2);
        assert_eq!(meshlets.meshlets[0].triangle_count, 4);
        assert_eq!(meshlets.meshlets[0].vertex_count, 4);
        assert_eq!(meshlets.meshlets[1].triangle_count, 4);
        assert_eq!(meshlets.meshlets[1].vertex_count, 4);

        let meshlets = build_meshlets_flex(ib, &vertices, 16, 4, 8, -1.0, 10.0);
        assert_eq!(meshlets.len(), 1);
        assert_eq!(meshlets.meshlets[0].triangle_count, 8);
        assert_eq!(meshlets.meshlets[0].vertex_count, 8);

        let meshlets = build_meshlets_flex(ib, &vertices, 16, 4, 8, -1.0, 1.0);
        assert_eq!(meshlets.len(), 2);
        assert_eq!(meshlets.meshlets[0].triangle_count, 4);
        assert_eq!(meshlets.meshlets[0].vertex_count, 4);
        assert_eq!(meshlets.meshlets[1].triangle_count, 4);
        assert_eq!(meshlets.meshlets[1].vertex_count, 4);
    }

    #[test]
    fn test_meshlets_spatial() {
        // Two tetrahedrons far apart (copied from vendor test)
        let vb: &[f32] = &[
            0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 10.0, 0.0, 0.0, 11.0, 0.0,
            0.0, 10.0, 1.0, 0.0, 10.0, 0.0, 1.0,
        ];

        let ib: &[u32] = &[
            0, 1, 2, 0, 2, 3, 0, 3, 1, 1, 3, 2, 4, 5, 6, 4, 6, 7, 4, 7, 5, 5, 7, 6,
        ];

        let vertices =
            VertexDataAdapter::new(typed_to_bytes(vb), 3 * mem::size_of::<f32>(), 0).unwrap();

        // Up to 2 meshlets with min_triangles=4
        assert_eq!(
            unsafe { ffi::meshopt_buildMeshletsBound(ib.len(), 16, 4) },
            2
        );

        // With strict limits, we should get one meshlet (max_triangles=8) or two (max_triangles=4)
        let meshlets = build_meshlets_spatial(ib, &vertices, 16, 8, 8, 0.0);
        assert_eq!(meshlets.len(), 1);
        assert_eq!(meshlets.meshlets[0].triangle_count, 8);
        assert_eq!(meshlets.meshlets[0].vertex_count, 8);

        let meshlets = build_meshlets_spatial(ib, &vertices, 16, 4, 4, 0.0);
        assert_eq!(meshlets.len(), 2);
        assert_eq!(meshlets.meshlets[0].triangle_count, 4);
        assert_eq!(meshlets.meshlets[0].vertex_count, 4);
        assert_eq!(meshlets.meshlets[1].triangle_count, 4);
        assert_eq!(meshlets.meshlets[1].vertex_count, 4);

        // With max_vertices=4 we should get two meshlets since we can't accommodate both
        let meshlets = build_meshlets_spatial(ib, &vertices, 4, 4, 8, 0.0);
        assert_eq!(meshlets.len(), 2);
        assert_eq!(meshlets.meshlets[0].triangle_count, 4);
        assert_eq!(meshlets.meshlets[0].vertex_count, 4);
        assert_eq!(meshlets.meshlets[1].triangle_count, 4);
        assert_eq!(meshlets.meshlets[1].vertex_count, 4);
    }
}