euv-core 0.57.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
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
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
use super::*;

/// Sanitizes a floating-point scalar by replacing non-finite values with `fallback`.
///
/// # Arguments
///
/// - `f32` - Input floating-point value.
/// - `f32` - Finite fallback value used when input is NaN or infinite.
///
/// # Returns
///
/// - `f32` - Guaranteed finite floating-point scalar.
#[must_use]
pub(crate) fn sanitize_scalar(value: f32, fallback: f32) -> f32 {
    if value.is_finite() { value } else { fallback }
}

/// Sanitizes a 3D vector component-wise by replacing non-finite values with `fallback`.
///
/// # Arguments
///
/// - `Vec3` - Input 3D vector.
/// - `Vec3` - Finite fallback vector.
///
/// # Returns
///
/// - `Vec3` - Guaranteed finite 3D vector.
#[must_use]
pub(crate) fn sanitize_vec3(value: Vec3, fallback: Vec3) -> Vec3 {
    Vec3::new(
        sanitize_scalar(value.get_x(), fallback.get_x()),
        sanitize_scalar(value.get_y(), fallback.get_y()),
        sanitize_scalar(value.get_z(), fallback.get_z()),
    )
}

/// Returns a guaranteed unit-length finite normal vector, falling back to `+Y` on degenerate input.
///
/// # Arguments
///
/// - `Vec3` - Candidate surface normal vector.
///
/// # Returns
///
/// - `Vec3` - Unit-length finite normal vector.
#[must_use]
pub(crate) fn safe_unit_normal(normal: Vec3) -> Vec3 {
    let clean: Vec3 = sanitize_vec3(normal, Vec3::new(0.0, 1.0, 0.0));
    let len_sq: f32 = clean.length_sq();
    if len_sq > MESH_OPS_EPSILON_SQ && len_sq.is_finite() {
        clean.scale(1.0 / len_sq.sqrt())
    } else {
        Vec3::new(0.0, 1.0, 0.0)
    }
}

/// Builds a `Vertex3D` populated with finite position, unit normal, primary UV, and white color.
///
/// # Arguments
///
/// - `Vec3` - Vertex local-space position.
/// - `Vec3` - Vertex surface normal.
/// - `[f32; 2]` - Primary UV coordinate.
///
/// # Returns
///
/// - `Vertex3D` - Populated 64-byte vertex with `uv0` flag enabled.
#[must_use]
pub(crate) fn make_textured_vertex(position: Vec3, normal: Vec3, uv0: [f32; 2]) -> Vertex3D {
    let clean_pos: Vec3 = sanitize_vec3(position, Vec3::zero());
    let clean_normal: Vec3 = safe_unit_normal(normal);
    let clean_uv: [f32; 2] = [sanitize_scalar(uv0[0], 0.0), sanitize_scalar(uv0[1], 0.0)];
    let fallback_axis: Vec3 = if clean_normal.get_y().abs() < 0.99 {
        Vec3::new(0.0, 1.0, 0.0)
    } else {
        Vec3::new(1.0, 0.0, 0.0)
    };
    let tangent_vec: Vec3 = safe_unit_normal(fallback_axis.cross(clean_normal));
    Vertex3D::from_full(
        clean_pos,
        clean_normal,
        [
            tangent_vec.get_x(),
            tangent_vec.get_y(),
            tangent_vec.get_z(),
            1.0,
        ],
        clean_uv,
        [0.0, 0.0],
        [255, 255, 255, 255],
        VERTEX_FLAG_UV0,
    )
}

/// Resolves or appends a material into `sub_materials` and returns its 1-based slot index.
///
/// # Arguments
///
/// - `PbrMaterial` - Material to locate or insert.
/// - `PbrMaterial` - Primary material occupying slot `0`.
/// - `&mut Vec<PbrMaterial>` - Mutable sub-material table.
///
/// # Returns
///
/// - `u16` - Resolved triangle material slot (`0` for primary, `1..` for sub-materials).
fn resolve_merged_material_slot(
    material: PbrMaterial,
    primary: PbrMaterial,
    sub_materials: &mut Vec<PbrMaterial>,
) -> u16 {
    if material == primary {
        return 0;
    }
    for (idx, existing) in sub_materials.iter().enumerate() {
        if *existing == material {
            return (idx + 1) as u16;
        }
    }
    sub_materials.push(material);
    sub_materials.len() as u16
}

/// Converts a finite non-negative `f32` into a monotonic `u64` sort key.
///
/// # Arguments
///
/// - `f32` - Non-negative cost value.
///
/// # Returns
///
/// - `u64` - Ordered unsigned integer key.
#[must_use]
fn ordered_cost_key(cost: f32) -> u64 {
    let clamped: f32 = if cost.is_finite() {
        cost.max(0.0)
    } else {
        f32::MAX
    };
    clamped.to_bits() as u64
}

/// Builds a canonical undirected edge key `(min, max)`.
///
/// # Arguments
///
/// - `u32` - First vertex index.
/// - `u32` - Second vertex index.
///
/// # Returns
///
/// - `(u32, u32)` - Ordered edge pair.
#[must_use]
fn canonical_edge(a: u32, b: u32) -> (u32, u32) {
    if a < b { (a, b) } else { (b, a) }
}

/// Merges multiple `Mesh3D` assets into a single indexed `Mesh3D`, preserving per-part materials.
///
/// # Arguments
///
/// - `&[Mesh3D]` - Slice of source meshes to combine.
/// - `&str` - Name assigned to the merged mesh.
///
/// # Returns
///
/// - `Mesh3D` - Combined mesh with unified vertex buffer, triangle indices, materials, and meshlets.
#[must_use]
pub fn merge_meshes(meshes: &[Mesh3D], name: &str) -> Mesh3D {
    let mesh_name: String = if name.is_empty() {
        MESH_OPS_DEFAULT_MERGED_NAME.to_string()
    } else {
        name.to_string()
    };
    let mut total_verts: usize = 0;
    let mut total_tris: usize = 0;
    let mut primary_material: Option<PbrMaterial> = None;
    let mut all_closed: bool = true;
    let mut non_empty_count: usize = 0;
    for mesh in meshes.iter() {
        total_verts += mesh.get_vertices().len();
        total_tris += mesh.get_indices().len();
        if !mesh.get_indices().is_empty() {
            non_empty_count += 1;
            if primary_material.is_none() {
                primary_material = Some(mesh.get_material());
            }
            if !mesh.get_is_closed() {
                all_closed = false;
            }
        }
    }
    let primary: PbrMaterial = primary_material.unwrap_or_default();
    if total_tris == 0 {
        return Mesh3D::from_parts(mesh_name, Vec::new(), Vec::new(), primary);
    }
    let mut vertices: Vec<Vertex3D> = Vec::with_capacity(total_verts);
    let mut indices: Vec<[u32; 3]> = Vec::with_capacity(total_tris);
    let mut sub_materials: Vec<PbrMaterial> = Vec::new();
    let mut tri_materials: Vec<u16> = Vec::with_capacity(total_tris);
    let mut uses_sub_materials: bool = false;
    for mesh in meshes.iter() {
        let src_verts: &[Vertex3D] = mesh.get_vertices();
        let src_tris: &[[u32; 3]] = mesh.get_indices();
        if src_verts.is_empty() || src_tris.is_empty() {
            continue;
        }
        let base_vertex: u32 = vertices.len() as u32;
        vertices.extend_from_slice(src_verts);
        let mesh_primary: PbrMaterial = mesh.get_material();
        for (tri_idx, tri) in src_tris.iter().enumerate() {
            indices.push([
                base_vertex + tri[0],
                base_vertex + tri[1],
                base_vertex + tri[2],
            ]);
            let (resolved_mat, _): (PbrMaterial, u16) =
                mesh.resolve_triangle_material(tri_idx, mesh_primary);
            let slot: u16 = resolve_merged_material_slot(resolved_mat, primary, &mut sub_materials);
            if slot != 0 {
                uses_sub_materials = true;
            }
            tri_materials.push(slot);
        }
    }
    let mut merged: Mesh3D = Mesh3D::from_parts(mesh_name, vertices, indices, primary);
    merged.set_is_closed(non_empty_count > 0 && all_closed);
    if uses_sub_materials {
        merged.set_sub_materials(sub_materials);
        merged.set_tri_materials(tri_materials);
    }
    merged
}

/// Applies an affine 4x4 transform to a `Mesh3D`, updating normals, tangents, winding, bounds, and meshlets.
///
/// # Arguments
///
/// - `&Mesh3D` - Source mesh.
/// - `&Mat4` - 4x4 transformation matrix.
///
/// # Returns
///
/// - `Mesh3D` - Transformed mesh with properly oriented normals and triangle winding.
#[must_use]
pub fn transform_mesh(mesh: &Mesh3D, transform: &Mat4) -> Mesh3D {
    let elems: [f32; 16] = transform.get_elements();
    let col0: Vec3 = Vec3::new(elems[0], elems[1], elems[2]);
    let col1: Vec3 = Vec3::new(elems[4], elems[5], elems[6]);
    let col2: Vec3 = Vec3::new(elems[8], elems[9], elems[10]);
    let det: f32 = col0.dot(col1.cross(col2));
    let flip_winding: bool = det.is_finite() && det < 0.0;
    let normal_basis: [Vec3; 3] = transform.normal_matrix_3x3();
    let src_verts: &[Vertex3D] = mesh.get_vertices();
    let mut out_verts: Vec<Vertex3D> = Vec::with_capacity(src_verts.len());
    for vert in src_verts.iter() {
        let new_pos: Vec3 = sanitize_vec3(transform.mul_point3(vert.get_position()), Vec3::zero());
        let raw_n: Vec3 = Mat4::transform_normal_with_basis(vert.get_normal(), normal_basis);
        let new_normal: Vec3 = safe_unit_normal(if flip_winding {
            raw_n.scale(-1.0)
        } else {
            raw_n
        });
        let old_t: [f32; 4] = vert.get_tangent();
        let raw_t: Vec3 = transform.mul_vec3(Vec3::new(old_t[0], old_t[1], old_t[2]));
        let ortho_t: Vec3 = raw_t.sub(new_normal.scale(new_normal.dot(raw_t)));
        let unit_t: Vec3 = if ortho_t.length_sq() > MESH_OPS_NORMAL_EPSILON {
            safe_unit_normal(ortho_t)
        } else {
            let axis: Vec3 = if new_normal.get_y().abs() < 0.99 {
                Vec3::new(0.0, 1.0, 0.0)
            } else {
                Vec3::new(1.0, 0.0, 0.0)
            };
            safe_unit_normal(axis.cross(new_normal))
        };
        let handedness: f32 = if flip_winding { -old_t[3] } else { old_t[3] };
        let clean_w: f32 = if handedness < 0.0 { -1.0 } else { 1.0 };
        out_verts.push(Vertex3D::from_full(
            new_pos,
            new_normal,
            [unit_t.get_x(), unit_t.get_y(), unit_t.get_z(), clean_w],
            vert.get_uv0(),
            vert.get_uv1(),
            vert.get_color0(),
            vert.get_flags(),
        ));
    }
    let src_tris: &[[u32; 3]] = mesh.get_indices();
    let mut out_tris: Vec<[u32; 3]> = Vec::with_capacity(src_tris.len());
    for tri in src_tris.iter() {
        if flip_winding {
            out_tris.push([tri[0], tri[2], tri[1]]);
        } else {
            out_tris.push(*tri);
        }
    }
    let mut out_mesh: Mesh3D = Mesh3D::from_parts(
        mesh.get_name().clone(),
        out_verts,
        out_tris,
        mesh.get_material(),
    );
    out_mesh.set_is_closed(mesh.get_is_closed());
    if !mesh.get_sub_materials().is_empty() {
        out_mesh.set_sub_materials(mesh.get_sub_materials().clone());
        out_mesh.set_tri_materials(mesh.get_tri_materials().clone());
    }
    out_mesh
}

/// Welds vertices within Euclidean distance `epsilon` using a 27-neighbor spatial hash grid.
///
/// # Arguments
///
/// - `&Mesh3D` - Source mesh to weld.
/// - `f32` - Position merge tolerance (`>= 1e-6`).
///
/// # Returns
///
/// - `Mesh3D` - Welded mesh with deduplicated vertices and degenerate triangles removed.
#[must_use]
pub fn weld_vertices(mesh: &Mesh3D, epsilon: f32) -> Mesh3D {
    let eps: f32 =
        sanitize_scalar(epsilon, MESH_OPS_MIN_WELD_EPSILON).max(MESH_OPS_MIN_WELD_EPSILON);
    let eps_sq: f32 = eps * eps;
    let inv_cell: f32 = 1.0 / eps;
    let src_verts: &[Vertex3D] = mesh.get_vertices();
    let src_tris: &[[u32; 3]] = mesh.get_indices();
    let mut buckets: HashMap<(i64, i64, i64), Vec<u32>> = HashMap::with_capacity(src_verts.len());
    let mut clusters: Vec<WeldAccumulator> = Vec::with_capacity(src_verts.len());
    let mut remap: Vec<u32> = Vec::with_capacity(src_verts.len());
    for vert in src_verts.iter() {
        let pos: Vec3 = sanitize_vec3(vert.get_position(), Vec3::zero());
        let cx: i64 = (pos.get_x() * inv_cell).floor() as i64;
        let cy: i64 = (pos.get_y() * inv_cell).floor() as i64;
        let cz: i64 = (pos.get_z() * inv_cell).floor() as i64;
        let mut matched: Option<u32> = None;
        for dx in -1_i64..=1_i64 {
            for dy in -1_i64..=1_i64 {
                for dz in -1_i64..=1_i64 {
                    if let Some(candidates) = buckets.get(&(cx + dx, cy + dy, cz + dz)) {
                        for &cluster_idx in candidates.iter() {
                            let anchor: Vec3 = clusters[cluster_idx as usize].get_anchor();
                            if pos.sub(anchor).length_sq() <= eps_sq {
                                matched = Some(cluster_idx);
                                break;
                            }
                        }
                    }
                    if matched.is_some() {
                        break;
                    }
                }
                if matched.is_some() {
                    break;
                }
            }
            if matched.is_some() {
                break;
            }
        }
        let uv0: [f32; 2] = vert.get_uv0();
        let uv1: [f32; 2] = vert.get_uv1();
        let col: [u8; 4] = vert.get_color0();
        let normal: Vec3 = safe_unit_normal(vert.get_normal());
        if let Some(cluster_idx) = matched {
            let acc: &mut WeldAccumulator = &mut clusters[cluster_idx as usize];
            acc.set_pos_sum(acc.get_pos_sum().add(pos));
            acc.set_normal_sum(acc.get_normal_sum().add(normal));
            let old_uv0: [f32; 2] = acc.get_uv0_sum();
            acc.set_uv0_sum([old_uv0[0] + uv0[0], old_uv0[1] + uv0[1]]);
            let old_uv1: [f32; 2] = acc.get_uv1_sum();
            acc.set_uv1_sum([old_uv1[0] + uv1[0], old_uv1[1] + uv1[1]]);
            let old_col: [f32; 4] = acc.get_color_sum();
            acc.set_color_sum([
                old_col[0] + (col[0] as f32),
                old_col[1] + (col[1] as f32),
                old_col[2] + (col[2] as f32),
                old_col[3] + (col[3] as f32),
            ]);
            acc.set_flags(acc.get_flags() | vert.get_flags());
            acc.set_count(acc.get_count() + 1);
            remap.push(cluster_idx);
        } else {
            let new_idx: u32 = clusters.len() as u32;
            clusters.push(WeldAccumulator {
                pos_sum: pos,
                normal_sum: normal,
                uv0_sum: uv0,
                uv1_sum: uv1,
                color_sum: [col[0] as f32, col[1] as f32, col[2] as f32, col[3] as f32],
                flags: vert.get_flags(),
                anchor: pos,
                count: 1,
            });
            buckets.entry((cx, cy, cz)).or_default().push(new_idx);
            remap.push(new_idx);
        }
    }
    let mut out_verts: Vec<Vertex3D> = Vec::with_capacity(clusters.len());
    for acc in clusters.iter() {
        let inv_count: f32 = 1.0 / (acc.get_count().max(1) as f32);
        let avg_pos: Vec3 = acc.get_pos_sum().scale(inv_count);
        let avg_n: Vec3 = safe_unit_normal(acc.get_normal_sum());
        let uv0_sum: [f32; 2] = acc.get_uv0_sum();
        let uv1_sum: [f32; 2] = acc.get_uv1_sum();
        let col_sum: [f32; 4] = acc.get_color_sum();
        let avg_col: [u8; 4] = [
            (col_sum[0] * inv_count).round().clamp(0.0, 255.0) as u8,
            (col_sum[1] * inv_count).round().clamp(0.0, 255.0) as u8,
            (col_sum[2] * inv_count).round().clamp(0.0, 255.0) as u8,
            (col_sum[3] * inv_count).round().clamp(0.0, 255.0) as u8,
        ];
        out_verts.push(Vertex3D::from_full(
            avg_pos,
            avg_n,
            [1.0, 0.0, 0.0, 1.0],
            [uv0_sum[0] * inv_count, uv0_sum[1] * inv_count],
            [uv1_sum[0] * inv_count, uv1_sum[1] * inv_count],
            avg_col,
            acc.get_flags(),
        ));
    }
    let mut out_tris: Vec<[u32; 3]> = Vec::with_capacity(src_tris.len());
    let src_tri_mats: &[u16] = mesh.get_tri_materials();
    let has_tri_mats: bool = !src_tri_mats.is_empty();
    let mut out_tri_mats: Vec<u16> =
        Vec::with_capacity(if has_tri_mats { src_tris.len() } else { 0 });
    for (tri_idx, tri) in src_tris.iter().enumerate() {
        let (a, b, c): (usize, usize, usize) = (tri[0] as usize, tri[1] as usize, tri[2] as usize);
        if a >= remap.len() || b >= remap.len() || c >= remap.len() {
            continue;
        }
        let i0: u32 = remap[a];
        let i1: u32 = remap[b];
        let i2: u32 = remap[c];
        if i0 == i1 || i1 == i2 || i2 == i0 {
            continue;
        }
        out_tris.push([i0, i1, i2]);
        if has_tri_mats {
            out_tri_mats.push(src_tri_mats.get(tri_idx).copied().unwrap_or(0));
        }
    }
    let mut out_mesh: Mesh3D = Mesh3D::from_parts(
        mesh.get_name().clone(),
        out_verts,
        out_tris,
        mesh.get_material(),
    );
    out_mesh.set_is_closed(mesh.get_is_closed());
    if has_tri_mats {
        out_mesh.set_sub_materials(mesh.get_sub_materials().clone());
        out_mesh.set_tri_materials(out_tri_mats);
    }
    out_mesh
}

/// Recomputes area-weighted smooth unit normals across all shared vertices of `mesh`.
///
/// # Arguments
///
/// - `&Mesh3D` - Source indexed mesh.
///
/// # Returns
///
/// - `Mesh3D` - Copy of `mesh` with refreshed unit smooth normals and meshlets.
#[must_use]
pub fn recompute_smooth_normals(mesh: &Mesh3D) -> Mesh3D {
    let mut out_mesh: Mesh3D = mesh.clone();
    let vert_count: usize = out_mesh.get_vertices().len();
    if vert_count == 0 {
        return out_mesh;
    }
    let mut accum: Vec<Vec3> = vec![Vec3::zero(); vert_count];
    for tri in out_mesh.get_indices().iter() {
        let (i0, i1, i2): (usize, usize, usize) =
            (tri[0] as usize, tri[1] as usize, tri[2] as usize);
        if i0 >= vert_count || i1 >= vert_count || i2 >= vert_count {
            continue;
        }
        let verts: &[Vertex3D] = out_mesh.get_vertices();
        let p0: Vec3 = verts[i0].get_position();
        let p1: Vec3 = verts[i1].get_position();
        let p2: Vec3 = verts[i2].get_position();
        let face_vec: Vec3 = p1.sub(p0).cross(p2.sub(p0));
        if face_vec.length_sq() > MESH_OPS_EPSILON_SQ && face_vec.length_sq().is_finite() {
            accum[i0] = accum[i0].add(face_vec);
            accum[i1] = accum[i1].add(face_vec);
            accum[i2] = accum[i2].add(face_vec);
        }
    }
    for (idx, vert) in out_mesh.get_mut_vertices().iter_mut().enumerate() {
        let sum_n: Vec3 = accum[idx];
        if sum_n.length_sq() > MESH_OPS_EPSILON_SQ {
            vert.set_normal(safe_unit_normal(sum_n));
        } else {
            vert.set_normal(safe_unit_normal(vert.get_normal()));
        }
    }
    let meshlets: Vec<Meshlet3D> =
        Mesh3D::build_meshlets_from_parts(out_mesh.get_vertices(), out_mesh.get_indices());
    out_mesh.set_meshlets(meshlets);
    out_mesh
}

/// Splits triangle vertices and assigns crisp flat outward unit normals to every triangle face.
///
/// # Arguments
///
/// - `&Mesh3D` - Source mesh.
///
/// # Returns
///
/// - `Mesh3D` - Faceted mesh with per-triangle flat unit normals.
#[must_use]
pub fn recompute_flat_normals(mesh: &Mesh3D) -> Mesh3D {
    let src_verts: &[Vertex3D] = mesh.get_vertices();
    let src_tris: &[[u32; 3]] = mesh.get_indices();
    let mut out_verts: Vec<Vertex3D> = Vec::with_capacity(src_tris.len() * 3);
    let mut out_tris: Vec<[u32; 3]> = Vec::with_capacity(src_tris.len());
    let src_tri_mats: &[u16] = mesh.get_tri_materials();
    let has_tri_mats: bool = !src_tri_mats.is_empty();
    let mut out_tri_mats: Vec<u16> =
        Vec::with_capacity(if has_tri_mats { src_tris.len() } else { 0 });
    for (tri_idx, tri) in src_tris.iter().enumerate() {
        let (i0, i1, i2): (usize, usize, usize) =
            (tri[0] as usize, tri[1] as usize, tri[2] as usize);
        if i0 >= src_verts.len() || i1 >= src_verts.len() || i2 >= src_verts.len() {
            continue;
        }
        let v0: Vertex3D = src_verts[i0];
        let v1: Vertex3D = src_verts[i1];
        let v2: Vertex3D = src_verts[i2];
        let face_n: Vec3 = safe_unit_normal(
            v1.get_position()
                .sub(v0.get_position())
                .cross(v2.get_position().sub(v0.get_position())),
        );
        let base: u32 = out_verts.len() as u32;
        for mut v in [v0, v1, v2] {
            v.set_normal(face_n);
            out_verts.push(v);
        }
        out_tris.push([base, base + 1, base + 2]);
        if has_tri_mats {
            out_tri_mats.push(src_tri_mats.get(tri_idx).copied().unwrap_or(0));
        }
    }
    let mut out_mesh: Mesh3D = Mesh3D::from_parts(
        mesh.get_name().clone(),
        out_verts,
        out_tris,
        mesh.get_material(),
    );
    out_mesh.set_is_closed(mesh.get_is_closed());
    if has_tri_mats {
        out_mesh.set_sub_materials(mesh.get_sub_materials().clone());
        out_mesh.set_tri_materials(out_tri_mats);
    }
    out_mesh
}

/// Generates tri-planar box-projected `uv0` coordinates scaled by `scale` from each vertex's dominant normal axis.
///
/// # Arguments
///
/// - `&Mesh3D` - Source mesh.
/// - `f32` - UV tiling scale factor applied to projected coordinates.
///
/// # Returns
///
/// - `Mesh3D` - Copy of `mesh` with finite box-projected `uv0` coordinates and `uv0` flags set.
#[must_use]
pub fn generate_box_projected_uvs(mesh: &Mesh3D, scale: f32) -> Mesh3D {
    let uv_scale: f32 = sanitize_scalar(scale, 1.0);
    let effective_scale: f32 = if uv_scale.abs() > 1e-6 { uv_scale } else { 1.0 };
    let mut out_mesh: Mesh3D = mesh.clone();
    for vert in out_mesh.get_mut_vertices().iter_mut() {
        let pos: Vec3 = vert.get_position();
        let normal: Vec3 = safe_unit_normal(vert.get_normal());
        let ax: f32 = normal.get_x().abs();
        let ay: f32 = normal.get_y().abs();
        let az: f32 = normal.get_z().abs();
        let uv: [f32; 2] = if ax >= ay && ax >= az {
            [pos.get_z() * effective_scale, pos.get_y() * effective_scale]
        } else if ay >= ax && ay >= az {
            [pos.get_x() * effective_scale, pos.get_z() * effective_scale]
        } else {
            [pos.get_x() * effective_scale, pos.get_y() * effective_scale]
        };
        vert.set_uv0([sanitize_scalar(uv[0], 0.0), sanitize_scalar(uv[1], 0.0)]);
        vert.set_flags(vert.get_flags() | VERTEX_FLAG_UV0);
    }
    out_mesh
}

/// Computes MikkTSpace-style Gram-Schmidt orthogonal tangent vectors `(tx, ty, tz, handedness)` for every vertex.
///
/// # Arguments
///
/// - `&Mesh3D` - Source mesh with positions, normals, and `uv0` texture coordinates.
///
/// # Returns
///
/// - `Mesh3D` - Copy of `mesh` with orthogonal unit tangents, handedness `±1.0`, and tangent flags enabled.
#[must_use]
pub fn compute_tangents(mesh: &Mesh3D) -> Mesh3D {
    let mut out_mesh: Mesh3D = mesh.clone();
    let vert_count: usize = out_mesh.get_vertices().len();
    if vert_count == 0 {
        return out_mesh;
    }
    let mut tan1: Vec<Vec3> = vec![Vec3::zero(); vert_count];
    let mut tan2: Vec<Vec3> = vec![Vec3::zero(); vert_count];
    let verts: &[Vertex3D] = out_mesh.get_vertices();
    for tri in out_mesh.get_indices().iter() {
        let (i0, i1, i2): (usize, usize, usize) =
            (tri[0] as usize, tri[1] as usize, tri[2] as usize);
        if i0 >= vert_count || i1 >= vert_count || i2 >= vert_count {
            continue;
        }
        let p0: Vec3 = verts[i0].get_position();
        let p1: Vec3 = verts[i1].get_position();
        let p2: Vec3 = verts[i2].get_position();
        let uv0: [f32; 2] = verts[i0].get_uv0();
        let uv1: [f32; 2] = verts[i1].get_uv0();
        let uv2: [f32; 2] = verts[i2].get_uv0();
        let e1: Vec3 = p1.sub(p0);
        let e2: Vec3 = p2.sub(p0);
        let du1: f32 = uv1[0] - uv0[0];
        let du2: f32 = uv2[0] - uv0[0];
        let dv1: f32 = uv1[1] - uv0[1];
        let dv2: f32 = uv2[1] - uv0[1];
        let det: f32 = du1 * dv2 - du2 * dv1;
        if !det.is_finite() || det.abs() < MESH_OPS_NORMAL_EPSILON {
            continue;
        }
        let inv_det: f32 = 1.0 / det;
        let area_weight: f32 = e1.cross(e2).length().max(1e-6);
        let sdir: Vec3 = Vec3::new(
            (dv2 * e1.get_x() - dv1 * e2.get_x()) * inv_det,
            (dv2 * e1.get_y() - dv1 * e2.get_y()) * inv_det,
            (dv2 * e1.get_z() - dv1 * e2.get_z()) * inv_det,
        )
        .scale(area_weight);
        let tdir: Vec3 = Vec3::new(
            (du1 * e2.get_x() - du2 * e1.get_x()) * inv_det,
            (du1 * e2.get_y() - du2 * e1.get_y()) * inv_det,
            (du1 * e2.get_z() - du2 * e1.get_z()) * inv_det,
        )
        .scale(area_weight);
        if sdir.length_sq().is_finite() && tdir.length_sq().is_finite() {
            tan1[i0] = tan1[i0].add(sdir);
            tan1[i1] = tan1[i1].add(sdir);
            tan1[i2] = tan1[i2].add(sdir);
            tan2[i0] = tan2[i0].add(tdir);
            tan2[i1] = tan2[i1].add(tdir);
            tan2[i2] = tan2[i2].add(tdir);
        }
    }
    for (idx, vert) in out_mesh.get_mut_vertices().iter_mut().enumerate() {
        let n: Vec3 = safe_unit_normal(vert.get_normal());
        let t: Vec3 = tan1[idx];
        let ortho: Vec3 = t.sub(n.scale(n.dot(t)));
        let unit_t: Vec3 = if ortho.length_sq() > MESH_OPS_NORMAL_EPSILON {
            safe_unit_normal(ortho)
        } else {
            let axis: Vec3 = if n.get_y().abs() < 0.99 {
                Vec3::new(0.0, 1.0, 0.0)
            } else {
                Vec3::new(1.0, 0.0, 0.0)
            };
            safe_unit_normal(axis.cross(n))
        };
        let handedness: f32 = if n.cross(unit_t).dot(tan2[idx]) < 0.0 {
            -1.0
        } else {
            1.0
        };
        vert.set_normal(n);
        vert.set_tangent([unit_t.get_x(), unit_t.get_y(), unit_t.get_z(), handedness]);
        vert.set_flags(vert.get_flags() | VERTEX_FLAG_TANGENT);
    }
    out_mesh
}

/// Checks whether collapsing edge `(v0, v1)` to `target_pos` preserves manifold link topology and avoids inverted triangles.
///
/// # Arguments
///
/// - `u32` - Kept vertex index `v0`.
/// - `u32` - Removed vertex index `v1`.
/// - `Vec3` - Proposed merged vertex position.
/// - `&[DecimationVertex]` - Active vertex array.
/// - `&[DecimationTriangle]` - Active triangle array.
/// - `&[Vec<usize>]` - Per-vertex incident triangle adjacency lists.
///
/// # Returns
///
/// - `bool` - `true` if the collapse is topologically safe and free of normal flips.
fn is_collapse_valid(
    v0: u32,
    v1: u32,
    target_pos: Vec3,
    verts: &[DecimationVertex],
    tris: &[DecimationTriangle],
    v_tris: &[Vec<usize>],
) -> bool {
    let mut nbrs0: Vec<u32> = Vec::with_capacity(v_tris[v0 as usize].len() * 2);
    let mut edge_tri_count: usize = 0;
    for &t_idx in v_tris[v0 as usize].iter() {
        let tri: DecimationTriangle = tris[t_idx];
        if !tri.get_alive() {
            continue;
        }
        let idx: [u32; 3] = tri.get_indices();
        let has_v1: bool = idx[0] == v1 || idx[1] == v1 || idx[2] == v1;
        if has_v1 {
            edge_tri_count += 1;
        }
        for &vid in idx.iter() {
            if vid != v0 && vid != v1 && !nbrs0.contains(&vid) {
                nbrs0.push(vid);
            }
        }
    }
    if edge_tri_count == 0 {
        return false;
    }
    let mut shared_nbrs: Vec<u32> = Vec::new();
    for &t_idx in v_tris[v1 as usize].iter() {
        let tri: DecimationTriangle = tris[t_idx];
        if !tri.get_alive() {
            continue;
        }
        for &vid in tri.get_indices().iter() {
            if vid != v0 && vid != v1 && nbrs0.contains(&vid) && !shared_nbrs.contains(&vid) {
                shared_nbrs.push(vid);
            }
        }
    }
    if shared_nbrs.len() != edge_tri_count {
        return false;
    }
    for &check_vid in [v0, v1].iter() {
        for &t_idx in v_tris[check_vid as usize].iter() {
            let tri: DecimationTriangle = tris[t_idx];
            if !tri.get_alive() {
                continue;
            }
            let idx: [u32; 3] = tri.get_indices();
            if (idx[0] == v0 || idx[1] == v0 || idx[2] == v0)
                && (idx[0] == v1 || idx[1] == v1 || idx[2] == v1)
            {
                continue;
            }
            let p0: Vec3 = verts[idx[0] as usize].get_position();
            let p1: Vec3 = verts[idx[1] as usize].get_position();
            let p2: Vec3 = verts[idx[2] as usize].get_position();
            let old_cross: Vec3 = p1.sub(p0).cross(p2.sub(p0));
            let np0: Vec3 = if idx[0] == v0 || idx[0] == v1 {
                target_pos
            } else {
                p0
            };
            let np1: Vec3 = if idx[1] == v0 || idx[1] == v1 {
                target_pos
            } else {
                p1
            };
            let np2: Vec3 = if idx[2] == v0 || idx[2] == v1 {
                target_pos
            } else {
                p2
            };
            let new_cross: Vec3 = np1.sub(np0).cross(np2.sub(np0));
            if new_cross.length_sq() <= MESH_OPS_EPSILON_SQ {
                return false;
            }
            if old_cross.length_sq() > MESH_OPS_EPSILON_SQ {
                let old_n: Vec3 = safe_unit_normal(old_cross);
                let new_n: Vec3 = safe_unit_normal(new_cross);
                if old_n.dot(new_n) <= MESH_OPS_FLIP_DOT_LIMIT {
                    return false;
                }
            }
        }
    }
    true
}

/// Simplifies a triangle mesh using Garland-Heckbert Quadric Error Metric (QEM) iterative edge collapse.
///
/// # Arguments
///
/// - `&Mesh3D` - Source triangle mesh.
/// - `f32` - Desired triangle ratio in `(0.0, 1.0]` relative to input triangle count.
///
/// # Returns
///
/// - `Mesh3D` - Decimated mesh preserving topology, materials, normals, bounds, and meshlets.
#[must_use]
pub fn decimate_mesh(mesh: &Mesh3D, target_ratio: f32) -> Mesh3D {
    let ratio: f32 = sanitize_scalar(target_ratio, 1.0).clamp(0.01, 1.0);
    let src_verts: &[Vertex3D] = mesh.get_vertices();
    let src_tris: &[[u32; 3]] = mesh.get_indices();
    if src_verts.is_empty() || src_tris.len() <= MESH_OPS_MIN_TRIS || ratio >= 0.999 {
        return mesh.clone();
    }
    let target_tris: usize = ((src_tris.len() as f32) * ratio)
        .round()
        .max(MESH_OPS_MIN_TRIS as f32) as usize;
    if target_tris >= src_tris.len() {
        return mesh.clone();
    }
    let mut verts: Vec<DecimationVertex> = Vec::with_capacity(src_verts.len());
    for vert in src_verts.iter() {
        let col: [u8; 4] = vert.get_color0();
        verts.push(DecimationVertex {
            position: sanitize_vec3(vert.get_position(), Vec3::zero()),
            normal: safe_unit_normal(vert.get_normal()),
            uv0: vert.get_uv0(),
            uv1: vert.get_uv1(),
            color: [col[0] as f32, col[1] as f32, col[2] as f32, col[3] as f32],
            flags: vert.get_flags(),
            quadric: QuadricErrorMatrix::default(),
            version: 0,
            alive: true,
        });
    }
    let src_tri_mats: &[u16] = mesh.get_tri_materials();
    let has_tri_mats: bool = !src_tri_mats.is_empty();
    let mut tris: Vec<DecimationTriangle> = Vec::with_capacity(src_tris.len());
    let mut v_tris: Vec<Vec<usize>> = vec![Vec::new(); verts.len()];
    let mut edge_counts: HashMap<(u32, u32), u32> = HashMap::with_capacity(src_tris.len() * 2);
    for (tri_idx, tri) in src_tris.iter().enumerate() {
        let (a, b, c): (u32, u32, u32) = (tri[0], tri[1], tri[2]);
        if (a as usize) >= verts.len()
            || (b as usize) >= verts.len()
            || (c as usize) >= verts.len()
            || a == b
            || b == c
            || c == a
        {
            continue;
        }
        let slot: u16 = if has_tri_mats {
            src_tri_mats.get(tri_idx).copied().unwrap_or(0)
        } else {
            0
        };
        let active_idx: usize = tris.len();
        tris.push(DecimationTriangle {
            indices: [a, b, c],
            material_slot: slot,
            alive: true,
        });
        v_tris[a as usize].push(active_idx);
        v_tris[b as usize].push(active_idx);
        v_tris[c as usize].push(active_idx);
        let p0: Vec3 = verts[a as usize].get_position();
        let p1: Vec3 = verts[b as usize].get_position();
        let p2: Vec3 = verts[c as usize].get_position();
        let cross_vec: Vec3 = p1.sub(p0).cross(p2.sub(p0));
        let area: f32 = cross_vec.length() * 0.5;
        if area > 1e-9 && area.is_finite() {
            let n: Vec3 = safe_unit_normal(cross_vec);
            let d: f32 = -n.dot(p0);
            let plane_q: QuadricErrorMatrix =
                QuadricErrorMatrix::from_plane(n.get_x(), n.get_y(), n.get_z(), d, area.max(1e-4));
            for &vid in [a, b, c].iter() {
                let cur_q: QuadricErrorMatrix = verts[vid as usize].get_quadric();
                verts[vid as usize].set_quadric(cur_q.combine(plane_q));
            }
        }
        for edge in [
            canonical_edge(a, b),
            canonical_edge(b, c),
            canonical_edge(c, a),
        ] {
            let count_entry: &mut u32 = edge_counts.entry(edge).or_insert(0);
            *count_entry += 1;
        }
    }
    for tri in tris.iter() {
        let idx: [u32; 3] = tri.get_indices();
        let p0: Vec3 = verts[idx[0] as usize].get_position();
        let p1: Vec3 = verts[idx[1] as usize].get_position();
        let p2: Vec3 = verts[idx[2] as usize].get_position();
        let face_n: Vec3 = safe_unit_normal(p1.sub(p0).cross(p2.sub(p0)));
        for (ea, eb) in [(idx[0], idx[1]), (idx[1], idx[2]), (idx[2], idx[0])] {
            let count: u32 = edge_counts
                .get(&canonical_edge(ea, eb))
                .copied()
                .unwrap_or(0);
            if count == 1 {
                let pa: Vec3 = verts[ea as usize].get_position();
                let pb: Vec3 = verts[eb as usize].get_position();
                let edge_vec: Vec3 = pb.sub(pa);
                let edge_len: f32 = edge_vec.length();
                if edge_len > 1e-6 {
                    let bn: Vec3 = safe_unit_normal(edge_vec.cross(face_n));
                    let bd: f32 = -bn.dot(pa);
                    let bq: QuadricErrorMatrix = QuadricErrorMatrix::from_plane(
                        bn.get_x(),
                        bn.get_y(),
                        bn.get_z(),
                        bd,
                        edge_len * MESH_OPS_BOUNDARY_WEIGHT,
                    );
                    let qa: QuadricErrorMatrix = verts[ea as usize].get_quadric();
                    let qb: QuadricErrorMatrix = verts[eb as usize].get_quadric();
                    verts[ea as usize].set_quadric(qa.combine(bq));
                    verts[eb as usize].set_quadric(qb.combine(bq));
                }
            }
        }
    }
    let mut heap: BTreeSet<DecimationCandidate> = BTreeSet::new();
    let mut seq: u64 = 0;
    for &(v0, v1) in edge_counts.keys() {
        let q_sum: QuadricErrorMatrix = verts[v0 as usize]
            .get_quadric()
            .combine(verts[v1 as usize].get_quadric());
        let (_, cost): (Vec3, f32) = q_sum.solve_optimal_point(
            verts[v0 as usize].get_position(),
            verts[v1 as usize].get_position(),
        );
        seq += 1;
        heap.insert(DecimationCandidate {
            cost_key: ordered_cost_key(cost),
            sequence: seq,
            v0,
            v1,
            ver0: 0,
            ver1: 0,
        });
    }
    let mut alive_tris: usize = tris.len();
    let mut neighbor_edges: Vec<u32> = Vec::with_capacity(32);
    while alive_tris > target_tris {
        let Some(cand) = heap.pop_first() else {
            break;
        };
        let v0: u32 = cand.get_v0();
        let v1: u32 = cand.get_v1();
        if v0 == v1 {
            continue;
        }
        let vert0: DecimationVertex = verts[v0 as usize];
        let vert1: DecimationVertex = verts[v1 as usize];
        if !vert0.get_alive()
            || !vert1.get_alive()
            || vert0.get_version() != cand.get_ver0()
            || vert1.get_version() != cand.get_ver1()
        {
            continue;
        }
        let q_sum: QuadricErrorMatrix = vert0.get_quadric().combine(vert1.get_quadric());
        let (target_pos, _): (Vec3, f32) =
            q_sum.solve_optimal_point(vert0.get_position(), vert1.get_position());
        if !is_collapse_valid(v0, v1, target_pos, &verts, &tris, &v_tris) {
            continue;
        }
        let seg: Vec3 = vert1.get_position().sub(vert0.get_position());
        let seg_len_sq: f32 = seg.length_sq();
        let alpha: f32 = if seg_len_sq > MESH_OPS_EPSILON_SQ {
            (target_pos.sub(vert0.get_position()).dot(seg) / seg_len_sq).clamp(0.0, 1.0)
        } else {
            0.5
        };
        let uv0_a: [f32; 2] = vert0.get_uv0();
        let uv0_b: [f32; 2] = vert1.get_uv0();
        let uv1_a: [f32; 2] = vert0.get_uv1();
        let uv1_b: [f32; 2] = vert1.get_uv1();
        let col_a: [f32; 4] = vert0.get_color();
        let col_b: [f32; 4] = vert1.get_color();
        let next_ver: u32 = vert0.get_version() + 1;
        verts[v0 as usize].set_position(target_pos);
        verts[v0 as usize].set_normal(safe_unit_normal(
            vert0.get_normal().lerp(vert1.get_normal(), alpha),
        ));
        verts[v0 as usize].set_uv0([
            uv0_a[0] + (uv0_b[0] - uv0_a[0]) * alpha,
            uv0_a[1] + (uv0_b[1] - uv0_a[1]) * alpha,
        ]);
        verts[v0 as usize].set_uv1([
            uv1_a[0] + (uv1_b[0] - uv1_a[0]) * alpha,
            uv1_a[1] + (uv1_b[1] - uv1_a[1]) * alpha,
        ]);
        verts[v0 as usize].set_color([
            col_a[0] + (col_b[0] - col_a[0]) * alpha,
            col_a[1] + (col_b[1] - col_a[1]) * alpha,
            col_a[2] + (col_b[2] - col_a[2]) * alpha,
            col_a[3] + (col_b[3] - col_a[3]) * alpha,
        ]);
        verts[v0 as usize].set_flags(vert0.get_flags() | vert1.get_flags());
        verts[v0 as usize].set_quadric(q_sum);
        verts[v0 as usize].set_version(next_ver);
        verts[v1 as usize].set_alive(false);
        let moved_tris: Vec<usize> = take(&mut v_tris[v1 as usize]);
        for t_idx in moved_tris.into_iter() {
            if !tris[t_idx].get_alive() {
                continue;
            }
            let mut idx: [u32; 3] = tris[t_idx].get_indices();
            for slot in idx.iter_mut() {
                if *slot == v1 {
                    *slot = v0;
                }
            }
            if idx[0] == idx[1] || idx[1] == idx[2] || idx[2] == idx[0] {
                tris[t_idx].set_alive(false);
                alive_tris = alive_tris.saturating_sub(1);
            } else {
                tris[t_idx].set_indices(idx);
                if !v_tris[v0 as usize].contains(&t_idx) {
                    v_tris[v0 as usize].push(t_idx);
                }
            }
        }
        v_tris[v0 as usize].retain(|t_idx: &usize| tris[*t_idx].get_alive());
        neighbor_edges.clear();
        for &t_idx in v_tris[v0 as usize].iter() {
            let idx: [u32; 3] = tris[t_idx].get_indices();
            for &vid in idx.iter() {
                if vid != v0 && verts[vid as usize].get_alive() && !neighbor_edges.contains(&vid) {
                    neighbor_edges.push(vid);
                }
            }
        }
        for &nbr in neighbor_edges.iter() {
            let (ea, eb): (u32, u32) = canonical_edge(v0, nbr);
            let combined_q: QuadricErrorMatrix = verts[ea as usize]
                .get_quadric()
                .combine(verts[eb as usize].get_quadric());
            let (_, edge_cost): (Vec3, f32) = combined_q.solve_optimal_point(
                verts[ea as usize].get_position(),
                verts[eb as usize].get_position(),
            );
            seq += 1;
            heap.insert(DecimationCandidate {
                cost_key: ordered_cost_key(edge_cost),
                sequence: seq,
                v0: ea,
                v1: eb,
                ver0: verts[ea as usize].get_version(),
                ver1: verts[eb as usize].get_version(),
            });
        }
    }
    let mut remap: Vec<u32> = vec![u32::MAX; verts.len()];
    let mut out_verts: Vec<Vertex3D> = Vec::with_capacity(verts.len());
    let mut out_tris: Vec<[u32; 3]> = Vec::with_capacity(alive_tris);
    let mut out_tri_mats: Vec<u16> = Vec::with_capacity(if has_tri_mats { alive_tris } else { 0 });
    for tri in tris.iter() {
        if !tri.get_alive() {
            continue;
        }
        let idx: [u32; 3] = tri.get_indices();
        let mut mapped: [u32; 3] = [0; 3];
        for (corner, &vid) in idx.iter().enumerate() {
            let slot: u32 = remap[vid as usize];
            if slot == u32::MAX {
                let new_id: u32 = out_verts.len() as u32;
                let dv: DecimationVertex = verts[vid as usize];
                let col: [f32; 4] = dv.get_color();
                out_verts.push(Vertex3D::from_full(
                    dv.get_position(),
                    dv.get_normal(),
                    [1.0, 0.0, 0.0, 1.0],
                    dv.get_uv0(),
                    dv.get_uv1(),
                    [
                        col[0].round().clamp(0.0, 255.0) as u8,
                        col[1].round().clamp(0.0, 255.0) as u8,
                        col[2].round().clamp(0.0, 255.0) as u8,
                        col[3].round().clamp(0.0, 255.0) as u8,
                    ],
                    dv.get_flags(),
                ));
                remap[vid as usize] = new_id;
                mapped[corner] = new_id;
            } else {
                mapped[corner] = slot;
            }
        }
        if mapped[0] != mapped[1] && mapped[1] != mapped[2] && mapped[2] != mapped[0] {
            out_tris.push(mapped);
            if has_tri_mats {
                out_tri_mats.push(tri.get_material_slot());
            }
        }
    }
    let mut out_mesh: Mesh3D = Mesh3D::from_parts(
        mesh.get_name().clone(),
        out_verts,
        out_tris,
        mesh.get_material(),
    );
    out_mesh.set_is_closed(mesh.get_is_closed());
    if has_tri_mats {
        out_mesh.set_sub_materials(mesh.get_sub_materials().clone());
        out_mesh.set_tri_materials(out_tri_mats);
    }
    let smoothed: Mesh3D = recompute_smooth_normals(&out_mesh);
    compute_tangents(&smoothed)
}

/// Builds an ordered multi-level `MeshLodChain` from `mesh` using the specified triangle-retention ratios.
///
/// # Arguments
///
/// - `&Mesh3D` - Highest-detail source `LOD0` mesh.
/// - `&[f32]` - Requested triangle-count ratios in `(0.0, 1.0]` (automatically sorted descending).
///
/// # Returns
///
/// - `MeshLodChain` - Ordered detail chain from highest to lowest triangle count.
#[must_use]
pub fn build_lod_chain(mesh: &Mesh3D, ratios: &[f32]) -> MeshLodChain {
    let mut clean_ratios: Vec<f32> = Vec::with_capacity(ratios.len());
    for &ratio in ratios.iter() {
        if ratio.is_finite() && ratio > 0.0 {
            clean_ratios.push(ratio.clamp(0.01, 1.0));
        }
    }
    clean_ratios.sort_by(|a: &f32, b: &f32| b.total_cmp(a));
    if clean_ratios.is_empty() {
        return MeshLodChain::single_level(mesh.clone());
    }
    let mut levels: Vec<Mesh3D> = Vec::with_capacity(clean_ratios.len());
    for (idx, &ratio) in clean_ratios.iter().enumerate() {
        if ratio >= 0.999 {
            if levels.is_empty() {
                levels.push(mesh.clone());
            }
        } else {
            let mut decimated: Mesh3D = decimate_mesh(mesh, ratio);
            decimated.set_name(format!("{}_lod{}", mesh.get_name(), idx));
            levels.push(decimated);
        }
    }
    if levels.is_empty() {
        levels.push(mesh.clone());
    }
    let mut chain: MeshLodChain = MeshLodChain::single_level(levels[0].clone());
    chain.set_levels(levels);
    chain
}