BREP_reconstruction 0.2.0

Kernel integration for neutral BREP_RANSAC recognition results
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
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
//! Optional interoperability with the public `brep_kernel` API.
//!
//! This module contains representation conversion only. Recognition remains
//! independent of kernel topology, boolean execution, and global scene state.

use crate::numerical;
use crate::{AnalyticSurface, Mesh, RecognitionError, SourceMetadata, SurfaceHint, Vec3};

/// Exact analytic information carried by one kernel face.
///
/// `surface` describes the unoriented infinite mathematical carrier. Face
/// orientation is deliberately retained in `orientation` instead of being
/// folded into an axis or normal. It combines `FaceRecord::same_sense` with
/// any parameter-normal gauge removed while canonicalizing the carrier, and
/// prevents a reversed STEP `ADVANCED_FACE` from changing its geometry.
#[derive(Clone, Debug, PartialEq)]
pub struct KernelFaceTruth {
    /// Sequential face number used by the kernel tessellator's `face_ids`.
    pub mesh_face_id: u32,
    /// Stable topology id from `FaceRecord::id`.
    pub source_face_id: u64,
    /// Optional stable source face name.
    pub source_face_name: Option<String>,
    /// Observed face orientation in the gauge of `surface`.
    ///
    /// This is normally `+1` for `same_sense` and `-1` otherwise. A kernel
    /// ruled revolution with negative generatrix height has the opposite
    /// parametric normal from our canonical cylinder/cone, so its sign is
    /// reversed during carrier conversion.
    pub orientation: i8,
    /// Exact infinite carrier extracted from the kernel face.
    pub surface: AnalyticSurface,
}

fn kernel_carrier_orientation_gauge(source: &brep_kernel::AnalyticSurface) -> i8 {
    match source {
        // For S(theta, t), dS/dtheta x dS/dt reverses when the axial
        // generatrix height reverses. Our cylinder/cone carrier deliberately
        // canonicalizes that parameterization away, so retain its normal
        // gauge here as a separate orientation sign.
        brep_kernel::AnalyticSurface::RuledRevolution { height, .. } if *height < 0.0 => -1,
        _ => 1,
    }
}

fn kernel_face_orientation(source: &brep_kernel::AnalyticSurface, same_sense: bool) -> i8 {
    (if same_sense { 1 } else { -1 }) * kernel_carrier_orientation_gauge(source)
}

fn invalid_kernel_analytic(reason: impl Into<String>) -> RecognitionError {
    RecognitionError::FitFailed {
        surface: None,
        reason: reason.into(),
    }
}

/// Convert an exact kernel analytic carrier into this crate's carrier model.
///
/// The kernel's general `Revolution` variant is intentionally returned as
/// `None`: it is not necessarily one of the five primitives represented by
/// [`AnalyticSurface`]. Invalid or degenerate primitive parameters are errors,
/// so corrupt source truth cannot silently become an exact RANSAC prior.
pub fn surface_from_kernel_analytic(
    source: &brep_kernel::AnalyticSurface,
) -> Result<Option<AnalyticSurface>, RecognitionError> {
    use brep_kernel::AnalyticSurface as KernelSurface;

    let converted = match source {
        KernelSurface::Plane {
            origin,
            u_dir,
            v_dir,
            ..
        } => {
            let normal = vec3_from_kernel(*u_dir)
                .cross(vec3_from_kernel(*v_dir))
                .normalized()
                .ok_or_else(|| invalid_kernel_analytic("kernel plane has degenerate directions"))?;
            AnalyticSurface::Plane(crate::PlaneSurface {
                origin: vec3_from_kernel(*origin),
                normal,
            })
        }
        KernelSurface::RuledRevolution {
            frame,
            rho0,
            rho1,
            height,
        } => {
            if !rho0.is_finite()
                || !rho1.is_finite()
                || !height.is_finite()
                || *rho0 < 0.0
                || *rho1 < 0.0
            {
                return Err(invalid_kernel_analytic(
                    "kernel ruled revolution has invalid radius or height",
                ));
            }
            let axis = vec3_from_kernel(frame.axis)
                .normalized()
                .ok_or_else(|| invalid_kernel_analytic("kernel revolution axis is degenerate"))?;
            let origin = vec3_from_kernel(frame.origin);
            let radius_scale = rho0.abs().max(rho1.abs()).max(1.0);
            if (*rho1 - *rho0).abs()
                <= numerical::brep::REVOLUTION_EQUAL_RADIUS_RELATIVE * radius_scale
            {
                if *rho0 <= 0.0 || height.abs() <= numerical::brep::REVOLUTION_MIN_ABSOLUTE_HEIGHT {
                    return Err(invalid_kernel_analytic(
                        "kernel cylinder has non-positive radius or zero height",
                    ));
                }
                AnalyticSurface::Cylinder(crate::CylinderSurface {
                    axis_origin: origin,
                    axis,
                    radius: *rho0,
                })
            } else {
                if height.abs() <= numerical::brep::REVOLUTION_MIN_ABSOLUTE_HEIGHT {
                    return Err(invalid_kernel_analytic("kernel cone has zero height"));
                }
                // rho(z) = rho0 + slope*z. Our cone axis points from the apex
                // into the represented nappe, hence the sign(slope) adjustment.
                let slope = (*rho1 - *rho0) / *height;
                if !slope.is_finite() || slope == 0.0 {
                    return Err(invalid_kernel_analytic("kernel cone has invalid slope"));
                }
                let apex_z = -*rho0 / slope;
                AnalyticSurface::Cone(crate::ConeSurface {
                    apex: origin + axis * apex_z,
                    axis: axis * slope.signum(),
                    half_angle: slope.abs().atan(),
                })
            }
        }
        KernelSurface::Sphere { frame, radius } => {
            let _axis = vec3_from_kernel(frame.axis)
                .normalized()
                .ok_or_else(|| invalid_kernel_analytic("kernel sphere frame is degenerate"))?;
            AnalyticSurface::Sphere(crate::SphereSurface {
                center: vec3_from_kernel(frame.origin),
                radius: *radius,
            })
        }
        KernelSurface::Torus {
            frame,
            major_radius,
            minor_radius,
        } => AnalyticSurface::Torus(crate::TorusSurface {
            center: vec3_from_kernel(frame.origin),
            axis: vec3_from_kernel(frame.axis)
                .normalized()
                .ok_or_else(|| invalid_kernel_analytic("kernel torus axis is degenerate"))?,
            major_radius: *major_radius,
            minor_radius: *minor_radius,
        }),
        KernelSurface::Revolution { .. } => return Ok(None),
    };

    if !converted.is_valid() {
        return Err(invalid_kernel_analytic(
            "kernel analytic carrier has invalid primitive parameters",
        ));
    }
    Ok(Some(converted))
}

/// Extract exact primitive truth from one face while preserving face sense as
/// separate metadata.
pub fn analytic_truth_from_face(
    face: &brep_kernel::FaceRecord,
    mesh_face_id: u32,
) -> Result<Option<KernelFaceTruth>, RecognitionError> {
    let Some(source) = face.surface.analytic() else {
        return Ok(None);
    };
    let Some(surface) = surface_from_kernel_analytic(source)? else {
        return Ok(None);
    };
    Ok(Some(KernelFaceTruth {
        mesh_face_id,
        source_face_id: face.id,
        source_face_name: face.name.clone(),
        orientation: kernel_face_orientation(source, face.same_sense),
        surface,
    }))
}

/// Enumerate exact primitive truth in the same shell/face order used by
/// `tessellate_brep_watertight` to assign sequential `face_ids`.
pub fn analytic_truths_from_solid(
    solid: &brep_kernel::BrepSolid,
) -> Result<Vec<KernelFaceTruth>, RecognitionError> {
    let mut truths = Vec::new();
    let mut mesh_face_id = 0u32;
    for shell in &solid.shells {
        for face in &shell.faces {
            if let Some(truth) = analytic_truth_from_face(face, mesh_face_id)? {
                truths.push(truth);
            }
            mesh_face_id = mesh_face_id.checked_add(1).ok_or_else(|| {
                RecognitionError::InvalidMesh("kernel solid has more than u32::MAX faces".into())
            })?;
        }
    }
    Ok(truths)
}

/// Populate exact source metadata for every tessellated face whose kernel
/// carrier is one of the five supported primitives.
///
/// Returns the number of metadata records added. Analytic faces that produced
/// no triangles (for example a degenerate trim) are skipped.
pub fn attach_solid_analytic_metadata(
    converted: &mut KernelMeshConversion,
    solid: &brep_kernel::BrepSolid,
    source_tolerance: Option<f64>,
) -> Result<usize, RecognitionError> {
    if source_tolerance.is_some_and(|value| !value.is_finite() || value <= 0.0) {
        return Err(RecognitionError::InvalidSelection(
            "source tolerance must be finite and positive".into(),
        ));
    }
    let start = converted.mesh.source_metadata.len();
    for truth in analytic_truths_from_solid(solid)? {
        let triangle_indices: Vec<usize> = converted
            .triangle_face_ids
            .iter()
            .enumerate()
            .filter_map(|(triangle, &face)| (face == Some(truth.mesh_face_id)).then_some(triangle))
            .collect();
        if triangle_indices.is_empty() {
            continue;
        }
        converted.mesh.source_metadata.push(SourceMetadata {
            version: 1,
            triangle_indices,
            hint: SurfaceHint::ExactCandidate {
                surface: truth.surface,
            },
            source_face_id: Some(truth.source_face_id),
            source_face_name: truth.source_face_name,
            source_surface_id: None,
            orientation: Some(truth.orientation),
            source_tolerance,
        });
    }
    Ok(converted.mesh.source_metadata.len() - start)
}

/// A converted kernel mesh together with its per-triangle, tessellator-local
/// face ownership.
///
/// `triangle_face_ids` contains `None` when the source mesh did not carry face
/// ownership. A present id is the kernel tessellator's sequential face index,
/// not the stable `FaceRecord::id`.
#[derive(Clone, Debug, PartialEq)]
pub struct KernelMeshConversion {
    /// Portable indexed recognition mesh.
    pub mesh: Mesh,
    /// Sequential tessellator face ownership for each triangle.
    pub triangle_face_ids: Vec<Option<u32>>,
}

/// Convert a kernel vector into the neutral recognition DTO.
pub fn vec3_from_kernel(value: brep_kernel::Vec3) -> Vec3 {
    Vec3::new(value.x, value.y, value.z)
}

/// Convert a neutral recognition vector into the kernel boundary type.
pub fn vec3_to_kernel(value: Vec3) -> brep_kernel::Vec3 {
    brep_kernel::Vec3::new(value.x, value.y, value.z)
}

/// Convert the kernel's flat indexed mesh without discarding its transient
/// per-triangle face ownership.
///
/// Kernel derivative normals are retained as per-vertex fitting hints.
/// Triangle normals are still derived from winding and remain authoritative
/// for adjacency, feature detection, region support, and orientation sign.
pub fn convert_kernel_mesh(
    source: &brep_kernel::Mesh,
) -> Result<KernelMeshConversion, RecognitionError> {
    if source.positions.is_empty() {
        return Err(RecognitionError::InvalidMesh(
            "kernel mesh has no positions".into(),
        ));
    }
    if !source.positions.len().is_multiple_of(3) {
        return Err(RecognitionError::InvalidMesh(
            "kernel position buffer must contain xyz triples".into(),
        ));
    }
    if source.indices.is_empty() || !source.indices.len().is_multiple_of(3) {
        return Err(RecognitionError::InvalidMesh(
            "kernel index buffer must contain triangles".into(),
        ));
    }
    if source
        .positions
        .iter()
        .any(|coordinate| !coordinate.is_finite())
    {
        return Err(RecognitionError::InvalidMesh(
            "kernel position buffer contains a non-finite coordinate".into(),
        ));
    }
    if !source.normals.is_empty() && source.normals.len() != source.positions.len() {
        return Err(RecognitionError::InvalidMesh(format!(
            "kernel normal buffer has {} coordinates for {} position coordinates",
            source.normals.len(),
            source.positions.len()
        )));
    }
    if source
        .normals
        .iter()
        .any(|coordinate| !coordinate.is_finite())
    {
        return Err(RecognitionError::InvalidMesh(
            "kernel normal buffer contains a non-finite coordinate".into(),
        ));
    }

    let vertex_count = source.positions.len() / 3;
    if source
        .indices
        .iter()
        .any(|&index| index as usize >= vertex_count)
    {
        return Err(RecognitionError::InvalidMesh(
            "kernel triangle index is outside the position buffer".into(),
        ));
    }
    let triangle_count = source.indices.len() / 3;
    if !source.face_ids.is_empty() && source.face_ids.len() != triangle_count {
        return Err(RecognitionError::InvalidMesh(format!(
            "kernel face-id buffer has {} entries for {triangle_count} triangles",
            source.face_ids.len()
        )));
    }

    let vertices = source
        .positions
        .chunks_exact(3)
        .map(|point| Vec3::new(point[0], point[1], point[2]))
        .collect();
    let vertex_normals = (!source.normals.is_empty()).then(|| {
        source
            .normals
            .chunks_exact(3)
            .map(|normal| Vec3::new(normal[0], normal[1], normal[2]))
            .collect()
    });
    let triangles = source
        .indices
        .chunks_exact(3)
        .map(|triangle| [triangle[0], triangle[1], triangle[2]])
        .collect();
    let triangle_face_ids = if source.face_ids.is_empty() {
        vec![None; triangle_count]
    } else {
        source.face_ids.iter().copied().map(Some).collect()
    };

    Ok(KernelMeshConversion {
        mesh: Mesh {
            vertices,
            triangles,
            vertex_normals,
            source_metadata: Vec::new(),
        },
        triangle_face_ids,
    })
}

/// Convenience conversion for callers that do not need source-face routing.
/// Prefer [`convert_kernel_mesh`] when constructing boolean-healing metadata.
pub fn mesh_from_kernel(source: &brep_kernel::Mesh) -> Result<Mesh, RecognitionError> {
    Ok(convert_kernel_mesh(source)?.mesh)
}

/// A finite, strictly increasing interval used to construct a native kernel
/// NURBS patch. Private fields prevent callers from bypassing validation.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FiniteInterval {
    start: f64,
    end: f64,
}

impl FiniteInterval {
    /// Validate and construct a finite, strictly increasing interval.
    pub fn new(start: f64, end: f64) -> Result<Self, RecognitionError> {
        let length = end - start;
        if !start.is_finite() || !end.is_finite() || !length.is_finite() || length <= 0.0 {
            return Err(RecognitionError::InvalidSelection(
                "surface interval bounds must be finite and strictly increasing".into(),
            ));
        }
        Ok(Self { start, end })
    }

    /// Return the inclusive lower construction bound.
    pub fn start(self) -> f64 {
        self.start
    }

    /// Return the inclusive upper construction bound.
    pub fn end(self) -> f64 {
        self.end
    }

    /// Return `end - start`.
    pub fn length(self) -> f64 {
        self.end - self.start
    }
}

/// Required finite construction bounds for carriers that are infinite in at
/// least one direction. These bounds create an untrimmed rectangular NURBS
/// patch; they are not BREP trim loops or p-curves.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FinitePatchBounds {
    /// Two finite parameter intervals for an untrimmed plane patch.
    Plane {
        /// First plane-basis interval.
        u: FiniteInterval,
        /// Second plane-basis interval.
        v: FiniteInterval,
    },
    /// Signed coordinates along a cylinder axis or cone axis. Cone bounds must
    /// lie strictly on the represented positive nappe.
    Axial(FiniteInterval),
}

impl FinitePatchBounds {
    /// Validate plane parameter bounds and construct [`Self::Plane`].
    pub fn plane(
        u_start: f64,
        u_end: f64,
        v_start: f64,
        v_end: f64,
    ) -> Result<Self, RecognitionError> {
        Ok(Self::Plane {
            u: FiniteInterval::new(u_start, u_end)?,
            v: FiniteInterval::new(v_start, v_end)?,
        })
    }

    /// Validate an axial interval and construct [`Self::Axial`].
    pub fn axial(start: f64, end: f64) -> Result<Self, RecognitionError> {
        Ok(Self::Axial(FiniteInterval::new(start, end)?))
    }
}

/// A native exact rational surface plus the recovered face orientation.
///
/// Orientation is deliberately not baked into the NURBS parameterization:
/// callers constructing a future `FaceRecord` must apply it as face sense
/// after creating valid trim curves, p-curves, and shared topology.
#[derive(Clone, Debug)]
pub struct OrientedNurbsSurface {
    /// Exact native kernel NURBS carrier geometry.
    pub surface: brep_kernel::NurbsSurface,
    /// Observed face sense, always `-1` or `+1`.
    pub orientation: i8,
}

fn native_surface_error(surface: AnalyticSurface, reason: impl Into<String>) -> RecognitionError {
    RecognitionError::FitFailed {
        surface: Some(surface.surface_type().name()),
        reason: format!("native NURBS construction failed: {}", reason.into()),
    }
}

/// Convert a recovered carrier to the kernel's exact native rational NURBS
/// representation over explicit finite construction bounds.
///
/// Plane, cylinder, and cone carriers require matching bounds. Sphere and
/// torus constructors already produce finite closed surfaces and therefore
/// require `None`. This function constructs surface geometry only: it does not
/// infer a trim domain, create a `FaceRecord`, or sew a shell.
pub fn nurbs_surface_from_analytic(
    surface: AnalyticSurface,
    orientation: i8,
    bounds: Option<FinitePatchBounds>,
) -> Result<OrientedNurbsSurface, RecognitionError> {
    if !matches!(orientation, -1 | 1) {
        return Err(RecognitionError::InvalidSelection(
            "surface orientation must be -1 or +1".into(),
        ));
    }
    if !surface.is_valid() {
        return Err(native_surface_error(surface, "invalid analytic parameters"));
    }
    let native = match (surface, bounds) {
        (AnalyticSurface::Plane(plane), Some(FinitePatchBounds::Plane { u, v })) => {
            let (u_direction, v_direction) = plane
                .normal
                .orthonormal_basis()
                .ok_or_else(|| native_surface_error(surface, "invalid plane basis"))?;
            let origin = plane.origin + u_direction * u.start() + v_direction * v.start();
            brep_kernel::make_plane(
                vec3_to_kernel(origin),
                vec3_to_kernel(u_direction),
                vec3_to_kernel(v_direction),
                u.length(),
                v.length(),
            )
        }
        (AnalyticSurface::Cylinder(cylinder), Some(FinitePatchBounds::Axial(axial))) => {
            let base = cylinder.axis_origin + cylinder.axis * axial.start();
            brep_kernel::make_cylinder_surface(
                vec3_to_kernel(base),
                vec3_to_kernel(cylinder.axis),
                cylinder.radius,
                axial.length(),
            )
        }
        (AnalyticSurface::Cone(cone), Some(FinitePatchBounds::Axial(axial))) => {
            if axial.start() <= 0.0 {
                return Err(RecognitionError::InvalidSelection(
                    "cone axial bounds must lie strictly on the positive nappe".into(),
                ));
            }
            let tangent = cone.half_angle.tan();
            let base = cone.apex + cone.axis * axial.start();
            brep_kernel::make_cone_surface(
                vec3_to_kernel(base),
                vec3_to_kernel(cone.axis),
                axial.start() * tangent,
                axial.end() * tangent,
                axial.length(),
            )
        }
        (AnalyticSurface::Sphere(sphere), None) => brep_kernel::make_sphere_surface(
            vec3_to_kernel(sphere.center),
            sphere.radius,
            brep_kernel::Vec3::new(0.0, 0.0, 1.0),
        ),
        (AnalyticSurface::Torus(torus), None) => brep_kernel::make_torus_surface(
            vec3_to_kernel(torus.center),
            vec3_to_kernel(torus.axis),
            torus.major_radius,
            torus.minor_radius,
        ),
        (AnalyticSurface::Plane(_), _) => {
            return Err(RecognitionError::InvalidSelection(
                "plane conversion requires plane u/v bounds".into(),
            ));
        }
        (AnalyticSurface::Cylinder(_), _) => {
            return Err(RecognitionError::InvalidSelection(
                "cylinder conversion requires axial bounds".into(),
            ));
        }
        (AnalyticSurface::Cone(_), _) => {
            return Err(RecognitionError::InvalidSelection(
                "cone conversion requires axial bounds".into(),
            ));
        }
        (AnalyticSurface::Sphere(_) | AnalyticSurface::Torus(_), Some(_)) => {
            return Err(RecognitionError::InvalidSelection(
                "sphere and torus conversion use their complete native domains and take no bounds"
                    .into(),
            ));
        }
    }
    .map_err(|reason| native_surface_error(surface, reason))?;
    Ok(OrientedNurbsSurface {
        surface: native,
        orientation,
    })
}

/// Tessellate one complete kernel solid, preserve face ownership and supplied
/// derivative normals, and attach exact metadata for every supported analytic
/// source face.
///
/// This is the preferred bridge for whole-body recognition and STEP corpus
/// validation. Unsupported/freeform faces receive no metadata and therefore
/// continue through generic recognition or remain unresolved.
pub fn tessellate_kernel_solid_with_metadata(
    solid: &brep_kernel::BrepSolid,
    chord_tolerance: f64,
    source_tolerance: Option<f64>,
) -> Result<KernelMeshConversion, RecognitionError> {
    if !chord_tolerance.is_finite() || chord_tolerance <= 0.0 {
        return Err(RecognitionError::InvalidSelection(
            "chord tolerance must be finite and positive".into(),
        ));
    }
    let source =
        brep_kernel::tessellate_brep_watertight(solid, chord_tolerance).map_err(|error| {
            RecognitionError::InvalidMesh(format!("kernel tessellation failed: {error}"))
        })?;
    let mut converted = convert_kernel_mesh(&source)?;
    attach_solid_analytic_metadata(&mut converted, solid, source_tolerance)?;
    Ok(converted)
}

/// Attach one host-provided source hint to every triangle carrying a specified
/// sequential kernel face id.
///
/// Stable topology identity is supplied separately because `mesh_face_id` is
/// only the flattened face number emitted by the tessellator.
#[allow(clippy::too_many_arguments)]
pub fn attach_face_metadata(
    converted: &mut KernelMeshConversion,
    mesh_face_id: u32,
    hint: SurfaceHint,
    source_face_id: Option<u64>,
    source_face_name: Option<String>,
    source_surface_id: Option<String>,
    orientation: Option<i8>,
    source_tolerance: Option<f64>,
) -> Result<(), RecognitionError> {
    if orientation.is_some_and(|sense| !matches!(sense, -1 | 1)) {
        return Err(RecognitionError::InvalidMesh(
            "source orientation must be -1 or +1".into(),
        ));
    }
    let triangle_indices: Vec<usize> = converted
        .triangle_face_ids
        .iter()
        .enumerate()
        .filter_map(|(triangle, &face)| (face == Some(mesh_face_id)).then_some(triangle))
        .collect();
    if triangle_indices.is_empty() {
        return Err(RecognitionError::InvalidSelection(format!(
            "kernel mesh contains no triangles for sequential face {mesh_face_id}"
        )));
    }
    converted.mesh.source_metadata.push(SourceMetadata {
        version: 1,
        triangle_indices,
        hint,
        source_face_id,
        source_face_name,
        source_surface_id,
        orientation,
        source_tolerance,
    });
    Ok(())
}

/// Convert a recognized mathematical carrier to the kernel mesh segmenter's
/// public carrier representation.
///
/// `orientation` is the observed face sense and must be `-1` or `+1`. Plane
/// carriers encode it by orienting their normal; curved kernel carriers expose
/// it as `sense`.
pub fn region_carrier_from_surface(
    surface: AnalyticSurface,
    orientation: i8,
) -> Result<brep_kernel::RegionCarrier, RecognitionError> {
    if !matches!(orientation, -1 | 1) {
        return Err(RecognitionError::InvalidSelection(
            "surface orientation must be -1 or +1".into(),
        ));
    }
    if !surface.is_valid() {
        return Err(RecognitionError::FitFailed {
            surface: Some(surface.surface_type().name()),
            reason: "cannot convert invalid analytic parameters".into(),
        });
    }
    let sign = orientation as f64;
    Ok(match surface {
        AnalyticSurface::Plane(plane) => brep_kernel::RegionCarrier::Plane {
            origin: vec3_to_kernel(plane.origin),
            normal: vec3_to_kernel(plane.normal * sign),
        },
        AnalyticSurface::Cylinder(cylinder) => brep_kernel::RegionCarrier::Cylinder {
            axis_point: vec3_to_kernel(cylinder.axis_origin),
            axis_dir: vec3_to_kernel(cylinder.axis),
            radius: cylinder.radius,
            sense: orientation,
        },
        AnalyticSurface::Cone(cone) => brep_kernel::RegionCarrier::Cone {
            apex: vec3_to_kernel(cone.apex),
            axis_dir: vec3_to_kernel(cone.axis),
            half_angle_rad: cone.half_angle,
            sense: orientation,
        },
        AnalyticSurface::Sphere(sphere) => brep_kernel::RegionCarrier::Sphere {
            center: vec3_to_kernel(sphere.center),
            radius: sphere.radius,
            sense: orientation,
        },
        AnalyticSurface::Torus(torus) => brep_kernel::RegionCarrier::Torus {
            center: vec3_to_kernel(torus.center),
            axis_dir: vec3_to_kernel(torus.axis),
            major_radius: torus.major_radius,
            minor_radius: torus.minor_radius,
            sense: orientation,
        },
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{CylinderSurface, PlaneSurface, SphereSurface, SurfaceType, TorusSurface};

    fn frame(origin: brep_kernel::Vec3, axis: brep_kernel::Vec3) -> brep_kernel::RevolutionFrame {
        let x_axis = axis.perpendicular().unwrap();
        brep_kernel::RevolutionFrame {
            origin,
            axis,
            x_axis,
            y_axis: axis.cross(x_axis).normalized().unwrap(),
        }
    }

    fn close(a: f64, b: f64) {
        assert!((a - b).abs() <= 1.0e-12, "{a} != {b}");
    }

    #[test]
    fn vec3_round_trip_is_lossless() {
        let point = Vec3::new(1.25, -2.5, 9.0);
        let kernel = vec3_to_kernel(point);
        assert_eq!(vec3_from_kernel(kernel), point);
    }

    #[test]
    fn mesh_conversion_preserves_indices_and_face_ownership() {
        let source = brep_kernel::Mesh {
            positions: vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0],
            normals: vec![0.0, 0.0, 2.0, 0.0, 0.0, 2.0, 0.0, 0.0, 2.0],
            indices: vec![0, 1, 2],
            face_ids: vec![7],
        };
        let converted = convert_kernel_mesh(&source).unwrap();
        assert_eq!(converted.mesh.triangles, vec![[0, 1, 2]]);
        assert_eq!(
            converted.mesh.vertex_normals,
            Some(vec![Vec3::new(0.0, 0.0, 2.0); 3])
        );
        assert_eq!(
            converted
                .mesh
                .analyze(&Default::default())
                .unwrap()
                .vertex_normals,
            Some(vec![Vec3::Z; 3])
        );
        assert_eq!(converted.triangle_face_ids, vec![Some(7)]);
    }

    #[test]
    fn mesh_conversion_rejects_misaligned_face_ids() {
        let source = brep_kernel::Mesh {
            positions: vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0],
            normals: vec![],
            indices: vec![0, 1, 2],
            face_ids: vec![1, 2],
        };
        assert!(convert_kernel_mesh(&source).is_err());
    }

    #[test]
    fn mesh_conversion_rejects_malformed_kernel_normals() {
        let base = brep_kernel::Mesh {
            positions: vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0],
            normals: vec![0.0, 0.0, 1.0],
            indices: vec![0, 1, 2],
            face_ids: vec![0],
        };
        assert!(convert_kernel_mesh(&base).is_err());
        let mut non_finite = base;
        non_finite.normals = vec![0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0];
        non_finite.normals[4] = f64::NAN;
        assert!(convert_kernel_mesh(&non_finite).is_err());
    }

    #[test]
    fn metadata_routes_transient_and_stable_face_ids_separately() {
        let source = brep_kernel::Mesh {
            positions: vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0],
            normals: vec![],
            indices: vec![0, 1, 2],
            face_ids: vec![3],
        };
        let mut converted = convert_kernel_mesh(&source).unwrap();
        attach_face_metadata(
            &mut converted,
            3,
            SurfaceHint::KnownType {
                surface_type: SurfaceType::Plane,
            },
            Some(9001),
            Some("CAP".into()),
            None,
            Some(1),
            Some(1.0e-7),
        )
        .unwrap();
        let metadata = &converted.mesh.source_metadata[0];
        assert_eq!(metadata.triangle_indices, vec![0]);
        assert_eq!(metadata.source_face_id, Some(9001));
    }

    #[test]
    fn all_analytic_surfaces_convert_to_native_nurbs_with_separate_orientation() {
        let cases = [
            (
                AnalyticSurface::Plane(PlaneSurface {
                    origin: Vec3::new(1.0, 2.0, 3.0),
                    normal: Vec3::new(0.2, -0.3, 0.9).normalized().unwrap(),
                }),
                Some(FinitePatchBounds::plane(-2.0, 3.0, -1.0, 4.0).unwrap()),
            ),
            (
                AnalyticSurface::Cylinder(CylinderSurface {
                    axis_origin: Vec3::new(-1.0, 0.5, 2.0),
                    axis: Vec3::new(0.1, 0.2, 0.97).normalized().unwrap(),
                    radius: 2.5,
                }),
                Some(FinitePatchBounds::axial(-3.0, 6.0).unwrap()),
            ),
            (
                AnalyticSurface::Cone(crate::ConeSurface {
                    apex: Vec3::new(0.5, -1.0, 2.0),
                    axis: Vec3::new(-0.2, 0.3, 0.93).normalized().unwrap(),
                    half_angle: 0.35,
                }),
                Some(FinitePatchBounds::axial(1.5, 7.0).unwrap()),
            ),
            (
                AnalyticSurface::Sphere(SphereSurface {
                    center: Vec3::new(3.0, -2.0, 1.0),
                    radius: 4.0,
                }),
                None,
            ),
            (
                AnalyticSurface::Torus(TorusSurface {
                    center: Vec3::new(-2.0, 1.0, 0.5),
                    axis: Vec3::new(0.2, 0.9, -0.3).normalized().unwrap(),
                    major_radius: 6.0,
                    minor_radius: 1.25,
                }),
                None,
            ),
        ];
        for (surface, bounds) in cases {
            let converted = nurbs_surface_from_analytic(surface, -1, bounds).unwrap();
            assert_eq!(converted.orientation, -1);
            let analytic = converted.surface.analytic().unwrap_or_else(|| {
                panic!("{:?} native patch not analytic", surface.surface_type())
            });
            let recovered = surface_from_kernel_analytic(analytic)
                .unwrap()
                .unwrap_or_else(|| panic!("{:?} did not round trip", surface.surface_type()));
            assert_eq!(recovered.surface_type(), surface.surface_type());
        }
    }

    #[test]
    fn native_nurbs_conversion_rejects_missing_or_mismatched_bounds() {
        let plane = AnalyticSurface::Plane(PlaneSurface {
            origin: Vec3::ZERO,
            normal: Vec3::Z,
        });
        assert!(FiniteInterval::new(1.0, 1.0).is_err());
        assert!(FiniteInterval::new(f64::NAN, 2.0).is_err());
        assert!(nurbs_surface_from_analytic(plane, 1, None).is_err());
        assert!(nurbs_surface_from_analytic(
            plane,
            1,
            Some(FinitePatchBounds::axial(0.0, 1.0).unwrap())
        )
        .is_err());
        let cone = AnalyticSurface::Cone(crate::ConeSurface {
            apex: Vec3::ZERO,
            axis: Vec3::Z,
            half_angle: 0.3,
        });
        assert!(nurbs_surface_from_analytic(
            cone,
            1,
            Some(FinitePatchBounds::axial(-1.0, 2.0).unwrap())
        )
        .is_err());
    }

    #[test]
    fn all_carriers_convert_with_orientation() {
        let cases = [
            AnalyticSurface::Plane(PlaneSurface {
                origin: Vec3::ZERO,
                normal: Vec3::Z,
            }),
            AnalyticSurface::Cylinder(CylinderSurface {
                axis_origin: Vec3::ZERO,
                axis: Vec3::Z,
                radius: 2.0,
            }),
            AnalyticSurface::Sphere(SphereSurface {
                center: Vec3::ZERO,
                radius: 3.0,
            }),
            AnalyticSurface::Torus(TorusSurface {
                center: Vec3::ZERO,
                axis: Vec3::Z,
                major_radius: 5.0,
                minor_radius: 1.0,
            }),
            AnalyticSurface::Cone(crate::ConeSurface {
                apex: Vec3::ZERO,
                axis: Vec3::Z,
                half_angle: 0.25,
            }),
        ];
        for surface in cases {
            let carrier = region_carrier_from_surface(surface, -1).unwrap();
            assert_eq!(carrier.kind(), surface.surface_type().name());
        }
        let plane = region_carrier_from_surface(cases[0], -1).unwrap();
        let brep_kernel::RegionCarrier::Plane { normal, .. } = plane else {
            unreachable!()
        };
        assert_eq!(normal.z, -1.0);
    }

    #[test]
    fn kernel_plane_truth_uses_parametric_normal_without_face_sense() {
        let source = brep_kernel::AnalyticSurface::Plane {
            origin: brep_kernel::Vec3::new(2.0, 3.0, 4.0),
            u_dir: brep_kernel::Vec3::new(2.0, 0.0, 0.0),
            v_dir: brep_kernel::Vec3::new(0.0, -3.0, 0.0),
            u_domain: [0.0, 1.0],
            v_domain: [0.0, 1.0],
        };
        let Some(AnalyticSurface::Plane(plane)) = surface_from_kernel_analytic(&source).unwrap()
        else {
            panic!("expected plane")
        };
        assert_eq!(plane.origin, Vec3::new(2.0, 3.0, 4.0));
        assert_eq!(plane.normal, -Vec3::Z);
    }

    #[test]
    fn ruled_revolution_converts_cylinder_and_signed_slope_cone() {
        let cylinder = brep_kernel::AnalyticSurface::RuledRevolution {
            frame: frame(
                brep_kernel::Vec3::new(1.0, 2.0, 3.0),
                brep_kernel::Vec3::new(0.0, 0.0, 1.0),
            ),
            rho0: 4.0,
            rho1: 4.0,
            height: -7.0,
        };
        let Some(AnalyticSurface::Cylinder(cylinder)) =
            surface_from_kernel_analytic(&cylinder).unwrap()
        else {
            panic!("expected cylinder")
        };
        assert_eq!(cylinder.axis_origin, Vec3::new(1.0, 2.0, 3.0));
        assert_eq!(cylinder.axis, Vec3::Z);
        close(cylinder.radius, 4.0);

        let cone = brep_kernel::AnalyticSurface::RuledRevolution {
            frame: frame(
                brep_kernel::Vec3::new(0.0, 0.0, 0.0),
                brep_kernel::Vec3::new(0.0, 0.0, 1.0),
            ),
            rho0: 4.0,
            rho1: 2.0,
            height: 5.0,
        };
        let Some(AnalyticSurface::Cone(cone)) = surface_from_kernel_analytic(&cone).unwrap() else {
            panic!("expected cone")
        };
        assert_eq!(cone.apex, Vec3::new(0.0, 0.0, 10.0));
        assert_eq!(cone.axis, -Vec3::Z);
        close(cone.half_angle, 0.4_f64.atan());
        let cone = AnalyticSurface::Cone(cone);
        close(cone.signed_distance(Vec3::new(4.0, 0.0, 0.0)), 0.0);
        close(cone.signed_distance(Vec3::new(2.0, 0.0, 5.0)), 0.0);
    }

    #[test]
    fn cone_conversion_preserves_nappe_and_parametric_orientation_gauge() {
        let origin = brep_kernel::Vec3::new(1.0, -2.0, 0.5);
        let axis = brep_kernel::Vec3::new(0.0, 0.0, 1.0);
        let rho0 = 3.0;
        for (height, delta_radius) in [(5.0, 2.0), (5.0, -2.0), (-5.0, 2.0), (-5.0, -2.0)] {
            let kernel_frame = frame(origin, axis);
            let source = brep_kernel::AnalyticSurface::RuledRevolution {
                frame: kernel_frame.clone(),
                rho0,
                rho1: rho0 + delta_radius,
                height,
            };
            let Some(AnalyticSurface::Cone(cone)) = surface_from_kernel_analytic(&source).unwrap()
            else {
                panic!("expected cone")
            };

            let slope = delta_radius / height;
            let expected_axis = vec3_from_kernel(axis) * slope.signum();
            let expected_apex = vec3_from_kernel(origin) + vec3_from_kernel(axis) * (-rho0 / slope);
            assert_eq!(cone.axis, expected_axis, "height={height}, slope={slope}");
            assert_eq!(cone.apex, expected_apex, "height={height}, slope={slope}");
            close(cone.half_angle, slope.abs().atan());

            // Compare the canonical cone normal with the kernel's
            // dS/dtheta x dS/dt normal at an interior point of the same
            // generatrix. Their only allowed difference is sign(height).
            let t = 0.37;
            let radial = vec3_from_kernel(kernel_frame.x_axis);
            let kernel_axis = vec3_from_kernel(kernel_frame.axis);
            let point = vec3_from_kernel(kernel_frame.origin)
                + radial * (rho0 + t * delta_radius)
                + kernel_axis * (t * height);
            let canonical = AnalyticSurface::Cone(cone);
            close(canonical.signed_distance(point), 0.0);
            let canonical_normal = canonical.normal_at(point).unwrap();
            let parametric_normal = (radial * height - kernel_axis * delta_radius)
                .normalized()
                .unwrap();
            let expected_gauge = if height < 0.0 { -1 } else { 1 };
            close(
                canonical_normal.dot(parametric_normal),
                expected_gauge as f64,
            );
            assert_eq!(
                kernel_carrier_orientation_gauge(&source),
                expected_gauge,
                "height={height}, slope={slope}"
            );
            assert_eq!(
                kernel_face_orientation(&source, true),
                expected_gauge,
                "same_sense=true, height={height}, slope={slope}"
            );
            assert_eq!(
                kernel_face_orientation(&source, false),
                -expected_gauge,
                "same_sense=false, height={height}, slope={slope}"
            );
        }
    }

    #[test]
    fn primitive_brep_truth_covers_five_types_and_keeps_face_sense_separate() {
        let cylinder = brep_kernel::make_cylinder_brep(
            brep_kernel::Vec3::new(0.0, 0.0, 0.0),
            brep_kernel::Vec3::new(0.0, 0.0, 1.0),
            2.0,
            4.0,
        )
        .unwrap();
        let truths = analytic_truths_from_solid(&cylinder).unwrap();
        assert_eq!(truths.len(), 3);
        assert!(truths
            .iter()
            .any(|truth| matches!(truth.surface, AnalyticSurface::Cylinder(_))));
        for truth in &truths {
            let face = &cylinder.shells[0].faces[truth.mesh_face_id as usize];
            assert_eq!(truth.orientation, if face.same_sense { 1 } else { -1 });
            if let AnalyticSurface::Plane(plane) = truth.surface {
                let brep_kernel::AnalyticSurface::Plane { u_dir, v_dir, .. } =
                    face.surface.analytic().unwrap()
                else {
                    unreachable!()
                };
                // The carrier normal remains the NURBS parameter normal even
                // for the bottom cap whose face sense is reversed.
                let expected = vec3_from_kernel(*u_dir)
                    .cross(vec3_from_kernel(*v_dir))
                    .normalized()
                    .unwrap();
                assert_eq!(plane.normal, expected);
            }
        }

        let cone = brep_kernel::make_cone_brep(
            brep_kernel::Vec3::new(0.0, 0.0, 0.0),
            brep_kernel::Vec3::new(0.0, 0.0, 1.0),
            3.0,
            1.0,
            5.0,
        )
        .unwrap();
        assert!(analytic_truths_from_solid(&cone)
            .unwrap()
            .iter()
            .any(|truth| matches!(truth.surface, AnalyticSurface::Cone(_))));

        let sphere = brep_kernel::make_sphere_brep(
            brep_kernel::Vec3::new(1.0, 2.0, 3.0),
            2.5,
            brep_kernel::Vec3::new(0.0, 0.0, 1.0),
        )
        .unwrap();
        assert!(matches!(
            analytic_truths_from_solid(&sphere).unwrap()[0].surface,
            AnalyticSurface::Sphere(_)
        ));

        let torus = brep_kernel::make_torus_brep(
            brep_kernel::Vec3::new(-1.0, 2.0, 0.5),
            brep_kernel::Vec3::new(0.0, 0.0, 1.0),
            5.0,
            1.25,
        )
        .unwrap();
        assert!(matches!(
            analytic_truths_from_solid(&torus).unwrap()[0].surface,
            AnalyticSurface::Torus(_)
        ));
    }

    #[test]
    fn solid_truth_metadata_matches_tessellator_face_ids() {
        let solid = brep_kernel::make_cylinder_brep(
            brep_kernel::Vec3::new(0.0, 0.0, 0.0),
            brep_kernel::Vec3::new(0.0, 0.0, 1.0),
            2.0,
            4.0,
        )
        .unwrap();
        let source = brep_kernel::tessellate_brep_watertight(&solid, 0.05).unwrap();
        let mut converted = convert_kernel_mesh(&source).unwrap();
        let attached =
            attach_solid_analytic_metadata(&mut converted, &solid, Some(1.0e-7)).unwrap();
        assert_eq!(attached, 3);
        assert_eq!(converted.mesh.source_metadata.len(), 3);
        for metadata in &converted.mesh.source_metadata {
            let stable_id = metadata.source_face_id.unwrap();
            let face = solid.shells[0]
                .faces
                .iter()
                .find(|face| face.id == stable_id)
                .unwrap();
            assert_eq!(
                metadata.orientation,
                Some(if face.same_sense { 1 } else { -1 })
            );
            assert!(matches!(metadata.hint, SurfaceHint::ExactCandidate { .. }));
            assert!(!metadata.triangle_indices.is_empty());
        }
    }

    #[test]
    fn step_round_trip_preserves_convertible_analytic_truth() {
        let fixtures = [
            (
                "cylinder",
                brep_kernel::make_cylinder_brep(
                    brep_kernel::Vec3::new(1.0, -2.0, 0.5),
                    brep_kernel::Vec3::new(0.0, 0.0, 1.0),
                    2.25,
                    4.5,
                )
                .unwrap(),
                SurfaceType::Cylinder,
            ),
            (
                "cone",
                brep_kernel::make_cone_brep(
                    brep_kernel::Vec3::new(0.0, 0.0, 0.0),
                    brep_kernel::Vec3::new(0.0, 0.0, 1.0),
                    3.0,
                    1.0,
                    5.0,
                )
                .unwrap(),
                SurfaceType::Cone,
            ),
            (
                "sphere",
                brep_kernel::make_sphere_brep(
                    brep_kernel::Vec3::new(2.0, 3.0, 4.0),
                    1.75,
                    brep_kernel::Vec3::new(0.0, 1.0, 0.0),
                )
                .unwrap(),
                SurfaceType::Sphere,
            ),
            (
                "torus",
                brep_kernel::make_torus_brep(
                    brep_kernel::Vec3::new(-1.0, 0.5, 2.0),
                    brep_kernel::Vec3::new(0.0, 0.0, 1.0),
                    4.0,
                    0.75,
                )
                .unwrap(),
                SurfaceType::Torus,
            ),
        ];

        for (label, original, expected_type) in fixtures {
            let step = brep_kernel::export_step(
                std::slice::from_ref(&original),
                label,
                "millimeter",
                "fixed",
            )
            .unwrap();
            let imported = brep_kernel::import_step(&step).unwrap();
            assert_eq!(imported.len(), 1, "{label}");
            let truths = analytic_truths_from_solid(&imported[0]).unwrap();
            assert!(
                truths
                    .iter()
                    .any(|truth| truth.surface.surface_type() == expected_type),
                "{label} STEP round trip lost {expected_type:?}: {truths:?}"
            );
            for truth in truths {
                let face = imported[0]
                    .shells
                    .iter()
                    .flat_map(|shell| &shell.faces)
                    .nth(truth.mesh_face_id as usize)
                    .unwrap();
                assert_eq!(truth.orientation, if face.same_sense { 1 } else { -1 });
            }
        }
    }

    #[test]
    fn kernel_tessellation_converts_for_exact_prior_workflow() {
        let solid = brep_kernel::make_cylinder_brep(
            brep_kernel::Vec3::new(0.0, 0.0, 0.0),
            brep_kernel::Vec3::new(0.0, 0.0, 1.0),
            2.0,
            4.0,
        )
        .unwrap();
        let source = brep_kernel::tessellate_brep_watertight(&solid, 0.05).unwrap();
        let mut converted = convert_kernel_mesh(&source).unwrap();
        attach_face_metadata(
            &mut converted,
            0,
            SurfaceHint::ExactCandidate {
                surface: AnalyticSurface::Cylinder(CylinderSurface {
                    axis_origin: Vec3::ZERO,
                    axis: Vec3::Z,
                    radius: 2.0,
                }),
            },
            Some(solid.shells[0].faces[0].id),
            solid.shells[0].faces[0].name.clone(),
            None,
            Some(if solid.shells[0].faces[0].same_sense {
                1
            } else {
                -1
            }),
            Some(1.0e-7),
        )
        .unwrap();
        let triangle_indices = converted.mesh.source_metadata[0].triangle_indices.clone();
        assert!(!triangle_indices.is_empty());
        converted.mesh.analyze(&Default::default()).unwrap();
        let options = crate::RecognitionOptions {
            distance_tolerance: 1.0e-7,
            normal_tolerance: 0.3,
            sampling: crate::SamplingMode::Vertices,
            ..Default::default()
        };
        let fit = crate::reconstruct_surface(
            &converted.mesh,
            &triangle_indices,
            &converted.mesh.source_metadata[0].hint,
            &options,
        )
        .unwrap();
        assert_eq!(fit.diagnostics.path, crate::FitPath::ExactCandidateReused);
        assert!(fit.diagnostics.exact_parameters_reused);
        let carrier = region_carrier_from_surface(fit.surface, fit.orientation).unwrap();
        assert_eq!(carrier.kind(), "cylinder");
    }
}