BREP_kernel 0.3.1

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
use super::*;

/// Extend a hole-wall offset carrier's trim past the opening planes it
/// pierces, so the arrangement — not a rim weld — closes the opening.
///
/// `offset_face_carrier` trims the offset carrier with the parametric IMAGE
/// of the source trim: every source rim point moves `distance` along the
/// local surface normal. When the hole wall meets the pierced face
/// perpendicularly, that image stays in the opening plane and the coplanar
/// rim welds close the shell. When the wall is OBLIQUE (tilted drill axis)
/// or CONICAL, the normal has a component along the opening normal and the
/// image rim leaves the plane — for a tilted cylinder it oscillates
/// sinusoidally about it (z = z₀ + d·n_z(θ)), for a cone it is a coaxial
/// circle shifted along the axis by d·sin(half-angle). The pair imprint
/// against the opening plane then only exists where the image OVERSHOOTS
/// the plane; on the fall-short side the offset skin ends mid-air inside
/// the material, the source rim and the image rim both stay one-use, and
/// the honesty gate refuses the shell.
///
/// The correct opening wall is the piece of the ORIGINAL pierced face's
/// plane between the source rim and the offset carrier's exact plane
/// section (Parasolid hollow semantics: the cavity is trimmed by the
/// opening surface). That is precisely what the arrangement already builds
/// on its own whenever the offset carrier REACHES through the plane — the
/// carrier × opening-plane imprint is the exact conic (analytic plane ×
/// quadric SSI), the carrier keeps its main fragment, and the wall
/// fragment on the opening plane is the flat annulus between the drilled
/// rim and that conic. So instead of welding the gap after assembly,
/// rebuild the qualifying carrier's trim as the full-period band of its
/// surface extended to the surface's own v-domain ends, which lie beyond
/// the opening planes (drill tools always overshoot the stock). Exactness
/// is free: the new rims are surface isolines and the conic trims come
/// from the analytic intersection.
///
/// Qualification is deliberately narrow so every landed lane keeps its
/// existing path (straight holes: coplanar rim-pair welds; frustum outer
/// walls: ruled band weld):
/// - the carrier face is a closed band: nothing but closed full-period
///   rims (exactly two), face-local seams, and degenerate placeholders;
/// - each rim edge is shared with a PLANAR opening face as an INNER
///   (hole) loop of that face — an outer-loop rim is the frustum lane,
///   where the opening face ends at the wall and the ruled band is the
///   landed closure;
/// - the rim's offset image genuinely leaves the opening plane (beyond
///   the weld tolerance band) — an in-plane image is the straight-hole
///   lane;
/// - both surface v-domain ends clear their opening planes on the far
///   side, so the extended band genuinely reaches through both openings
///   (when the surface itself stops short, nothing can close the shell
///   and the honest refusal stands).
pub(super) fn extend_offset_carriers_past_open_hole_rims(
    carriers: &mut [Carrier],
    source: &BrepSolid,
    source_faces: &[&FaceRecord],
    opening_set: &HashSet<u64>,
    smooth_pairs: &HashSet<(usize, usize)>,
    scale: f64,
) -> Result<HashSet<usize>, String> {
    let weld_band = 2e-3f64.max(scale * 5e-5);
    let source_edge_by_id = source
        .edges
        .iter()
        .map(|edge| (edge.id, edge))
        .collect::<HashMap<_, _>>();
    let mut extended = HashSet::default();
    'carrier: for index in 0..carriers.len() {
        if !matches!(carriers[index].kind, OffsetFaceRole::Offset) {
            continue;
        }
        // Smooth-synchronized carriers had boundary curves rewritten against
        // their tangent neighbours; leave them to that machinery.
        if smooth_pairs
            .iter()
            .any(|(first, second)| *first == index || *second == index)
        {
            continue;
        }
        let Some(source_face) = source_faces
            .iter()
            .find(|face| face.id == carriers[index].source_face_id)
        else {
            continue;
        };
        let mut local_uses = HashMap::<u64, usize>::default();
        for coedge in source_face
            .loops
            .iter()
            .flat_map(|loop_record| &loop_record.coedges)
        {
            *local_uses.entry(coedge.edge_id).or_default() += 1;
        }
        // A closed band trims to nothing but rims + face-local seams.
        let mut rims = Vec::new();
        for (loop_index, loop_record) in source_face.loops.iter().enumerate() {
            for (coedge_index, coedge) in loop_record.coedges.iter().enumerate() {
                let Some(edge) = source_edge_by_id.get(&coedge.edge_id) else {
                    continue 'carrier;
                };
                if edge.degenerate {
                    continue;
                }
                match local_uses[&coedge.edge_id] {
                    2 => {}
                    1 if edge.start_vertex_id == edge.end_vertex_id => {
                        rims.push((loop_index, coedge_index, (*edge).clone()));
                    }
                    _ => continue 'carrier,
                }
            }
        }
        if rims.len() != 2 {
            continue;
        }
        let carrier_face = carriers[index].solid.shells[0].faces[0].clone();
        let surface = carrier_face.surface.clone();
        let [su0, su1] = surface.domain_u()?;
        let [sv0, sv1] = surface.domain_v()?;
        let v_mid = (sv0 + sv1) * 0.5;
        // The band must close in u (a periodic wall around the hole bore).
        if surface
            .evaluate(su0, v_mid)?
            .sub(surface.evaluate(su1, v_mid)?)
            .length()
            > weld_band
        {
            continue;
        }
        let mut rim_planes = Vec::new();
        for (loop_index, coedge_index, rim_edge) in &rims {
            let source_coedge = &source_face.loops[*loop_index].coedges[*coedge_index];
            // Full-period rim: its pcurve sweeps the whole u domain.
            let [p0, p1] = source_coedge.pcurve.domain()?;
            let mut u_low = f64::MAX;
            let mut u_high = f64::MIN;
            let mut v_mean = 0.0f64;
            for sample in 0..=32 {
                let uv = source_coedge
                    .pcurve
                    .evaluate(p0 + (p1 - p0) * sample as f64 / 32.0)?;
                u_low = u_low.min(uv.x);
                u_high = u_high.max(uv.x);
                v_mean += uv.y / 33.0;
            }
            let u_span = su1 - su0;
            if (u_low - su0).abs() > u_span * 1e-3 || (u_high - su1).abs() > u_span * 1e-3 {
                continue 'carrier;
            }
            // The rim must bound a PLANAR opening face as an INNER loop.
            let Some(opening) = source_faces.iter().find(|face| {
                opening_set.contains(&face.id)
                    && face
                        .loops
                        .iter()
                        .flat_map(|loop_record| &loop_record.coedges)
                        .any(|coedge| coedge.edge_id == rim_edge.id)
            }) else {
                continue 'carrier;
            };
            let Some((plane_point, plane_normal)) =
                planar_surface_frame(&opening.surface, weld_band)?
            else {
                continue 'carrier;
            };
            let mut rim_loop_area = None;
            let mut largest_other = 0.0f64;
            for loop_record in &opening.loops {
                let area = parameter_space_area(&FaceRecord {
                    id: 0,
                    surface: opening.surface.clone(),
                    same_sense: true,
                    loops: vec![loop_record.clone()],
                    name: None,
                })?
                .abs();
                if loop_record
                    .coedges
                    .iter()
                    .any(|coedge| coedge.edge_id == rim_edge.id)
                {
                    rim_loop_area = Some(area);
                } else {
                    largest_other = largest_other.max(area);
                }
            }
            let Some(rim_loop_area) = rim_loop_area else {
                continue 'carrier;
            };
            if rim_loop_area >= largest_other {
                continue 'carrier;
            }
            // The offset image of the rim must genuinely leave the plane
            // (the carrier mirrors the source loop/coedge structure 1:1).
            let image_coedge = &carrier_face.loops[*loop_index].coedges[*coedge_index];
            let Some(image_edge) = carriers[index]
                .solid
                .edges
                .iter()
                .find(|edge| edge.id == image_coedge.edge_id)
            else {
                continue 'carrier;
            };
            let mut off_plane = 0.0f64;
            for sample in 0..=32 {
                let point = image_edge.curve.evaluate(
                    image_edge.t0 + (image_edge.t1 - image_edge.t0) * sample as f64 / 32.0,
                )?;
                off_plane = off_plane.max(point.sub(plane_point).dot(plane_normal).abs());
            }
            if off_plane <= weld_band {
                continue 'carrier;
            }
            rim_planes.push((v_mean, plane_point, plane_normal));
        }
        // Pair each surface v-domain end with the opening plane of the rim
        // nearer to it, and require the extended isoline to clear that plane
        // on the far side (opposite the band interior).
        rim_planes.sort_by(|first, second| first.0.total_cmp(&second.0));
        let interior = surface.evaluate((su0 + su1) * 0.5, v_mid)?;
        for (v_end, (_, plane_point, plane_normal)) in [(sv0, rim_planes[0]), (sv1, rim_planes[1])]
        {
            let interior_sign = interior.sub(plane_point).dot(plane_normal).signum();
            let iso = surface.iso_curve_v(v_end)?;
            let [t0, t1] = iso.domain()?;
            for sample in 0..=32 {
                let point = iso.evaluate(t0 + (t1 - t0) * sample as f64 / 32.0)?;
                if point.sub(plane_point).dot(plane_normal) * interior_sign > -weld_band {
                    continue 'carrier;
                }
            }
        }
        // Rebuild the carrier as the full-domain band with exact isoline
        // rims — structurally the same face a freshly made cylinder/cone
        // side carries, which is the arrangement's best-tested input.
        let winding = parameter_space_area(&carrier_face)?;
        let bottom_rim = surface.iso_curve_v(sv0)?;
        let top_rim = surface.iso_curve_v(sv1)?;
        let seam = surface.iso_curve_u(su0)?;
        let [bottom_t0, bottom_t1] = bottom_rim.domain()?;
        let [top_t0, top_t1] = top_rim.domain()?;
        let corner_bottom = surface.evaluate(su0, sv0)?;
        let corner_top = surface.evaluate(su0, sv1)?;
        let flat = |u: f64, v: f64| Vec3::new(u, v, 0.0);
        let mut coedges = vec![
            CoedgeRecord {
                id: 1,
                edge_id: 1,
                forward: true,
                pcurve: crate::make_line(flat(su0, sv0), flat(su1, sv0))?,
            },
            CoedgeRecord {
                id: 2,
                edge_id: 3,
                forward: true,
                pcurve: crate::make_line(flat(su1, sv0), flat(su1, sv1))?,
            },
            CoedgeRecord {
                id: 3,
                edge_id: 2,
                forward: false,
                pcurve: crate::make_line(flat(su1, sv1), flat(su0, sv1))?,
            },
            CoedgeRecord {
                id: 4,
                edge_id: 3,
                forward: false,
                pcurve: crate::make_line(flat(su0, sv1), flat(su0, sv0))?,
            },
        ];
        if winding < 0.0 {
            coedges.reverse();
            for coedge in &mut coedges {
                coedge.forward = !coedge.forward;
                coedge.pcurve = coedge.pcurve.reversed()?;
            }
        }
        os_debug!(
            "carrier[{index}] src={} extended past opening planes: band v=({sv0:.4},{sv1:.4})",
            carriers[index].source_face_id,
        );
        carriers[index].solid = BrepSolid {
            id: carriers[index].solid.id,
            vertices: vec![
                VertexRecord {
                    id: 1,
                    point: corner_bottom,
                },
                VertexRecord {
                    id: 2,
                    point: corner_top,
                },
            ],
            edges: vec![
                EdgeRecord {
                    id: 1,
                    curve: bottom_rim,
                    t0: bottom_t0,
                    t1: bottom_t1,
                    start_vertex_id: 1,
                    end_vertex_id: 1,
                    degenerate: false,
                    name: None,
                },
                EdgeRecord {
                    id: 2,
                    curve: top_rim,
                    t0: top_t0,
                    t1: top_t1,
                    start_vertex_id: 2,
                    end_vertex_id: 2,
                    degenerate: false,
                    name: None,
                },
                EdgeRecord {
                    id: 3,
                    curve: seam,
                    t0: sv0,
                    t1: sv1,
                    start_vertex_id: 1,
                    end_vertex_id: 2,
                    degenerate: false,
                    name: None,
                },
            ],
            shells: vec![ShellRecord {
                id: 1,
                faces: vec![FaceRecord {
                    id: carrier_face.id,
                    surface,
                    same_sense: carrier_face.same_sense,
                    loops: vec![LoopRecord { id: 1, coedges }],
                    name: carrier_face.name.clone(),
                }],
            }],
            genus: 0,
        };
        extended.insert(index);
    }
    Ok(extended)
}

/// Fall-short curved carriers: the sibling disease to the oblique-bore lane
/// above, on the OTHER side of the opening. When a retained CURVED face meets
/// an opening face and its centre of curvature lies BEYOND the opening
/// surface, the offset image of the shared rim moves INTO the material —
/// radial offsetting scales the trim away from the plane. E.g. a sphere gouge
/// whose centre sits outside the box: cavity radius r offsets to r+d, and a
/// rim point p on the opening plane maps to c + (r+d)/r·(p−c), strictly on
/// the material side whenever c is beyond the plane. The trimmed carrier then
/// NEVER reaches the opening surface, the carrier × opening-wall SSI finds
/// nothing (correctly — the trimmed patches are disjoint), the offset skin
/// ends mid-air, and the honesty gate refuses the shell.
///
/// The cure is the oblique lane's cure: rebuild the qualifying carrier's trim
/// so the surface reaches THROUGH the opening plane and let the arrangement
/// cut it back with the exact plane × quadric section. Here the trim becomes
/// the surface's FULL domain (a gouge rim is a partial arc chain against the
/// opening's outer loop — there is no band structure to preserve); a pole at
/// a v-domain end collapses to a degenerate edge exactly like a freshly made
/// sphere face, the arrangement's best-tested input.
///
/// Qualification (narrow, so every landed lane keeps its path):
/// - Offset carrier, curved, not smooth-paired, not rebuilt by the oblique
///   lane above;
/// - the source face shares a non-degenerate edge with a PLANAR opening face;
/// - that rim's offset image falls ENTIRELY on the material side of the
///   opening plane (beyond the weld band) — an image that reaches or crosses
///   the plane is the arrangement's ordinary imprint case (it needs no help);
/// - the surface's full domain genuinely crosses the opening plane on the
///   outside — a surface that stops at the opening (cone base, frustum caps)
///   keeps its ruled-weld lane;
/// - the surface closes in u, so the full-domain face is seam-gluable.
pub(super) fn extend_fallshort_curved_carriers(
    carriers: &mut [Carrier],
    source: &BrepSolid,
    source_faces: &[&FaceRecord],
    opening_set: &HashSet<u64>,
    smooth_pairs: &HashSet<(usize, usize)>,
    already_extended: &HashSet<usize>,
    scale: f64,
    distance: f64,
) -> Result<usize, String> {
    let weld_band = 2e-3f64.max(scale * 5e-5);
    let source_edge_by_id = source
        .edges
        .iter()
        .map(|edge| (edge.id, edge))
        .collect::<HashMap<_, _>>();
    let mut extended = 0usize;
    'carrier: for index in 0..carriers.len() {
        if !matches!(carriers[index].kind, OffsetFaceRole::Offset)
            || already_extended.contains(&index)
        {
            continue;
        }
        if smooth_pairs
            .iter()
            .any(|(first, second)| *first == index || *second == index)
        {
            continue;
        }
        let Some(source_face) = source_faces
            .iter()
            .find(|face| face.id == carriers[index].source_face_id)
        else {
            continue;
        };
        // Affine carriers translate along their normal: the shared rim's
        // image stays on the opening surface by construction.
        if source_face.surface.is_affine()? {
            continue;
        }
        let carrier_face = carriers[index].solid.shells[0].faces[0].clone();
        let surface = carrier_face.surface.clone();
        let [su0, su1] = surface.domain_u()?;
        let [sv0, sv1] = surface.domain_v()?;
        let v_mid = (sv0 + sv1) * 0.5;
        // The full-domain rebuild needs a seam-gluable (u-closed) surface.
        if surface
            .evaluate(su0, v_mid)?
            .sub(surface.evaluate(su1, v_mid)?)
            .length()
            > weld_band
        {
            continue;
        }
        let mut qualifies = false;
        'rims: for (loop_index, loop_record) in source_face.loops.iter().enumerate() {
            for (coedge_index, coedge) in loop_record.coedges.iter().enumerate() {
                let Some(edge) = source_edge_by_id.get(&coedge.edge_id) else {
                    continue;
                };
                if edge.degenerate {
                    continue;
                }
                let Some(opening) = source_faces.iter().find(|face| {
                    opening_set.contains(&face.id)
                        && face
                            .loops
                            .iter()
                            .flat_map(|loop_record| &loop_record.coedges)
                            .any(|other| other.edge_id == coedge.edge_id)
                }) else {
                    continue;
                };
                let Some((plane_point, mut plane_normal)) =
                    planar_surface_frame(&opening.surface, weld_band)?
                else {
                    continue;
                };
                // Orient the plane normal OUTWARD (off the material) via the
                // opening face's own oriented normal. A revolved cap's
                // parameterization can be degenerate at some boundary uv
                // (partials vanish on the axis) — probe coedge midpoints
                // until one yields a normal; none at all disqualifies the rim
                // rather than failing the whole shell.
                let Some(outward) = opening
                    .loops
                    .iter()
                    .flat_map(|loop_record| &loop_record.coedges)
                    .find_map(|opening_coedge| {
                        let [p0, p1] = opening_coedge.pcurve.domain().ok()?;
                        let opening_uv =
                            opening_coedge.pcurve.evaluate((p0 + p1) * 0.5).ok()?;
                        face_normal(opening, opening_uv.x, opening_uv.y).ok()
                    })
                else {
                    continue;
                };
                if plane_normal.dot(outward) < 0.0 {
                    plane_normal = plane_normal.scale(-1.0);
                }
                // A CLOSED full rim on the opening's OUTER loop is the ruled
                // weld's territory (a dome/frustum lateral ending at its cap:
                // the exact band between the coaxial rims is the landed
                // closure). A closed rim qualifies here only as an INNER
                // (hole) loop — a pocket carved interior to the opening face.
                // Open arc chains (a gouge across the face's outer boundary)
                // always qualify: no band structure exists for them.
                if edge.start_vertex_id == edge.end_vertex_id {
                    let mut rim_loop_area = None;
                    let mut largest_other = 0.0f64;
                    for loop_record in &opening.loops {
                        let area = parameter_space_area(&FaceRecord {
                            id: 0,
                            surface: opening.surface.clone(),
                            same_sense: true,
                            loops: vec![loop_record.clone()],
                            name: None,
                        })?
                        .abs();
                        if loop_record
                            .coedges
                            .iter()
                            .any(|other| other.edge_id == coedge.edge_id)
                        {
                            rim_loop_area = Some(area);
                        } else {
                            largest_other = largest_other.max(area);
                        }
                    }
                    let Some(rim_loop_area) = rim_loop_area else {
                        continue;
                    };
                    if rim_loop_area >= largest_other {
                        continue;
                    }
                }
                // Fall-short: the rim's offset image sits strictly on the
                // material side (the carrier mirrors the source loop/coedge
                // structure 1:1 — a missing mirror means another lane already
                // reshaped this carrier).
                let Some(image_coedge) = carrier_face
                    .loops
                    .get(loop_index)
                    .and_then(|loop_record| loop_record.coedges.get(coedge_index))
                else {
                    continue 'carrier;
                };
                let Some(image_edge) = carriers[index]
                    .solid
                    .edges
                    .iter()
                    .find(|edge| edge.id == image_coedge.edge_id)
                else {
                    continue 'carrier;
                };
                let mut falls_short = true;
                for sample in 0..=16 {
                    let point = image_edge.curve.evaluate(
                        image_edge.t0 + (image_edge.t1 - image_edge.t0) * sample as f64 / 16.0,
                    )?;
                    if point.sub(plane_point).dot(plane_normal) > -weld_band {
                        falls_short = false;
                        break;
                    }
                }
                if !falls_short {
                    continue;
                }
                // The full domain must genuinely cross the opening plane —
                // otherwise extension cannot reach it either and the honest
                // refusal stands.
                let mut crosses = false;
                'grid: for iu in 0..=16 {
                    for iv in 0..=16 {
                        let point = surface.evaluate(
                            su0 + (su1 - su0) * iu as f64 / 16.0,
                            sv0 + (sv1 - sv0) * iv as f64 / 16.0,
                        )?;
                        if point.sub(plane_point).dot(plane_normal) > weld_band {
                            crosses = true;
                            break 'grid;
                        }
                    }
                }
                if crosses {
                    qualifies = true;
                    break 'rims;
                }
            }
        }
        if !qualifies {
            continue;
        }
        if rebuild_carrier_full_domain(
            &mut carriers[index],
            source_face,
            weld_band,
            distance,
            index,
            "a fall-short opening rim",
        )? {
            extended += 1;
        }
    }
    Ok(extended)
}

/// Rebuild an offset carrier as its surface's FULL-DOMAIN face: seam edge
/// used twice, v-domain ends as closed rims — or degenerate point edges when
/// the iso curve collapses (poles), matching a freshly made sphere face. Any
/// interior loops (holes) in the source trim disappear with the rebuild — the
/// surplus sheet is cut back by the imprint pairs + fragment classification.
/// Returns false (carrier untouched) when the surface is not u-closed.
fn rebuild_carrier_full_domain(
    carrier: &mut Carrier,
    source_face: &FaceRecord,
    weld_band: f64,
    distance: f64,
    index: usize,
    reason: &str,
) -> Result<bool, String> {
    let carrier_face = carrier.solid.shells[0].faces[0].clone();
    let mut surface = carrier_face.surface.clone();
    let [mut su0, mut su1] = surface.domain_u()?;
    let [mut sv0, mut sv1] = surface.domain_v()?;
    let v_mid = (sv0 + sv1) * 0.5;
    // The full-domain rebuild needs a seam-gluable (u-closed) surface.
    if surface
        .evaluate(su0, v_mid)?
        .sub(surface.evaluate(su1, v_mid)?)
        .length()
        > weld_band
    {
        return Ok(false);
    }
    // A SPHERE source gets its carrier rebuilt on the EXACT full offset
    // sphere. App-built sphere nets are v-clipped short of a pole, so
    // "full domain" of the fitted offset surface still misses a polar
    // cap; when the offset sphere pokes through the opening plane near
    // that pole (the missing-cap band is only a few degrees wide), the
    // rim arcs the shell needs run through the missing cap, the imprint
    // clips them away, and the loop on this carrier can never close.
    // The analytic rebuild also replaces the Greville fit's pole rows
    // (fit error grows unbounded at a degenerate row) with exact ones.
    if let Some(crate::AnalyticSurface::Sphere { frame, radius }) =
        crate::analytic_surface::recognize(&source_face.surface)
    {
        let mid = surface.evaluate((su0 + su1) * 0.5, (sv0 + sv1) * 0.5)?;
        let measured = mid.sub(frame.origin).length();
        let grown = radius + distance.abs();
        let shrunk = (radius - distance.abs()).abs();
        // The fitted carrier disambiguates cavity (grown) vs boss
        // (shrunk); the analytic radius itself stays exact.
        let target = if (measured - grown).abs() <= (measured - shrunk).abs() {
            grown
        } else {
            shrunk
        };
        if (measured - target).abs() <= weld_band.max(distance.abs() * 0.5) && target > weld_band {
            let full = crate::make_sphere_surface(frame.origin, target, frame.axis)?;
            let [fu0, fu1] = full.domain_u()?;
            let [fv0, fv1] = full.domain_v()?;
            let old_normal = surface.normal((su0 + su1) * 0.5, (sv0 + sv1) * 0.5)?;
            let radial = mid.sub(frame.origin).normalized()?;
            let sample = full.evaluate((fu0 + fu1) * 0.5, (fv0 + fv1) * 0.5)?;
            let new_normal = full.normal((fu0 + fu1) * 0.5, (fv0 + fv1) * 0.5)?;
            let new_radial = sample.sub(frame.origin).normalized()?;
            // The rebuilt net must agree with the fitted carrier on which
            // side the surface normal faces; a mismatch would silently
            // invert the face, so refuse the rebuild instead (the honest
            // refusal downstream is strictly better than a wrong solid).
            if (old_normal.dot(radial) > 0.0) == (new_normal.dot(new_radial) > 0.0) {
                os_debug!("carrier[{index}] rebuilt on the exact full offset sphere r={target:.6}");
                surface = full;
                (su0, su1, sv0, sv1) = (fu0, fu1, fv0, fv1);
            } else {
                os_debug!("carrier[{index}] sphere rebuild skipped: orientation mismatch");
            }
        } else {
            os_debug!(
                "carrier[{index}] sphere rebuild skipped: measured radius {measured:.6} \
                 matches neither grown nor shrunk offset of {radius:.6}"
            );
        }
    }
    let winding = parameter_space_area(&carrier_face)?;
    let pole_point = |iso: &crate::NurbsCurve| -> Result<Option<Vec3>, String> {
        let [t0, t1] = iso.domain()?;
        let anchor = iso.evaluate(t0)?;
        let mut deviation = 0.0f64;
        for sample in 1..=8 {
            let point = iso.evaluate(t0 + (t1 - t0) * sample as f64 / 8.0)?;
            deviation = deviation.max(point.sub(anchor).length());
        }
        os_debug!("  pole probe: max deviation {deviation:.6}");
        Ok((deviation <= weld_band).then_some(anchor))
    };
    let bottom_iso = surface.iso_curve_v(sv0)?;
    let top_iso = surface.iso_curve_v(sv1)?;
    let bottom_pole = pole_point(&bottom_iso)?;
    let top_pole = pole_point(&top_iso)?;
    let corner_bottom = surface.evaluate(su0, sv0)?;
    let corner_top = surface.evaluate(su0, sv1)?;
    let seam = surface.iso_curve_u(su0)?;
    let v_end_edge = |id: u64,
                      iso: crate::NurbsCurve,
                      pole: Option<Vec3>,
                      vertex: u64|
     -> Result<EdgeRecord, String> {
        Ok(match pole {
            Some(point) => EdgeRecord {
                id,
                curve: crate::make_line(point, point)?,
                t0: 0.0,
                t1: 1.0,
                start_vertex_id: vertex,
                end_vertex_id: vertex,
                degenerate: true,
                name: None,
            },
            None => {
                let [t0, t1] = iso.domain()?;
                EdgeRecord {
                    id,
                    curve: iso,
                    t0,
                    t1,
                    start_vertex_id: vertex,
                    end_vertex_id: vertex,
                    degenerate: false,
                    name: None,
                }
            }
        })
    };
    let flat = |u: f64, v: f64| Vec3::new(u, v, 0.0);
    let mut coedges = vec![
        CoedgeRecord {
            id: 1,
            edge_id: 1,
            forward: true,
            pcurve: crate::make_line(flat(su0, sv0), flat(su1, sv0))?,
        },
        CoedgeRecord {
            id: 2,
            edge_id: 3,
            forward: true,
            pcurve: crate::make_line(flat(su1, sv0), flat(su1, sv1))?,
        },
        CoedgeRecord {
            id: 3,
            edge_id: 2,
            forward: false,
            pcurve: crate::make_line(flat(su1, sv1), flat(su0, sv1))?,
        },
        CoedgeRecord {
            id: 4,
            edge_id: 3,
            forward: false,
            pcurve: crate::make_line(flat(su0, sv1), flat(su0, sv0))?,
        },
    ];
    if winding < 0.0 {
        coedges.reverse();
        for coedge in &mut coedges {
            coedge.forward = !coedge.forward;
            coedge.pcurve = coedge.pcurve.reversed()?;
        }
    }
    os_debug!(
        "carrier[{index}] src={} extended to full domain past {reason} \
         (poles: bottom={} top={})",
        carrier.source_face_id,
        bottom_pole.is_some(),
        top_pole.is_some(),
    );
    carrier.solid = BrepSolid {
        id: carrier.solid.id,
        vertices: vec![
            VertexRecord {
                id: 1,
                point: corner_bottom,
            },
            VertexRecord {
                id: 2,
                point: corner_top,
            },
        ],
        edges: vec![
            v_end_edge(1, bottom_iso, bottom_pole, 1)?,
            v_end_edge(2, top_iso, top_pole, 2)?,
            EdgeRecord {
                id: 3,
                curve: seam,
                t0: sv0,
                t1: sv1,
                start_vertex_id: 1,
                end_vertex_id: 2,
                degenerate: false,
                name: None,
            },
        ],
        shells: vec![ShellRecord {
            id: 1,
            faces: vec![FaceRecord {
                id: carrier_face.id,
                surface,
                same_sense: carrier_face.same_sense,
                loops: vec![LoopRecord { id: 1, coedges }],
                name: carrier_face.name.clone(),
            }],
        }],
        genus: 0,
    };
    Ok(true)
}

/// REFLEX-RIM lane: an offset carrier whose (curved, u-closed) source face
/// joins a RETAINED neighbour at a reflex edge cannot keep its source-sized
/// trim — the true offset∩offset junction lies PAST the cloned rim (miter
/// overshoot), and when the rim is an interior loop (a boss piercing the
/// face: cylinder through a cone) or a mid-surface arc, no amount of trim
/// stretching re-covers it (a hole excludes the junction band in uv
/// outright). Rebuild such carriers as full-domain faces: the imprint pairs
/// then carve the true junction into BOTH sheets as one shared cut and the
/// surplus is dropped by fragment classification. Runs on BOTH attempts (not
/// gated behind the extension retry): without it these shells close WRONGLY
/// (membrane caps over each rim copy), which is worse than any refusal.
pub(super) fn rebuild_reflex_rim_carriers(
    carriers: &mut [Carrier],
    source: &BrepSolid,
    source_faces: &[&FaceRecord],
    smooth_pairs: &HashSet<(usize, usize)>,
    scale: f64,
    distance: f64,
) -> Result<HashSet<usize>, String> {
    let weld_band = 2e-3f64.max(scale * 5e-5);
    let mut rebuilt = HashSet::default();
    for index in 0..carriers.len() {
        if !matches!(carriers[index].kind, OffsetFaceRole::Offset) {
            continue;
        }
        if smooth_pairs
            .iter()
            .any(|(first, second)| *first == index || *second == index)
        {
            continue;
        }
        let Some(source_face) = source_faces
            .iter()
            .find(|face| face.id == carriers[index].source_face_id)
        else {
            continue;
        };
        if source_face.surface.is_affine()? {
            continue;
        }
        if face_reflex_miter_tan(source, source_face)?.is_none() {
            continue;
        }
        if rebuild_carrier_full_domain(
            &mut carriers[index],
            source_face,
            weld_band,
            distance,
            index,
            "a reflex junction rim",
        )? {
            rebuilt.insert(index);
        }
    }
    Ok(rebuilt)
}

/// When `face` meets a neighbour at a REFLEX (concave) edge — the material
/// dihedral exceeds π (a pocket's internal corner: material wraps 270° around
/// the edge) — returns the WORST miter factor tan(θn/2) over samples along
/// its reflex edges, where θn is the angle between the two faces' outward
/// normals. At such an edge this face's offset skin must GROW past the source
/// footprint to reach the neighbour's offset: the offsets meet at arc
/// overshoot d·tan(θn/2) past the source rim (d for a perpendicular join,
/// unbounded as the join becomes tangential), so a flat d-sized extension
/// only covers joins at 90° or steeper. Sign convention verified on a box
/// (all edges convex → cross·tangent > 0 with the coedge-oriented tangent);
/// a smooth/tangent join (|n1×n2| ≈ 0) is neither. `None` = no reflex edge.
pub(super) fn face_reflex_miter_tan(source: &BrepSolid, face: &FaceRecord) -> Result<Option<f64>, String> {
    let edge_by_id = source
        .edges
        .iter()
        .map(|edge| (edge.id, edge))
        .collect::<HashMap<_, _>>();
    let faces = source
        .shells
        .iter()
        .flat_map(|shell| &shell.faces)
        .collect::<Vec<_>>();
    let mut worst: Option<f64> = None;
    for loop_record in &face.loops {
        for coedge in &loop_record.coedges {
            let Some(edge) = edge_by_id.get(&coedge.edge_id) else {
                continue;
            };
            if edge.degenerate {
                continue;
            }
            let Some((mate, mate_coedge)) = faces.iter().find_map(|other| {
                if other.id == face.id {
                    return None;
                }
                other
                    .loops
                    .iter()
                    .flat_map(|loop_record| &loop_record.coedges)
                    .find(|other_coedge| other_coedge.edge_id == coedge.edge_id)
                    .map(|other_coedge| (*other, other_coedge))
            }) else {
                continue;
            };
            // The crossing angle varies along a curved junction (a cylinder
            // piercing a cone runs from steep to shallow around the quartic
            // rim) — sample several stations and keep the worst miter.
            for fraction in [0.1f64, 0.3, 0.5, 0.7, 0.9] {
                let t_sample = edge.t0 + (edge.t1 - edge.t0) * fraction;
                let step = ((edge.t1 - edge.t0) * 1e-3).max(1e-9);
                let before = edge.curve.evaluate(t_sample - step)?;
                let after = edge.curve.evaluate(t_sample + step)?;
                let mut tangent = after.sub(before);
                if tangent.length() <= 1e-12 {
                    continue;
                }
                if !coedge.forward {
                    tangent = tangent.scale(-1.0);
                }
                let this_fraction = if coedge.forward { fraction } else { 1.0 - fraction };
                let mate_fraction = if mate_coedge.forward { fraction } else { 1.0 - fraction };
                let uv_this = {
                    let [a, b] = coedge.pcurve.domain()?;
                    coedge.pcurve.evaluate(a + (b - a) * this_fraction)?
                };
                let uv_mate = {
                    let [a, b] = mate_coedge.pcurve.domain()?;
                    mate_coedge.pcurve.evaluate(a + (b - a) * mate_fraction)?
                };
                let n_this = face_normal(face, uv_this.x, uv_this.y)?;
                let n_mate = face_normal(mate, uv_mate.x, uv_mate.y)?;
                let cross = n_this.cross(n_mate);
                if cross.length() <= 1e-6 {
                    continue;
                }
                if cross.dot(tangent) < 0.0 {
                    let cos_normals = n_this.dot(n_mate).clamp(-1.0, 1.0);
                    let half = cos_normals.acos() * 0.5;
                    worst = Some(worst.unwrap_or(0.0).max(half.tan()));
                }
            }
        }
    }
    Ok(worst)
}

pub(super) fn source_by_id_lookup<'a>(
    source_faces: &[&'a FaceRecord],
    face_id: u64,
) -> Option<&'a FaceRecord> {
    source_faces.iter().find(|face| face.id == face_id).copied()
}

pub(super) fn sample_separation(first: &[Vec3], second: &[Vec3]) -> f64 {
    first
        .iter()
        .flat_map(|a| second.iter().map(move |b| a.sub(*b).length()))
        .fold(f64::INFINITY, f64::min)
}

pub(super) fn opening_wall_seeds(
    opening: &FaceRecord,
    carrier: &FaceRecord,
    source: &BrepSolid,
    opening_set: &HashSet<u64>,
    distance: f64,
) -> Result<Vec<Vec2>, String> {
    let source_faces = source
        .shells
        .iter()
        .flat_map(|shell| &shell.faces)
        .collect::<Vec<_>>();
    let mut seeds = Vec::new();
    for opening_use in opening
        .loops
        .iter()
        .flat_map(|loop_record| &loop_record.coedges)
    {
        let Some((neighbor, neighbor_use)) = source_faces.iter().find_map(|face| {
            if face.id == opening.id || opening_set.contains(&face.id) {
                return None;
            }
            face.loops
                .iter()
                .flat_map(|loop_record| &loop_record.coedges)
                .find(|coedge| coedge.edge_id == opening_use.edge_id)
                .map(|coedge| (*face, coedge))
        }) else {
            continue;
        };
        let [opening_start, opening_end] = opening_use.pcurve.domain()?;
        let opening_uv = opening_use
            .pcurve
            .evaluate((opening_start + opening_end) * 0.5)?;
        let original = opening.surface.evaluate(opening_uv.x, opening_uv.y)?;
        let [neighbor_start, neighbor_end] = neighbor_use.pcurve.domain()?;
        let neighbor_uv = neighbor_use
            .pcurve
            .evaluate((neighbor_start + neighbor_end) * 0.5)?;
        // The opening point stepped off along the NEIGHBOUR's offset direction:
        // the shared evaluator's normal, but anchored at a point on a different
        // face, so only the direction is borrowed.
        let expected = original.add(
            face_offsets(neighbor)
                .normal(neighbor_uv.x, neighbor_uv.y)?
                .scale(-distance),
        );
        let halfway = original.add(expected.sub(original).scale(0.5));
        let projection = project_point_to_surface(&carrier.surface, halfway)?;
        seeds.push(Vec2 {
            x: projection.u,
            y: projection.v,
        });
    }
    Ok(seeds)
}