BREP_kernel 0.15.0

A boundary representation (BREP) geometry kernel for building CAD applications.
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
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
use super::*;

struct RegionOutcome {
    fit: CandidateFit,
    accepted: bool,
    area: f64,
    bbox: (Vec3, Vec3),
    triangle_count: usize,
}

/// Try the analytic cascade plane → cylinder → cone → sphere → torus on one
/// region; the first carrier within tolerance wins.
fn fit_region(data: &MeshData, tri_ids: &[u32], options: &SegmentOptions) -> RegionOutcome {
    let vert_ids = region_vertices(data, tri_ids);
    let bbox = region_bbox(data, &vert_ids);
    let area: f64 = tri_ids.iter().map(|&t| data.tris[t as usize].area).sum();
    let scale = {
        let diag = bbox.1.sub(bbox.0).length();
        if diag > 0.0 {
            diag
        } else {
            data.diag.max(1e-12)
        }
    };
    let tol_abs = options.fit_tolerance * scale;
    let mut outcome = RegionOutcome {
        fit: CandidateFit {
            carrier: RegionCarrier::Freeform,
            max_dev: 0.0,
            rms_dev: 0.0,
            max_normal_angle_deg: 0.0,
        },
        accepted: false,
        area,
        bbox,
        triangle_count: tri_ids.len(),
    };
    if tri_ids.len() < options.min_region_triangles || vert_ids.len() < 3 {
        return outcome;
    }
    let candidates = [
        fit_plane(data, tri_ids, &vert_ids),
        fit_cylinder(data, tri_ids, &vert_ids),
        fit_cone(data, tri_ids, &vert_ids, tol_abs),
        fit_sphere(data, tri_ids, &vert_ids),
        fit_torus(data, tri_ids, &vert_ids),
    ];
    for candidate in candidates {
        if let Some(fit) = candidate {
            if std::env::var("BREP_DEBUG_SEG").is_ok() {
                eprintln!(
                    "[seg] region tris={} candidate={} max_dev={:.3e} tol_abs={:.3e} max_ang={:.3}",
                    tri_ids.len(),
                    fit.carrier.kind(),
                    fit.max_dev,
                    tol_abs,
                    fit.max_normal_angle_deg
                );
            }
            if fit.max_dev.is_finite()
                && fit.max_dev <= tol_abs
                && fit.max_normal_angle_deg <= options.normal_tolerance_deg
            {
                outcome.fit = fit;
                outcome.accepted = true;
                return outcome;
            }
        }
    }
    outcome
}

// ---------------------------------------------------------------------------
// Region growing and refinement
// ---------------------------------------------------------------------------

fn grow_regions(data: &MeshData, options: &SegmentOptions) -> Vec<Vec<u32>> {
    let cos_gate = options.deflection_angle_deg.to_radians().cos();
    let tri_count = data.tris.len();
    let mut assigned = vec![false; tri_count];
    let mut regions = Vec::new();
    let mut stack = Vec::new();
    for seed in 0..tri_count {
        if assigned[seed] || data.tris[seed].skip {
            continue;
        }
        assigned[seed] = true;
        stack.push(seed as u32);
        let mut region = Vec::new();
        while let Some(t) = stack.pop() {
            region.push(t);
            let tri = &data.tris[t as usize];
            for corner in 0..3 {
                let first = tri.verts[corner];
                let second = tri.verts[(corner + 1) % 3];
                if first == second {
                    continue;
                }
                let Some(incident) = data.edges.get(&edge_key(first, second)) else {
                    continue;
                };
                // Only manifold (two-sided) edges are smooth crossings.
                if incident.len() != 2 {
                    continue;
                }
                for &other in incident {
                    if other == t || assigned[other as usize] {
                        continue;
                    }
                    let neighbor = &data.tris[other as usize];
                    if neighbor.skip {
                        continue;
                    }
                    if tri.normal.dot(neighbor.normal) >= cos_gate {
                        assigned[other as usize] = true;
                        stack.push(other);
                    }
                }
            }
        }
        region.sort_unstable();
        regions.push(region);
    }
    regions
}

/// Regions whose area is below this fraction of the total mesh area are
/// dissolved into their largest neighboring region before fitting.  Needle
/// triangles at tessellation poles wall themselves off into 1–2-triangle
/// islands; the app's minimum-region-size gating served the same purpose.
const REGION_ABSORB_AREA_FRACTION: f64 = 1e-6;

/// Merge negligible regions into their largest-area neighbor (repeats until
/// stable so chains of islands resolve).  Regions with no neighbor at all
/// stay as they are.
fn absorb_tiny_regions(data: &MeshData, regions: &mut Vec<Vec<u32>>) {
    let total_area: f64 = data
        .tris
        .iter()
        .filter(|tri| !tri.skip)
        .map(|tri| tri.area)
        .sum();
    let floor = total_area * REGION_ABSORB_AREA_FRACTION;
    if !(floor > 0.0) {
        return;
    }
    let mut region_of = vec![usize::MAX; data.tris.len()];
    for (r, list) in regions.iter().enumerate() {
        for &t in list {
            region_of[t as usize] = r;
        }
    }
    let mut areas: Vec<f64> = regions
        .iter()
        .map(|list| list.iter().map(|&t| data.tris[t as usize].area).sum())
        .collect();
    let mut changed = true;
    while changed {
        changed = false;
        for r in 0..regions.len() {
            if regions[r].is_empty() || areas[r] >= floor {
                continue;
            }
            // Find adjacent regions, traversing THROUGH region-less
            // (skipped sliver) triangles — pole islands are often fenced
            // off from the main region by a ring of skipped needles.
            let mut target: Option<usize> = None;
            let mut visited: rustc_hash::FxHashSet<u32> = regions[r].iter().copied().collect();
            let mut frontier: Vec<u32> = regions[r].clone();
            while let Some(t) = frontier.pop() {
                let tri = &data.tris[t as usize];
                for corner in 0..3 {
                    let first = tri.verts[corner];
                    let second = tri.verts[(corner + 1) % 3];
                    if first == second {
                        continue;
                    }
                    if let Some(incident) = data.edges.get(&edge_key(first, second)) {
                        for &other in incident {
                            if visited.contains(&other) {
                                continue;
                            }
                            let neighbor = region_of[other as usize];
                            if neighbor == usize::MAX {
                                // Skipped triangle: pass through it.
                                visited.insert(other);
                                frontier.push(other);
                                continue;
                            }
                            if neighbor == r {
                                continue;
                            }
                            target = match target {
                                None => Some(neighbor),
                                Some(current) => Some(if areas[neighbor] > areas[current] {
                                    neighbor
                                } else {
                                    current
                                }),
                            };
                        }
                    }
                }
            }
            if let Some(target) = target {
                let moved = std::mem::take(&mut regions[r]);
                for &t in &moved {
                    region_of[t as usize] = target;
                }
                areas[target] += areas[r];
                areas[r] = 0.0;
                regions[target].extend(moved);
                changed = true;
            }
        }
    }
    regions.retain(|list| !list.is_empty());
    for list in regions.iter_mut() {
        list.sort_unstable();
    }
}

/// Connected components of `tri_ids` across shared (welded) edges,
/// restricted to the given set.
fn connected_components(data: &MeshData, tri_ids: &[u32]) -> Vec<Vec<u32>> {
    let member: rustc_hash::FxHashSet<u32> = tri_ids.iter().copied().collect();
    let mut assigned: rustc_hash::FxHashSet<u32> = rustc_hash::FxHashSet::default();
    let mut components = Vec::new();
    let mut stack = Vec::new();
    for &seed in tri_ids {
        if assigned.contains(&seed) {
            continue;
        }
        assigned.insert(seed);
        stack.push(seed);
        let mut component = Vec::new();
        while let Some(t) = stack.pop() {
            component.push(t);
            let tri = &data.tris[t as usize];
            for corner in 0..3 {
                let first = tri.verts[corner];
                let second = tri.verts[(corner + 1) % 3];
                if first == second {
                    continue;
                }
                if let Some(incident) = data.edges.get(&edge_key(first, second)) {
                    for &other in incident {
                        if other != t && member.contains(&other) && !assigned.contains(&other) {
                            assigned.insert(other);
                            stack.push(other);
                        }
                    }
                }
            }
        }
        component.sort_unstable();
        components.push(component);
    }
    components
}

/// Split a region the cascade could not classify: peel tangent cylinders,
/// cones and spheres out of it first (the most specific test — a group
/// must lie on ONE carrier at the mesh's precision), then seed-plane-
/// anchored coplanar groups (the app's planar extraction) out of what is
/// left, and re-fit the remaining connected components.  Planes come second
/// because a coarse strip of a cylinder is a coplanar group too, and one
/// wide enough to pass the planar area gate would otherwise be peeled as a
/// plane before the cylinder it belongs to was ever tried.  Returns the
/// partition with each piece's fit outcome.
fn refine_region(
    data: &MeshData,
    tri_ids: &[u32],
    options: &SegmentOptions,
) -> Vec<(Vec<u32>, RegionOutcome)> {
    let vert_ids = region_vertices(data, tri_ids);
    let (low, high) = region_bbox(data, &vert_ids);
    let scale = {
        let diag = high.sub(low).length();
        if diag > 0.0 {
            diag
        } else {
            data.diag.max(1e-12)
        }
    };
    let dist_gate = options.fit_tolerance * scale;
    let cos_gate = options.planar_extraction_angle_deg.to_radians().cos();
    let region_area: f64 = tri_ids.iter().map(|&t| data.tris[t as usize].area).sum();
    let min_group_area = region_area * (options.planar_min_area_percent / 100.0).clamp(0.0, 1.0);
    let min_group_tris = options.min_region_triangles.max(2);

    let (mut pieces, leftover) = peel_carriers(data, tri_ids, options);
    let member: rustc_hash::FxHashSet<u32> = leftover.iter().copied().collect();
    let mut order: Vec<u32> = leftover.clone();
    order.sort_by(|&a, &b| {
        data.tris[b as usize]
            .area
            .total_cmp(&data.tris[a as usize].area)
            .then(a.cmp(&b))
    });

    let mut group_of: HashMap<u32, usize> = HashMap::default();
    let mut planar_groups: Vec<Vec<u32>> = Vec::new();
    let mut stack = Vec::new();
    for &seed in &order {
        if group_of.contains_key(&seed) {
            continue;
        }
        let seed_tri = &data.tris[seed as usize];
        let seed_normal = seed_tri.normal;
        let seed_origin = seed_tri.centroid;
        let coplanar = |t: u32| -> bool {
            let tri = &data.tris[t as usize];
            if tri.normal.dot(seed_normal) < cos_gate {
                return false;
            }
            tri.verts
                .iter()
                .all(|&v| data.verts[v].sub(seed_origin).dot(seed_normal).abs() <= dist_gate)
        };
        if !coplanar(seed) {
            continue;
        }
        // Grow the seed plane over not-yet-grouped region triangles.
        let mut visited: rustc_hash::FxHashSet<u32> = rustc_hash::FxHashSet::default();
        visited.insert(seed);
        stack.push(seed);
        let mut group = Vec::new();
        while let Some(t) = stack.pop() {
            group.push(t);
            let tri = &data.tris[t as usize];
            for corner in 0..3 {
                let first = tri.verts[corner];
                let second = tri.verts[(corner + 1) % 3];
                if first == second {
                    continue;
                }
                if let Some(incident) = data.edges.get(&edge_key(first, second)) {
                    for &other in incident {
                        if other == t
                            || !member.contains(&other)
                            || group_of.contains_key(&other)
                            || visited.contains(&other)
                        {
                            continue;
                        }
                        if coplanar(other) {
                            visited.insert(other);
                            stack.push(other);
                        }
                    }
                }
            }
        }
        let group_area: f64 = group.iter().map(|&t| data.tris[t as usize].area).sum();
        if group.len() >= min_group_tris && group_area >= min_group_area {
            let id = planar_groups.len();
            for &t in &group {
                group_of.insert(t, id);
            }
            group.sort_unstable();
            planar_groups.push(group);
        }
    }

    let remainder: Vec<u32> = leftover
        .iter()
        .copied()
        .filter(|t| !group_of.contains_key(t))
        .collect();

    for group in planar_groups {
        let outcome = fit_region(data, &group, options);
        pieces.push((group, outcome));
    }
    for component in connected_components(data, &remainder) {
        let outcome = fit_region(data, &component, options);
        pieces.push((component, outcome));
    }
    pieces
}

/// Precision bar of the cylinder peel as a fraction of the compound
/// region's scale: far below the acceptance tolerance (so the first strip
/// past a tangent junction is refused) and far above the vertex noise of an
/// exact tessellation.
const CYLINDER_PEEL_PRECISION_FRACTION: f64 = 1e-5;
/// Floor of that bar from the coordinate magnitude: single-precision
/// sources quantize at a few ulps of their largest coordinate.
const CYLINDER_PEEL_COORDINATE_FRACTION: f64 = 1e-6;
/// Adjacent triangles whose normals agree within this angle are one planar
/// facet (a tessellated strip) and are peeled together.
const CYLINDER_PEEL_FACET_ANGLE_RAD: f64 = 1e-4;
/// Rings of facets gathered around a seed facet before the seed fit: three
/// rows at least, because two rows of cells lie on two coaxial circles,
/// which every revolve fits exactly.
const CYLINDER_PEEL_SEED_RINGS: usize = 3;

/// Carrier kinds the peel tries, in cascade order, with the smallest vertex
/// support that makes a claim at the precision bar evidence rather than an
/// interpolation: three times the carrier's degrees of freedom (a cylinder
/// has five, a cone six, a sphere four).  Each pass works on what the
/// previous ones left.
///
/// The cone pass runs before the cylinder pass: a cone strip one column
/// wide (its vertices on the two rim circles) reads as a cylinder about its
/// generatrix at 5.6e-5 against a 7.5e-5 bar, and such strips cut the cone
/// into patches its own pass could no longer seed; claimed whole first, the
/// cone leaves no strip to misread. A cylinder offered to the cone pass fits
/// a cone of zero half-angle that the cascade reads as a cylinder, which the
/// kind check declines, so the cylinder pass still claims it.
const PEEL_KINDS: [(&str, usize); 4] =
    [("cone", 18), ("cylinder", 15), ("sphere", 12), ("torus", 21)];

/// Peel single-carrier groups off a tangent-smooth compound the cascade
/// could not classify: a rounded outline (arcs of different radii joined on
/// rulings), a fillet running out into a boss, a dome sitting on a chamfer
/// ring.
///
/// The acceptance tolerance is far too loose to separate tangent surfaces:
/// at the junction of two arcs the first strip on the far side deviates by
/// a fraction of the acceptance bar and the normal gate admits several
/// more.  Growth therefore runs at a precision bar and is judged by the
/// re-fit residual of the grown group: a wave of neighboring facets is kept
/// when the joint fit still sits at precision, otherwise each facet is
/// tried alone.  Facets — coplanar triangle groups, the strips of a
/// tessellated cylinder — move as a whole so a region boundary never runs
/// down a strip's diagonal.  Each finished group is then accepted through
/// the ordinary cascade at the user tolerance.  Cylinders are peeled
/// first, then cones, then spheres.  Returns the pieces and the triangles
/// no carrier claimed.
fn peel_carriers(
    data: &MeshData,
    tri_ids: &[u32],
    options: &SegmentOptions,
) -> (Vec<(Vec<u32>, RegionOutcome)>, Vec<u32>) {
    let debug = std::env::var("BREP_DEBUG_SEG").is_ok();
    let started = debug.then(web_time::Instant::now);
    let local: HashMap<u32, usize> = tri_ids
        .iter()
        .enumerate()
        .map(|(index, &t)| (t, index))
        .collect();
    let vert_ids = region_vertices(data, tri_ids);
    let (low, high) = region_bbox(data, &vert_ids);
    let scale = {
        let diag = high.sub(low).length();
        if diag > 0.0 {
            diag
        } else {
            data.diag.max(1e-12)
        }
    };
    let accept_tol = options.fit_tolerance * scale;
    let coordinate = vert_ids
        .iter()
        .map(|&v| {
            let p = data.verts[v];
            p.x.abs().max(p.y.abs()).max(p.z.abs())
        })
        .fold(0.0_f64, f64::max);
    let bar = (scale * CYLINDER_PEEL_PRECISION_FRACTION)
        .max(coordinate * CYLINDER_PEEL_COORDINATE_FRACTION);
    if bar >= accept_tol {
        return (Vec::new(), tri_ids.to_vec());
    }
    let cos_normal_gate = options.normal_tolerance_deg.to_radians().cos();
    let cos_facet = CYLINDER_PEEL_FACET_ANGLE_RAD.cos();

    // Facets: union of coplanar edge-adjacent member triangles.
    let mut parent: Vec<usize> = (0..tri_ids.len()).collect();
    fn find(parent: &mut [usize], x: usize) -> usize {
        crate::union_find::find_root(parent, x)
    }
    let mut adjacency: Vec<Vec<usize>> = vec![Vec::new(); tri_ids.len()];
    for (index, &t) in tri_ids.iter().enumerate() {
        let tri = &data.tris[t as usize];
        for corner in 0..3 {
            let first = tri.verts[corner];
            let second = tri.verts[(corner + 1) % 3];
            if first == second {
                continue;
            }
            let Some(incident) = data.edges.get(&edge_key(first, second)) else {
                continue;
            };
            for &other in incident {
                let Some(&other_index) = local.get(&other) else {
                    continue;
                };
                if other_index == index {
                    continue;
                }
                adjacency[index].push(other_index);
                if tri.normal.dot(data.tris[other as usize].normal) >= cos_facet {
                    let a = find(&mut parent, index);
                    let b = find(&mut parent, other_index);
                    if a != b {
                        parent[a] = b;
                    }
                }
            }
        }
    }
    let mut facet_of = vec![usize::MAX; tri_ids.len()];
    let mut facets: Vec<Vec<usize>> = Vec::new();
    for index in 0..tri_ids.len() {
        let root = find(&mut parent, index);
        if facet_of[root] == usize::MAX {
            facet_of[root] = facets.len();
            facets.push(Vec::new());
        }
        facet_of[index] = facet_of[root];
        facets[facet_of[index]].push(index);
    }
    let mut facet_neighbors: Vec<Vec<usize>> = vec![Vec::new(); facets.len()];
    for (index, others) in adjacency.iter().enumerate() {
        for &other in others {
            let (a, b) = (facet_of[index], facet_of[other]);
            if a != b && !facet_neighbors[a].contains(&b) {
                facet_neighbors[a].push(b);
            }
        }
    }
    let facet_area: Vec<f64> = facets
        .iter()
        .map(|facet| {
            facet
                .iter()
                .map(|&index| data.tris[tri_ids[index] as usize].area)
                .sum()
        })
        .collect();

    let facet_tris = |facet_ids: &[usize]| -> Vec<u32> {
        facet_ids
            .iter()
            .flat_map(|&facet| facets[facet].iter().map(|&index| tri_ids[index]))
            .collect()
    };
    let fit_kind = |kind: &str, facet_ids: &[usize]| -> Option<CandidateFit> {
        let tris = facet_tris(facet_ids);
        let verts = region_vertices(data, &tris);
        match kind {
            "cylinder" => fit_cylinder(data, &tris, &verts),
            "cone" => fit_cone(data, &tris, &verts, accept_tol),
            "sphere" => fit_sphere(data, &tris, &verts),
            "torus" => fit_torus_refined(data, &tris, &verts, 10.0 * accept_tol),
            _ => None,
        }
    };
    let fit_facets = |kind: &str, facet_ids: &[usize]| -> Option<CandidateFit> {
        fit_kind(kind, facet_ids).filter(|fit| fit.max_dev.is_finite() && fit.max_dev <= bar)
    };
    // A growing torus refits from its own current carrier: the cold fit
    // (normal-line axis, then a vertex refinement) per wave is what made a
    // dense fillet band cost a minute.
    let grow_fit = |kind: &str, facet_ids: &[usize], carrier: &RegionCarrier| -> Option<CandidateFit> {
        if kind != "torus" {
            return fit_facets(kind, facet_ids);
        }
        let tris = facet_tris(facet_ids);
        let verts = region_vertices(data, &tris);
        refine_torus_carrier(data, &tris, &verts, carrier, TORUS_REFINE_ITERATIONS)
            .filter(|fit| fit.max_dev.is_finite() && fit.max_dev <= bar)
    };
    // Every vertex of the facet on the carrier at the precision bar.
    let held_by = |carrier: &RegionCarrier, facet: usize| -> bool {
        facets[facet].iter().all(|&index| {
            data.tris[tri_ids[index] as usize]
                .verts
                .iter()
                .all(|&v| carrier_distance(carrier, data.verts[v]) <= bar)
        })
    };
    // Loose pre-filter against the current carrier: the refit decides.
    let plausible = |carrier: &RegionCarrier, facet: usize| -> bool {
        let sense = carrier_sense(carrier);
        facets[facet].iter().all(|&index| {
            let tri = &data.tris[tri_ids[index] as usize];
            let Some(normal) = carrier_normal(carrier, tri.centroid) else {
                return false;
            };
            tri.normal.dot(normal) * sense >= cos_normal_gate
                && tri
                    .verts
                    .iter()
                    .all(|&v| carrier_distance(carrier, data.verts[v]) <= accept_tol)
        })
    };

    // Dihedral between two neighbouring facets (their first triangles'
    // normals: a facet is coplanar at 1e-4 rad).
    let facet_dihedral = |a: usize, b: usize| -> f64 {
        let na = data.tris[tri_ids[facets[a][0]] as usize].normal;
        let nb = data.tris[tri_ids[facets[b][0]] as usize].normal;
        na.dot(nb).clamp(-1.0, 1.0).acos()
    };
    // Three times the median dihedral of the seed's own in-region edges, or
    // no gate at all for a seed with fewer than two neighbours.
    let seed_dihedral_gate = |seed: usize| -> f64 {
        let mut dihedrals: Vec<f64> = facet_neighbors[seed].iter().map(|&o| facet_dihedral(seed, o)).collect();
        if dihedrals.len() < 2 {
            return f64::INFINITY;
        }
        dihedrals.sort_by(f64::total_cmp);
        3.0 * dihedrals[dihedrals.len() / 2]
    };

    let mut order: Vec<usize> = (0..facets.len()).collect();
    order.sort_by(|&a, &b| facet_area[b].total_cmp(&facet_area[a]).then(a.cmp(&b)));
    if let Some(started) = started {
        eprintln!(
            "[seg] peel timing: {} facets of {} tris built in {:.1} ms",
            facets.len(),
            tri_ids.len(),
            started.elapsed().as_secs_f64() * 1e3
        );
    }
    let mut assigned = vec![false; facets.len()];
    let mut pieces: Vec<(Vec<u32>, RegionOutcome)> = Vec::new();
    // A torus seed is tried once across all rounds: the rounds exist for a
    // one-strip wall whose seed neighbourhood clears once its dome is
    // claimed, and a torus band that failed once does not become one.
    let mut torus_tried = vec![false; facets.len()];
    // Rounds until nothing new is claimed: a wall one strip tall has its
    // seed neighborhood polluted by the dome or fillet beyond its rim until
    // that neighbor has been claimed by its own pass.
    loop {
    let claimed = pieces.len();
    for (kind, min_vertices) in PEEL_KINDS {
    let mut tried = vec![false; facets.len()];
    // Seed-stage accounting for the trace: how many seeds the pass tried,
    // how many seed fits it got at the bar, the best seed residual it saw
    // refused, and how many grown groups fell under the support floor.
    let (mut seeds_tried, mut seed_fits, mut small_groups) = (0usize, 0usize, 0usize);
    let mut best_refused_seed = f64::INFINITY;
    for &seed in &order {
        if assigned[seed] || tried[seed] || (kind == "torus" && torus_tried[seed]) {
            continue;
        }
        tried[seed] = true;
        if kind == "torus" {
            torus_tried[seed] = true;
        }
        let mut group = vec![seed];
        let mut in_group = vec![false; facets.len()];
        in_group[seed] = true;
        let mut frontier = vec![seed];
        // A ring neighbour across a crease is left out: on an anisotropic
        // tessellation whose columns span a wall's full height, every seed
        // neighbourhood of the bore touches the countersink cone across a
        // 26.6-degree crease and no whole-neighbourhood fit can pass the bar.
        // The crease is an outlier among the seed's own dihedrals (3.6 degrees
        // between its columns), so a neighbour is admitted only when its
        // dihedral across the shared edge is at most three times the median
        // dihedral of the seed facet's own in-region edges.
        let dihedral_gate = seed_dihedral_gate(seed);
        for _ in 0..CYLINDER_PEEL_SEED_RINGS {
            let mut next = Vec::new();
            for &facet in &frontier {
                for &other in &facet_neighbors[facet] {
                    if !assigned[other] && !in_group[other] && facet_dihedral(facet, other) <= dihedral_gate {
                        in_group[other] = true;
                        group.push(other);
                        next.push(other);
                    }
                }
            }
            frontier = next;
        }
        seeds_tried += 1;
        let Some(seed_fit) = fit_facets(kind, &group) else {
            if debug {
                if let Some(fit) = fit_kind(kind, &group) {
                    best_refused_seed = best_refused_seed.min(fit.max_dev);
                }
            }
            continue;
        };
        seed_fits += 1;
        let mut carrier = seed_fit.carrier;
        let mut blocked = vec![false; facets.len()];
        let mut blocked_list: Vec<usize> = Vec::new();
        // Growth, then a sweep of the facets blocked while the carrier was
        // still settling on a small support: those on its final estimate at
        // the bar are admitted in one refit and growth resumes from them.
        // Without the sweep a densely gridded band leaves hundreds of two-
        // and four-triangle slivers behind, each re-fitted on its own later.
        loop {
        loop {
            let mut wave = Vec::new();
            for &facet in &group {
                for &other in &facet_neighbors[facet] {
                    if !assigned[other]
                        && !in_group[other]
                        && !blocked[other]
                        && !wave.contains(&other)
                        && plausible(&carrier, other)
                    {
                        wave.push(other);
                    }
                }
            }
            if wave.is_empty() {
                break;
            }
            let mut trial = group.clone();
            trial.extend(wave.iter().copied());
            if let Some(fit) = grow_fit(kind, &trial, &carrier) {
                for &facet in &wave {
                    in_group[facet] = true;
                }
                group = trial;
                carrier = fit.carrier;
                continue;
            }
            // The wave crossed a junction: admit its facets one at a time.
            // A torus admits the facets its current carrier already holds at
            // the bar, then refits once: a refit per junction facet is what
            // a dense freeform compound cannot afford.
            if kind == "torus" {
                let (inside, outside): (Vec<usize>, Vec<usize>) =
                    wave.into_iter().partition(|&facet| held_by(&carrier, facet));
                for facet in outside {
                    blocked[facet] = true;
                    blocked_list.push(facet);
                }
                if inside.is_empty() {
                    break;
                }
                let mut trial = group.clone();
                trial.extend(inside.iter().copied());
                let Some(fit) = grow_fit(kind, &trial, &carrier) else {
                    for facet in inside {
                        blocked[facet] = true;
                        blocked_list.push(facet);
                    }
                    break;
                };
                for &facet in &inside {
                    in_group[facet] = true;
                }
                group = trial;
                carrier = fit.carrier;
                continue;
            }
            let mut accepted_any = false;
            for facet in wave {
                let mut trial = group.clone();
                trial.push(facet);
                if let Some(fit) = grow_fit(kind, &trial, &carrier) {
                    in_group[facet] = true;
                    group = trial;
                    carrier = fit.carrier;
                    accepted_any = true;
                } else {
                    blocked[facet] = true;
                    blocked_list.push(facet);
                }
            }
            if !accepted_any {
                break;
            }
        }
        blocked_list.retain(|&facet| blocked[facet] && !in_group[facet]);
        let held: Vec<usize> = blocked_list
            .iter()
            .copied()
            .filter(|&facet| held_by(&carrier, facet))
            .collect();
        if held.is_empty() {
            break;
        }
        let mut trial = group.clone();
        trial.extend(held.iter().copied());
        let Some(fit) = grow_fit(kind, &trial, &carrier) else {
            break;
        };
        for &facet in &held {
            in_group[facet] = true;
            blocked[facet] = false;
        }
        group = trial;
        carrier = fit.carrier;
        }
        let mut tris = facet_tris(&group);
        if tris.len() < options.min_region_triangles.max(4)
            || region_vertices(data, &tris).len() < min_vertices
        {
            small_groups += 1;
            continue;
        }
        tris.sort_unstable();
        let outcome = fit_peeled(data, &tris, options);
        if debug {
            let size = match outcome.fit.carrier {
                RegionCarrier::Cylinder { radius, .. } | RegionCarrier::Sphere { radius, .. } => {
                    format!(" r={radius:.4}")
                }
                RegionCarrier::Cone { half_angle_rad, apex, axis_dir, .. } => {
                    format!(
                        " ha={:.2}deg apex=({:.3},{:.3},{:.3}) axis=({:+.4},{:+.4},{:+.4})",
                        half_angle_rad.to_degrees(),
                        apex.x, apex.y, apex.z,
                        axis_dir.x, axis_dir.y, axis_dir.z
                    )
                }
                RegionCarrier::Torus { center, axis_dir, major_radius, minor_radius, .. } => {
                    format!(
                        " R={major_radius:.4} r={minor_radius:.4} centre=({:.3},{:.3},{:.3}) axis=({:+.4},{:+.4},{:+.4})",
                        center.x, center.y, center.z, axis_dir.x, axis_dir.y, axis_dir.z
                    )
                }
                _ => String::new(),
            };
            let (low, high) = region_bbox(data, &region_vertices(data, &tris));
            eprintln!(
                "[seg] peel {kind}: seed facet {seed} grew {} facets / {} tris at {bar:.3e}; cascade {}{size} accepted={} max_dev={:.3e} max_ang={:.2} bbox [{:.2},{:.2},{:.2}]..[{:.2},{:.2},{:.2}]",
                group.len(),
                tris.len(),
                outcome.fit.carrier.kind(),
                outcome.accepted,
                outcome.fit.max_dev,
                outcome.fit.max_normal_angle_deg,
                low.x, low.y, low.z, high.x, high.y, high.z
            );
        }
        if !outcome.accepted || outcome.fit.carrier.kind() != kind {
            continue;
        }
        // A torus is claimed only as a FULL band around its axis — the
        // shape a mesh rebuild can bound by closed rings. A partial torus
        // (a fillet running along an arc of an outline) stays with the
        // planar strips it has always been read as.
        if kind == "torus" && !covers_full_azimuth(data, &tris, &outcome.fit.carrier) {
            continue;
        }
        for &facet in &group {
            assigned[facet] = true;
        }
        pieces.push((tris, outcome));
    }
    if debug {
        eprintln!(
            "[seg] peel {kind} seeds: {seeds_tried} tried, {seed_fits} seed fits at {bar:.3e}, best refused seed max_dev={best_refused_seed:.3e}, {small_groups} grown groups under the support floor ({min_vertices} vertices)"
        );
    }
    }
    if pieces.len() == claimed {
        break;
    }
    }
    if let Some(started) = started {
        eprintln!(
            "[seg] peel timing: seeds done at {:.1} ms, {} pieces",
            started.elapsed().as_secs_f64() * 1e3,
            pieces.len()
        );
    }
    if pieces.is_empty() {
        return (pieces, tri_ids.to_vec());
    }
    absorb_held_pieces(data, options, bar, &mut pieces, &facets, &facet_of, &local, &facet_neighbors, debug);
    if let Some(started) = started {
        eprintln!(
            "[seg] peel timing: absorption done at {:.1} ms, {} pieces",
            started.elapsed().as_secs_f64() * 1e3,
            pieces.len()
        );
    }
    // A leftover strip whose every peeled neighbor is the same carrier is an
    // interior gap — a tessellator T-vertex on a rim chord — not a
    // junction: it rejoins that carrier when the union still passes the
    // cascade at the user tolerance.  A strip straddling the tangent point
    // of two different carriers stays out and becomes its own small facet.
    let mut piece_of_facet = vec![usize::MAX; facets.len()];
    for (piece, (tris, _)) in pieces.iter().enumerate() {
        for &t in tris {
            piece_of_facet[facet_of[local[&t]]] = piece;
        }
    }
    let leftover_tris: Vec<u32> = (0..tri_ids.len())
        .filter(|&index| !assigned[facet_of[index]])
        .map(|index| tri_ids[index])
        .collect();
    let compat_tol = options.fit_tolerance * data.diag.max(1e-12);
    let mut remainder = Vec::new();
    for component in connected_components(data, &leftover_tris) {
        let mut adjacent_pieces: Vec<usize> = Vec::new();
        for &t in &component {
            for &other in &facet_neighbors[facet_of[local[&t]]] {
                let piece = piece_of_facet[other];
                if piece != usize::MAX && !adjacent_pieces.contains(&piece) {
                    adjacent_pieces.push(piece);
                }
            }
        }
        let Some(&first) = adjacent_pieces.first() else {
            remainder.extend(component);
            continue;
        };
        let same_carrier = adjacent_pieces.iter().all(|&piece| {
            carriers_compatible(
                &pieces[first].1.fit.carrier,
                &pieces[piece].1.fit.carrier,
                compat_tol,
                true,
            )
        });
        if !same_carrier {
            remainder.extend(straddle_rejoin(data, options, bar, &mut pieces, &adjacent_pieces, component));
            continue;
        }
        let mut union: Vec<u32> = pieces[first].0.iter().chain(component.iter()).copied().collect();
        union.sort_unstable();
        let outcome = fit_peeled(data, &union, options);
        let rejoined = outcome.accepted
            && outcome.fit.carrier.kind() == pieces[first].1.fit.carrier.kind();
        if debug {
            eprintln!(
                "[seg] peel: leftover of {} tris between {} peeled piece(s): union {} accepted={} max_dev={:.3e}",
                component.len(),
                adjacent_pieces.len(),
                outcome.fit.carrier.kind(),
                outcome.accepted,
                outcome.fit.max_dev
            );
        }
        if rejoined {
            pieces[first] = (union, outcome);
        } else {
            remainder.extend(straddle_rejoin(data, options, bar, &mut pieces, &adjacent_pieces, component));
        }
    }
    remainder.sort_unstable();
    if let Some(started) = started {
        eprintln!(
            "[seg] peel timing: leftovers done at {:.1} ms, {} remainder tris",
            started.elapsed().as_secs_f64() * 1e3,
            remainder.len()
        );
    }
    (pieces, remainder)
}

/// A piece every vertex of which lies on a neighbouring, larger piece's
/// carrier at the precision bar is a sub-patch of that carrier, not evidence
/// of a kind of its own: the cone pass claimed 144 triangles off the plane
/// rim of a densely gridded fillet torus at 3.9e-4 against a 4.1e-4 bar
/// before the torus pass reached the band, and the rebuild then demoted the
/// torus for the cone edge across it. Such a piece rejoins the neighbour
/// whose carrier holds it closest when the union still passes the cascade
/// as that neighbour's kind; a pair that fails stays apart. Repeats until
/// nothing rejoins.
#[allow(clippy::too_many_arguments)]
fn absorb_held_pieces(
    data: &MeshData,
    options: &SegmentOptions,
    bar: f64,
    pieces: &mut Vec<(Vec<u32>, RegionOutcome)>,
    facets: &[Vec<usize>],
    facet_of: &[usize],
    local: &HashMap<u32, usize>,
    facet_neighbors: &[Vec<usize>],
    debug: bool,
) {
    let mut refused: Vec<(Vec<u32>, Vec<u32>)> = Vec::new();
    loop {
        let mut piece_of_facet = vec![usize::MAX; facets.len()];
        for (piece, (tris, _)) in pieces.iter().enumerate() {
            for &t in tris {
                piece_of_facet[facet_of[local[&t]]] = piece;
            }
        }
        let area: Vec<f64> = pieces
            .iter()
            .map(|(tris, _)| tris.iter().map(|&t| data.tris[t as usize].area).sum())
            .collect();
        let mut by_area: Vec<usize> = (0..pieces.len()).collect();
        by_area.sort_by(|&a, &b| area[a].total_cmp(&area[b]).then(a.cmp(&b)));
        let mut merge = None;
        for &small in &by_area {
            let verts = region_vertices(data, &pieces[small].0);
            let mut neighbours: Vec<usize> = Vec::new();
            for &t in &pieces[small].0 {
                for &other in &facet_neighbors[facet_of[local[&t]]] {
                    let piece = piece_of_facet[other];
                    if piece != usize::MAX && piece != small && !neighbours.contains(&piece) {
                        neighbours.push(piece);
                    }
                }
            }
            let best = neighbours
                .iter()
                .copied()
                .filter(|&large| area[large] > area[small])
                .filter(|&large| {
                    !refused
                        .iter()
                        .any(|(a, b)| *a == pieces[small].0 && *b == pieces[large].0)
                })
                .filter_map(|large| {
                    let carrier = &pieces[large].1.fit.carrier;
                    let worst = verts
                        .iter()
                        .map(|&v| carrier_distance(carrier, data.verts[v]))
                        .fold(0.0_f64, f64::max);
                    (worst <= bar).then_some((large, worst))
                })
                .min_by(|a, b| a.1.total_cmp(&b.1).then(a.0.cmp(&b.0)));
            if let Some((large, worst)) = best {
                merge = Some((small, large, worst));
                break;
            }
        }
        let Some((small, large, worst)) = merge else {
            break;
        };
        let mut union: Vec<u32> = pieces[large].0.iter().chain(pieces[small].0.iter()).copied().collect();
        union.sort_unstable();
        let outcome = fit_peeled(data, &union, options);
        let rejoined = outcome.accepted
            && outcome.fit.carrier.kind() == pieces[large].1.fit.carrier.kind();
        if debug {
            eprintln!(
                "[seg] peel absorb: {} piece of {} tris lies on the {} piece of {} tris at {worst:.3e} (bar {bar:.3e}); union {} accepted={} max_dev={:.3e}",
                pieces[small].1.fit.carrier.kind(),
                pieces[small].0.len(),
                pieces[large].1.fit.carrier.kind(),
                pieces[large].0.len(),
                outcome.fit.carrier.kind(),
                outcome.accepted,
                outcome.fit.max_dev
            );
        }
        if rejoined {
            pieces[large] = (union, outcome);
            pieces.remove(small);
        } else {
            refused.push((pieces[small].0.clone(), pieces[large].0.clone()));
        }
    }
}

/// The cascade's verdict on a peeled piece. The cascade keeps its plain
/// torus fit; a torus the peel grew and judged at the precision bar carries
/// the vertex-refined carrier instead, so a mesh rebuild gets its true
/// axis and radii.
fn fit_peeled(data: &MeshData, tris: &[u32], options: &SegmentOptions) -> RegionOutcome {
    let mut outcome = fit_region(data, tris, options);
    if outcome.accepted && outcome.fit.carrier.kind() == "torus" {
        let verts = region_vertices(data, tris);
        if let Some(refined) =
            refine_torus_carrier(data, tris, &verts, &outcome.fit.carrier, TORUS_REFINE_ITERATIONS)
        {
            if refined.max_dev < outcome.fit.max_dev {
                outcome.fit = refined;
            }
        }
    }
    outcome
}

/// Whether a torus region's vertices surround its axis with no azimuthal gap
/// wider than a twelfth of a turn.
fn covers_full_azimuth(data: &MeshData, tri_ids: &[u32], carrier: &RegionCarrier) -> bool {
    let RegionCarrier::Torus { center, axis_dir, .. } = carrier else {
        return false;
    };
    let Ok(axis) = axis_dir.normalized() else {
        return false;
    };
    let Ok(x_axis) = axis.perpendicular() else {
        return false;
    };
    let y_axis = axis.cross(x_axis);
    let mut angles = region_vertices(data, tri_ids)
        .into_iter()
        .map(|v| {
            let d = data.verts[v].sub(*center);
            d.dot(y_axis).atan2(d.dot(x_axis))
        })
        .collect::<Vec<_>>();
    if angles.len() < 3 {
        return false;
    }
    angles.sort_by(f64::total_cmp);
    let wrap = angles[0] + std::f64::consts::TAU - angles[angles.len() - 1];
    let widest = angles
        .windows(2)
        .map(|pair| pair[1] - pair[0])
        .fold(wrap, f64::max);
    widest <= std::f64::consts::TAU / 12.0
}

/// A leftover strip at the tangent junction of DIFFERENT carriers (the
/// first row of a fillet torus against its cylinder) is not one carrier's
/// gap, but each of its triangles still lies on exactly one side. A triangle
/// joins the adjacent piece whose carrier holds all three of its vertices
/// within the peel's precision bar (the closest when several do), and a
/// piece that took any is re-fitted and must still pass the cascade as the
/// same kind, or it keeps its old triangles and they stay out. A triangle
/// no adjacent carrier holds at the bar is returned.
fn straddle_rejoin(
    data: &MeshData,
    options: &SegmentOptions,
    bar: f64,
    pieces: &mut [(Vec<u32>, RegionOutcome)],
    adjacent_pieces: &[usize],
    component: Vec<u32>,
) -> Vec<u32> {
    let mut taken: Vec<Vec<u32>> = vec![Vec::new(); adjacent_pieces.len()];
    let mut left = Vec::new();
    for t in component {
        let tri = &data.tris[t as usize];
        let best = adjacent_pieces
            .iter()
            .enumerate()
            .filter_map(|(slot, &piece)| {
                let carrier = &pieces[piece].1.fit.carrier;
                let worst = tri
                    .verts
                    .iter()
                    .map(|&v| carrier_distance(carrier, data.verts[v]))
                    .fold(0.0_f64, f64::max);
                (worst <= bar).then_some((slot, worst))
            })
            .min_by(|a, b| a.1.total_cmp(&b.1));
        match best {
            Some((slot, _)) => taken[slot].push(t),
            None => left.push(t),
        }
    }
    for (slot, extra) in taken.into_iter().enumerate() {
        if extra.is_empty() {
            continue;
        }
        let piece = adjacent_pieces[slot];
        let mut union: Vec<u32> = pieces[piece].0.iter().chain(extra.iter()).copied().collect();
        union.sort_unstable();
        let outcome = fit_peeled(data, &union, options);
        if outcome.accepted && outcome.fit.carrier.kind() == pieces[piece].1.fit.carrier.kind() {
            pieces[piece] = (union, outcome);
        } else {
            left.extend(extra);
        }
    }
    left
}

// ---------------------------------------------------------------------------
// Entry point
// ---------------------------------------------------------------------------

/// Segment a triangle mesh into smooth regions and recognize each region's
/// analytic carrier.  `positions` are xyz triples; `indices` is a triangle
/// index buffer, or empty to treat `positions` as a raw soup of consecutive
/// triangles (the STL layout of `read_stl`).
pub fn segment_mesh_faces(
    positions: &[f64],
    indices: &[u32],
    options: &SegmentOptions,
) -> Result<MeshSegmentation, String> {
    if !(options.deflection_angle_deg > 0.0) || !options.deflection_angle_deg.is_finite() {
        return Err("segment_mesh_faces: deflection angle must be positive".into());
    }
    if !(options.fit_tolerance > 0.0) || !options.fit_tolerance.is_finite() {
        return Err("segment_mesh_faces: fit tolerance must be positive".into());
    }
    let data = build_mesh_data(positions, indices, options)?;
    Ok(segment_prepared(&data, options))
}

/// Segmentation core on an already-welded mesh: shared by the analysis entry
/// (`segment_mesh_faces`) and the BREP rebuild (`mesh_regions_to_brep`), so
/// both see identical triangle/vertex indexing.
pub(super) fn segment_prepared(data: &MeshData, options: &SegmentOptions) -> MeshSegmentation {
    segment_prepared_with(data, options, noisy_polyhedron_enabled())
}

/// `BREP_MESH_NOISY_POLYHEDRON` (batch 102; promoted ON 2026-11-08,
/// promotion 15, `BREP_MESH_NOISY_POLYHEDRON=0` restores the old path): a
/// mesh whose every grown region reads as a plane within
/// [`NOISY_POLYHEDRON_PLANE_FACTOR`] times the plane bar is taken as a noisy
/// polyhedron, every region a plane. Switch grammar: `0|off|false` off,
/// `1|on|true` on, anything else the default. Read once per process.
pub(super) fn noisy_polyhedron_enabled() -> bool {
    static ENABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *ENABLED.get_or_init(|| {
        match std::env::var("BREP_MESH_NOISY_POLYHEDRON").as_deref().map(str::to_ascii_lowercase).as_deref() {
            Ok("1" | "on" | "true") => true,
            Ok("0" | "off" | "false") => false,
            _ => true,
        }
    })
}

/// How far past the cascade's plane bar (`fit_tolerance` times the region's
/// diagonal) a region of a noisy polyhedron may sit. The census's 14 jittered
/// boxes the plane bar refused read at most 6.6 times the bar, and no other
/// census mesh reads as all planes within 20 (`sim199b.py`).
const NOISY_POLYHEDRON_PLANE_FACTOR: f64 = 10.0;

/// The most vertices a region past the plane bar may have and still be read
/// as jitter: the parameter count of the cascade's richest carrier (the
/// torus: centre, axis, two radii). With no more vertices than that a curved
/// carrier can pass through all of them, so the cascade's curved fit is no
/// evidence of curvature (the jittered box's two-triangle sides have four
/// vertices, and the sphere through them is exact). A region with more is
/// judged by its fit: the 0.25 mm dome of the app's domed-block fixture, 289
/// vertices, sits 5.7 times past its plane bar and is a dome, not noise
/// (promotion 15 gate, 2026-11-08). No census region past the bar has more
/// than four vertices (`sim203.py`).
const NOISY_POLYHEDRON_MAX_PAST_BAR_VERTICES: usize = 7;

/// Every grown region as a plane, when every one of them fits a plane within
/// [`NOISY_POLYHEDRON_PLANE_FACTOR`] times the cascade's plane bar and the
/// normal tolerance, at least one of them is past the plane bar itself, and
/// every one past the bar has at most [`NOISY_POLYHEDRON_MAX_PAST_BAR_VERTICES`]
/// vertices. `None` otherwise, and the cascade decides as before.
///
/// A jittered box with two triangles per side gives each side four vertices
/// off one plane by more than the bar: the cascade then refuses the plane and
/// takes the sphere through those four points (exact by construction), or
/// leaves the side freeform. Judged one region at a time a wider plane bar
/// would also take the two-triangle islands that jitter cuts out of a
/// cylinder, so the bar widens only for a mesh that is planes everywhere.
fn noisy_polyhedron_regions(
    data: &MeshData,
    regions: &[Vec<u32>],
    options: &SegmentOptions,
) -> Option<Vec<(Vec<u32>, RegionOutcome)>> {
    let mut any_past_bar = false;
    let mut out = Vec::with_capacity(regions.len());
    for region in regions {
        let vert_ids = region_vertices(data, region);
        if region.len() < options.min_region_triangles || vert_ids.len() < 3 {
            return None;
        }
        let bbox = region_bbox(data, &vert_ids);
        let diag = bbox.1.sub(bbox.0).length();
        let scale = if diag > 0.0 { diag } else { data.diag.max(1e-12) };
        let tol_abs = options.fit_tolerance * scale;
        let fit = fit_plane(data, region, &vert_ids)?;
        if !(fit.max_dev.is_finite()
            && fit.max_dev <= NOISY_POLYHEDRON_PLANE_FACTOR * tol_abs
            && fit.max_normal_angle_deg <= options.normal_tolerance_deg)
        {
            return None;
        }
        if fit.max_dev > tol_abs {
            if vert_ids.len() > NOISY_POLYHEDRON_MAX_PAST_BAR_VERTICES {
                return None;
            }
            any_past_bar = true;
        }
        let area: f64 = region.iter().map(|&t| data.tris[t as usize].area).sum();
        out.push((
            region.clone(),
            RegionOutcome {
                fit,
                accepted: true,
                area,
                bbox,
                triangle_count: region.len(),
            },
        ));
    }
    any_past_bar.then_some(out)
}

pub(super) fn segment_prepared_with(
    data: &MeshData,
    options: &SegmentOptions,
    noisy_polyhedron: bool,
) -> MeshSegmentation {
    let mut raw_regions = grow_regions(data, options);
    absorb_tiny_regions(data, &mut raw_regions);

    let noisy = if noisy_polyhedron {
        noisy_polyhedron_regions(data, &raw_regions, options)
    } else {
        None
    };
    if std::env::var("BREP_DEBUG_SEG").is_ok() && noisy.is_some() {
        eprintln!("[seg] noisy polyhedron: {} regions taken as planes", raw_regions.len());
    }
    // A noisy polyhedron skips the cascade: its regions are all planes.
    let cascade = if noisy.is_some() { Vec::new() } else { raw_regions };
    let mut final_regions: Vec<(Vec<u32>, RegionOutcome)> = noisy.unwrap_or_default();
    for region in cascade {
        let outcome = fit_region(data, &region, options);
        if outcome.accepted {
            final_regions.push((region, outcome));
            continue;
        }
        // Tangent-smooth compound (or genuinely freeform): try to split it.
        let pieces = refine_region(data, &region, options);
        if pieces.len() <= 1 {
            // Refinement did not split anything; keep the region whole.
            final_regions.push((region, outcome));
        } else {
            final_regions.extend(pieces);
        }
    }

    // Reunite regions the growing/refinement pipeline split although they
    // lie on ONE carrier (a cap triangle isolated behind skipped slivers, a
    // blend peeled into two coaxial pieces).  Downstream consumers — the
    // BREP rebuild above all — rely on "one region per face".
    merge_compatible_regions(data, &mut final_regions, options);

    let mut triangle_region_ids = vec![UNASSIGNED_REGION; data.tris.len()];
    let mut regions = Vec::with_capacity(final_regions.len());
    for (id, (tri_ids, outcome)) in final_regions.into_iter().enumerate() {
        for &t in &tri_ids {
            triangle_region_ids[t as usize] = id as u32;
        }
        regions.push(MeshRegion {
            id: id as u32,
            triangle_count: outcome.triangle_count,
            area: outcome.area,
            bbox_min: outcome.bbox.0,
            bbox_max: outcome.bbox.1,
            carrier: outcome.fit.carrier,
            max_deviation: outcome.fit.max_dev,
            rms_deviation: outcome.fit.rms_dev,
            max_normal_angle_deg: outcome.fit.max_normal_angle_deg,
        });
    }

    // Attach degenerate/micro triangles to an adjacent region when one
    // exists: the neighbor whose carrier the sliver's vertices actually sit
    // on (a T-junction needle lies in one of its neighboring planes, not
    // on the fillet it happens to touch first).  Multi-pass so chains of
    // skipped slivers resolve through their assigned neighbors.
    let mut changed = true;
    while changed {
        changed = false;
        for t in 0..data.tris.len() {
            if triangle_region_ids[t] != UNASSIGNED_REGION {
                continue;
            }
            let tri = &data.tris[t];
            let mut adopted: Option<(f64, u32)> = None;
            for corner in 0..3 {
                let first = tri.verts[corner];
                let second = tri.verts[(corner + 1) % 3];
                if first == second {
                    continue;
                }
                if let Some(incident) = data.edges.get(&edge_key(first, second)) {
                    for &other in incident {
                        let region = triangle_region_ids[other as usize];
                        if other as usize == t || region == UNASSIGNED_REGION {
                            continue;
                        }
                        let carrier = &regions[region as usize].carrier;
                        let distance = tri
                            .verts
                            .iter()
                            .map(|&v| carrier_distance(carrier, data.verts[v]))
                            .fold(0.0_f64, f64::max);
                        let candidate = (distance, region);
                        adopted = Some(match adopted {
                            Some(current)
                                if current.0 < candidate.0
                                    || (current.0 == candidate.0 && current.1 <= candidate.1) =>
                            {
                                current
                            }
                            _ => candidate,
                        });
                    }
                }
            }
            if let Some((_, region)) = adopted {
                triangle_region_ids[t] = region;
                changed = true;
            }
        }
    }

    MeshSegmentation {
        triangle_region_ids,
        regions,
        triangle_count: data.tris.len(),
        welded_vertex_count: data.verts.len(),
    }
}

/// Outward carrier normal at a point (before the region's sense), or `None`
/// where the field is singular (on an axis, at a center) or for `Freeform`.
fn carrier_normal(carrier: &RegionCarrier, p: Vec3) -> Option<Vec3> {
    match carrier {
        RegionCarrier::Plane { normal, .. } => Some(*normal),
        RegionCarrier::Cylinder {
            axis_point,
            axis_dir,
            ..
        } => {
            let d = p.sub(*axis_point);
            d.sub(axis_dir.scale(d.dot(*axis_dir))).normalized().ok()
        }
        RegionCarrier::Cone {
            apex,
            axis_dir,
            half_angle_rad,
            ..
        } => {
            let d = p.sub(*apex);
            let radial = d.sub(axis_dir.scale(d.dot(*axis_dir))).normalized().ok()?;
            let (sin_a, cos_a) = half_angle_rad.sin_cos();
            Some(radial.scale(cos_a).sub(axis_dir.scale(sin_a)))
        }
        RegionCarrier::Sphere { center, .. } => p.sub(*center).normalized().ok(),
        RegionCarrier::Torus {
            center,
            axis_dir,
            major_radius,
            ..
        } => {
            let d = p.sub(*center);
            let s = d.dot(*axis_dir);
            let radial = d.sub(axis_dir.scale(s)).normalized().ok()?;
            let tube_center = center.add(radial.scale(*major_radius));
            p.sub(tube_center).normalized().ok()
        }
        RegionCarrier::Freeform => None,
    }
}

/// The region's orientation sense as a sign, `1.0` for planes and freeform.
fn carrier_sense(carrier: &RegionCarrier) -> f64 {
    match carrier {
        RegionCarrier::Cylinder { sense, .. }
        | RegionCarrier::Cone { sense, .. }
        | RegionCarrier::Sphere { sense, .. }
        | RegionCarrier::Torus { sense, .. } => f64::from(*sense),
        _ => 1.0,
    }
}

/// Distance of a point from a carrier; `Freeform` is infinitely far.
fn carrier_distance(carrier: &RegionCarrier, p: Vec3) -> f64 {
    match carrier {
        RegionCarrier::Plane { origin, normal } => p.sub(*origin).dot(*normal).abs(),
        RegionCarrier::Cylinder {
            axis_point,
            axis_dir,
            radius,
            ..
        } => {
            let d = p.sub(*axis_point);
            (d.sub(axis_dir.scale(d.dot(*axis_dir))).length() - radius).abs()
        }
        RegionCarrier::Cone {
            apex,
            axis_dir,
            half_angle_rad,
            ..
        } => {
            let d = p.sub(*apex);
            let s = d.dot(*axis_dir);
            let r = d.sub(axis_dir.scale(s)).length();
            ((r - s * half_angle_rad.tan()) * half_angle_rad.cos()).abs()
        }
        RegionCarrier::Sphere { center, radius, .. } => (p.sub(*center).length() - radius).abs(),
        RegionCarrier::Torus {
            center,
            axis_dir,
            major_radius,
            minor_radius,
            ..
        } => {
            let d = p.sub(*center);
            let s = d.dot(*axis_dir);
            let rho = d.sub(axis_dir.scale(s)).length();
            ((rho - major_radius).hypot(s) - minor_radius).abs()
        }
        RegionCarrier::Freeform => f64::INFINITY,
    }
}

/// Do two accepted carriers describe the same surface (within `tol` for
/// distances, tight angular bands for directions)?  Freeform never matches.
/// `adjacent` says the regions share an edge: only then may two cylinder
/// fits disagree on their axis by the noise over the axial extent, because
/// two disjoint faces of one infinite cylinder (the two ends of a mirrored
/// part, the two levels of a slot) must stay two regions.
fn carriers_compatible(a: &RegionCarrier, b: &RegionCarrier, tol: f64, adjacent: bool) -> bool {
    const ANGULAR: f64 = 1e-6;
    match (a, b) {
        (
            RegionCarrier::Plane {
                origin: o1,
                normal: n1,
            },
            RegionCarrier::Plane {
                origin: o2,
                normal: n2,
            },
        ) => {
            n1.cross(*n2).length() <= ANGULAR
                && n1.dot(*n2) > 0.0
                && o2.sub(*o1).dot(*n1).abs() <= tol
        }
        (
            RegionCarrier::Cylinder {
                axis_point: p1,
                axis_dir: a1,
                radius: r1,
                sense: s1,
            },
            RegionCarrier::Cylinder {
                axis_point: p2,
                axis_dir: a2,
                radius: r2,
                sense: s2,
            },
        ) => {
            // Independent fits of one cylinder from noisy vertices disagree
            // on the axis direction by the noise over the axial extent; the
            // band is the angle that moves the surface by `tol` at the rim.
            // The union re-fit is the real test.
            let angular = if adjacent {
                ANGULAR.max(tol / r1.max(*r2).max(1e-12))
            } else {
                ANGULAR
            };
            let offset = p2.sub(*p1);
            s1 == s2
                && a1.cross(*a2).length() <= angular
                && (r1 - r2).abs() <= tol
                && offset.sub(a1.scale(offset.dot(*a1))).length() <= tol
        }
        (
            RegionCarrier::Cone {
                apex: p1,
                axis_dir: a1,
                half_angle_rad: h1,
                sense: s1,
            },
            RegionCarrier::Cone {
                apex: p2,
                axis_dir: a2,
                half_angle_rad: h2,
                sense: s2,
            },
        ) => {
            s1 == s2
                && a1.cross(*a2).length() <= ANGULAR
                && a1.dot(*a2) > 0.0
                && (h1 - h2).abs() <= ANGULAR
                && p2.sub(*p1).length() <= tol
        }
        (
            RegionCarrier::Sphere {
                center: c1,
                radius: r1,
                sense: s1,
            },
            RegionCarrier::Sphere {
                center: c2,
                radius: r2,
                sense: s2,
            },
        ) => s1 == s2 && c2.sub(*c1).length() <= tol && (r1 - r2).abs() <= tol,
        (
            RegionCarrier::Torus {
                center: c1,
                axis_dir: a1,
                major_radius: mj1,
                minor_radius: mn1,
                sense: s1,
            },
            RegionCarrier::Torus {
                center: c2,
                axis_dir: a2,
                major_radius: mj2,
                minor_radius: mn2,
                sense: s2,
            },
        ) => {
            s1 == s2
                && a1.cross(*a2).length() <= ANGULAR
                && c2.sub(*c1).length() <= tol
                && (mj1 - mj2).abs() <= tol
                && (mn1 - mn2).abs() <= tol
        }
        _ => false,
    }
}

/// Merge edge-adjacent regions whose accepted carriers agree, repeating
/// until stable.  Adjacency counts paths THROUGH skipped (degenerate/micro)
/// triangles — exactly the fences that isolate cap islands in the first
/// place.  A merge is only applied when the union re-fits cleanly on the
/// same carrier kind, so this pass can only improve the segmentation.
fn merge_compatible_regions(
    data: &MeshData,
    regions: &mut Vec<(Vec<u32>, RegionOutcome)>,
    options: &SegmentOptions,
) {
    let tol = options.fit_tolerance * data.diag.max(1e-12);
    loop {
        let mut region_of = vec![usize::MAX; data.tris.len()];
        for (index, (tris, _)) in regions.iter().enumerate() {
            for &t in tris {
                region_of[t as usize] = index;
            }
        }
        // Directly edge-adjacent pairs.
        let mut direct: std::collections::BTreeSet<(usize, usize)> =
            std::collections::BTreeSet::new();
        for incident in data.edges.values() {
            if incident.len() != 2 {
                continue;
            }
            let (a, b) = (
                region_of[incident[0] as usize],
                region_of[incident[1] as usize],
            );
            if a != b && a != usize::MAX && b != usize::MAX {
                direct.insert((a.min(b), a.max(b)));
            }
        }
        let mut pairs = direct.clone();
        // Pairs bridged by connected runs of region-less (skipped) triangles.
        let mut seen = vec![false; data.tris.len()];
        for seed in 0..data.tris.len() {
            if seen[seed] || region_of[seed] != usize::MAX {
                continue;
            }
            let mut stack = vec![seed];
            let mut touched: Vec<usize> = Vec::new();
            seen[seed] = true;
            while let Some(t) = stack.pop() {
                let tri = &data.tris[t];
                for corner in 0..3 {
                    let first = tri.verts[corner];
                    let second = tri.verts[(corner + 1) % 3];
                    if first == second {
                        continue;
                    }
                    if let Some(incident) = data.edges.get(&edge_key(first, second)) {
                        for &other in incident {
                            let other = other as usize;
                            if other == t {
                                continue;
                            }
                            let region = region_of[other];
                            if region == usize::MAX {
                                if !seen[other] {
                                    seen[other] = true;
                                    stack.push(other);
                                }
                            } else if !touched.contains(&region) {
                                touched.push(region);
                            }
                        }
                    }
                }
            }
            touched.sort_unstable();
            for i in 0..touched.len() {
                for j in i + 1..touched.len() {
                    pairs.insert((touched[i], touched[j]));
                }
            }
        }

        let mut merged_any = false;
        'pairs: for (a, b) in pairs {
            let (first, second) = (&regions[a], &regions[b]);
            if !first.1.accepted || !second.1.accepted {
                continue;
            }
            if !carriers_compatible(
                &first.1.fit.carrier,
                &second.1.fit.carrier,
                tol,
                direct.contains(&(a, b)),
            ) {
                continue;
            }
            let mut union: Vec<u32> = first.0.iter().chain(second.0.iter()).copied().collect();
            union.sort_unstable();
            let outcome = fit_region(data, &union, options);
            if !outcome.accepted || outcome.fit.carrier.kind() != first.1.fit.carrier.kind() {
                continue;
            }
            regions[a] = (union, outcome);
            regions.remove(b);
            merged_any = true;
            break 'pairs;
        }
        if !merged_any {
            return;
        }
    }
}