BREP_kernel 0.13.2

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
use crate::KernelRefusal;
use super::*;
use super::edge_conform::edge_lies_on;

/// Last-resort weld for a CLOSED assembly still carrying one-use edges: two
/// geometrically IDENTICAL one-use edges (same span, mutually coincident within
/// tolerance) are one shared boundary that fragmentation duplicated instead of
/// welding — an FP-sensitive miss in `Assembler::edge` (observed only under the
/// wasm build when unioning an extruded partial-revolve SECTOR face back onto
/// its revolve, where a residual off-axis apex leaves near-coincident arc
/// slivers). `conform_overlapping_one_use_edges` only handles PARTIAL overlaps
/// (it splits at a partner's interior vertex); identical spans have no interior
/// split point and slip through. Redirect every coedge of the duplicate onto
/// the survivor with matching orientation so the edge becomes two-use and the
/// shell closes; the now-unused duplicate is dropped by the later
/// used-edge retain. A one-use edge only exists in an ALREADY-BROKEN closed
/// assembly, so this cannot alter a well-formed result, and `validate()` still
/// guards the output.
pub(super) fn weld_identical_coincident_one_use_edges(
    assembler: &mut Assembler,
    faces: &mut [FaceRecord],
) -> Result<bool, KernelRefusal> {
    let mut use_counts = HashMap::<u64, usize>::default();
    for coedge in faces
        .iter()
        .flat_map(|face| &face.loops)
        .flat_map(|loop_record| &loop_record.coedges)
    {
        *use_counts.entry(coedge.edge_id).or_default() += 1;
    }
    let vertex_map = assembler
        .vertices
        .iter()
        .map(|vertex| (vertex.id, vertex.point))
        .collect::<HashMap<_, _>>();
    let one_use = assembler
        .edges
        .iter()
        .filter(|edge| use_counts.get(&edge.id) == Some(&1) && !edge.degenerate)
        .cloned()
        .collect::<Vec<_>>();
    if one_use.len() < 2 {
        return Ok(false);
    }
    let tolerance = assembler.tolerance.max(1e-3);
    // duplicate edge id -> (survivor id, flip coedge orientation)
    let mut redirect = HashMap::<u64, (u64, bool)>::default();
    // Sharing an edge also identifies its two endpoint pairs. Leaving the
    // duplicate's neighbours on separate vertices opens their loops even when
    // every edge has two coedges. Plan the endpoint identifications atomically,
    // rejecting any plan that would collapse an existing non-degenerate edge.
    let mut vertex_redirect = HashMap::<u64, u64>::default();
    fn root(redirect: &HashMap<u64, u64>, mut id: u64) -> u64 {
        while let Some(&next) = redirect.get(&id) {
            id = next;
        }
        id
    }
    for (index, survivor) in one_use.iter().enumerate() {
        if redirect.contains_key(&survivor.id) {
            continue;
        }
        let survivor_start = vertex_map[&survivor.start_vertex_id];
        let survivor_end = vertex_map[&survivor.end_vertex_id];
        for duplicate in one_use.iter().skip(index + 1) {
            if redirect.contains_key(&duplicate.id) {
                continue;
            }
            let duplicate_start = vertex_map[&duplicate.start_vertex_id];
            let duplicate_end = vertex_map[&duplicate.end_vertex_id];
            let aligned_error = survivor_start.sub(duplicate_start).length()
                .max(survivor_end.sub(duplicate_end).length());
            let reversed_error = survivor_start.sub(duplicate_end).length()
                .max(survivor_end.sub(duplicate_start).length());
            let aligned = aligned_error <= tolerance;
            let reversed = reversed_error <= tolerance;
            if !aligned && !reversed {
                continue;
            }
            // Endpoint coincidence alone can pair a chord with a bulged arc:
            // require the whole spans to lie on each other before welding.
            let coincident_span = (edge_lies_on(survivor, duplicate, tolerance)?
                && edge_lies_on(duplicate, survivor, tolerance)?)
                // Endpoint coincidence is already established by `aligned`/
                // `reversed`. When a duplicate's CURVE endpoint drifts a whisker
                // off its own vertex (an imported SSI endpoint a couple 1e-4
                // short — the very corner that also broke the face-111 cut), its
                // 0.0/1.0 samples project just OUTSIDE the survivor's [0,1] span,
                // so the full-span `edge_lies_on` spuriously fails one direction
                // on a fraction-range technicality while the spans genuinely
                // coincide. Fall back to an INTERIOR-only span check (0.25/0.5/
                // 0.75) for a pair whose endpoints already match. Additive: only
                // rescues welds the strict test rejects, and a chord-vs-bulged-
                // arc still fails because the interior sagitta exceeds tolerance.
                || (edge_interior_lies_on(survivor, duplicate, tolerance)?
                    && edge_interior_lies_on(duplicate, survivor, tolerance)?);
            if !coincident_span {
                continue;
            }
            // A short edge can fit BOTH endpoint correspondences inside the
            // repair band. The band admits the weld; the closer correspondence
            // determines its direction. Otherwise an aligned micro-edge is
            // reversed merely because its length is smaller than the band.
            let flip = reversed && (!aligned || reversed_error <= aligned_error);
            let mut proposed = vertex_redirect.clone();
            let pairs = if flip {
                [(duplicate.start_vertex_id, survivor.end_vertex_id),
                 (duplicate.end_vertex_id, survivor.start_vertex_id)]
            } else {
                [(duplicate.start_vertex_id, survivor.start_vertex_id),
                 (duplicate.end_vertex_id, survivor.end_vertex_id)]
            };
            for (from, to) in pairs {
                let (from, to) = (root(&proposed, from), root(&proposed, to));
                if from != to {
                    proposed.insert(from, to);
                }
            }
            if proposed.keys().any(|id|
                vertex_map[id].sub(vertex_map[&root(&proposed, *id)]).length() > tolerance
            ) || assembler.edges.iter().any(|edge| {
                !edge.degenerate && edge.start_vertex_id != edge.end_vertex_id
                    && root(&proposed, edge.start_vertex_id)
                        == root(&proposed, edge.end_vertex_id)
            }) {
                continue;
            }
            vertex_redirect = proposed;
            redirect.insert(duplicate.id, (survivor.id, flip));
        }
    }
    if redirect.is_empty() {
        return Ok(false);
    }
    for edge in &mut assembler.edges {
        let start = root(&vertex_redirect, edge.start_vertex_id);
        let end = root(&vertex_redirect, edge.end_vertex_id);
        if start == edge.start_vertex_id && end == edge.end_vertex_id {
            continue;
        }
        let curve = super::builder::snap_edge_curve_endpoints(
            edge.curve.clone(), edge.t0, edge.t1,
            vertex_map[&start], vertex_map[&end],
        )?;
        let [t0, t1] = curve.domain().map_err(|error|
            crate::KernelRefusal::internal(crate::KernelStage::Sew,
                "assemble.refusal_welds", error.to_string()))?;
        edge.curve = curve;
        edge.t0 = t0;
        edge.t1 = t1;
        edge.start_vertex_id = start;
        edge.end_vertex_id = end;
    }
    for face in faces.iter_mut() {
        for loop_record in &mut face.loops {
            for coedge in &mut loop_record.coedges {
                if let Some(&(survivor_id, flip)) = redirect.get(&coedge.edge_id) {
                    coedge.edge_id = survivor_id;
                    if flip {
                        coedge.forward = !coedge.forward;
                    }
                }
            }
        }
    }
    Ok(true)
}

/// Weld near-duplicate vertices left by tangency-degraded SSI endpoints (see
/// call site).  Greedy nearest-first over pairs closer than a √tol-scaled band,
/// skipping pairs already joined by a non-degenerate edge (welding those would
/// collapse the edge).  The survivor is the vertex its incident curve endpoints
/// agree with best (the operand's exact vertex, not the marched seam end); the
/// loser's edges are re-pointed and any curve endpoint that no longer lands on
/// the surviving vertex is clamped onto it (only when the edge parameter is the
/// curve's own domain end, so trimmed sub-curves are never distorted).  Returns
/// the number of welds performed.  One weld per Euler deficit unit is enough,
/// but the caller re-checks the genus, so welding stops via the pair list.
pub(super) fn weld_tangency_duplicate_vertices(
    vertices: &mut Vec<VertexRecord>,
    edges: &mut [EdgeRecord],
    tolerance: f64,
    limit: usize,
) -> usize {
    let band = tangency_weld_band(vertices, tolerance);

    let mut connected = rustc_hash::FxHashSet::<(u64, u64)>::default();
    for edge in edges.iter().filter(|edge| !edge.degenerate) {
        let (a, b) = (edge.start_vertex_id, edge.end_vertex_id);
        connected.insert((a.min(b), a.max(b)));
    }

    let mut pairs: Vec<(f64, u64, u64)> = Vec::new();
    for (i, a) in vertices.iter().enumerate() {
        for b in vertices.iter().skip(i + 1) {
            let distance = a.point.sub(b.point).length();
            if distance < band && !connected.contains(&(a.id.min(b.id), a.id.max(b.id))) {
                pairs.push((distance, a.id, b.id));
            }
        }
    }
    pairs.sort_by(|x, y| x.0.partial_cmp(&y.0).expect("finite distances"));

    let endpoint_error = vertex_endpoint_error;

    let mut welds = 0usize;
    for (_, a, b) in pairs {
        // `limit` caps welds per call so the caller can DEFICIT-GATE: weld one
        // pair, recompute the genus, and stop the instant it is integral. The
        // greedy pair list contains more merges than the Euler deficit requires
        // (every duplicate vertex, not just the deficit count), so welding it to
        // exhaustion OVERSHOOTS an integral state back to non-integral (observed:
        // deficit -1, two duplicates, welding both lands at +1). Stopping at the
        // deficit keeps the genuine tangent-seam merges without inventing a
        // spurious pinch from a coincidence the assembly did not need closed.
        if welds >= limit {
            break;
        }
        if !vertices.iter().any(|v| v.id == a) || !vertices.iter().any(|v| v.id == b) {
            continue; // already consumed by an earlier weld
        }
        let (survivor, loser) =
            if endpoint_error(vertices, edges, a) <= endpoint_error(vertices, edges, b) {
                (a, b)
            } else {
                (b, a)
            };
        weld_vertex_onto(vertices, edges, loser, survivor, band);
        welds += 1;
    }
    welds
}

/// Weld band of the tangency repairs: tangent-order marching drift is
/// O(√tol·scale); 10× headroom, floored at the model tolerance itself.
fn tangency_weld_band(vertices: &[VertexRecord], tolerance: f64) -> f64 {
    let scale = vertices
        .iter()
        .map(|v| v.point.length())
        .fold(1.0_f64, f64::max);
    (tolerance.max(1e-12).sqrt() * scale * 10.0).max(tolerance * 10.0)
}

/// How well a vertex's incident curve endpoints agree with its position —
/// the exact operand vertex scores ~0, a drifted section endpoint ~O(band).
fn vertex_endpoint_error(vertices: &[VertexRecord], edges: &[EdgeRecord], id: u64) -> f64 {
    let point = match vertices.iter().find(|v| v.id == id) {
        Some(v) => v.point,
        None => return f64::INFINITY,
    };
    let mut worst = 0.0_f64;
    for edge in edges.iter().filter(|edge| !edge.degenerate) {
        if edge.start_vertex_id == id {
            if let Ok(p) = edge.curve.evaluate(edge.t0) {
                worst = worst.max(p.sub(point).length());
            }
        }
        if edge.end_vertex_id == id {
            if let Ok(p) = edge.curve.evaluate(edge.t1) {
                worst = worst.max(p.sub(point).length());
            }
        }
    }
    worst
}

/// OPEN-CORNER WELD (repair-not-refuse): a loop whose consecutive SECTION
/// coedges end on two DIFFERENT vertices within the tangency band is welded
/// shut there.
///
/// Where two section curves cross at an isolated tangent node — the two
/// ellipses of an equal-radius cylinder pair meet at the points where the
/// cylinders are tangent — each curve is split at the node by its own face's
/// arrangement, and the two split points disagree by the arrangement's chord
/// error (measured 1.4e-5 on the 2026-10-11 report's r = 5 pair, against the
/// assembler's 1e-7 vertex weld). A loop that walks from one curve onto the
/// other at the node then has an open corner: the result a SUBTRACT leaves
/// there (the cut body pinched into two pieces touching at the node) carries
/// eight of them and refused as `invalid topology`, while the union's and
/// the intersection's single-shell results happened to be caught by the
/// Euler-gated duplicate-vertex weld below — a gate that reads `2S − χ` and
/// is blind to a pinch BETWEEN two shells, whose shared vertex keeps the
/// count integral.
///
/// The node's signature is a corner where BOTH coedges are section edges
/// (`section_edges`: the imprint's pieces and the sub-edges the arrangement
/// derived from them, every edge without an operand boundary key): two
/// curves the imprint minted, meeting at two vertices a chord error apart.
/// A corner between a section edge and an
/// operand edge, or between two operand edges, is a different defect — a
/// section clipped short of a rim, a hairline sliver bridging a gap — with
/// its own lanes (`conform_unmatched_one_use_edges`, the heal chain), and
/// welding it pre-empts them: measured on the ABC `00000312#p7 × sphere`
/// fixture, where an unrestricted corner weld chained three vertices into
/// one and closed a sliver edge onto itself. Hence the restriction, and the
/// connectivity test against the LIVE edges before every weld: a pair an
/// edge joins is never welded, however the pass reached it. The survivor is
/// the vertex its incident curves agree with better (the exact node), and
/// the drifted curve endpoints are clamped onto it. Returns the surviving
/// vertex ids (the debug line names them).
pub(super) fn weld_open_loop_corners(
    vertices: &mut Vec<VertexRecord>,
    edges: &mut [EdgeRecord],
    faces: &[FaceRecord],
    section_edges: &HashSet<u64>,
    tolerance: f64,
) -> Vec<u64> {
    let band = tangency_weld_band(vertices, tolerance);
    let debug = std::env::var("BREP_DEBUG_BOOL").is_ok();
    let mut survivors = Vec::new();
    // Welds chain (a corner's loser may be another corner's survivor), so
    // the scan repeats until a pass welds nothing.
    loop {
        let endpoints: HashMap<u64, (u64, u64)> = edges
            .iter()
            .map(|edge| (edge.id, (edge.start_vertex_id, edge.end_vertex_id)))
            .collect();
        let point = |id: u64| vertices.iter().find(|v| v.id == id).map(|v| v.point);
        let mut pairs: Vec<(f64, u64, u64)> = Vec::new();
        for loop_record in faces.iter().flat_map(|face| &face.loops) {
            let count = loop_record.coedges.len();
            for index in 0..count {
                let current = &loop_record.coedges[index];
                let next = &loop_record.coedges[(index + 1) % count];
                if !section_edges.contains(&current.edge_id) || !section_edges.contains(&next.edge_id) {
                    continue;
                }
                let (Some(&(s0, e0)), Some(&(s1, e1))) =
                    (endpoints.get(&current.edge_id), endpoints.get(&next.edge_id))
                else {
                    continue;
                };
                let leaving = if current.forward { e0 } else { s0 };
                let arriving = if next.forward { s1 } else { e1 };
                if leaving == arriving {
                    continue;
                }
                let key = (leaving.min(arriving), leaving.max(arriving));
                if pairs.iter().any(|(_, a, b)| (*a, *b) == key) {
                    continue;
                }
                let (Some(a), Some(b)) = (point(leaving), point(arriving)) else {
                    continue;
                };
                let distance = a.sub(b).length();
                if distance <= band {
                    pairs.push((distance, key.0, key.1));
                }
            }
        }
        if pairs.is_empty() {
            break;
        }
        pairs.sort_by(|x, y| x.0.partial_cmp(&y.0).expect("finite distances"));
        let mut welded = 0usize;
        for (distance, a, b) in pairs {
            if !vertices.iter().any(|v| v.id == a) || !vertices.iter().any(|v| v.id == b) {
                continue; // consumed by an earlier weld of this pass
            }
            // Against the LIVE edges: an earlier weld of this pass may have
            // re-pointed an edge onto one of the pair.
            let joined = edges.iter().any(|edge| {
                !edge.degenerate
                    && ((edge.start_vertex_id == a && edge.end_vertex_id == b)
                        || (edge.start_vertex_id == b && edge.end_vertex_id == a))
            });
            if joined {
                continue;
            }
            if debug {
                eprintln!(
                    "boolean assembly: open section corner between vertices {a} and {b}, {distance:.3e} apart (band {band:.3e})"
                );
            }
            let (survivor, loser) = if vertex_endpoint_error(vertices, edges, a)
                <= vertex_endpoint_error(vertices, edges, b)
            {
                (a, b)
            } else {
                (b, a)
            };
            weld_vertex_onto(vertices, edges, loser, survivor, band);
            survivors.push(survivor);
            welded += 1;
        }
        if welded == 0 {
            break;
        }
    }
    survivors.sort_unstable();
    survivors.dedup();
    survivors
}

/// Give every vertex used by edges of MORE THAN ONE shell its own vertex
/// record per shell, so two edge-disconnected shells touching at a point are
/// two closed manifold shells rather than one complex pinched at a vertex.
/// Shells are edge-connected face groups, so a vertex used by two of them is
/// exactly a point contact between separate bodies: the subtract that cuts a
/// cylinder with an equal-radius crossing cylinder leaves two pieces that
/// touch at the two tangent points, and nothing else. One node there may be
/// welded by the assembler's own vertex weld (the two ellipses' split points
/// within 1e-7) and the other by the open-corner weld above, so this reads
/// the shells, not the welds: a shared vertex of EITHER origin would leave
/// `V − E + F` one short per contact — an odd count refuses outright, an
/// even one validates with a genus read as 1. Returns the records added.
pub(super) fn split_vertices_shared_across_shells(
    vertices: &mut Vec<VertexRecord>,
    edges: &mut [EdgeRecord],
    shells: &[ShellRecord],
    next_vertex_id: &mut u64,
) -> usize {
    if shells.len() < 2 {
        return 0;
    }
    let mut shell_of_edge: HashMap<u64, usize> = HashMap::default();
    for (shell_index, shell) in shells.iter().enumerate() {
        for coedge in shell
            .faces
            .iter()
            .flat_map(|face| &face.loops)
            .flat_map(|loop_record| &loop_record.coedges)
        {
            shell_of_edge.insert(coedge.edge_id, shell_index);
        }
    }
    // vertex id → the shells whose edges use it, in shell order.
    let mut shells_of_vertex: HashMap<u64, Vec<usize>> = HashMap::default();
    for edge in edges.iter() {
        let Some(&shell_index) = shell_of_edge.get(&edge.id) else {
            continue;
        };
        for vertex_id in [edge.start_vertex_id, edge.end_vertex_id] {
            let users = shells_of_vertex.entry(vertex_id).or_default();
            if !users.contains(&shell_index) {
                users.push(shell_index);
            }
        }
    }
    let mut shared: Vec<(u64, Vec<usize>)> = shells_of_vertex
        .into_iter()
        .filter(|(_, users)| users.len() > 1)
        .collect();
    shared.sort_unstable();
    let mut added = 0usize;
    for (vertex_id, mut users) in shared {
        let Some(point) = vertices.iter().find(|v| v.id == vertex_id).map(|v| v.point) else {
            continue;
        };
        users.sort_unstable();
        // The first shell keeps the record; every other shell gets a copy.
        for &shell_index in users.iter().skip(1) {
            let copy = *next_vertex_id;
            *next_vertex_id += 1;
            vertices.push(VertexRecord { id: copy, point });
            for edge in edges.iter_mut() {
                if shell_of_edge.get(&edge.id) != Some(&shell_index) {
                    continue;
                }
                if edge.start_vertex_id == vertex_id {
                    edge.start_vertex_id = copy;
                }
                if edge.end_vertex_id == vertex_id {
                    edge.end_vertex_id = copy;
                }
            }
            added += 1;
        }
    }
    added
}

/// `BREP_PINCH_VERTEX_FANS` (default on; `=0` restores the genus refusal on a
/// pinched shell): see [`split_pinched_vertices_by_fan`]. Promoted once the
/// watertight tessellation meshes a pinch edge-manifold (mesher
/// `BREP_TESS_PINCH_CUSP`): viviani-cut reads its closed form and its mesh closes.
pub(super) fn pinch_vertex_fans_enabled() -> bool {
    switch!("BREP_PINCH_VERTEX_FANS", true)
}

/// A vertex where ONE shell touches itself (the ball bored by Viviani's
/// cylinder: two slivers meeting at the tangent node) carries two or more
/// separate fans of faces: walking corner to corner around it never gets from
/// one to the other. Counted once, it knocks the Euler characteristic off by
/// one per extra fan and the genus reads non-integral. Each fan past the first
/// gets its own copy of the vertex, as two shells touching at a point get one
/// each ([`split_vertices_shared_across_shells`]), so the count reads the
/// surface the solid has. A fan is a class of edge ends at the vertex, joined
/// by each face corner there (the end of one coedge and the start of the next)
/// and by a degenerate edge's two ends. Returns the copies added.
pub(super) fn split_pinched_vertices_by_fan(
    vertices: &mut Vec<VertexRecord>,
    edges: &mut [EdgeRecord],
    shells: &[ShellRecord],
    next_vertex_id: &mut u64,
) -> usize {
    let index_of: HashMap<u64, usize> = edges.iter().enumerate().map(|(index, edge)| (edge.id, index)).collect();
    // An edge end: (edge index, true for its start).
    type End = (usize, bool);
    let vertex_of = |edges: &[EdgeRecord], end: End| if end.1 { edges[end.0].start_vertex_id } else { edges[end.0].end_vertex_id };
    let mut parent: HashMap<End, End> = HashMap::default();
    fn find(parent: &mut HashMap<End, End>, end: End) -> End {
        let mut root = end;
        while let Some(&next) = parent.get(&root) {
            if next == root {
                break;
            }
            root = next;
        }
        parent.insert(end, root);
        root
    }
    let mut union = |parent: &mut HashMap<End, End>, a: End, b: End| {
        let (ra, rb) = (find(parent, a), find(parent, b));
        if ra != rb {
            parent.insert(ra.max(rb), ra.min(rb));
        }
    };
    for (index, edge) in edges.iter().enumerate() {
        parent.entry((index, true)).or_insert((index, true));
        parent.entry((index, false)).or_insert((index, false));
        if edge.degenerate {
            union(&mut parent, (index, true), (index, false));
        }
    }
    for loop_record in shells.iter().flat_map(|shell| &shell.faces).flat_map(|face| &face.loops) {
        let count = loop_record.coedges.len();
        for at in 0..count {
            let (here, next) = (&loop_record.coedges[at], &loop_record.coedges[(at + 1) % count]);
            let (Some(&a), Some(&b)) = (index_of.get(&here.edge_id), index_of.get(&next.edge_id)) else {
                continue;
            };
            // The coedge's end, then the next coedge's start.
            let end_of_here: End = (a, !here.forward);
            let start_of_next: End = (b, next.forward);
            if vertex_of(edges, end_of_here) == vertex_of(edges, start_of_next) {
                union(&mut parent, end_of_here, start_of_next);
            }
        }
    }
    // vertex → its fans (root → the ends in it), in a stable order.
    let mut fans: std::collections::BTreeMap<u64, std::collections::BTreeMap<End, Vec<End>>> = Default::default();
    for index in 0..edges.len() {
        for start in [true, false] {
            let end = (index, start);
            let root = find(&mut parent, end);
            fans.entry(vertex_of(edges, end)).or_default().entry(root).or_default().push(end);
        }
    }
    let mut added = 0usize;
    for (vertex_id, groups) in fans {
        if groups.len() < 2 {
            continue;
        }
        let Some(point) = vertices.iter().find(|vertex| vertex.id == vertex_id).map(|vertex| vertex.point) else {
            continue;
        };
        for (_, ends) in groups.into_iter().skip(1) {
            let copy = *next_vertex_id;
            *next_vertex_id += 1;
            vertices.push(VertexRecord { id: copy, point });
            for (index, start) in ends {
                if start {
                    edges[index].start_vertex_id = copy;
                } else {
                    edges[index].end_vertex_id = copy;
                }
            }
            added += 1;
        }
    }
    added
}

/// Re-point every edge endpoint from `loser` to `survivor`, clamp curve
/// domain-end endpoints that drifted (by less than `band`) onto the surviving
/// vertex, and drop the losing vertex record.  Shared by the tangency
/// duplicate-vertex weld and the edge-conformance merge lane.
fn weld_vertex_onto(
    vertices: &mut Vec<VertexRecord>,
    edges: &mut [EdgeRecord],
    loser: u64,
    survivor: u64,
    band: f64,
) {
    let Some(target) = vertices.iter().find(|v| v.id == survivor).map(|v| v.point) else {
        return;
    };
    for edge in edges.iter_mut() {
        if edge.start_vertex_id == loser {
            edge.start_vertex_id = survivor;
        }
        if edge.end_vertex_id == loser {
            edge.end_vertex_id = survivor;
        }
        if edge.degenerate {
            continue;
        }
        // Clamp drifted curve endpoints onto the surviving vertex.
        if edge.start_vertex_id == survivor || edge.end_vertex_id == survivor {
            if let Ok([d0, d1]) = edge.curve.domain() {
                if edge.start_vertex_id == survivor && (edge.t0 - d0).abs() < 1e-12 {
                    if let Ok(p) = edge.curve.evaluate(edge.t0) {
                        let gap = p.sub(target).length();
                        if gap > 0.0 && gap < band {
                            let w = edge.curve.control_points[0].w;
                            edge.curve.control_points[0] = crate::Vec4 {
                                x: target.x * w,
                                y: target.y * w,
                                z: target.z * w,
                                w,
                            };
                        }
                    }
                }
                if edge.end_vertex_id == survivor && (edge.t1 - d1).abs() < 1e-12 {
                    if let Ok(p) = edge.curve.evaluate(edge.t1) {
                        let gap = p.sub(target).length();
                        if gap > 0.0 && gap < band {
                            let last = edge.curve.control_points.len() - 1;
                            let w = edge.curve.control_points[last].w;
                            edge.curve.control_points[last] = crate::Vec4 {
                                x: target.x * w,
                                y: target.y * w,
                                z: target.z * w,
                                w,
                            };
                        }
                    }
                }
            }
        }
    }
    vertices.retain(|v| v.id != loser);
}

/// EDGE-conformance repair for an otherwise-refused CLOSED assembly — the
/// edge-level sibling of `weld_tangency_duplicate_vertices`.  Tangency-degraded
/// SSI endpoints converge only O(√tol·scale) from the operand's exact station
/// (measured 1.568e-4 on the scale-14 extruded-boss fixture at tol 1e-7, where
/// √tol·scale ≈ 4.4e-3), so nearby face boundaries can follow the same locus
/// within that band yet be emitted as DIFFERENT edges/trims that the assembler
/// weld (exact-band) cannot unify.  Two deterministic lanes, each verified
/// geometrically before any mutation:
///
/// 1. MERGE — two one-use edges from different loops whose spans mutually lie
///    within the band and whose endpoints correspond pairwise are one boundary
///    emitted twice.  The lower (degree, id) record survives (operand
///    analytics beat marched SSI fits); the loser's coedge is redirected onto
///    it with a pcurve rebuilt on its own face's surface, and the loser's
///    endpoint vertices are welded onto the survivor's.
/// 2. BRIDGE — a loop that is OPEN between vertices va→vb whose gap is exactly
///    spanned by a one-use edge of ANOTHER loop (the hairline sliver the
///    neighbour's arrangement split created but this face's did not) gets a
///    conforming coedge of that edge inserted with the opposite sense and a
///    pcurve built on the gap face's surface.
///
/// Runs ONLY from refusal paths, so it can never alter a succeeding boolean;
/// the caller re-runs the Euler check and the final full `validate()` still
/// gates the result.  Returns the number of repairs applied.
pub(in crate::boolean) fn conform_unmatched_one_use_edges(
    vertices: &mut Vec<VertexRecord>,
    edges: &mut Vec<EdgeRecord>,
    shells: &mut [ShellRecord],
    tolerance: f64,
) -> Result<usize, KernelRefusal> {
    let scale = vertices
        .iter()
        .map(|v| v.point.length())
        .fold(1.0_f64, f64::max);
    // SSI tangency drift is O(√tol·scale); no headroom multiplier (the band is
    // already ~28× the measured drift), floored at 10× the model tolerance and
    // therefore far below any feature size the arrangement can represent.
    let band = (tolerance.max(1e-12).sqrt() * scale).max(tolerance * 10.0);
    let fit_tolerance = tolerance.max(band / 10.0);
    let pcurve_limit = KernelTolerances::for_scale(scale, tolerance).pcurve_consistency;
    let debug = std::env::var("BREP_DEBUG_BOOL").is_ok();

    // edge id -> every (shell, face, loop, coedge, forward) use.
    fn collect_uses(
        shells: &[ShellRecord],
    ) -> HashMap<u64, Vec<(usize, usize, usize, usize, bool)>> {
        let mut uses = HashMap::<u64, Vec<(usize, usize, usize, usize, bool)>>::default();
        for (shell_index, shell) in shells.iter().enumerate() {
            for (face_index, face) in shell.faces.iter().enumerate() {
                for (loop_index, loop_record) in face.loops.iter().enumerate() {
                    for (coedge_index, coedge) in loop_record.coedges.iter().enumerate() {
                        uses.entry(coedge.edge_id).or_default().push((
                            shell_index,
                            face_index,
                            loop_index,
                            coedge_index,
                            coedge.forward,
                        ));
                    }
                }
            }
        }
        uses
    }

    let mut repairs = 0usize;

    // LANE A: merge duplicated hairline one-use pairs.
    {
        let uses = collect_uses(shells);
        let vertex_point = vertices
            .iter()
            .map(|v| (v.id, v.point))
            .collect::<HashMap<_, _>>();
        let mut one_use = edges
            .iter()
            .filter(|edge| !edge.degenerate && uses.get(&edge.id).map(Vec::len) == Some(1))
            .map(|edge| edge.id)
            .collect::<Vec<_>>();
        one_use.sort_unstable();
        let mut consumed = HashSet::<u64>::default();
        // (survivor id, loser id, reversed correspondence)
        let mut merges = Vec::<(u64, u64, bool)>::new();
        for (index, &first_id) in one_use.iter().enumerate() {
            if consumed.contains(&first_id) {
                continue;
            }
            for &second_id in &one_use[index + 1..] {
                if consumed.contains(&second_id) {
                    continue;
                }
                let first = edges.iter().find(|edge| edge.id == first_id).unwrap();
                let second = edges.iter().find(|edge| edge.id == second_id).unwrap();
                // Never merge two edges of the same face loop.
                let first_use = uses[&first_id][0];
                let second_use = uses[&second_id][0];
                if (first_use.0, first_use.1, first_use.2)
                    == (second_use.0, second_use.1, second_use.2)
                {
                    continue;
                }
                let (Some(&fs), Some(&fe), Some(&ss), Some(&se)) = (
                    vertex_point.get(&first.start_vertex_id),
                    vertex_point.get(&first.end_vertex_id),
                    vertex_point.get(&second.start_vertex_id),
                    vertex_point.get(&second.end_vertex_id),
                ) else {
                    continue;
                };
                let aligned = fs.sub(ss).length() <= band && fe.sub(se).length() <= band;
                let reversed = fs.sub(se).length() <= band && fe.sub(ss).length() <= band;
                if !aligned && !reversed {
                    continue;
                }
                if !(edge_lies_on(first, second, band)? && edge_lies_on(second, first, band)?) {
                    continue;
                }
                let first_wins = (first.curve.degree, first.id) <= (second.curve.degree, second.id);
                let (survivor, loser) = if first_wins {
                    (first_id, second_id)
                } else {
                    (second_id, first_id)
                };
                merges.push((survivor, loser, !aligned));
                consumed.insert(first_id);
                consumed.insert(second_id);
                break;
            }
        }
        for (survivor_id, loser_id, reversed) in merges {
            let survivor = edges
                .iter()
                .find(|edge| edge.id == survivor_id)
                .unwrap()
                .clone();
            let loser = edges
                .iter()
                .find(|edge| edge.id == loser_id)
                .unwrap()
                .clone();
            if !(survivor.t0.is_finite() && survivor.t1.is_finite() && survivor.t0 < survivor.t1) {
                continue;
            }
            // Evaluate both endpoint welds against the current edge table,
            // including changes from earlier successful merges. Close rims
            // cannot authorize erasing an existing material-thickness edge.
            let survivor_pair = if reversed {
                [survivor.end_vertex_id, survivor.start_vertex_id]
            } else {
                [survivor.start_vertex_id, survivor.end_vertex_id]
            };
            let endpoint_pairs = [loser.start_vertex_id, loser.end_vertex_id]
                .into_iter().zip(survivor_pair).collect::<Vec<_>>();
            let redirected = |mut id| {
                for &(from, to) in &endpoint_pairs {
                    if id == from { id = to; }
                }
                id
            };
            if edges.iter().any(|edge| !edge.degenerate
                && edge.start_vertex_id != edge.end_vertex_id
                && redirected(edge.start_vertex_id) == redirected(edge.end_vertex_id)) {
                if debug {
                    eprintln!("conform: merge {loser_id}->{survivor_id} rejected (collapses an existing edge)");
                }
                continue;
            }
            let (shell_index, face_index, loop_index, coedge_index, old_forward) =
                uses[&loser_id][0];
            let new_forward = if reversed { !old_forward } else { old_forward };
            let face = &mut shells[shell_index].faces[face_index];
            let Ok(pcurve) = build_pcurve_on_surface_range(
                &face.surface,
                &survivor.curve,
                survivor.t0,
                survivor.t1,
                new_forward,
                fit_tolerance,
            ) else {
                continue;
            };
            let Ok(error) = adaptive_coedge_error(
                &face.surface,
                &pcurve,
                &survivor.curve,
                &survivor,
                new_forward,
                pcurve_limit,
            ) else {
                continue;
            };
            if error > pcurve_limit {
                if debug {
                    eprintln!(
                        "conform: merge {loser_id}->{survivor_id} rejected (pcurve error {error:.2e} > {pcurve_limit:.2e})"
                    );
                }
                continue;
            }
            {
                let coedge = &mut face.loops[loop_index].coedges[coedge_index];
                coedge.edge_id = survivor_id;
                coedge.forward = new_forward;
                coedge.pcurve = pcurve;
            }
            edges.retain(|edge| edge.id != loser_id);
            for (loser_vertex, survivor_vertex) in [loser.start_vertex_id, loser.end_vertex_id]
                .into_iter()
                .zip(survivor_pair)
            {
                if loser_vertex != survivor_vertex {
                    weld_vertex_onto(vertices, edges, loser_vertex, survivor_vertex, band);
                }
            }
            if debug {
                eprintln!(
                    "conform: merged duplicate one-use edge {loser_id} onto {survivor_id} (reversed={reversed})"
                );
            }
            repairs += 1;
        }
    }

    // LANE B: bridge open loop gaps with an existing one-use edge.
    {
        let uses = collect_uses(shells);
        let edge_by_id = edges
            .iter()
            .map(|edge| (edge.id, edge.clone()))
            .collect::<HashMap<_, _>>();
        let mut sorted_edge_ids = edges
            .iter()
            .filter(|edge| !edge.degenerate)
            .map(|edge| edge.id)
            .collect::<Vec<_>>();
        sorted_edge_ids.sort_unstable();
        let mut next_coedge_id = shells
            .iter()
            .flat_map(|shell| &shell.faces)
            .flat_map(|face| &face.loops)
            .flat_map(|loop_record| &loop_record.coedges)
            .map(|coedge| coedge.id)
            .max()
            .unwrap_or(0)
            + 1;
        let mut consumed = HashSet::<u64>::default();
        // (shell, face, loop, insert position, coedge)
        let mut plans = Vec::<(usize, usize, usize, usize, CoedgeRecord)>::new();
        for (shell_index, shell) in shells.iter().enumerate() {
            for (face_index, face) in shell.faces.iter().enumerate() {
                for (loop_index, loop_record) in face.loops.iter().enumerate() {
                    let count = loop_record.coedges.len();
                    if count == 0 {
                        continue;
                    }
                    for position in 0..count {
                        let current = &loop_record.coedges[position];
                        let next = &loop_record.coedges[(position + 1) % count];
                        let (Some(current_edge), Some(next_edge)) = (
                            edge_by_id.get(&current.edge_id),
                            edge_by_id.get(&next.edge_id),
                        ) else {
                            continue;
                        };
                        let gap_start = if current.forward {
                            current_edge.end_vertex_id
                        } else {
                            current_edge.start_vertex_id
                        };
                        let gap_end = if next.forward {
                            next_edge.start_vertex_id
                        } else {
                            next_edge.end_vertex_id
                        };
                        if gap_start == gap_end {
                            continue;
                        }
                        for &candidate_id in &sorted_edge_ids {
                            if consumed.contains(&candidate_id) {
                                continue;
                            }
                            let Some(edge_uses) = uses.get(&candidate_id) else {
                                continue;
                            };
                            if edge_uses.len() != 1 {
                                continue;
                            }
                            let (use_shell, use_face, use_loop, _, use_forward) = edge_uses[0];
                            if (use_shell, use_face, use_loop)
                                == (shell_index, face_index, loop_index)
                            {
                                continue;
                            }
                            let edge = &edge_by_id[&candidate_id];
                            let forward = if edge.start_vertex_id == gap_start
                                && edge.end_vertex_id == gap_end
                            {
                                true
                            } else if edge.end_vertex_id == gap_start
                                && edge.start_vertex_id == gap_end
                            {
                                false
                            } else {
                                continue;
                            };
                            // A manifold edge is traversed once in each sense.
                            if use_forward == forward {
                                continue;
                            }
                            if !(edge.t0.is_finite() && edge.t1.is_finite() && edge.t0 < edge.t1) {
                                continue;
                            }
                            let Ok(pcurve) = build_pcurve_on_surface_range(
                                &face.surface,
                                &edge.curve,
                                edge.t0,
                                edge.t1,
                                forward,
                                fit_tolerance,
                            ) else {
                                continue;
                            };
                            let Ok(error) = adaptive_coedge_error(
                                &face.surface,
                                &pcurve,
                                &edge.curve,
                                edge,
                                forward,
                                pcurve_limit,
                            ) else {
                                continue;
                            };
                            if error > pcurve_limit {
                                if debug {
                                    eprintln!(
                                        "conform: bridge of edge {candidate_id} into face {} rejected (pcurve error {error:.2e} > {pcurve_limit:.2e})",
                                        face.id
                                    );
                                }
                                continue;
                            }
                            plans.push((
                                shell_index,
                                face_index,
                                loop_index,
                                position + 1,
                                CoedgeRecord {
                                    id: next_coedge_id,
                                    edge_id: candidate_id,
                                    forward,
                                    pcurve,
                                },
                            ));
                            next_coedge_id += 1;
                            consumed.insert(candidate_id);
                            if debug {
                                eprintln!(
                                    "conform: bridging open gap in face {} loop {} with one-use edge {candidate_id} (forward={forward})",
                                    face.id, loop_index
                                );
                            }
                            break;
                        }
                    }
                }
            }
        }
        // Apply per loop in descending position so earlier insertions do not
        // shift later ones.
        plans.sort_by(|a, b| (a.0, a.1, a.2, b.3).cmp(&(b.0, b.1, b.2, a.3)));
        for (shell_index, face_index, loop_index, position, coedge) in plans {
            shells[shell_index].faces[face_index].loops[loop_index]
                .coedges
                .insert(position, coedge);
            repairs += 1;
        }
    }

    Ok(repairs)
}

/// Recompute the derived genus with the same shell-aware Euler formula
/// `validate()` checks against (left untouched when the counts do not give an
/// integral genus — validation then reports the real defect).
pub(super) fn refresh_derived_genus(solid: &mut BrepSolid) {
    let hole_count = solid.bounding_hole_count();
    let face_count: i64 = solid
        .shells
        .iter()
        .map(|shell| shell.faces.len() as i64)
        .sum();
    let edge_count = solid.edges.iter().filter(|edge| !edge.degenerate).count() as i64;
    let live_vertices = solid
        .edges
        .iter()
        .filter(|edge| !edge.degenerate)
        .flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id])
        .collect::<HashSet<_>>();
    let vertex_count = solid
        .vertices
        .iter()
        .filter(|vertex| live_vertices.contains(&vertex.id))
        .count() as i64;
    let euler = vertex_count - edge_count + face_count - hole_count;
    let numerator = solid.shells.len() as i64 * 2 - euler;
    if numerator >= 0 && numerator % 2 == 0 {
        solid.genus = numerator / 2;
    }
}