BREP_kernel 0.2.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
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.
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);
}

#[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: still an HONEST REFUSAL. The bore carrier's
// SURFACE only spans the drill's own extent (y −1..21), so no lane can
// reach the grown bottom plane at y=−1.5, and the padded bottom carrier's
// UV-stretched hole loop (r=4 → 4.6) has no imprint to cut it — the
// grown bottom's r=2.5 opening cannot be built. Guard that this stays an
// error (a wrong-but-watertight shell would be strictly worse). Landing
// it needs a curved-carrier extension past RETAINED grown planes (surface
// extension or analytic rebuild), plus interior-loop treatment for padded
// RETAINED carriers.
#[test]
fn outward_shell_bore_through_opened_face_still_refuses() {
    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));
    assert!(
        offset_shell(&solid, &[opening], -1.5).is_err(),
        "outward through-bore is unsupported and must refuse, not emit a wrong shell"
    );
}

// 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}"
    );
}

// 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));
    assert!(offset_shell(&solid, &[dome], 0.4).is_err());
}

#[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"));
}