BREP_kernel 0.4.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
use super::*;
use crate::{
    boolean_operation, fillet_edges, make_arc, make_box_brep, make_cone_brep,
    make_cylinder_brep, make_line, make_sphere_brep, revolve_profile_brep,
    solid_mass_properties, BooleanOperation, BooleanOptions,
};

/// Face whose sampled centroid is furthest along `axis`.
fn extreme_face_id(solid: &BrepSolid, axis: Vec3) -> u64 {
    let mut best = f64::NEG_INFINITY;
    let mut id = 0;
    for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
        if let Ok(point) = face.surface.evaluate(0.5, 0.5) {
            let value = point.dot(axis);
            if value > best {
                best = value;
                id = face.id;
            }
        }
    }
    id
}

fn one_use_edge_count(solid: &BrepSolid) -> usize {
    let mut counts = HashMap::<u64, usize>::default();
    for coedge in solid
        .shells
        .iter()
        .flat_map(|shell| &shell.faces)
        .flat_map(|face| &face.loops)
        .flat_map(|loop_record| &loop_record.coedges)
    {
        *counts.entry(coedge.edge_id).or_default() += 1;
    }
    counts.values().filter(|count| **count == 1).count()
}

/// One-use REAL edges: a degenerate pole placeholder is face-local by
/// design and stays one-use on any solid with a surface-of-revolution
/// pole (sphere caps), so watertightness is "no one-use 1-cells".
fn open_real_edge_count(solid: &BrepSolid) -> usize {
    let mut counts = HashMap::<u64, usize>::default();
    for coedge in solid
        .shells
        .iter()
        .flat_map(|shell| &shell.faces)
        .flat_map(|face| &face.loops)
        .flat_map(|loop_record| &loop_record.coedges)
    {
        *counts.entry(coedge.edge_id).or_default() += 1;
    }
    solid
        .edges
        .iter()
        .filter(|edge| !edge.degenerate && counts.get(&edge.id).copied().unwrap_or(0) == 1)
        .count()
}

/// Spherical-cap solid: the sphere `radius` about the origin cut by the
/// plane z = `cut_z` (0 < cut_z < radius). Faces: the spherical dome and
/// the flat disk — the purest "spherical face at the opening" fixture.
/// The planar face whose parametric centre sits highest along +Z (a
/// frustum's top when its axis is Z).
fn topmost_planar_face_id(solid: &BrepSolid) -> u64 {
    solid
        .shells
        .iter()
        .flat_map(|shell| &shell.faces)
        .filter(|face| face.surface.is_affine().unwrap_or(false))
        .max_by(|first, second| {
            let first_z = first.surface.evaluate(0.5, 0.5).unwrap().z;
            let second_z = second.surface.evaluate(0.5, 0.5).unwrap().z;
            first_z.total_cmp(&second_z)
        })
        .unwrap()
        .id
}

fn spherical_cap_solid(radius: f64, cut_z: f64) -> BrepSolid {
    let rim_radius = (radius * radius - cut_z * cut_z).sqrt();
    let start_angle = cut_z.atan2(rim_radius);
    let dome = make_arc(
        Vec3::default(),
        Vec3::new(1.0, 0.0, 0.0),
        Vec3::new(0.0, 0.0, 1.0),
        radius,
        start_angle,
        std::f64::consts::FRAC_PI_2,
    )
    .unwrap();
    let disk = make_line(
        Vec3::new(0.0, 0.0, cut_z),
        Vec3::new(rim_radius, 0.0, cut_z),
    )
    .unwrap();
    let axis_line = make_line(Vec3::new(0.0, 0.0, radius), Vec3::new(0.0, 0.0, cut_z)).unwrap();
    revolve_profile_brep(
        &[disk, dome, axis_line],
        Vec3::default(),
        Vec3::new(0.0, 0.0, 1.0),
        std::f64::consts::TAU,
    )
    .unwrap()
}

/// Cup: cylinder side r=`radius` for z in [0, `height`] over a
/// hemispherical bottom (sphere `radius` about the origin), flat top
/// disk at z=`height`.
fn hemisphere_cup(radius: f64, height: f64) -> BrepSolid {
    let top = make_line(Vec3::new(0.0, 0.0, height), Vec3::new(radius, 0.0, height)).unwrap();
    let side = make_line(Vec3::new(radius, 0.0, height), Vec3::new(radius, 0.0, 0.0)).unwrap();
    let dome = make_arc(
        Vec3::default(),
        Vec3::new(1.0, 0.0, 0.0),
        Vec3::new(0.0, 0.0, -1.0),
        radius,
        0.0,
        std::f64::consts::FRAC_PI_2,
    )
    .unwrap();
    let axis_line =
        make_line(Vec3::new(0.0, 0.0, -radius), Vec3::new(0.0, 0.0, height)).unwrap();
    revolve_profile_brep(
        &[top, side, dome, axis_line],
        Vec3::default(),
        Vec3::new(0.0, 0.0, 1.0),
        std::f64::consts::TAU,
    )
    .unwrap()
}

#[test]
fn cylinder_open_top_shell_is_watertight_with_exact_wall_volume() {
    // A cylinder shelled inward (retained curved side is perpendicular to
    // the opening plane) is the canonical rim-weld case: the offset side's
    // top rim is a closed circle coplanar with the opening cap. Before the
    // coplanar-rim weld it dangled one-use and the shell split into two
    // components; it must now be a single watertight shell.
    let axis = Vec3::new(0.0, 0.0, 1.0);
    let cylinder = make_cylinder_brep(Vec3::default(), axis, 2.0, 4.0).unwrap();
    let top = extreme_face_id(&cylinder, axis);
    let result = offset_shell(&cylinder, &[top], 0.5).unwrap();

    assert!(
        result.solid.validate().is_empty(),
        "{:?}",
        result.solid.validate()
    );
    assert_eq!(one_use_edge_count(&result.solid), 0, "no open rim edges");
    assert_eq!(result.solid.shells.len(), 1, "one connected shell");
    assert!(result.face_images.iter().all(|image| cylinder
        .shells
        .iter()
        .flat_map(|shell| &shell.faces)
        .any(|face| face.id == image.source_face_id)));

    // Wall thickness 0.5: outer r=2 h=4, inner cavity r=1.5 from z=0.5..4.
    let outer = std::f64::consts::PI * 2.0_f64.powi(2) * 4.0;
    let inner = std::f64::consts::PI * 1.5_f64.powi(2) * 3.5;
    let expected = outer - inner;
    let volume = solid_mass_properties(&result.solid).unwrap().volume;
    assert!((volume - expected).abs() < 1e-3, "{volume} vs {expected}");

    // The diagnostic wrapper must accept it as shippable (validation clean).
    let outcome = offset_shell_with_diagnostics(&cylinder, &[top], 0.5, None).unwrap();
    assert!(outcome.diagnostics.shippable());
    assert_eq!(outcome.diagnostics.counters["validate.issues"], 0);
}

#[test]
fn cone_open_top_shell_is_watertight_with_exact_wall_volume() {
    // A truncated cone's retained side is OBLIQUE to the opening, so the
    // offset rim leaves the opening plane: it is a smaller coaxial circle
    // sitting below the opening. weld_ruled_offset_rims rebuilds the
    // mis-built flat opening cap into the exact conical frustum band through
    // the two coaxial rims, so the shell closes watertight with no dangling
    // one-use rim (the deeper case the coplanar-rim weld cannot reach).
    let axis = Vec3::new(0.0, 0.0, 1.0);
    let cone = make_cone_brep(Vec3::default(), axis, 2.0, 1.0, 4.0).unwrap();
    let top = extreme_face_id(&cone, axis);
    let result = offset_shell(&cone, &[top], 0.4).unwrap();

    assert!(
        result.solid.validate().is_empty(),
        "{:?}",
        result.solid.validate()
    );
    assert_eq!(one_use_edge_count(&result.solid), 0, "no open rim edges");
    assert_eq!(result.solid.shells.len(), 1, "one connected shell");

    // Exact wall volume by frustum decomposition: the source frustum minus
    // the inward-offset cavity frustum minus the cork above the offset top
    // rim. The offset is a normal offset of 0.4; the cone's outward normal
    // in (r,z) is (4,1)/sqrt(17), so every generator point shifts inward by
    // (-1.6,-0.4)/sqrt(17).
    let root17 = 17.0_f64.sqrt();
    let (base_r, base_z) = (2.0 - 1.6 / root17, -0.4 / root17);
    let top_r = 1.0 - 1.6 / root17;
    let top_z = 4.0 - 0.4 / root17;
    let cap_r = base_r - (0.4 - base_z) / 4.0; // offset cone radius at z = 0.4
    let pi = std::f64::consts::PI;
    let frustum = |r0: f64, r1: f64, h: f64| pi * h / 3.0 * (r0 * r0 + r0 * r1 + r1 * r1);
    let source = frustum(2.0, 1.0, 4.0);
    let cavity = frustum(cap_r, top_r, top_z - 0.4);
    let cork = frustum(top_r, 1.0, 4.0 - top_z);
    let expected = source - cavity - cork;
    let volume = solid_mass_properties(&result.solid).unwrap().volume;
    assert!((volume - expected).abs() < 2e-3, "{volume} vs {expected}");

    // The diagnostic wrapper must accept it as shippable (validation clean).
    let outcome = offset_shell_with_diagnostics(&cone, &[top], 0.4, None).unwrap();
    assert!(outcome.diagnostics.shippable());
    assert_eq!(outcome.diagnostics.counters["validate.issues"], 0);
}

#[test]
fn open_top_box_offsets_to_exact_hollow_volume() {
    let source = make_box_brep(Vec3::default(), 4.0, 4.0, 4.0).unwrap();
    let top = source.shells[0]
        .faces
        .iter()
        .find(|face| {
            let point = face.surface.evaluate(0.5, 0.5).unwrap();
            (point.z - 4.0).abs() < 1e-9
        })
        .unwrap();
    let result = offset_shell(&source, &[top.id], 0.5).unwrap();
    assert!(result.solid.validate().is_empty());
    assert!(result.face_images.iter().all(|image| source
        .shells
        .iter()
        .flat_map(|shell| &shell.faces)
        .any(|face| face.id == image.source_face_id)));
    let volume = solid_mass_properties(&result.solid).unwrap().volume;
    assert!((volume - 32.5).abs() < 1e-5, "{volume}");
}

#[test]
fn sphere_opening_shell_is_watertight_with_exact_sector_volume() {
    // SPHERE opening: a spherical-cap solid (dome + flat disk) shelled
    // inward with the disk as the opening — the only retained face is the
    // sphere. The offset dome's rim is a smaller coaxial circle BELOW the
    // opening plane (the dome is less than a hemisphere, so the rim
    // normal points outward-and-up); the ruled weld rebuilds the flat
    // disk cap into the exact normal-ruled band between the two rims — a
    // cone frustum through the shared sphere centre's radial lines, since
    // the offset rim is the source rim scaled about that centre. The
    // result is the exact spherical SECTOR shell:
    //   V = (2π/3)(1 − c/R)(R³ − (R−d)³).
    let radius = 2.0;
    let cut_z = 1.0;
    let distance = 0.3;
    let solid = spherical_cap_solid(radius, cut_z);
    let disk = extreme_face_id(&solid, Vec3::new(0.0, 0.0, -1.0));
    let result = offset_shell(&solid, &[disk], distance).unwrap();

    assert!(
        result.solid.validate().is_empty(),
        "{:?}",
        result.solid.validate()
    );
    assert_eq!(open_real_edge_count(&result.solid), 0, "no open rim edges");
    assert_eq!(result.solid.shells.len(), 1, "one connected shell");
    assert!(result.face_images.iter().all(|image| solid
        .shells
        .iter()
        .flat_map(|shell| &shell.faces)
        .any(|face| face.id == image.source_face_id)));

    let expected = 2.0 * std::f64::consts::PI / 3.0
        * (1.0 - cut_z / radius)
        * (radius.powi(3) - (radius - distance).powi(3));
    let volume = solid_mass_properties(&result.solid).unwrap().volume;
    assert!(
        (volume - expected).abs() < 1e-6,
        "{volume} vs {expected} (diff {:.3e})",
        volume - expected
    );

    let outcome = offset_shell_with_diagnostics(&solid, &[disk], distance, None).unwrap();
    assert!(outcome.diagnostics.shippable());
    assert_eq!(outcome.diagnostics.counters["validate.issues"], 0);
}

/// Translation invariance (offset-unification audit slice 0).
///
/// Offset-shell's `scale` used to be the maximum distance of a vertex from the
/// WORLD ORIGIN, so every band derived from it (`tolerance`, `pair_tolerance`,
/// the SSI step cap, the coincidence / offset-skin / completion / assembly
/// widths) widened as the part was moved away from the origin and ignored the
/// part's size.  The identical shell now solves identically wherever it is
/// modelled; before, the far twin's bands were hundreds of times looser, so the
/// two were not solving the same problem at all.
#[test]
fn box_shell_is_translation_invariant_far_from_the_origin() {
    let shell_at = |origin: Vec3| {
        let solid = make_box_brep(origin, 20.0, 20.0, 20.0).unwrap();
        let top = extreme_face_id(&solid, Vec3::new(0.0, 0.0, 1.0));
        offset_shell(&solid, &[top], 1.5).expect("box shell must succeed")
    };
    let near = shell_at(Vec3::new(0.0, 0.0, 0.0));
    let away = shell_at(Vec3::new(5000.0, -2000.0, 800.0));

    for (label, result) in [("near", &near), ("away", &away)] {
        let issues = result.solid.validate();
        assert!(issues.is_empty(), "{label} shell invalid: {issues:?}");
        assert_eq!(open_real_edge_count(&result.solid), 0, "{label}: open rims");
    }
    // Same topology and the same volume: only the coordinates differ, so any
    // residual gap is mass-property float noise at 5e3 numerics, not a
    // different solve.
    let faces = |solid: &BrepSolid| -> usize { solid.shells.iter().map(|s| s.faces.len()).sum() };
    assert_eq!(
        faces(&near.solid),
        faces(&away.solid),
        "translating the part changed the shell's face count"
    );
    let near_volume = solid_mass_properties(&near.solid).unwrap().volume;
    let away_volume = solid_mass_properties(&away.solid).unwrap().volume;
    assert!(
        (near_volume - away_volume).abs() <= 1e-6 * near_volume.abs(),
        "shell volume moved with placement: {near_volume} vs {away_volume}"
    );
}

#[test]
fn hemisphere_cup_shell_is_watertight() {
    // Sphere at the BOTTOM, smoothly joined to the cylinder wall, shelled
    // through the flat top opening. The rim welds through the arrangement
    // path (the revolved-plane cap fragments properly), which keeps the
    // carrier's faithful fitted rim — watertight and valid, with the
    // volume good to the polyline's chord sag (~1e-3 here), not exact.
    let solid = hemisphere_cup(2.0, 3.0);
    let top = extreme_face_id(&solid, Vec3::new(0.0, 0.0, 1.0));
    let result = offset_shell(&solid, &[top], 0.4).unwrap();

    assert!(
        result.solid.validate().is_empty(),
        "{:?}",
        result.solid.validate()
    );
    assert_eq!(open_real_edge_count(&result.solid), 0, "no open rim edges");
    assert_eq!(result.solid.shells.len(), 1, "one connected shell");

    let pi = std::f64::consts::PI;
    let expected = pi
        * ((4.0 * 3.0 + 2.0 / 3.0 * 8.0) - (1.6f64.powi(2) * 3.0 + 2.0 / 3.0 * 1.6f64.powi(3)));
    let volume = solid_mass_properties(&result.solid).unwrap().volume;
    assert!(
        (volume - expected).abs() < 5e-3,
        "{volume} vs {expected} (diff {:.3e})",
        volume - expected
    );
}

#[test]
fn tube_open_both_ends_shells_to_exact_annulus_walls() {
    // MULTI-OPENING: a cylinder open at BOTH ends shells to a straight
    // tube. Each end leaves an orphan offset rim in its own opening
    // plane; the coplanar weld holes both wall disks independently, the
    // rim isoline re-analyticization swaps the carrier's fitted polyline
    // rims for the offset surface's exact circles, and the affine-plane
    // pcurve mapping makes the annulus trims exact — so the wall volume
    // is the exact annulus × length (integrator precision, ~1e-10).
    let axis = Vec3::new(0.0, 0.0, 1.0);
    let cylinder = make_cylinder_brep(Vec3::default(), axis, 2.0, 4.0).unwrap();
    let top = extreme_face_id(&cylinder, axis);
    let bottom = extreme_face_id(&cylinder, axis.scale(-1.0));
    let result = offset_shell(&cylinder, &[top, bottom], 0.5).unwrap();

    assert!(
        result.solid.validate().is_empty(),
        "{:?}",
        result.solid.validate()
    );
    assert_eq!(one_use_edge_count(&result.solid), 0, "no open rim edges");
    assert_eq!(result.solid.shells.len(), 1, "one connected shell");

    let expected = std::f64::consts::PI * (2.0f64.powi(2) - 1.5f64.powi(2)) * 4.0;
    let volume = solid_mass_properties(&result.solid).unwrap().volume;
    assert!(
        (volume - expected).abs() < 1e-6,
        "{volume} vs {expected} (diff {:.3e})",
        volume - expected
    );

    let outcome = offset_shell_with_diagnostics(&cylinder, &[top, bottom], 0.5, None).unwrap();
    assert!(outcome.diagnostics.shippable());
    assert_eq!(outcome.diagnostics.counters["validate.issues"], 0);
}

#[test]
fn frustum_open_both_ends_shells_watertight_with_exact_wall_volume() {
    // MULTI-OPENING with an OBLIQUE wall: the truncated cone open at both
    // ends. The bottom rim resolves through the arrangement (the offset
    // cone pierces the bottom plane), while the top rim needs the ruled
    // frustum-band weld — and the band's owner-pcurve rewrite must not
    // clobber the band's own rim coedge now that cap and owner share one
    // connected shell (the regression this fixture pins).
    let axis = Vec3::new(0.0, 0.0, 1.0);
    let cone = make_cone_brep(Vec3::default(), axis, 2.0, 1.0, 4.0).unwrap();
    let top = extreme_face_id(&cone, axis);
    let bottom = extreme_face_id(&cone, axis.scale(-1.0));
    let distance = 0.3;
    let result = offset_shell(&cone, &[top, bottom], distance).unwrap();

    assert!(
        result.solid.validate().is_empty(),
        "{:?}",
        result.solid.validate()
    );
    assert_eq!(one_use_edge_count(&result.solid), 0, "no open rim edges");
    assert_eq!(result.solid.shells.len(), 1, "one connected shell");

    // Exact wall volume. The cavity cone is the source cone shifted
    // radially by Δ = d·√17/4 (normal offset of a slope −1/4 generator);
    // it exits the bottom plane (arrangement trim) and ends at the offset
    // top rim at z₁ = H − d/√17, above which the wall is bounded by the
    // ruled band r = R₁ + 4(z − H) instead:
    //   V = πΔ∫₀^{z₁}(2r_src − Δ)dz + π∫_{z₁}^{H}(r_src² − r_band²)dz.
    let root17 = 17.0f64.sqrt();
    let delta = distance * root17 / 4.0;
    let tau = distance / root17;
    let z1 = 4.0 - tau;
    let pi = std::f64::consts::PI;
    let first = pi * delta * ((4.0 - delta) * z1 - z1 * z1 / 4.0);
    let second = pi * (4.25 * tau * tau - 5.3125 * tau * tau * tau);
    let expected = first + second;
    let volume = solid_mass_properties(&result.solid).unwrap().volume;
    assert!(
        (volume - expected).abs() < 1e-4,
        "{volume} vs {expected} (diff {:.3e})",
        volume - expected
    );
}

#[test]
fn box_through_hole_open_both_ends_shells_to_two_wall_tubes() {
    // MULTI-OPENING through-hole: a box with a drilled hole, shelled with
    // BOTH hole-bearing faces open. At each opening the hole wall and its
    // offset image both end on dangling rims that no wall fragment
    // touches — the rim-PAIR weld builds the missing flat annulus at each
    // end. The result is legitimately TWO closed components (the outer
    // wall tube and the hole wall tube — nothing connects them once both
    // ends are open), each oriented outward.
    let box_solid = make_box_brep(Vec3::default(), 4.0, 4.0, 4.0).unwrap();
    let drill = make_cylinder_brep(
        Vec3::new(2.0, 2.0, -1.0),
        Vec3::new(0.0, 0.0, 1.0),
        1.0,
        6.0,
    )
    .unwrap();
    let solid = boolean_operation(
        &box_solid,
        &drill,
        BooleanOperation::Subtract,
        &BooleanOptions::default(),
    )
    .unwrap();
    let top = extreme_face_id(&solid, Vec3::new(0.0, 0.0, 1.0));
    let bottom = extreme_face_id(&solid, Vec3::new(0.0, 0.0, -1.0));
    let result = offset_shell(&solid, &[top, bottom], 0.3).unwrap();

    assert!(
        result.solid.validate().is_empty(),
        "{:?}",
        result.solid.validate()
    );
    assert_eq!(one_use_edge_count(&result.solid), 0, "no open rim edges");
    assert_eq!(result.solid.shells.len(), 2, "outer tube + hole tube");

    // Outer tube: 4×4 minus 3.4×3.4 cross-section × height. Hole tube:
    // annulus r 1.0..1.3 × height.
    let pi = std::f64::consts::PI;
    let expected = (16.0 - 3.4f64 * 3.4) * 4.0 + pi * (1.3f64.powi(2) - 1.0) * 4.0;
    let volume = solid_mass_properties(&result.solid).unwrap().volume;
    assert!(
        (volume - expected).abs() < 1e-5,
        "{volume} vs {expected} (diff {:.3e})",
        volume - expected
    );
}

#[test]
fn oblique_cylinder_through_hole_shells_watertight_with_exact_wall_volume() {
    // NON-COPLANAR RIM PAIRS, oblique lane: a cylindrical through-hole
    // whose axis is tilted 30 degrees from the pierced faces' normal,
    // both pierced faces opened. The offset image of each drilled rim is
    // a NON-PLANAR wave about the opening plane (z = z0 + d*n_z(theta)),
    // so no rim weld applies; the carrier-extension lane rebuilds the
    // offset bore as the full drill band, the arrangement trims it with
    // the exact plane-conic (concentric ellipse), and the opening wall is
    // the flat elliptic annulus in the ORIGINAL pierced face's plane.
    // Result: two closed components (outer wall box + oblique hole tube).
    //
    // Closed-form wall volume: outer frame (10x6 - 9.5x5.5 cross-section
    // x height) plus the oblique tube — by Cavalieri each z-slice of the
    // tube is an elliptic annulus of area pi*(r_out^2 - r_in^2)/cos(tilt),
    // so its volume is the perpendicular annulus area times the axis
    // length between the planes (height/cos(tilt)).
    let tilt = 30f64.to_radians();
    let pi = std::f64::consts::PI;
    let expected =
        (60.0 - 9.5f64 * 5.5) * 6.0 + pi * (0.95f64.powi(2) - 0.49) * 6.0 / tilt.cos();
    let mut witnessed = Vec::new();
    // Determinism: three consecutive builds must agree bit-for-bit on the
    // shell statistics and the integrated volume.
    for _ in 0..3 {
        let box_solid = make_box_brep(Vec3::default(), 10.0, 6.0, 6.0).unwrap();
        let axis = Vec3::new(tilt.sin(), 0.0, tilt.cos());
        let drill = make_cylinder_brep(
            Vec3::new(5.0 - 4.5 * axis.x, 3.0, 3.0 - 4.5 * axis.z),
            axis,
            0.7,
            9.0,
        )
        .unwrap();
        let solid = boolean_operation(
            &box_solid,
            &drill,
            BooleanOperation::Subtract,
            &BooleanOptions::default(),
        )
        .unwrap();
        let top = extreme_face_id(&solid, Vec3::new(0.0, 0.0, 1.0));
        let bottom = extreme_face_id(&solid, Vec3::new(0.0, 0.0, -1.0));
        let result = offset_shell(&solid, &[top, bottom], 0.25).unwrap();

        assert!(
            result.solid.validate().is_empty(),
            "{:?}",
            result.solid.validate()
        );
        assert_eq!(one_use_edge_count(&result.solid), 0, "no open rim edges");
        assert_eq!(result.solid.shells.len(), 2, "outer box + oblique tube");

        let volume = solid_mass_properties(&result.solid).unwrap().volume;
        assert!(
            (volume - expected).abs() < 1e-5,
            "{volume} vs {expected} (diff {:.3e})",
            volume - expected
        );
        let faces = result
            .solid
            .shells
            .iter()
            .map(|shell| shell.faces.len())
            .sum::<usize>();
        witnessed.push((faces, volume));
    }
    for later in &witnessed[1..] {
        assert_eq!(witnessed[0].0, later.0, "run-to-run face-count drift");
        // Face-summation order costs a few ulps; anything larger would be
        // a genuinely different assembly.
        assert!(
            (witnessed[0].1 - later.1).abs() < 1e-9,
            "run-to-run volume drift: {} vs {}",
            witnessed[0].1,
            later.1
        );
    }
}

#[test]
fn conical_through_hole_shells_watertight_with_exact_wall_volume() {
    // NON-COPLANAR RIM PAIRS, tapered lane: a conical through-bore open
    // at both ends. The offset image of each drilled rim is a coaxial
    // circle shifted ALONG the axis by d*sin(half-angle) — off the
    // opening plane, and with no mis-built cap to rebuild (the opening
    // face already has the hole), so neither the ruled-band nor the
    // coplanar-pair weld applies. The carrier-extension lane closes both
    // ends with the flat annuli in the pierced faces' planes against the
    // offset cone's exact plane sections.
    //
    // Closed-form wall volume: r(z) = 1.2 - (z+1)/12 (drill r 1.2 -> 0.7
    // over height 6, so slope s = -1/12); the offset bore at equal z is
    // r(z) + delta with delta = d*sqrt(1+s^2), hence
    //   V_tube = pi*delta*Int_0^4 (2 r(z) + delta) dz
    //          = pi*delta*(7.6 + 4*delta).
    let pi = std::f64::consts::PI;
    let s = -1.0f64 / 12.0;
    let delta = 0.3 * (1.0 + s * s).sqrt();
    let expected = (16.0 - 3.4f64 * 3.4) * 4.0 + pi * delta * (7.6 + 4.0 * delta);
    let mut witnessed = Vec::new();
    for _ in 0..3 {
        let box_solid = make_box_brep(Vec3::default(), 4.0, 4.0, 4.0).unwrap();
        let drill = make_cone_brep(
            Vec3::new(2.0, 2.0, -1.0),
            Vec3::new(0.0, 0.0, 1.0),
            1.2,
            0.7,
            6.0,
        )
        .unwrap();
        let solid = boolean_operation(
            &box_solid,
            &drill,
            BooleanOperation::Subtract,
            &BooleanOptions::default(),
        )
        .unwrap();
        let top = extreme_face_id(&solid, Vec3::new(0.0, 0.0, 1.0));
        let bottom = extreme_face_id(&solid, Vec3::new(0.0, 0.0, -1.0));
        let result = offset_shell(&solid, &[top, bottom], 0.3).unwrap();

        assert!(
            result.solid.validate().is_empty(),
            "{:?}",
            result.solid.validate()
        );
        assert_eq!(one_use_edge_count(&result.solid), 0, "no open rim edges");
        assert_eq!(result.solid.shells.len(), 2, "outer box + tapered tube");

        let volume = solid_mass_properties(&result.solid).unwrap().volume;
        assert!(
            (volume - expected).abs() < 1e-5,
            "{volume} vs {expected} (diff {:.3e})",
            volume - expected
        );
        let faces = result
            .solid
            .shells
            .iter()
            .map(|shell| shell.faces.len())
            .sum::<usize>();
        witnessed.push((faces, volume));
    }
    for later in &witnessed[1..] {
        assert_eq!(witnessed[0].0, later.0, "run-to-run face-count drift");
        // Face-summation order costs a few ulps; anything larger would be
        // a genuinely different assembly.
        assert!(
            (witnessed[0].1 - later.1).abs() < 1e-9,
            "run-to-run volume drift: {} vs {}",
            witnessed[0].1,
            later.1
        );
    }
}

#[test]
fn oblique_through_hole_rim_pair_still_refuses() {
    // What still refuses (narrowed 2026-08-04): a tapered through-bore
    // whose OFFSET wall grows past the cavity side walls — here the bore
    // offsets to r=1.7375 at z=0 while the offset box walls sit 1.7 from
    // the bore axis, so the extended offset cone genuinely pierces all
    // four cavity walls near the bottom opening. The carrier-extension
    // lane fires, the harder arrangement it produces fails to fragment,
    // and the pipeline falls back to the un-extended lane — whose rims
    // stay coaxial but non-coplanar with no cap to rebuild, so the
    // honesty gate refuses with its canonical message rather than
    // shipping a non-watertight shell. (Cleanly-cleared tapered bores now
    // succeed: see conical_through_hole_shells_watertight_...)
    let box_solid = make_box_brep(Vec3::default(), 4.0, 4.0, 4.0).unwrap();
    let drill = make_cone_brep(
        Vec3::new(2.0, 2.0, -1.0),
        Vec3::new(0.0, 0.0, 1.0),
        1.6,
        0.6,
        6.0,
    )
    .unwrap();
    let solid = boolean_operation(
        &box_solid,
        &drill,
        BooleanOperation::Subtract,
        &BooleanOptions::default(),
    )
    .unwrap();
    let top = extreme_face_id(&solid, Vec3::new(0.0, 0.0, 1.0));
    let bottom = extreme_face_id(&solid, Vec3::new(0.0, 0.0, -1.0));
    let error = offset_shell(&solid, &[top, bottom], 0.3).unwrap_err();
    assert!(
        error.contains("unwelded rim leaves a non-watertight shell"),
        "{error}"
    );
}

// An opening face CARVED BY A SPHERE shells watertight. The retained
// sphere-cavity wall must offset (radius 8 → 9.5) so the inner skin closes
// the shell; that only happens once the carrier bound encloses the offset
// SURFACE (not just its trim rim), letting the offset sphere be imprinted by
// — and fragmented against — the offset wall planes it crosses. Before that
// fix the offset sphere was dropped, stranding the wall annulus in a
// disconnected shell and refusing as "non-watertight".
#[test]
fn sphere_carved_opening_shell_is_watertight() {
    // Box [0,20]³ (make_box_brep is min-corner based); a sphere centered
    // under the +Y face at (10,15,10) pokes through it, carving a circular
    // hole in Box_PY — the opening. The sphere top (y=23) clears the face
    // (y=20), so the retained cavity wall offsets to radius 9.5 and its
    // inner skin must close the shell.
    let box_solid = make_box_brep(Vec3::default(), 20.0, 20.0, 20.0).unwrap();
    // Pole along +Z, AWAY from the +Y opening — a pole coincident with the
    // opening rim is a separate seam-singularity trap, not what this covers.
    let sphere =
        make_sphere_brep(Vec3::new(10.0, 15.0, 10.0), 8.0, Vec3::new(0.0, 0.0, 1.0)).unwrap();
    let carved = boolean_operation(
        &box_solid,
        &sphere,
        BooleanOperation::Subtract,
        &BooleanOptions::default(),
    )
    .unwrap();
    // The +Y face (carries the sphere hole) is the opening.
    let opening = extreme_face_id(&carved, Vec3::new(0.0, 1.0, 0.0));
    let result = offset_shell(&carved, &[opening], 1.5).unwrap();

    assert!(
        result.solid.validate().is_empty(),
        "{:?}",
        result.solid.validate()
    );
    assert_eq!(result.solid.shells.len(), 1, "one connected shell");
    assert_eq!(open_real_edge_count(&result.solid), 0, "no open rim edges");
    // The offset sphere (inner cavity wall) survived selection.
    assert!(
        result
            .face_images
            .iter()
            .any(|image| matches!(image.role, OffsetFaceRole::Offset)
                && !carved
                    .shells
                    .iter()
                    .flat_map(|shell| &shell.faces)
                    .find(|face| face.id == image.source_face_id)
                    .and_then(|face| face.surface.is_affine().ok())
                    .unwrap_or(true)),
        "the curved (sphere) cavity wall must appear as an offset image"
    );
    // A 1.5-thick wall shell: positive, and well under the solid 20³ box.
    let volume = solid_mass_properties(&result.solid).unwrap().volume;
    assert!(
        volume > 0.0 && volume < 8000.0,
        "hollow shell wall volume implausible: {volume}"
    );
}

// PARTIAL-ARC carved opening: a horizontal side cylinder grazes the
// opening face, leaving an open arc chain on its outer boundary (audit
// A3b). The carrier/arrangement machinery closes it natively.
#[test]
fn side_arc_carved_opening_shells_watertight() {
    let box_solid = make_box_brep(Vec3::default(), 20.0, 20.0, 20.0).unwrap();
    let side = make_cylinder_brep(
        Vec3::new(-5.0, 20.0, 10.0),
        Vec3::new(1.0, 0.0, 0.0),
        6.0,
        30.0,
    )
    .unwrap();
    let solid = boolean_operation(
        &box_solid,
        &side,
        BooleanOperation::Subtract,
        &BooleanOptions::default(),
    )
    .unwrap();
    let opening = extreme_face_id(&solid, Vec3::new(0.0, 1.0, 0.0));
    let result = offset_shell(&solid, &[opening], 1.5).unwrap();

    assert!(
        result.solid.validate().is_empty(),
        "{:?}",
        result.solid.validate()
    );
    assert_eq!(result.solid.shells.len(), 1, "one connected shell");
    assert_eq!(open_real_edge_count(&result.solid), 0, "no open rim edges");
    let volume = solid_mass_properties(&result.solid).unwrap().volume;
    assert!(
        volume > 0.0 && volume < 8000.0,
        "hollow shell wall volume implausible: {volume}"
    );
}

// CONE-CRATER opening (audit A3a): an apex-down cone carved into the
// opening face leaves a conic crater whose inward offset self-intersects
// at the apex; the apex-cap sphere carrier caps it, and the cap's
// SSI-fitted ring arcs arrive as GEOMETRIC DUPLICATES of the offset
// frustum's iso-edge subcurves (same endpoints, parameterization-skewed
// midpoints, so the fragment segment keys never unify them).
// `weld_duplicate_one_use_arcs` must recognize each coincident pair as
// ONE edge — completion previously papered over the "open" ring with
// duplicate frustum faces (3-use arcs) and the shell refused.
//
// The correct result is honestly TWO shells: the box walls, plus the
// crater's 1.5-thick funnel — the funnel's top annulus (r 6..7.875 about
// the box center) never reaches the box side walls (the nearest inner
// wall plane is 8.5 from center), so the funnel is a separate closed
// solid.
#[test]
fn cone_crater_opening_shells_watertight_with_exact_wall_volume() {
    let box_solid = make_box_brep(Vec3::default(), 20.0, 20.0, 20.0).unwrap();
    let crater = make_cone_brep(
        Vec3::new(10.0, 24.0, 10.0),
        Vec3::new(0.0, -1.0, 0.0),
        9.0,
        0.0,
        12.0,
    )
    .unwrap();
    let carved = boolean_operation(
        &box_solid,
        &crater,
        BooleanOperation::Subtract,
        &BooleanOptions::default(),
    )
    .unwrap();
    // Pick the +Y planar face explicitly: sampling ignores trim, so the
    // extreme-centroid helper could land on the cone.
    let opening = carved
        .shells
        .iter()
        .flat_map(|shell| &shell.faces)
        .find(|face| {
            face.surface.is_affine().unwrap_or(false)
                && (face.surface.evaluate(0.5, 0.5).unwrap().y - 20.0).abs() < 1e-9
        })
        .unwrap()
        .id;
    let result = offset_shell(&carved, &[opening], 1.5).unwrap();

    assert!(
        result.solid.validate().is_empty(),
        "{:?}",
        result.solid.validate()
    );
    assert_eq!(open_real_edge_count(&result.solid), 0, "no open rim edges");
    assert_eq!(
        result.solid.shells.len(),
        2,
        "box walls + detached crater funnel"
    );
    assert!(result.face_images.iter().all(|image| carved
        .shells
        .iter()
        .flat_map(|shell| &shell.faces)
        .any(|face| face.id == image.source_face_id)));

    // Exact wall algebra. Source: the box minus the crater cone (radius 6
    // where it meets the y=20 face, apex (10,12,10)). Cavity: the box
    // shrunk 1.5 on five sides minus the DILATED crater — the offset cone
    // {r = 0.75(y - 9.5)} down to its tangency ring with the apex ball
    // (y = 11.1, r = 1.2), then the r=1.5 ball cap about the apex down to
    // y = 10.5. The exact volume doubles as the orientation check: an
    // inside-out funnel would still validate but subtract its volume.
    let pi = std::f64::consts::PI;
    let source = 8000.0 - 96.0 * pi;
    let dilated_crater = pi
        * (0.5625 * (10.5f64.powi(3) - 1.6f64.powi(3)) / 3.0
            + (2.25 * 0.6 - (1.5f64.powi(3) - 0.9f64.powi(3)) / 3.0));
    let cavity = 17.0 * 18.5 * 17.0 - dilated_crater;
    let expected = source - cavity;
    let volume = solid_mass_properties(&result.solid).unwrap().volume;
    assert!(
        (volume - expected).abs() < 5e-3,
        "{volume} vs {expected} (diff {:.3e})",
        volume - expected
    );
}

// APEX (pointed) cone shelled through its BASE: the retained lateral
// face's inward offset crosses the axis — the sampled far row becomes a
// mirrored ring (radius d·cos half-angle) and the surface self-pinches.
// The pinch retrim in `offset_surface` ends the carrier at the true
// cavity apex, and the singular-row normal override keeps the apex
// samples on the per-ruling limit instead of the axis. Exact sector
// algebra: shell = cone − cavity cone (cavity apex at h − d/sin α,
// cavity base radius from the offset ruling at z=0).
#[test]
fn apex_cone_open_base_shells_watertight_with_exact_wall_volume() {
    let radius = 8.0f64;
    let height = 12.0f64;
    let distance = 1.0f64;
    let cone = make_cone_brep(
        Vec3::default(),
        Vec3::new(0.0, 0.0, 1.0),
        radius,
        0.0,
        height,
    )
    .unwrap();
    let base = extreme_face_id(&cone, Vec3::new(0.0, 0.0, -1.0));
    let result = offset_shell(&cone, &[base], distance).unwrap();

    assert!(
        result.solid.validate().is_empty(),
        "{:?}",
        result.solid.validate()
    );
    assert_eq!(result.solid.shells.len(), 1, "one connected shell");
    assert_eq!(open_real_edge_count(&result.solid), 0, "no open rim edges");

    let slant = (radius * radius + height * height).sqrt();
    let sin_alpha = radius / slant;
    // Offset ruling: base point moves d·(h, -Δρ)/L → cavity base radius
    // at z = 0 and cavity apex on the axis at h − d/sin α.
    let cavity_apex_z = height - distance / sin_alpha;
    let cavity_base_radius = {
        // Radius of the offset ruling where it crosses z = 0.
        let base_offset_r = radius - distance * height / slant;
        let base_offset_z = -distance * radius / slant;
        base_offset_r + base_offset_z * (base_offset_r / (cavity_apex_z - base_offset_z))
    };
    let pi = std::f64::consts::PI;
    let expected = pi * radius * radius * height / 3.0
        - pi * cavity_base_radius * cavity_base_radius * cavity_apex_z / 3.0;
    let volume = solid_mass_properties(&result.solid).unwrap().volume;
    // 1e-3 band: the cavity's base rim is an SSI-fitted conic (~2.6e-5
    // floor), everything else is analytic-exact.
    assert!(
        (volume - expected).abs() < 1e-3,
        "{volume} vs {expected} (diff {:.3e})",
        volume - expected
    );
}

// OUTWARD shell (negative distance): thicken a box's retained walls
// outward, +Y open. The opening-wall ring between the source outline and
// the grown outline needs the wall carrier imprinted against the retained
// SOURCE faces (they are not carriers, so no carrier×carrier pair cuts the
// ring's inner boundary). Exact volume: grown box minus source box.
#[test]
fn outward_shell_open_top_box_has_exact_grown_wall_volume() {
    let box_solid = make_box_brep(Vec3::default(), 20.0, 20.0, 20.0).unwrap();
    let opening = extreme_face_id(&box_solid, Vec3::new(0.0, 1.0, 0.0));
    let result = offset_shell(&box_solid, &[opening], -1.5).unwrap();

    assert!(
        result.solid.validate().is_empty(),
        "{:?}",
        result.solid.validate()
    );
    assert_eq!(result.solid.shells.len(), 1, "one connected shell");
    assert_eq!(open_real_edge_count(&result.solid), 0, "no open rim edges");
    // Outer [−1.5,21.5]×[−1.5,20]×[−1.5,21.5] minus the 20³ source.
    let expected = 23.0 * 21.5 * 23.0 - 8000.0;
    let volume = solid_mass_properties(&result.solid).unwrap().volume;
    assert!(
        (volume - expected).abs() < 1e-6,
        "{volume} vs {expected} (diff {:.3e})",
        volume - expected
    );
}

// OUTWARD shell of a box with a CONIC CRATER carved into the opened +Y
// face (apex-down cone, base r=9 at y=24, apex at y=12 → crater rim r=6
// in the opening plane). The pad-stretched wall carrier used to scale the
// crater rim OUTWARD with the grown outline (r=6 → 6.9), so the two
// circles the wall must be cut by (the source rim r=6 and the shrunk
// offset-cone section r=4.125) fell inside its enlarged hole and both
// imprints clipped to nothing. Dropping interior wall loops lets the
// imprints cut the true rims; the void-wall guard drops the cavity-mouth
// disk. Result: TWO closed components — the grown box shell and the
// crater funnel (source cone + parallel offset cone, apex at
// y = 12 + |d|/sin α = 14.5, joined by the flat rim annulus).
//
// Exact volume: [grown box − offset-cone piece (r=4.125 over y 14.5..20)]
// − [source box − source-cone piece (r=6 over y 12..20)].
#[test]
fn outward_shell_conic_crater_carved_opening_has_exact_wall_volume() {
    let box_solid = make_box_brep(Vec3::default(), 20.0, 20.0, 20.0).unwrap();
    let cone = make_cone_brep(
        Vec3::new(10.0, 24.0, 10.0),
        Vec3::new(0.0, -1.0, 0.0),
        9.0,
        0.0,
        12.0,
    )
    .unwrap();
    let solid = boolean_operation(
        &box_solid,
        &cone,
        BooleanOperation::Subtract,
        &BooleanOptions::default(),
    )
    .unwrap();
    let opening = extreme_face_id(&solid, Vec3::new(0.0, 1.0, 0.0));
    let result = offset_shell(&solid, &[opening], -1.5).unwrap();

    assert!(
        result.solid.validate().is_empty(),
        "{:?}",
        result.solid.validate()
    );
    assert_eq!(
        result.solid.shells.len(),
        2,
        "grown box shell + crater funnel"
    );
    assert_eq!(open_real_edge_count(&result.solid), 0, "no open rim edges");
    let pi = std::f64::consts::PI;
    let grown = 23.0 * 21.5 * 23.0 - pi * 4.125f64.powi(2) * 5.5 / 3.0;
    let source = 8000.0 - pi * 36.0 * 8.0 / 3.0;
    let expected = grown - source;
    let volume = solid_mass_properties(&result.solid).unwrap().volume;
    // 1e-3 band: the crater rim cuts are SSI-fitted conics; everything
    // else is analytic-exact.
    assert!(
        (volume - expected).abs() < 1e-3,
        "{volume} vs {expected} (diff {:.3e})",
        volume - expected
    );
}

// OUTWARD shell of the sphere-gouged box (the inward rung geometry of
// `sphere_carved_opening_shell_is_watertight`, run with d = −1.5): the
// r=8 cavity sphere shrinks to r=6.5 and the fall-short lane extends the
// fitted offset sphere to its full domain so the wall-plane section
// (r=√(6.5²−25)) exists. Same wall-carrier interior-loop fix as the
// crater test. Result: grown box shell + closed gouge dome.
#[test]
fn outward_shell_sphere_carved_opening_shells_watertight() {
    let box_solid = make_box_brep(Vec3::default(), 20.0, 20.0, 20.0).unwrap();
    let sphere =
        make_sphere_brep(Vec3::new(10.0, 15.0, 10.0), 8.0, Vec3::new(0.0, 0.0, 1.0)).unwrap();
    let solid = boolean_operation(
        &box_solid,
        &sphere,
        BooleanOperation::Subtract,
        &BooleanOptions::default(),
    )
    .unwrap();
    let opening = extreme_face_id(&solid, Vec3::new(0.0, 1.0, 0.0));
    let result = offset_shell(&solid, &[opening], -1.5).unwrap();

    assert!(
        result.solid.validate().is_empty(),
        "{:?}",
        result.solid.validate()
    );
    assert_eq!(
        result.solid.shells.len(),
        2,
        "grown box shell + gouge dome"
    );
    assert_eq!(open_real_edge_count(&result.solid), 0, "no open rim edges");
    // Exact closed form: sphere-below-plane(r, cap height) for the source
    // (r=8, cap 3) and shrunk (r=6.5, cap 1.5) cavities. The offset
    // sphere is a Greville-fitted carrier (not analytic), which costs
    // ~5e-5 relative volume on the dome component — hence the 0.1 band
    // on the total; the box component is asserted exact separately so a
    // topology drift cannot hide inside the loose band.
    let pi = std::f64::consts::PI;
    let below =
        |r: f64, h: f64| 4.0 / 3.0 * pi * r.powi(3) - pi * h * h * (3.0 * r - h) / 3.0;
    let grown = 23.0 * 21.5 * 23.0 - below(6.5, 1.5);
    let source = 8000.0 - below(8.0, 3.0);
    let expected = grown - source;
    let volume = solid_mass_properties(&result.solid).unwrap().volume;
    assert!(
        (volume - expected).abs() < 0.1,
        "{volume} vs {expected} (diff {:.3e})",
        volume - expected
    );
    // The gouge misses every side face, so the box component is the plain
    // grown frame — analytic-exact.
    let box_component = result
        .solid
        .shells
        .iter()
        .map(|shell| {
            let single = BrepSolid {
                id: result.solid.id,
                vertices: result.solid.vertices.clone(),
                edges: result.solid.edges.clone(),
                shells: vec![shell.clone()],
                genus: 0,
            };
            solid_mass_properties(&single).unwrap().volume
        })
        .fold(0.0f64, f64::max);
    assert!(
        (box_component - 3373.5).abs() < 1e-6,
        "grown box component should be exact: {box_component}"
    );
}

// OUTWARD shell of a box with a straight through-bore (r=4, axis +Y)
// behind the opened +Y face. Two lanes had to land for this: the bore
// carrier's ruled extension now grows the TRIM by |d| (it used to grow the
// drill surface's own ends, so a sub-range trim moved by less and never
// reached the grown −Y plane), and the padded −Y carrier drops its
// uv-scaled hole loop so the shrunk bore can hole it. Exact volume: grown
// box minus the r=2.5 offset bore, minus the source (box minus r=4 bore).
#[test]
fn outward_shell_bore_through_opened_face_has_exact_wall_volume() {
    let box_solid = make_box_brep(Vec3::default(), 20.0, 20.0, 20.0).unwrap();
    let drill = make_cylinder_brep(
        Vec3::new(10.0, -1.0, 10.0),
        Vec3::new(0.0, 1.0, 0.0),
        4.0,
        22.0,
    )
    .unwrap();
    let solid = boolean_operation(
        &box_solid,
        &drill,
        BooleanOperation::Subtract,
        &BooleanOptions::default(),
    )
    .unwrap();
    let opening = extreme_face_id(&solid, Vec3::new(0.0, 1.0, 0.0));
    let result = offset_shell(&solid, &[opening], -1.5).unwrap();

    assert!(
        result.solid.validate().is_empty(),
        "{:?}",
        result.solid.validate()
    );
    assert_eq!(result.solid.shells.len(), 1, "one connected shell");
    assert_eq!(open_real_edge_count(&result.solid), 0, "no open rim edges");
    let pi = std::f64::consts::PI;
    let grown = 23.0 * 21.5 * 23.0 - pi * 2.5f64.powi(2) * 21.5;
    let source = 8000.0 - pi * 16.0 * 20.0;
    let expected = grown - source;
    let volume = solid_mass_properties(&result.solid).unwrap().volume;
    assert!(
        (volume - expected).abs() < 1e-3,
        "{volume} vs {expected} (diff {:.3e})",
        volume - expected
    );
}

// OUTWARD shell of the same drilled box opened at a face the bore does NOT
// touch (−Z): both bore rims land on grown RETAINED planes (y=−1.5 and
// y=21.5), so the shell closes only if the extended bore carrier reaches
// both and each padded plane can be holed by it. Exact volume: grown box
// minus the r=2.5 bore through its full height, minus the source.
#[test]
fn outward_shell_bore_behind_retained_faces_has_exact_wall_volume() {
    let box_solid = make_box_brep(Vec3::default(), 20.0, 20.0, 20.0).unwrap();
    let drill = make_cylinder_brep(
        Vec3::new(10.0, -1.0, 10.0),
        Vec3::new(0.0, 1.0, 0.0),
        4.0,
        22.0,
    )
    .unwrap();
    let solid = boolean_operation(
        &box_solid,
        &drill,
        BooleanOperation::Subtract,
        &BooleanOptions::default(),
    )
    .unwrap();
    let opening = extreme_face_id(&solid, Vec3::new(0.0, 0.0, -1.0));
    let result = offset_shell(&solid, &[opening], -1.5).unwrap();

    assert!(
        result.solid.validate().is_empty(),
        "{:?}",
        result.solid.validate()
    );
    assert_eq!(result.solid.shells.len(), 1, "one connected shell");
    assert_eq!(open_real_edge_count(&result.solid), 0, "no open rim edges");
    let pi = std::f64::consts::PI;
    let grown = 23.0 * 23.0 * 21.5 - pi * 2.5f64.powi(2) * 23.0;
    let source = 8000.0 - pi * 16.0 * 20.0;
    let expected = grown - source;
    let volume = solid_mass_properties(&result.solid).unwrap().volume;
    assert!(
        (volume - expected).abs() < 1e-3,
        "{volume} vs {expected} (diff {:.3e})",
        volume - expected
    );
}

// OUTWARD shell with TWO ADJACENT openings (−Z and −X). The two extended
// wall planes cross along the shared source edge: without a wall × wall
// imprint the z=0 wall's source-rim chain stayed open on the x=0 side (its
// neighbour there is an opening, not a retained face) and the wall never
// fragmented into its ring; and once cut, the sheet in FRONT of the −X
// opening (x∈[−1.5,0]) sits within |d| of a retained corner edge and read
// as wall thickness. Exact volume: the grown box clipped to x ≥ 0, z ≥ 0
// minus the source box.
#[test]
fn outward_shell_two_adjacent_openings_has_exact_grown_wall_volume() {
    let box_solid = make_box_brep(Vec3::default(), 20.0, 20.0, 20.0).unwrap();
    let bottom = extreme_face_id(&box_solid, Vec3::new(0.0, 0.0, -1.0));
    let side = extreme_face_id(&box_solid, Vec3::new(-1.0, 0.0, 0.0));
    let result = offset_shell(&box_solid, &[bottom, side], -1.5).unwrap();

    assert!(
        result.solid.validate().is_empty(),
        "{:?}",
        result.solid.validate()
    );
    assert_eq!(result.solid.shells.len(), 1, "one connected shell");
    assert_eq!(open_real_edge_count(&result.solid), 0, "no open rim edges");
    // [0,21.5]×[−1.5,21.5]×[0,21.5] minus the 20³ source.
    let expected = 21.5 * 23.0 * 21.5 - 8000.0;
    let volume = solid_mass_properties(&result.solid).unwrap().volume;
    assert!(
        (volume - expected).abs() < 1e-6,
        "{volume} vs {expected} (diff {:.3e})",
        volume - expected
    );
}

// The user-reported outward shell (2026-09-06): a 20³ box with a through-
// bore along +Y (r≈4.679 — the pin's surface spans y −5..25, so the bore
// trim is a SUB-RANGE of its ruling), three r=4 fillets meeting in a corner
// blend at (20,20,20), opened at the two ADJACENT faces −Z and −X, grown
// OUTWARD by 1. Every lane above had to hold at once: the wall × wall cut and
// the in-front-of-another-opening guard, the trim-aware bore extension with
// the loop-free padded planes, the reflex probe reading the blend junctions
// as smooth, and the junction-aware pad that lets boundary synchronization
// pair each plane with its fillet and each fillet's end with the corner
// sphere. Exact closed form with the corner cove:
//   grown = [0,21]×[−1,21]×[0,21] − fillets(r=5) − bore(r=3.679, h=22),
//   source = 20³ − fillets(r=4) − bore(r=4.679, h=20),
// where fillets(r) = (1−π/4)·r²·Σ(Lᵢ−r) + (r³ − πr³/6). The blend offsets
// are Greville-fitted, hence the 2e-2 band (the source itself measures 3e-3
// off its closed form).
#[test]
fn outward_shell_user_bore_fillets_two_openings_has_exact_wall_volume() {
    let pi = std::f64::consts::PI;
    let pin_radius = 4.679_072_596_154_671;
    let box_solid = make_box_brep(Vec3::default(), 20.0, 20.0, 20.0).unwrap();
    let pin = make_cylinder_brep(
        Vec3::new(10.0, -5.0, 10.0),
        Vec3::new(0.0, 1.0, 0.0),
        pin_radius,
        30.0,
    )
    .unwrap();
    let cut = boolean_operation(
        &box_solid,
        &pin,
        BooleanOperation::Subtract,
        &BooleanOptions::default(),
    )
    .unwrap();
    let solid = fillet_edges(
        &cut,
        &[
            Vec3::new(20.0, 20.0, 10.0),
            Vec3::new(20.0, 10.0, 20.0),
            Vec3::new(10.0, 20.0, 20.0),
        ],
        None,
        4.0,
        false,
        Some("F"),
    )
    .unwrap();
    assert!(solid.validate().is_empty(), "{:?}", solid.validate());
    let planar_extreme = |axis: Vec3| {
        solid
            .shells
            .iter()
            .flat_map(|shell| &shell.faces)
            .filter(|face| face.surface.is_affine().unwrap_or(false))
            .max_by(|first, second| {
                let first_value = first.surface.evaluate(0.5, 0.5).unwrap().dot(axis);
                let second_value = second.surface.evaluate(0.5, 0.5).unwrap().dot(axis);
                first_value.total_cmp(&second_value)
            })
            .unwrap()
            .id
    };
    let bottom = planar_extreme(Vec3::new(0.0, 0.0, -1.0));
    let side = planar_extreme(Vec3::new(-1.0, 0.0, 0.0));
    let result = offset_shell(&solid, &[bottom, side], -1.0).unwrap();

    assert!(
        result.solid.validate().is_empty(),
        "{:?}",
        result.solid.validate()
    );
    assert_eq!(result.solid.shells.len(), 1, "one connected shell");
    assert_eq!(open_real_edge_count(&result.solid), 0, "no open rim edges");
    let fillets = |r: f64, lengths: [f64; 3]| {
        (1.0 - pi / 4.0) * r * r * lengths.iter().map(|length| length - r).sum::<f64>()
            + (r.powi(3) - pi * r.powi(3) / 6.0)
    };
    let grown = 21.0 * 22.0 * 21.0
        - fillets(5.0, [21.0, 22.0, 21.0])
        - pi * (pin_radius - 1.0).powi(2) * 22.0;
    let source = 8000.0 - fillets(4.0, [20.0, 20.0, 20.0]) - pi * pin_radius.powi(2) * 20.0;
    let expected = grown - source;
    let volume = solid_mass_properties(&result.solid).unwrap().volume;
    assert!(
        (volume - expected).abs() < 2e-2,
        "{volume} vs {expected} (diff {:.3e})",
        volume - expected
    );
}

// CONCAVE solid: a box with a blind rectangular side pocket, shelled
// through an UNCARVED face. At each of the pocket's reflex (concave)
// edges the offset skin must GROW past the source footprint (source wall
// [5,15] → skin [3.5,16.5]) to meet its neighbours' offsets — the
// reflex-gated planar carrier extension supplies exactly that. Before it,
// source-sized trims left gaps no miter could bridge (~20 one-use edges).
#[test]
fn concave_pocket_solid_shells_watertight_through_uncarved_face() {
    let box_solid = make_box_brep(Vec3::default(), 20.0, 20.0, 20.0).unwrap();
    let pocket = make_box_brep(Vec3::new(15.0, 5.0, 5.0), 6.0, 10.0, 10.0).unwrap();
    let solid = boolean_operation(
        &box_solid,
        &pocket,
        BooleanOperation::Subtract,
        &BooleanOptions::default(),
    )
    .unwrap();
    // +Y face: planar and untouched by the pocket (pocket spans y 5..15).
    let opening = extreme_face_id(&solid, Vec3::new(0.0, 1.0, 0.0));
    let result = offset_shell(&solid, &[opening], 1.5).unwrap();

    assert!(
        result.solid.validate().is_empty(),
        "{:?}",
        result.solid.validate()
    );
    assert_eq!(result.solid.shells.len(), 1, "one connected shell");
    assert_eq!(open_real_edge_count(&result.solid), 0, "no open rim edges");
    let volume = solid_mass_properties(&result.solid).unwrap().volume;
    assert!(
        volume > 0.0 && volume < 8000.0,
        "hollow shell wall volume implausible: {volume}"
    );
}

// L-shaped solid (a full-height step removed from the box), shelled
// through the CARVED face: the step's vertical reflex edge crosses the
// opening itself. Covers the reflex extension interacting with the
// opening-wall machinery.
#[test]
fn l_step_solid_shells_watertight_through_carved_face() {
    let box_solid = make_box_brep(Vec3::default(), 20.0, 20.0, 20.0).unwrap();
    let step = make_box_brep(Vec3::new(10.0, 10.0, -1.0), 11.0, 11.0, 22.0).unwrap();
    let solid = boolean_operation(
        &box_solid,
        &step,
        BooleanOperation::Subtract,
        &BooleanOptions::default(),
    )
    .unwrap();
    let opening = extreme_face_id(&solid, Vec3::new(0.0, 1.0, 0.0));
    let result = offset_shell(&solid, &[opening], 1.5).unwrap();

    assert!(
        result.solid.validate().is_empty(),
        "{:?}",
        result.solid.validate()
    );
    assert_eq!(open_real_edge_count(&result.solid), 0, "no open rim edges");
    let volume = solid_mass_properties(&result.solid).unwrap().volume;
    assert!(
        volume > 0.0 && volume < 8000.0,
        "hollow shell wall volume implausible: {volume}"
    );
}

// The user's 2026-09-07 "Offset shell fails" document: a sphere (r≈8.3)
// centred on the base of a frustum (r 13.58 → 11.26, h=10), unioned, and
// shelled INWARD (d=1) through the frustum's top. The frustum's base is an
// ANNULUS: its outer rim is convex (the frustum side) but its inner rim —
// where the sphere's lower half emerges — is REFLEX, so the base carrier is
// reflex-extended. The pad slides the plane's net under the cloned pcurves,
// which carried the INTERIOR loop outward with the outline: the r=8.3 hole
// scaled to r=9.22 while the shrunk offset sphere (rebuilt full-domain,
// r=7.3) crosses the offset plane at r=7.23 — inside the enlarged hole. No
// imprint, the hole rim stayed one-use, and the shell refused ("unwelded
// rim leaves a non-watertight shell"). The padded plane now drops its
// interior loops (as the outward lane already did) so the sphere's imprint
// cuts the true hole, and the selection seed is the source seed's offset
// image located on the carrier (the raw source uv read OUTSIDE its own
// annulus on the slid net).
//
// Closed-form wall volume, round numbers R=8, frustum 13.5→11, h=10, d=1,
// with α the half-angle (tan α = 0.25):
//   source  = hemisphere(R) + frustum(13.5, 11, 10)
//   cavity  = frustum from z=d (r = r(d) − d/cos α) up to the offset side's
//             image rim (rt − d·cos α at z = h − d·sin α)
//   cork    = the ruled band from that image rim to the source top rim —
//             the frustum-opening closure `cone_open_top_shell_…` pins
//   dome    = sphere(R − d) below z = d (sphere minus the cap above it)
//   wall    = source − cavity − cork − dome
#[test]
fn sphere_under_frustum_base_annulus_shells_through_top_with_exact_wall_volume() {
    let pi = std::f64::consts::PI;
    let axis = Vec3::new(0.0, 0.0, 1.0);
    let (radius, r_bottom, r_top, height, d) = (8.0f64, 13.5f64, 11.0f64, 10.0f64, 1.0f64);
    let sphere = make_sphere_brep(Vec3::default(), radius, axis).unwrap();
    let cone = make_cone_brep(Vec3::default(), axis, r_bottom, r_top, height).unwrap();
    let solid = boolean_operation(
        &sphere,
        &cone,
        BooleanOperation::Union,
        &BooleanOptions::default(),
    )
    .unwrap();
    assert!(solid.validate().is_empty(), "{:?}", solid.validate());
    let top = topmost_planar_face_id(&solid);
    let result = offset_shell(&solid, &[top], d).unwrap();

    assert!(
        result.solid.validate().is_empty(),
        "{:?}",
        result.solid.validate()
    );
    assert_eq!(result.solid.shells.len(), 1, "one connected shell");
    assert_eq!(open_real_edge_count(&result.solid), 0, "no open rim edges");

    let frustum = |r0: f64, r1: f64, h: f64| pi * h / 3.0 * (r0 * r0 + r0 * r1 + r1 * r1);
    let alpha = ((r_bottom - r_top) / height).atan();
    let r_at = |z: f64| r_bottom - (r_bottom - r_top) * z / height;
    let rim_r = r_top - d * alpha.cos();
    let rim_z = height - d * alpha.sin();
    let source = 2.0 / 3.0 * pi * radius.powi(3) + frustum(r_bottom, r_top, height);
    let cavity = frustum(r_at(d) - d / alpha.cos(), rim_r, rim_z - d);
    let cork = frustum(rim_r, r_top, height - rim_z);
    let inner = radius - d;
    let cap_h = inner - d;
    let dome = 4.0 / 3.0 * pi * inner.powi(3) - pi * cap_h * cap_h * (3.0 * inner - cap_h) / 3.0;
    let expected = source - cavity - cork - dome;
    let volume = solid_mass_properties(&result.solid).unwrap().volume;
    assert!(
        (volume - expected).abs() < 1e-3,
        "{volume} vs {expected} (diff {:.3e})",
        volume - expected
    );
}

// The OUTWARD lane of the same geometry (the user's second 2026-09-07
// document, d = −0.5). Two pads of exactly |d| fell short of an ACUTE
// junction:
//   - the frustum's base (material dihedral 90° − α) — the outward offsets
//     of the cone side and the base plane meet d·tan(45° + α/2) ≈ 1.26·d
//     past the rim, so the cone carrier ended above the padded base plane
//     and the pair imprint was skipped on bounds;
//   - the opening rim, where the offset cone crosses the opening plane
//     d/cos α past the source rim, outside the wall padded by d.
// Both pads now scale with the sampled junction angle. Closed form: the
// grown solid is clipped flush at the opening plane (as the outward box
// test pins), so
//   grown = frustum(rb + d·tan α + d/cos α, rt + d/cos α, h + d)
//         + ball(R + d) below z = −d   (cap height R)
//   wall  = grown − (frustum(rb, rt, h) + hemisphere(R))
#[test]
fn outward_shell_sphere_under_frustum_base_has_exact_grown_wall_volume() {
    let pi = std::f64::consts::PI;
    let axis = Vec3::new(0.0, 0.0, 1.0);
    let (radius, r_bottom, r_top, height, d) = (8.0f64, 13.5f64, 11.0f64, 10.0f64, 0.5f64);
    let sphere = make_sphere_brep(Vec3::default(), radius, axis).unwrap();
    let cone = make_cone_brep(Vec3::default(), axis, r_bottom, r_top, height).unwrap();
    let solid = boolean_operation(
        &sphere,
        &cone,
        BooleanOperation::Union,
        &BooleanOptions::default(),
    )
    .unwrap();
    assert!(solid.validate().is_empty(), "{:?}", solid.validate());
    let top = topmost_planar_face_id(&solid);
    let result = offset_shell(&solid, &[top], -d).unwrap();

    assert!(
        result.solid.validate().is_empty(),
        "{:?}",
        result.solid.validate()
    );
    assert_eq!(result.solid.shells.len(), 1, "one connected shell");
    assert_eq!(open_real_edge_count(&result.solid), 0, "no open rim edges");

    let frustum = |r0: f64, r1: f64, h: f64| pi * h / 3.0 * (r0 * r0 + r0 * r1 + r1 * r1);
    let tan_alpha = (r_bottom - r_top) / height;
    let cos_alpha = tan_alpha.atan().cos();
    let grown = frustum(
        r_bottom + d * tan_alpha + d / cos_alpha,
        r_top + d / cos_alpha,
        height + d,
    ) + pi * radius * radius * (2.0 * radius + 3.0 * d) / 3.0;
    let source = frustum(r_bottom, r_top, height) + 2.0 / 3.0 * pi * radius.powi(3);
    let expected = grown - source;
    let volume = solid_mass_properties(&result.solid).unwrap().volume;
    assert!(
        (volume - expected).abs() < 1e-3,
        "{volume} vs {expected} (diff {:.3e})",
        volume - expected
    );
}

// The two pads in isolation: a bare frustum (r 13.5 → 11, h = 10) opened
// at its top and shelled OUTWARD by 0.5. Its base is the acute junction
// (cone × plane, nothing reflex anywhere) and its opening rim is the
// oblique one (offset cone crossing the opening plane d/cos α out).
//   wall = frustum(rb + d·tan α + d/cos α, rt + d/cos α, h + d) − frustum(rb, rt, h)
#[test]
fn outward_shell_frustum_open_top_has_exact_grown_wall_volume() {
    let pi = std::f64::consts::PI;
    let axis = Vec3::new(0.0, 0.0, 1.0);
    let (r_bottom, r_top, height, d) = (13.5f64, 11.0f64, 10.0f64, 0.5f64);
    let solid = make_cone_brep(Vec3::default(), axis, r_bottom, r_top, height).unwrap();
    let top = topmost_planar_face_id(&solid);
    let result = offset_shell(&solid, &[top], -d).unwrap();

    assert!(
        result.solid.validate().is_empty(),
        "{:?}",
        result.solid.validate()
    );
    assert_eq!(result.solid.shells.len(), 1, "one connected shell");
    assert_eq!(open_real_edge_count(&result.solid), 0, "no open rim edges");

    let frustum = |r0: f64, r1: f64, h: f64| pi * h / 3.0 * (r0 * r0 + r0 * r1 + r1 * r1);
    let tan_alpha = (r_bottom - r_top) / height;
    let cos_alpha = tan_alpha.atan().cos();
    let expected = frustum(
        r_bottom + d * tan_alpha + d / cos_alpha,
        r_top + d / cos_alpha,
        height + d,
    ) - frustum(r_bottom, r_top, height);
    let volume = solid_mass_properties(&result.solid).unwrap().volume;
    assert!(
        (volume - expected).abs() < 1e-3,
        "{volume} vs {expected} (diff {:.3e})",
        volume - expected
    );
}

// The same defect with a RULED neighbour: a cylindrical boss (r=4, h=5) on
// a 20³ box's top, shelled INWARD (d=1) through the bottom. The top face's
// interior loop (the boss root) is reflex; its offset must shrink to the
// offset boss (r=3), which the reflex-extended boss carrier imprints once
// the padded plane stops carrying the loop outward. The cavity runs from
// the opening plane z=0 up to the offset top z=19, then up the boss:
//   wall = (8000 + π·4²·5) − (18·18·19 + π·3²·5)
#[test]
fn cylindrical_boss_on_box_top_shells_through_bottom_with_exact_wall_volume() {
    let pi = std::f64::consts::PI;
    let box_solid = make_box_brep(Vec3::default(), 20.0, 20.0, 20.0).unwrap();
    let boss = make_cylinder_brep(
        Vec3::new(10.0, 10.0, 20.0),
        Vec3::new(0.0, 0.0, 1.0),
        4.0,
        5.0,
    )
    .unwrap();
    let solid = boolean_operation(
        &box_solid,
        &boss,
        BooleanOperation::Union,
        &BooleanOptions::default(),
    )
    .unwrap();
    assert!(solid.validate().is_empty(), "{:?}", solid.validate());
    let bottom = extreme_face_id(&solid, Vec3::new(0.0, 0.0, -1.0));
    let result = offset_shell(&solid, &[bottom], 1.0).unwrap();

    assert!(
        result.solid.validate().is_empty(),
        "{:?}",
        result.solid.validate()
    );
    assert_eq!(result.solid.shells.len(), 1, "one connected shell");
    assert_eq!(open_real_edge_count(&result.solid), 0, "no open rim edges");
    let expected = (8000.0 + pi * 16.0 * 5.0) - (18.0 * 18.0 * 19.0 + pi * 9.0 * 5.0);
    let volume = solid_mass_properties(&result.solid).unwrap().volume;
    assert!(
        (volume - expected).abs() < 1e-3,
        "{volume} vs {expected} (diff {:.3e})",
        volume - expected
    );
}

// A fillet meeting the opening rim PERPENDICULARLY: box [0,20]^3 with
// fillet r=3 on the vertical edge x=20,y=20, shelled through the +Z face
// (a square opening with one rounded corner), d=1.5. The fillet's offset
// carrier (the r=1.5 coaxial cylinder) is perpendicular to the opening
// plane and reaches it, so the ordinary imprint path closes the shell.
// (The TANGENT variant — fillets on the opening face's own rim edges —
// still refuses: audit ledger A3c, the fall-short crest band class.)
// Closed-form wall volume with cove(r) = r² − πr²/4:
// fixture = 8000 − cove(3)·20, cavity = (17² − cove(1.5))·18.5.
#[test]
fn vertical_edge_fillet_at_opening_corner_shells_to_exact_hollow_volume() {
    let box_solid = make_box_brep(Vec3::default(), 20.0, 20.0, 20.0).unwrap();
    let solid = fillet_edges(
        &box_solid,
        &[Vec3::new(20.0, 20.0, 10.0)],
        None,
        3.0,
        false,
        Some("F"),
    )
    .unwrap();
    assert!(solid.validate().is_empty(), "{:?}", solid.validate());
    // surface.evaluate ignores trim — the fillet cylinder's carrier
    // reaches z=20 — so filter to affine (planar) faces before taking
    // the max-z centroid.
    let top = solid
        .shells
        .iter()
        .flat_map(|shell| &shell.faces)
        .filter(|face| face.surface.is_affine().unwrap_or(false))
        .max_by(|first, second| {
            let first_z = first.surface.evaluate(0.5, 0.5).unwrap().z;
            let second_z = second.surface.evaluate(0.5, 0.5).unwrap().z;
            first_z.total_cmp(&second_z)
        })
        .unwrap()
        .id;
    let result = offset_shell(&solid, &[top], 1.5).unwrap();

    assert!(
        result.solid.validate().is_empty(),
        "{:?}",
        result.solid.validate()
    );
    assert_eq!(one_use_edge_count(&result.solid), 0, "no open rim edges");
    assert_eq!(result.solid.shells.len(), 1, "one connected shell");
    let cove = |radius: f64| radius * radius * (1.0 - std::f64::consts::PI / 4.0);
    let fixture = 8000.0 - cove(3.0) * 20.0;
    let cavity = (17.0 * 17.0 - cove(1.5)) * 18.5;
    let expected = fixture - cavity;
    let volume = solid_mass_properties(&result.solid).unwrap().volume;
    assert!((volume - expected).abs() < 2e-2, "{volume} vs {expected}");
}

#[test]
fn sphere_as_opening_face_still_refuses() {
    // What still refuses: using the CURVED sphere face itself as the
    // opening (shelling a hemisphere-bottom cup through its dome). The
    // opening-wall machinery only recovers planar/ruled opening walls, so
    // this can never assemble watertight. The refusal MODE is not pinned:
    // depending on assembly ordering deeper in the shared boolean
    // machinery it surfaces either as the honesty gate ("unwelded rim
    // leaves a non-watertight shell") or as the assembler's own
    // "non-positive volume" rejection — both are loud refusals, never a
    // silent bad solid. The deterministic message pin lives in
    // `oblique_through_hole_rim_pair_still_refuses`.
    let solid = hemisphere_cup(2.0, 3.0);
    let dome = extreme_face_id(&solid, Vec3::new(0.0, 0.0, -1.0));
    let error = offset_shell(&solid, &[dome], 0.4)
        .expect_err("a curved opening face must refuse, not ship a shell");
    // Not pinned to ONE message (see above), but pinned to the two LOUD
    // refusals that are the acceptable outcomes.  A bare `is_err()` would also
    // accept a panic-turned-error, an argument-validation reject that never
    // reached the shell machinery, or any future refusal that fires for an
    // unrelated reason — none of which would show that the opening-wall gate
    // is still doing its job.
    assert!(
        error.contains("unwelded rim leaves a non-watertight shell")
            || error.contains("non-positive volume"),
        "expected the honesty gate or the assembler's volume reject, got: {error}"
    );
}

#[test]
fn diagnostic_offset_shell_reports_validation_metrics() {
    let source = make_box_brep(Vec3::default(), 4.0, 4.0, 4.0).unwrap();
    let top = source.shells[0]
        .faces
        .iter()
        .find(|face| {
            let point = face.surface.evaluate(0.5, 0.5).unwrap();
            (point.z - 4.0).abs() < 1e-9
        })
        .unwrap();
    let outcome = offset_shell_with_diagnostics(&source, &[top.id], 0.5, None).unwrap();
    assert!(outcome.diagnostics.shippable());
    assert_eq!(outcome.diagnostics.counters["collect.opening_faces"], 1);
    assert_eq!(outcome.diagnostics.counters["validate.issues"], 0);
    assert!(outcome
        .diagnostics
        .measurements
        .contains_key("validate.max_pcurve_error"));
}