Skip to main content

brep_boolean/healing/
sew.rs

1//! Standalone heal/sew — Golovanov's "sewing": assemble a valid oriented
2//! shell out of faces whose boundary representations were built independently
3//! (imported shells, detached face groups, healing after hand edits).
4//!
5//! The boolean assembler and the offset pipeline each carry private sewing
6//! passes specialised to their own invariants (`sew_coincident_one_use_edges`
7//! requires already-opposed traversals; the offset welds know their rims).
8//! This module is the GENERAL entry: it pairs coincident one-use boundary
9//! edges by geometry alone — open chains by matched endpoints + locus
10//! agreement, closed rims by mutual locus agreement — WITHOUT any orientation
11//! precondition, because a face soup's components may be arbitrarily flipped.
12//! Orientation is repaired after pairing: coedge-direction coherence is
13//! propagated across the now-shared edges and the whole solid is flipped
14//! outward by signed volume.
15//!
16//! Sewing is BEST-EFFORT and honest: pairs that cannot be joined within
17//! tolerance stay open and are counted in the report; nothing is force-welded.
18
19use crate::{KernelRefusal, KernelStage, OrRefuse};
20use crate::mass_properties::{sign_coarse_thin_enabled, solid_sign_coarse_certificate, solid_signed_volume, solid_signed_volume_for_sign, COARSE_SIGN_DEPTH};
21use crate::orientation::{flip_all_faces, orient_open_solid_faces};
22use crate::topology::{BrepSolid, CoedgeRecord, EdgeRecord, FaceRecord, ShellRecord, VertexRecord};
23use crate::{build_pcurve_on_surface, project_point_to_curve, NurbsCurve, Vec3};
24use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
25use serde::{Deserialize, Serialize};
26
27#[derive(Clone, Debug, Serialize, Deserialize)]
28pub struct SewReport {
29    pub edges_sewn: usize,
30    pub shells_merged: usize,
31    pub open_edges_before: usize,
32    pub open_edges_after: usize,
33    pub oriented_outward: bool,
34    pub issues: Vec<String>,
35}
36
37fn one_use_edge_ids(solid: &BrepSolid) -> HashSet<u64> {
38    let mut counts = HashMap::<u64, usize>::default();
39    for coedge in solid
40        .shells
41        .iter()
42        .flat_map(|shell| &shell.faces)
43        .flat_map(|face| &face.loops)
44        .flat_map(|loop_record| &loop_record.coedges)
45    {
46        *counts.entry(coedge.edge_id).or_default() += 1;
47    }
48    counts
49        .into_iter()
50        .filter(|(_, count)| *count == 1)
51        .map(|(id, _)| id)
52        .collect()
53}
54
55fn curve_point(edge: &EdgeRecord, fraction: f64) -> Result<Vec3, KernelRefusal> {
56    edge.curve
57        .evaluate(edge.t0 + (edge.t1 - edge.t0) * fraction).or_refuse(KernelStage::Sew, "evaluate")
58}
59
60/// Worst distance from sampled points of `piece` to the locus of `carrier`.
61fn locus_deviation(
62    piece: &EdgeRecord,
63    carrier: &EdgeRecord,
64    samples: usize,
65) -> Result<f64, KernelRefusal> {
66    let mut worst = 0.0f64;
67    for index in 0..=samples {
68        let point = curve_point(piece, index as f64 / samples as f64)?;
69        worst = worst.max(project_point_to_curve(&carrier.curve, point).or_refuse(KernelStage::Sew, "project_point_to_curve")?.distance);
70    }
71    Ok(worst)
72}
73
74/// Pointwise agreement at matched fractions — the two edges are not merely
75/// the same locus but the SAME parametrization (the duplicated-edge case),
76/// letting a rebind keep the existing pcurve exactly.
77fn same_parametrization(
78    first: &EdgeRecord,
79    second: &EdgeRecord,
80    tolerance: f64,
81) -> Result<bool, KernelRefusal> {
82    for index in 0..=8 {
83        let fraction = index as f64 / 8.0;
84        if curve_point(first, fraction)?
85            .sub(curve_point(second, fraction)?)
86            .length()
87            > tolerance
88        {
89            return Ok(false);
90        }
91    }
92    Ok(true)
93}
94
95/// The 3D walk this coedge's loop takes along its edge, sampled from its
96/// pcurve through its face surface. Fractions 0 and 0.35: an interior second
97/// sample avoids the antipodal-projection ambiguity a closed rim has at 0.5.
98fn walk_points(face: &FaceRecord, coedge: &CoedgeRecord) -> Result<[Vec3; 2], KernelRefusal> {
99    let [start, end] = coedge.pcurve.domain().or_refuse(KernelStage::Sew, "domain")?;
100    let sample = |fraction: f64| -> Result<Vec3, String> {
101        let uv = coedge.pcurve.evaluate(start + (end - start) * fraction)?;
102        face.surface.evaluate(uv.x, uv.y)
103    };
104    Ok([sample(0.0).or_refuse(KernelStage::Sew, "sample")?, sample(0.35).or_refuse(KernelStage::Sew, "sample")?])
105}
106
107/// One planned coedge rebind, resolved before any mutation so a failed plan
108/// (an unprojectable pcurve, say) leaves the pair untouched and open.
109struct RebindPatch {
110    shell: usize,
111    face: usize,
112    loop_index: usize,
113    coedge: usize,
114    forward: bool,
115    pcurve: Option<NurbsCurve>,
116}
117
118/// Plan the rebind of every coedge referencing `remove` onto `keep`. The
119/// coedge's `forward` is derived from the 3D walk its existing pcurve
120/// produces (geometry is authoritative — components may be flipped), the
121/// pcurve is kept when the parametrizations agree and refit otherwise.
122fn plan_rebind(
123    solid: &BrepSolid,
124    keep: &EdgeRecord,
125    remove: &EdgeRecord,
126    tolerance: f64,
127) -> Result<Vec<RebindPatch>, KernelRefusal> {
128    let identical = same_parametrization(keep, remove, tolerance)?;
129    let closed = keep.start_vertex_id == keep.end_vertex_id;
130    let period = keep.t1 - keep.t0;
131    let mut patches = Vec::new();
132    for (shell_index, shell) in solid.shells.iter().enumerate() {
133        for (face_index, face) in shell.faces.iter().enumerate() {
134            for (loop_index, loop_record) in face.loops.iter().enumerate() {
135                for (coedge_index, coedge) in loop_record.coedges.iter().enumerate() {
136                    if coedge.edge_id != remove.id {
137                        continue;
138                    }
139                    let [walk_start, walk_next] = walk_points(face, coedge)?;
140                    let t_start = project_point_to_curve(&keep.curve, walk_start).or_refuse(KernelStage::Sew, "project_point_to_curve")?.u;
141                    let t_next = project_point_to_curve(&keep.curve, walk_next).or_refuse(KernelStage::Sew, "project_point_to_curve")?.u;
142                    let forward = if closed {
143                        let mut delta = t_next - t_start;
144                        while delta > period * 0.5 {
145                            delta -= period;
146                        }
147                        while delta < -period * 0.5 {
148                            delta += period;
149                        }
150                        delta > 0.0
151                    } else {
152                        t_next > t_start
153                    };
154                    let pcurve = if identical {
155                        None
156                    } else {
157                        let traversal = if forward {
158                            keep.curve.clone()
159                        } else {
160                            keep.curve.reversed().or_refuse(KernelStage::Sew, "reversed")?
161                        };
162                        Some(build_pcurve_on_surface(&face.surface, &traversal).or_refuse(KernelStage::Sew, "build_pcurve_on_surface")?)
163                    };
164                    patches.push(RebindPatch {
165                        shell: shell_index,
166                        face: face_index,
167                        loop_index,
168                        coedge: coedge_index,
169                        forward,
170                        pcurve,
171                    });
172                }
173            }
174        }
175    }
176    Ok(patches)
177}
178
179fn apply_rebind(
180    solid: &mut BrepSolid,
181    keep: &EdgeRecord,
182    remove: &EdgeRecord,
183    patches: Vec<RebindPatch>,
184    tolerance: f64,
185) {
186    for patch in patches {
187        let coedge = &mut solid.shells[patch.shell].faces[patch.face].loops[patch.loop_index]
188            .coedges[patch.coedge];
189        coedge.edge_id = keep.id;
190        coedge.forward = patch.forward;
191        if let Some(pcurve) = patch.pcurve {
192            coedge.pcurve = pcurve;
193        }
194    }
195    solid.edges.retain(|edge| edge.id != remove.id);
196    // Weld the removed edge's endpoint vertices into the kept edge's, so
197    // OTHER edges of the removed component (a loop mixes sewn rim edges with
198    // still-duplicate interior edges) chain through the shared vertices.
199    // Only coincident endpoints weld — a rotated closed rim keeps its own
200    // seam vertex.
201    let point_of = |vertex_id: u64| {
202        solid
203            .vertices
204            .iter()
205            .find(|vertex| vertex.id == vertex_id)
206            .map(|vertex| vertex.point)
207    };
208    let mut welds = Vec::<(u64, u64)>::new();
209    for from in [remove.start_vertex_id, remove.end_vertex_id] {
210        let Some(from_point) = point_of(from) else {
211            continue;
212        };
213        let target = [keep.start_vertex_id, keep.end_vertex_id]
214            .into_iter()
215            .filter_map(|candidate| {
216                point_of(candidate).map(|point| (candidate, point.sub(from_point).length()))
217            })
218            .min_by(|first, second| first.1.total_cmp(&second.1));
219        if let Some((to, distance)) = target {
220            if distance <= tolerance && from != to {
221                welds.push((from, to));
222            }
223        }
224    }
225    for (from, to) in welds {
226        for edge in &mut solid.edges {
227            if edge.start_vertex_id == from {
228                edge.start_vertex_id = to;
229            }
230            if edge.end_vertex_id == from {
231                edge.end_vertex_id = to;
232            }
233        }
234    }
235}
236
237/// Decide which of an accepted pair is KEPT and which is REMOVED.
238///
239/// For an open chain, and for a closed rim whose two copies share a seam
240/// point, either direction works and the scan's own order stands — `first` is
241/// kept, exactly as before.
242///
243/// A seam-ROTATED closed rim is different, and the difference is not cosmetic.
244/// The removed rim takes its seam vertex out of the solid with it, so every
245/// OTHER edge that chained through that vertex is left chaining through
246/// nothing. `apply_rebind` deliberately does not drag it onto the kept rim's
247/// seam — a rotated closed rim keeps its own seam vertex, because moving it
248/// would pull a real edge endpoint an arbitrary arc round the circle, off its
249/// own curve — so the tear is not repaired, it is inherited. Sewn that way a
250/// cylinder comes back with `edges_sewn: 1, open_edges_after: 0` over a wall
251/// loop torn at the seam: a report that reads like success.
252///
253/// The direction that works is the one whose REMOVED rim's seam vertex bounds
254/// no other edge. When neither qualifies — both seams anchor real geometry —
255/// no rebind keeps both loops closed, and the pair is left OPEN and counted
256/// rather than sewn into a solid whose own report contradicts its issues.
257fn orient_pair<'a>(
258    solid: &BrepSolid,
259    first: &'a EdgeRecord,
260    second: &'a EdgeRecord,
261    points: &HashMap<u64, Vec3>,
262    tolerance: f64,
263) -> Option<(&'a EdgeRecord, &'a EdgeRecord)> {
264    // The caller has already rejected mismatched closedness, so testing
265    // `first` tests both.
266    if first.start_vertex_id != first.end_vertex_id {
267        return Some((first, second));
268    }
269    let (Some(&first_seam), Some(&second_seam)) = (
270        points.get(&first.start_vertex_id),
271        points.get(&second.start_vertex_id),
272    ) else {
273        return Some((first, second));
274    };
275    if first_seam.sub(second_seam).length() <= tolerance {
276        // Seams coincide: `apply_rebind`'s weld joins them and every loop
277        // through either one still chains. Order is free.
278        return Some((first, second));
279    }
280    let seam_is_exclusive = |rim: &EdgeRecord| {
281        !solid.edges.iter().any(|edge| {
282            edge.id != rim.id
283                && (edge.start_vertex_id == rim.start_vertex_id
284                    || edge.end_vertex_id == rim.start_vertex_id)
285        })
286    };
287    if seam_is_exclusive(second) {
288        Some((first, second))
289    } else if seam_is_exclusive(first) {
290        Some((second, first))
291    } else {
292        None
293    }
294}
295
296/// Merge shells that now share an edge into single shells (union-find).
297fn merge_connected_shells(solid: &mut BrepSolid) -> usize {
298    let mut owner_of_edge = HashMap::<u64, usize>::default();
299    let mut parent = (0..solid.shells.len()).collect::<Vec<_>>();
300    fn root(parent: &mut [usize], index: usize) -> usize {
301        crate::union_find::find_root(parent, index)
302    }
303    for (shell_index, shell) in solid.shells.iter().enumerate() {
304        for coedge in shell
305            .faces
306            .iter()
307            .flat_map(|face| &face.loops)
308            .flat_map(|loop_record| &loop_record.coedges)
309        {
310            if let Some(&other) = owner_of_edge.get(&coedge.edge_id) {
311                let first = root(&mut parent, other);
312                let second = root(&mut parent, shell_index);
313                if first != second {
314                    parent[second] = first;
315                }
316            } else {
317                owner_of_edge.insert(coedge.edge_id, shell_index);
318            }
319        }
320    }
321    let before = solid.shells.len();
322    let original = std::mem::take(&mut solid.shells);
323    let mut merged = Vec::<ShellRecord>::new();
324    let mut group_of = HashMap::<usize, usize>::default();
325    for (index, shell) in original.into_iter().enumerate() {
326        let group = root(&mut parent, index);
327        if let Some(&target) = group_of.get(&group) {
328            merged[target].faces.extend(shell.faces);
329        } else {
330            group_of.insert(group, merged.len());
331            merged.push(shell);
332        }
333    }
334    solid.shells = merged;
335    before - solid.shells.len()
336}
337
338/// Which `second` candidates the pair search offers for a given `first`.
339///
340/// The two strategies feed the SAME loop body in the SAME ascending order, so
341/// "the prefilter is correct" reduces to one claim: the offered list is a
342/// SUPERSET of the candidates that could pass. Nothing else in the search can
343/// differ, which is what makes the parity test (`sew_prefilter_parity`) a real
344/// proof rather than a spot check — first-match-wins makes iteration order
345/// part of the RESULT, not just the cost.
346#[derive(Clone, Copy, PartialEq, Eq, Debug)]
347enum PairSearch {
348    /// Production: neighbourhood query for open chains, closed-rim shortlist
349    /// for closed rims.
350    Hashed,
351    /// The reference brute-force scan the prefilter must reproduce exactly.
352    #[cfg_attr(not(test), allow(dead_code))]
353    Exhaustive,
354}
355
356/// The integer cell of `point`, or `None` when the coordinates cannot be
357/// bucketed at all (non-finite, or so large the index overflows the i64 key).
358/// A `None` anywhere disables the prefilter for the whole pass rather than
359/// silently dropping a candidate — exact parity with the exhaustive scan is
360/// the contract, and one lost candidate would break it.
361fn grid_cell(point: Vec3, cell: f64) -> Option<[i64; 3]> {
362    let mut key = [0i64; 3];
363    for (slot, value) in key.iter_mut().zip([point.x, point.y, point.z]) {
364        if !value.is_finite() {
365            return None;
366        }
367        let scaled = (value / cell).floor();
368        // 9e15 keeps the cast well inside i64 and inside f64's exact-integer
369        // range, so `as i64` is a faithful conversion, not a saturating one.
370        if !scaled.is_finite() || scaled.abs() > 9.0e15 {
371            return None;
372        }
373        *slot = scaled as i64;
374    }
375    Some(key)
376}
377
378/// Uniform spatial hash over the ENDPOINTS of the open one-use candidates —
379/// the prefilter that turns the pair search from a full rescan per accepted
380/// pair into a neighbourhood query.
381///
382/// Cells are `2·tolerance` wide, not `tolerance`. A partner endpoint is at
383/// most `tolerance = cell/2` away, i.e. at most HALF a cell, so it lands in
384/// this cell or an immediate neighbour with a full half-cell of slack — slack
385/// that absorbs the rounding of the `point/cell` division. At `cell =
386/// tolerance` two points exactly `tolerance` apart can straddle two cell
387/// boundaries and the 3×3×3 block would still hold them, but with zero margin
388/// for the division's last bit; the factor of two costs one extra ring of
389/// mostly-empty buckets and buys certainty.
390struct EndpointGrid {
391    cell: f64,
392    buckets: HashMap<[i64; 3], Vec<usize>>,
393}
394
395impl EndpointGrid {
396    /// Bucket every open candidate under BOTH of its endpoints.
397    ///
398    /// Closed rims are deliberately absent. They are paired by mutual locus
399    /// agreement alone — `sew_solid`'s closed branch never looks at a vertex —
400    /// and a seam-ROTATED duplicate rim shares its partner's locus while
401    /// sharing no point position at all, so any point-keyed bucket (midpoint
402    /// included) would drop exactly the pair the closed lane exists to catch.
403    /// Closed rims therefore keep a linear shortlist; see `offer_seconds`.
404    ///
405    /// Candidates whose vertex records are missing are absent too: the
406    /// exhaustive scan `continue`s such a pair outright, so dropping it here
407    /// changes nothing.
408    fn build(endpoints: &[Option<[Vec3; 2]>], closed: &[bool], tolerance: f64) -> Option<Self> {
409        let cell = 2.0 * tolerance;
410        if !(cell.is_finite() && cell > 0.0) {
411            return None;
412        }
413        let mut buckets = HashMap::<[i64; 3], Vec<usize>>::default();
414        for (position, ends) in endpoints.iter().enumerate() {
415            if closed[position] {
416                continue;
417            }
418            let Some(ends) = ends else {
419                continue;
420            };
421            for point in ends {
422                buckets
423                    .entry(grid_cell(*point, cell)?)
424                    .or_default()
425                    .push(position);
426            }
427        }
428        Some(EndpointGrid { cell, buckets })
429    }
430
431    /// Every open candidate with an endpoint in the 3×3×3 block around
432    /// `point`, ascending and deduplicated. A superset of "has an endpoint
433    /// within tolerance of `point`", which is all the pair search needs.
434    /// `false` means the point itself is unbucketable and the caller must not
435    /// trust the (empty) answer.
436    fn near(&self, point: Vec3, out: &mut Vec<usize>) -> bool {
437        out.clear();
438        let Some(centre) = grid_cell(point, self.cell) else {
439            return false;
440        };
441        for dx in -1..=1 {
442            for dy in -1..=1 {
443                for dz in -1..=1 {
444                    if let Some(bucket) =
445                        self.buckets
446                            .get(&[centre[0] + dx, centre[1] + dy, centre[2] + dz])
447                    {
448                        out.extend_from_slice(bucket);
449                    }
450                }
451            }
452        }
453        out.sort_unstable();
454        out.dedup();
455        true
456    }
457}
458
459/// Fill `offered` with the `second` positions to test against
460/// `candidates[first_position]`, ASCENDING — the order the exhaustive scan
461/// used, which first-match-wins makes load-bearing.
462///
463/// Three lanes, each a provable superset of what can pass:
464/// - **No grid** (prefilter disabled, or `PairSearch::Exhaustive`): every
465///   later position, i.e. the original scan verbatim.
466/// - **Closed `first`**: the later CLOSED positions. An open `second` is
467///   rejected by the `first_closed != second_closed` test before any
468///   geometry is touched, so shortlisting them away changes nothing — but
469///   nothing finer is available, because closed-rim pairing reads the locus
470///   and not any point (see `EndpointGrid::build`). Closed rims stay
471///   quadratic in their own (small) count; that is honest, not hidden.
472/// - **Open `first`**: one neighbourhood query around `first`'s START point.
473///   An open pair is accepted only when `first`'s start matches `second`'s
474///   start (direct) or `second`'s end (reversed), so EVERY pair that can pass
475///   has an endpoint within tolerance of that single point, and one query is
476///   a complete superset. A `first` whose vertex records are missing offers
477///   nothing, matching the exhaustive scan's `continue`.
478#[allow(clippy::too_many_arguments)]
479fn offer_seconds(
480    grid: Option<&EndpointGrid>,
481    first_position: usize,
482    first_closed: bool,
483    endpoints: &[Option<[Vec3; 2]>],
484    closed_positions: &[usize],
485    candidate_count: usize,
486    neighbours: &mut Vec<usize>,
487    offered: &mut Vec<usize>,
488) {
489    offered.clear();
490    let Some(grid) = grid else {
491        offered.extend(first_position + 1..candidate_count);
492        return;
493    };
494    if first_closed {
495        offered.extend(
496            closed_positions
497                .iter()
498                .copied()
499                .filter(|&position| position > first_position),
500        );
501        return;
502    }
503    let Some([start, _]) = endpoints[first_position] else {
504        return;
505    };
506    if grid.near(start, neighbours) {
507        offered.extend(
508            neighbours
509                .iter()
510                .copied()
511                .filter(|&position| position > first_position),
512        );
513    }
514}
515
516/// Best-effort sew of a solid's open boundary edges.
517///
518/// Pairs coincident one-use edges (open chains by matched endpoints + locus
519/// agreement, closed rims by mutual locus agreement) and rebinds each pair to
520/// one shared edge, merging the shells they join. Orientation carries NO
521/// precondition: after pairing, coedge-direction coherence is propagated
522/// across the shared edges and the result is flipped outward by signed
523/// volume. Unsewable gaps stay open and are reported, never force-welded.
524pub fn sew_solid(solid: &BrepSolid, tolerance: f64) -> Result<(BrepSolid, SewReport), KernelRefusal> {
525    let (sewn, report, _examined) = sew_solid_with_search(solid, tolerance, PairSearch::Hashed)?;
526    Ok((sewn, report))
527}
528
529/// [`sew_solid`] with the pair-search strategy exposed, plus the number of
530/// (first, second) pairs the search actually examined.
531///
532/// The count is what the scaling smoke asserts on: it is a deterministic
533/// function of the input, where wall time is not, so a band set from it is a
534/// real bound rather than a machine-speed lottery.
535fn sew_solid_with_search(
536    solid: &BrepSolid,
537    tolerance: f64,
538    search: PairSearch,
539) -> Result<(BrepSolid, SewReport, usize), KernelRefusal> {
540    sew_solid_with_pattern(solid, tolerance, search, None)
541}
542
543/// [`sew_solid_with_search`] told, by [`sew_rotated_copies`], that `solid`
544/// is rotated copies of one cell ([`PatternHint`]), so that the orientation
545/// may be read from one copy ([`sew_sign_by_pattern`]).
546fn sew_solid_with_pattern(
547    solid: &BrepSolid,
548    tolerance: f64,
549    search: PairSearch,
550    pattern: Option<&PatternHint>,
551) -> Result<(BrepSolid, SewReport, usize), KernelRefusal> {
552    if !(tolerance.is_finite() && tolerance > 0.0) {
553        return Err(KernelRefusal::input(KernelStage::Collect, "tolerance", "sew_solid: tolerance must be positive"));
554    }
555    let mut result = solid.clone();
556    let open_edges_before = one_use_edge_ids(&result).len();
557    let mut edges_sewn = 0usize;
558    let mut pairs_examined = 0usize;
559    // Pairs whose rebind plan failed (unprojectable pcurve) — left open
560    // rather than retried forever.
561    //
562    // Keyed UNORDERED, because `orient_pair` may swap which of the two is kept
563    // and which is removed. Keyed by (keep, remove) the block would be looked
564    // up under (first, second), miss on a swapped pair, and the scan would
565    // re-offer it, re-swap it, and fail to plan it again on every outer
566    // iteration — nothing having been mutated in between, that is a hang, not
567    // a retry. A pair that cannot be rebound is blocked whichever way round.
568    let mut blocked = HashSet::<(u64, u64)>::default();
569    let unordered = |first: u64, second: u64| (first.min(second), first.max(second));
570    let mut offered = Vec::<usize>::new();
571    let mut neighbours = Vec::<usize>::new();
572    loop {
573        let one_use = one_use_edge_ids(&result);
574        // Candidate POSITIONS into `result.edges`, in edge order — the same
575        // sequence the exhaustive scan walked, without cloning a NURBS curve
576        // per candidate per accepted pair (that clone was the other O(k·n)
577        // term hiding behind the O(k·n²) comparison count).
578        let candidates = result
579            .edges
580            .iter()
581            .enumerate()
582            .filter(|(_, edge)| !edge.degenerate && one_use.contains(&edge.id))
583            .map(|(index, _)| index)
584            .collect::<Vec<_>>();
585        let points = result
586            .vertices
587            .iter()
588            .map(|vertex| (vertex.id, vertex.point))
589            .collect::<HashMap<_, _>>();
590        let closed = candidates
591            .iter()
592            .map(|&index| {
593                let edge = &result.edges[index];
594                edge.start_vertex_id == edge.end_vertex_id
595            })
596            .collect::<Vec<_>>();
597        // Both endpoint positions, or `None` when a vertex record is missing —
598        // exactly the tuple the exhaustive scan destructures, hoisted out of
599        // the inner loop so each candidate's two lookups happen once.
600        let endpoints = candidates
601            .iter()
602            .map(|&index| {
603                let edge = &result.edges[index];
604                match (
605                    points.get(&edge.start_vertex_id),
606                    points.get(&edge.end_vertex_id),
607                ) {
608                    (Some(&start), Some(&end)) => Some([start, end]),
609                    _ => None,
610                }
611            })
612            .collect::<Vec<_>>();
613        let closed_positions = (0..candidates.len())
614            .filter(|&position| closed[position])
615            .collect::<Vec<_>>();
616        let grid = match search {
617            PairSearch::Hashed => EndpointGrid::build(&endpoints, &closed, tolerance),
618            PairSearch::Exhaustive => None,
619        };
620
621        let mut chosen = None;
622        'pairs: for first_position in 0..candidates.len() {
623            let first = &result.edges[candidates[first_position]];
624            let first_closed = closed[first_position];
625            offer_seconds(
626                grid.as_ref(),
627                first_position,
628                first_closed,
629                &endpoints,
630                &closed_positions,
631                candidates.len(),
632                &mut neighbours,
633                &mut offered,
634            );
635            for second_position in offered.iter().copied() {
636                let second = &result.edges[candidates[second_position]];
637                pairs_examined += 1;
638                if blocked.contains(&unordered(first.id, second.id)) {
639                    continue;
640                }
641                if first_closed != closed[second_position] {
642                    continue;
643                }
644                if !first_closed {
645                    let (Some([fs, fe]), Some([ss, se])) =
646                        (endpoints[first_position], endpoints[second_position])
647                    else {
648                        continue;
649                    };
650                    let direct =
651                        fs.sub(ss).length() <= tolerance && fe.sub(se).length() <= tolerance;
652                    let reversed =
653                        fs.sub(se).length() <= tolerance && fe.sub(ss).length() <= tolerance;
654                    if !direct && !reversed {
655                        continue;
656                    }
657                }
658                if locus_deviation(first, second, 8)? > tolerance
659                    || locus_deviation(second, first, 8)? > tolerance
660                {
661                    continue;
662                }
663                let Some((keep, remove)) = orient_pair(&result, first, second, &points, tolerance)
664                else {
665                    // A seam-rotated rim pair with no safe direction: leave it
666                    // open, do not sew a torn loop shut.
667                    continue;
668                };
669                chosen = Some((keep.clone(), remove.clone()));
670                break 'pairs;
671            }
672        }
673        let Some((keep, remove)) = chosen else {
674            break;
675        };
676        match plan_rebind(&result, &keep, &remove, tolerance) {
677            Ok(patches) => {
678                apply_rebind(&mut result, &keep, &remove, patches, tolerance);
679                edges_sewn += 1;
680            }
681            Err(_) => {
682                blocked.insert(unordered(keep.id, remove.id));
683            }
684        }
685    }
686    // Drop vertices only referenced by removed duplicate edges.
687    let used_vertices = result
688        .edges
689        .iter()
690        .flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id])
691        .collect::<HashSet<_>>();
692    result
693        .vertices
694        .retain(|vertex| used_vertices.contains(&vertex.id));
695
696    let shells_merged = merge_connected_shells(&mut result);
697    let mut oriented_outward = false;
698    if edges_sewn > 0 {
699        // Components can arrive arbitrarily flipped; make the coedge
700        // directions coherent across the shared edges, then restore outward
701        // normals by signed volume.
702        // Each face's sense before orientation, for the pattern reading only.
703        let senses: HashMap<u64, bool> = if pattern.is_some() {
704            result.shells.iter().flat_map(|shell| &shell.faces).map(|face| (face.id, face.same_sense)).collect()
705        } else {
706            HashMap::default()
707        };
708        orient_open_solid_faces(&mut result)?;
709        let bar = tolerance * tolerance * tolerance;
710        let check = sew_sign_reading_check();
711        let by_pattern = match (pattern, sew_pattern_sign_mode()) {
712            (Some(hint), crate::env_read::Mode::On) if !check => sew_sign_by_pattern(&result, &senses, hint, bar),
713            (Some(hint), crate::env_read::Mode::Check) => {
714                // Held to the full integral: a verdict it gives must be the
715                // integral's, and the integral must clear the bar.
716                let started = web_time::Instant::now();
717                let pattern_reading = sew_sign_by_pattern(&result, &senses, hint, bar);
718                let ms = started.elapsed().as_secs_f64() * 1e3;
719                let volume = solid_signed_volume(&result).ok();
720                let exact = volume.filter(|volume| volume.abs() > bar).map(|volume| volume < 0.0);
721                let verdict = |flip: Option<bool>| match flip { Some(false) => "outward", Some(true) => "flipped", None => "none" };
722                eprintln!(
723                    "sew.sign_pattern{} pattern={} exact={} volume={:.6e} copies={} ms={ms:.3}",
724                    if pattern_reading.is_some() && pattern_reading != exact { " DISAGREE" } else { "" },
725                    verdict(pattern_reading),
726                    verdict(exact),
727                    volume.unwrap_or(f64::NAN),
728                    hint.count,
729                );
730                None
731            }
732            _ => None,
733        };
734        let reading = by_pattern.or_else(|| sew_sign_by_reading(&result, bar, check));
735        match reading {
736            Some(flip) if !check => {
737                if flip {
738                    flip_all_faces(&mut result)?;
739                }
740                oriented_outward = true;
741            }
742            _ => {
743                let exact = solid_signed_volume(&result);
744                if check {
745                    let agree = match (reading, exact.as_ref()) {
746                        (Some(flip), Ok(volume)) => flip == (*volume < 0.0) && volume.abs() > bar,
747                        _ => true,
748                    };
749                    eprintln!(
750                        "sew.sign_reading{} decided={} volume={:?}",
751                        if agree { "" } else { " DISAGREE" },
752                        match reading { Some(false) => "outward", Some(true) => "flipped", None => "none" },
753                        exact.as_ref().ok(),
754                    );
755                }
756                if let Ok(volume) = exact {
757                    if volume < 0.0 {
758                        flip_all_faces(&mut result)?;
759                    }
760                    oriented_outward = volume.abs() > bar;
761                }
762            }
763        }
764    }
765    // Re-derive genus from the Euler characteristic (V − E + F − H = 2 − 2g,
766    // H counting inner loops, matching validate()) so validation sees the
767    // merged topology, not the input's bookkeeping. Only when sewing actually
768    // changed the topology — a no-op must not touch a valid genus.
769    if edges_sewn > 0 || shells_merged > 0 {
770        let vertex_count = result.vertices.len() as i64;
771        let edge_count = result.edges.iter().filter(|edge| !edge.degenerate).count() as i64;
772        let face_count = result
773            .shells
774            .iter()
775            .map(|shell| shell.faces.len())
776            .sum::<usize>() as i64;
777        let ring_count = result
778            .shells
779            .iter()
780            .flat_map(|shell| &shell.faces)
781            .map(|face| face.loops.len().saturating_sub(1))
782            .sum::<usize>() as i64;
783        let numerator = 2 - (vertex_count - edge_count + face_count - ring_count);
784        if numerator >= 0 && numerator % 2 == 0 {
785            result.genus = numerator / 2;
786        }
787    }
788    let open_edges_after = one_use_edge_ids(&result).len();
789    let issues = result
790        .validate()
791        .into_iter()
792        .map(|issue| issue.message)
793        .collect();
794    Ok((
795        result,
796        SewReport {
797            edges_sewn,
798            shells_merged,
799            open_edges_before,
800            open_edges_after,
801            oriented_outward,
802            issues,
803        },
804        pairs_examined,
805    ))
806}
807
808/// `BREP_SEW_SIGN_READING` (default on; `0`/`off` integrates the full mass
809/// properties as before): the sewn result's orientation read
810/// for its sign alone, instead of by its full mass properties (area and volume
811/// integrated to the mass cache's precision, most of a large sew's time).
812///
813/// The sew needs two answers from the volume `v`: flip when `v < 0`, and call
814/// the body oriented when `|v| > bar` (`bar` = tolerance³). The sign reading
815/// ([`solid_signed_volume_for_sign`]) returns a value whose comparison with ITS
816/// bar is the exact integral's comparison, and nothing more. So:
817///
818/// * read against `bar`: above it, `v > bar`, so no flip and oriented;
819/// * otherwise read against `-bar` (the faces' terms are memoised by the first
820///   read): below it, `v < -bar`, so flip and oriented;
821/// * anything else (`|v| <= bar`, a sliver of no thickness, or an error in
822///   either read) decides nothing here: `None`, and the caller integrates the
823///   full volume exactly as before.
824///
825/// Where it answers and the full integral would succeed, its answer is the
826/// exact path's. The reading skips work the integral does (control-net
827/// bounds, skipped straight-chord corrections), so it can also answer where
828/// the integral would have failed and left the body unflipped and not
829/// oriented. The second read's certificates can only prove a value above
830/// their bar, so against `-bar` it is the reading itself that decides; an
831/// inside-out sew pays for both. `check` reads it even with the switch off
832/// (the caller then still integrates and compares).
833/// What [`sew_rotated_copies`] tells the sew about its soup: face `f` of the
834/// cell is face `f + (k + 1) * span` of copy `k`, every copy turned about the
835/// axis through `axis_origin`, and the copies make one full turn.
836struct PatternHint {
837    /// The cell's kept face ids, in the cell's order.
838    kept: Vec<u64>,
839    span: u64,
840    count: usize,
841    axis_origin: Vec3,
842    full_turn: bool,
843}
844
845/// `BREP_SEW_PATTERN_SIGN` (default on since 2026-11-21: check mode agreed on
846/// every caller, the bench's two hobbed gears, and it reaches nothing but
847/// [`sew_rotated_copies`]; `0` off, `check` reads it beside the
848/// full integral and prints one `sew.sign_pattern` line per sew, ` DISAGREE`
849/// where it decides otherwise): [`sew_rotated_copies`] reads the sewn
850/// pattern's orientation from one copy ([`sew_sign_by_pattern`]).
851fn sew_pattern_sign_mode() -> crate::env_read::Mode {
852    crate::mode_switch!("BREP_SEW_PATTERN_SIGN", true)
853}
854
855/// The sewn pattern's orientation read from ONE copy: `Some(true)` to flip,
856/// `Some(false)` to keep, `None` to leave it to the readings as before.
857///
858/// A face's volume term about a point `p`, `(1/3) ∫ (S − p) · N dA`, is
859/// unchanged when the face is turned about an axis through `p`: the turn
860/// moves `S − p` and `N` alike. So when every copy's SEWN faces are copy 0's
861/// sewn faces turned (and the copies close one full turn), the solid's signed
862/// volume is `count` times the sum of copy 0's terms about a point on the axis.
863/// That is checked, cheaply and by provenance, before it is used:
864/// - one shell, every non-degenerate edge used twice (closed);
865/// - `orient_open_solid_faces` flipped no face, or every face (a mixed flip
866///   would make the copies differ in sense);
867/// - every sewn face belongs to exactly one copy by its id offset, each copy
868///   holds every kept face once, and each face of copy `k` matches its copy-0
869///   face in carrier degrees, control net size, sense, loop count and every
870///   loop's coedge count (a face the sew merged, split or re-trimmed across a
871///   copy boundary breaks this and falls back);
872/// - the copies are turns in floating point and their sewn trims re-project
873///   per copy, so the reading decides only when `count · Σ` clears the bar by
874///   `1e-2` of `count · Σ |term|` (orders of magnitude above that rounding,
875///   and above the trimmed integrator's known loop-start sensitivity).
876fn sew_sign_by_pattern(result: &BrepSolid, senses: &HashMap<u64, bool>, hint: &PatternHint, bar: f64) -> Option<bool> {
877    if !hint.full_turn || hint.count == 0 || hint.kept.is_empty() {
878        return None;
879    }
880    let [shell] = result.shells.as_slice() else {
881        return None;
882    };
883    let degenerate: HashSet<u64> = result.edges.iter().filter(|edge| edge.degenerate).map(|edge| edge.id).collect();
884    let mut uses = HashMap::<u64, usize>::default();
885    for coedge in shell.faces.iter().flat_map(|face| &face.loops).flat_map(|loop_record| &loop_record.coedges) {
886        if !degenerate.contains(&coedge.edge_id) {
887            *uses.entry(coedge.edge_id).or_default() += 1;
888        }
889    }
890    if uses.values().any(|&count| count != 2) {
891        return None;
892    }
893    let flipped = shell.faces.iter().filter(|face| senses.get(&face.id).is_some_and(|&sense| sense != face.same_sense)).count();
894    if shell.faces.iter().any(|face| !senses.contains_key(&face.id)) || (flipped != 0 && flipped != shell.faces.len()) {
895        return None;
896    }
897    if shell.faces.len() != hint.count * hint.kept.len() {
898        return None;
899    }
900    let by_id: HashMap<u64, &FaceRecord> = shell.faces.iter().map(|face| (face.id, face)).collect();
901    let shape = |face: &FaceRecord| {
902        (
903            face.surface.degree_u,
904            face.surface.degree_v,
905            face.surface.control_points.len(),
906            face.surface.control_points.first().map_or(0, Vec::len),
907            face.same_sense,
908            face.loops.iter().map(|loop_record| loop_record.coedges.len()).collect::<Vec<_>>(),
909        )
910    };
911    let mut sum = 0.0f64;
912    let mut magnitude = 0.0f64;
913    for &kept in &hint.kept {
914        let first = by_id.get(&(kept + hint.span))?;
915        let first_shape = shape(first);
916        for k in 1..hint.count as u64 {
917            let copy = by_id.get(&(kept + (k + 1) * hint.span))?;
918            if shape(copy) != first_shape {
919                return None;
920            }
921        }
922        let terms = crate::mass_properties::face_volume_terms_about(first, hint.axis_origin).ok()?;
923        if !terms[0].is_finite() {
924            return None;
925        }
926        sum += terms[0];
927        magnitude += terms[0].abs();
928    }
929    let count = hint.count as f64;
930    let (volume, margin) = (count * sum, bar + 1e-2 * count * magnitude);
931    if !(volume.is_finite() && margin.is_finite()) {
932        None
933    } else if volume > margin {
934        Some(false)
935    } else if volume < -margin {
936        Some(true)
937    } else {
938        None
939    }
940}
941
942/// Sew `count` copies of `cell`'s faces `kept_faces`, copy `k` turned by
943/// `k · step` (radians, right-handed about `axis_direction`) about the axis
944/// through `axis_origin`, into one solid: the faces left out are the cell's
945/// faces on the surfaces dividing it from its neighbours, where a copy meets
946/// the next. The soup is the cell's kept faces per copy, ids offset per copy
947/// by one span past the cell's largest id (copy `k` by `(k + 1) · span`),
948/// with the edges and vertices they use, sewn as [`sew_solid`] sews.
949/// Beside the solid and its report, the result's face ids by copy (copy `k`
950/// at index `k`, each in the cell's face order).
951///
952/// The orientation: with `BREP_SEW_PATTERN_SIGN` (default on) and `count · step` one
953/// full turn, it is read from one copy ([`sew_sign_by_pattern`]), else as
954/// [`sew_solid`] reads it. About the z axis through the origin each turn is
955/// the matrix `[c −s 0 0; s c 0 0; 0 0 1 0]` of `(s, c) = (k·step).sin_cos()`.
956///
957/// Refused: a cell that is not a plain solid of one shell (a cellular body's
958/// regions would name the cell's ids), no kept face, a kept id the cell
959/// lacks, a zero count, a non-finite or zero axis, a non-finite step, or ids
960/// too large for `count + 1` spans.
961pub fn sew_rotated_copies(
962    cell: &BrepSolid,
963    kept_faces: &[u64],
964    axis_origin: Vec3,
965    axis_direction: Vec3,
966    step: f64,
967    count: usize,
968    tolerance: f64,
969) -> Result<(BrepSolid, SewReport, Vec<Vec<u64>>), KernelRefusal> {
970    let refuse = |what: &'static str, why: String| Err(KernelRefusal::input(KernelStage::Collect, what, why));
971    let [shell] = cell.shells.as_slice() else {
972        return refuse("cell", "sew_rotated_copies: the cell is not one shell".into());
973    };
974    if cell.kind != crate::BodyKind::Solid || !cell.cells.is_empty() {
975        return refuse("cell", "sew_rotated_copies: the cell is not a plain solid".into());
976    }
977    if kept_faces.is_empty() {
978        return refuse("kept_faces", "sew_rotated_copies: no face of the cell is kept".into());
979    }
980    if let Some(missing) = kept_faces.iter().find(|&&id| !shell.faces.iter().any(|face| face.id == id)) {
981        return refuse("kept_faces", format!("sew_rotated_copies: the cell has no face {missing}"));
982    }
983    if count == 0 {
984        return refuse("count", "sew_rotated_copies: count must be at least one".into());
985    }
986    if !step.is_finite() || ![axis_origin.x, axis_origin.y, axis_origin.z].iter().all(|v| v.is_finite()) {
987        return refuse("step", "sew_rotated_copies: the step and the axis origin must be finite".into());
988    }
989    // Scaled to its largest component first, so that no square overflows.
990    let largest = axis_direction.x.abs().max(axis_direction.y.abs()).max(axis_direction.z.abs());
991    let axis = (largest > 0.0 && largest.is_finite())
992        .then(|| Vec3::new(axis_direction.x / largest, axis_direction.y / largest, axis_direction.z / largest).normalized().ok())
993        .flatten()
994        .filter(|axis| (axis.length() - 1.0).abs() <= 1e-12);
995    let Some(axis) = axis else {
996        return refuse("axis_direction", "sew_rotated_copies: the axis direction must be a finite, non-zero vector".into());
997    };
998    let along_z = axis_direction.x == 0.0 && axis_direction.y == 0.0 && axis_direction.z > 0.0;
999    let turn = |angle: f64| -> Result<crate::transform_topology::AffineTransform, KernelRefusal> {
1000        let (s, c) = angle.sin_cos();
1001        let r = if along_z {
1002            [[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]
1003        } else {
1004            let (x, y, z) = (axis.x, axis.y, axis.z);
1005            let t = 1.0 - c;
1006            [
1007                [c + t * x * x, t * x * y - s * z, t * x * z + s * y],
1008                [t * x * y + s * z, c + t * y * y, t * y * z - s * x],
1009                [t * x * z - s * y, t * y * z + s * x, c + t * z * z],
1010            ]
1011        };
1012        let o = axis_origin;
1013        let moved = |row: [f64; 3]| row[0] * o.x + row[1] * o.y + row[2] * o.z;
1014        let shift = if o.x == 0.0 && o.y == 0.0 && o.z == 0.0 {
1015            [0.0; 3]
1016        } else {
1017            [o.x - moved(r[0]), o.y - moved(r[1]), o.z - moved(r[2])]
1018        };
1019        crate::transform_topology::AffineTransform::new([
1020            r[0][0], r[0][1], r[0][2], shift[0], //
1021            r[1][0], r[1][1], r[1][2], shift[1], //
1022            r[2][0], r[2][1], r[2][2], shift[2], //
1023            0.0, 0.0, 0.0, 1.0,
1024        ])
1025        .map_err(|why| KernelRefusal::input(KernelStage::Collect, "step", format!("sew_rotated_copies: {why}")))
1026    };
1027    let kept: Vec<u64> = shell.faces.iter().map(|face| face.id).filter(|id| kept_faces.contains(id)).collect();
1028    let kept_set: HashSet<u64> = kept.iter().copied().collect();
1029    let largest_id = cell
1030        .vertices
1031        .iter()
1032        .map(|vertex| vertex.id)
1033        .chain(cell.edges.iter().map(|edge| edge.id))
1034        .chain(shell.faces.iter().flat_map(|face| {
1035            std::iter::once(face.id).chain(face.loops.iter().flat_map(|loop_record| {
1036                std::iter::once(loop_record.id).chain(loop_record.coedges.iter().map(|coedge| coedge.id))
1037            }))
1038        }))
1039        .max()
1040        .unwrap_or(0);
1041    // Every id of copy k is below (k + 2) * span: count + 1 spans must fit.
1042    let spans = (count as u64).checked_add(1);
1043    let Some(span) = largest_id.checked_add(1).filter(|span| spans.is_some_and(|spans| span.checked_mul(spans).is_some())) else {
1044        return refuse("cell", "sew_rotated_copies: the cell's ids are too large for this many copies".into());
1045    };
1046    let mut soup = cell.clone();
1047    soup.shells[0].faces.clear();
1048    soup.vertices.clear();
1049    soup.edges.clear();
1050    for k in 0..count as u64 {
1051        let copy = crate::transform_topology::transform_brep(cell, turn(step * k as f64)?, false)
1052            .map_err(|why| KernelRefusal::internal(KernelStage::Collect, "transform", format!("sew_rotated_copies: {why}")))?;
1053        let offset = (k + 1) * span;
1054        let mut used_edges = HashSet::default();
1055        for face in copy.shells[0].faces.iter().filter(|face| kept_set.contains(&face.id)) {
1056            let mut face = face.clone();
1057            face.id += offset;
1058            for loop_record in &mut face.loops {
1059                loop_record.id += offset;
1060                for coedge in &mut loop_record.coedges {
1061                    used_edges.insert(coedge.edge_id);
1062                    coedge.id += offset;
1063                    coedge.edge_id += offset;
1064                }
1065            }
1066            soup.shells[0].faces.push(face);
1067        }
1068        let mut used_vertices = HashSet::default();
1069        for edge in copy.edges.iter().filter(|edge| used_edges.contains(&edge.id)) {
1070            let mut edge = edge.clone();
1071            used_vertices.extend([edge.start_vertex_id, edge.end_vertex_id]);
1072            edge.id += offset;
1073            edge.start_vertex_id += offset;
1074            edge.end_vertex_id += offset;
1075            soup.edges.push(edge);
1076        }
1077        for vertex in copy.vertices.iter().filter(|vertex| used_vertices.contains(&vertex.id)) {
1078            let mut vertex = vertex.clone();
1079            vertex.id += offset;
1080            soup.vertices.push(vertex);
1081        }
1082    }
1083    let full_turn = ((count as f64) * step.abs() - std::f64::consts::TAU).abs() <= 1e-9 * std::f64::consts::TAU;
1084    let hint = PatternHint { kept: kept.clone(), span, count, axis_origin, full_turn };
1085    let (sewn, report, _) = sew_solid_with_pattern(&soup, tolerance, PairSearch::Hashed, Some(&hint))?;
1086    let present: HashSet<u64> = sewn.shells.iter().flat_map(|shell| &shell.faces).map(|face| face.id).collect();
1087    let copy_faces = (0..count as u64)
1088        .map(|k| kept.iter().map(|id| id + (k + 1) * span).filter(|id| present.contains(id)).collect())
1089        .collect();
1090    Ok((sewn, report, copy_faces))
1091}
1092
1093fn sew_sign_by_reading(solid: &BrepSolid, bar: f64, check: bool) -> Option<bool> {
1094    if !(check || sew_sign_reading_enabled()) || !(bar > 0.0) || !bar.is_finite() {
1095        return None;
1096    }
1097    let (coarse_on, coarse_check) = (sew_sign_coarse_enabled(), sew_sign_coarse_check());
1098    let coarse = if coarse_on && !coarse_check { sew_sign_by_coarse_certificate(solid, bar) } else { None };
1099    if let (Some(flip), true, false) = (coarse, coarse_on, coarse_check) {
1100        return Some(flip);
1101    }
1102    let decided = (|| {
1103        if solid_signed_volume_for_sign(solid, bar).ok()? > bar {
1104            return Some(false);
1105        }
1106        if solid_signed_volume_for_sign(solid, -bar).ok()? < -bar {
1107            return Some(true);
1108        }
1109        None
1110    })();
1111    if coarse_check {
1112        // The certificate is held to the full integral: its interval must
1113        // hold it, and a verdict it settles must be the integral's. One line
1114        // per depth, so a census shows what each depth would decide.
1115        let volume = solid_signed_volume(solid).ok();
1116        let exact = volume.filter(|volume| volume.abs() > bar).map(|volume| volume < 0.0);
1117        for depth in [COARSE_SIGN_DEPTH, 2, 3] {
1118            let started = web_time::Instant::now();
1119            let certificate = solid_sign_coarse_certificate(solid, depth);
1120            let ms = started.elapsed().as_secs_f64() * 1e3;
1121            let settled = certificate.and_then(|certificate| coarse_verdict(certificate.reading, certificate.bound, bar));
1122            let held = match (certificate, volume) {
1123                (Some(certificate), Some(volume)) => (volume - certificate.reading).abs() <= certificate.bound,
1124                _ => true,
1125            };
1126            let agree = held && (settled.is_none() || settled == exact);
1127            let (reading, bound, skipped) =
1128                certificate.map_or((f64::NAN, f64::NAN, f64::NAN), |c| (c.reading, c.bound, c.skipped));
1129            eprintln!(
1130                "sew.sign_coarse{} depth={depth} thin={} coarse={} exact={} reading={reading:.6e} bound={bound:.3e} skipped={skipped:.3e} volume={:.6e} bar={bar:.1e} ms={ms:.3}",
1131                if agree { "" } else { " DISAGREE" },
1132                sign_coarse_thin_enabled(),
1133                match settled { Some(false) => "outward", Some(true) => "flipped", None => "none" },
1134                match exact { Some(false) => "outward", Some(true) => "flipped", None => "none" },
1135                volume.unwrap_or(f64::NAN),
1136            );
1137        }
1138    }
1139    decided
1140}
1141
1142/// The orientation the coarse certificate settles, if any. Contract: the
1143/// certificate (`solid_sign_coarse_certificate`) gives an interval
1144/// `reading ± bound` that holds the volume. A verdict comes only when the
1145/// whole interval clears the bar. Flip (`Some(true)`) when it lies below
1146/// `-bar`, keep (`Some(false)`) when it lies above `bar`. Otherwise `None`:
1147/// the sign reading and the full integral decide, as they would without it.
1148/// That covers no certificate, a straddling interval, and anything
1149/// non-finite.
1150fn sew_sign_by_coarse_certificate(solid: &BrepSolid, bar: f64) -> Option<bool> {
1151    let certificate = solid_sign_coarse_certificate(solid, COARSE_SIGN_DEPTH)?;
1152    coarse_verdict(certificate.reading, certificate.bound, bar)
1153}
1154
1155fn coarse_verdict(reading: f64, bound: f64, bar: f64) -> Option<bool> {
1156    if !(reading.is_finite() && bound.is_finite() && bound >= 0.0) {
1157        return None;
1158    }
1159    if reading - bound > bar {
1160        Some(false)
1161    } else if reading + bound < -bar {
1162        Some(true)
1163    } else {
1164        None
1165    }
1166}
1167
1168/// `BREP_SEW_SIGN_COARSE` (default on since 2026-11-20; `=0` skips the
1169/// coarse certificate): the sew's orientation is first read
1170/// by the coarse certificate ([`sew_sign_by_coarse_certificate`]); where that
1171/// settles it, the sign reading and the full integral are not run.
1172fn sew_sign_coarse_enabled() -> bool {
1173    crate::switch!("BREP_SEW_SIGN_COARSE", true)
1174}
1175
1176/// `BREP_SEW_SIGN_COARSE_CHECK=1`: let the old path decide, and print, per
1177/// sew and per depth, one `sew.sign_coarse` line with the certificate's
1178/// reading, bound and verdict against the full integral (` DISAGREE` where
1179/// the interval misses the integral or the verdict differs).
1180fn sew_sign_coarse_check() -> bool {
1181    crate::debug_flag!("BREP_SEW_SIGN_COARSE_CHECK")
1182}
1183
1184fn sew_sign_reading_enabled() -> bool {
1185    crate::switch!("BREP_SEW_SIGN_READING", true)
1186}
1187
1188/// `BREP_SEW_SIGN_READING_CHECK=1`: run the reading AND the full integral,
1189/// let the integral decide, and print one `sew.sign_reading` line per sew
1190/// (` DISAGREE` where the reading decided otherwise), for an agreement census.
1191fn sew_sign_reading_check() -> bool {
1192    crate::debug_flag!("BREP_SEW_SIGN_READING_CHECK")
1193}
1194
1195
1196
1197/// Split PINCHED vertices — points where two (or more) umbrella fans of
1198/// faces meet at a single vertex record. Local manifold checks (edge use
1199/// counts, loop closure, orientation) cannot see a pinch; it surfaces only
1200/// as an odd Euler characteristic. The link of a manifold boundary vertex is
1201/// a single edge-connected fan: union incident edges through every loop
1202/// CORNER at the vertex (consecutive coedges meeting there inside one face);
1203/// more than one component means distinct fans sharing the record — give
1204/// each extra fan its own vertex at the same point and reassign that fan's
1205/// edge endpoints. Geometry is untouched; only identity is repaired.
1206pub fn split_pinched_vertices(solid: &mut BrepSolid) -> Result<usize, KernelRefusal> {
1207    let mut split_count = 0usize;
1208    let vertex_ids: Vec<u64> = solid.vertices.iter().map(|vertex| vertex.id).collect();
1209    let mut next_id = solid
1210        .vertices
1211        .iter()
1212        .map(|vertex| vertex.id)
1213        .chain(solid.edges.iter().map(|edge| edge.id))
1214        .max()
1215        .unwrap_or(0)
1216        + 1;
1217    // id -> index maps built once. This routine only mutates edge endpoints
1218    // in place and appends vertices, so indices never shift: every lookup
1219    // returns the identical live record the previous `.iter().find(id==)`
1220    // scans returned. Kills the O(V*coedges*E) nested edge find below.
1221    let edge_of_id: HashMap<u64, usize> = solid
1222        .edges
1223        .iter()
1224        .enumerate()
1225        .map(|(index, edge)| (edge.id, index))
1226        .collect();
1227    let vertex_of_id: HashMap<u64, usize> = solid
1228        .vertices
1229        .iter()
1230        .enumerate()
1231        .map(|(index, vertex)| (vertex.id, index))
1232        .collect();
1233    for vertex_id in vertex_ids {
1234        // Incident edges (either endpoint; closed and degenerate included so
1235        // pole/seam structures stay connected through their corners).
1236        let incident: Vec<u64> = solid
1237            .edges
1238            .iter()
1239            .filter(|edge| edge.start_vertex_id == vertex_id || edge.end_vertex_id == vertex_id)
1240            .map(|edge| edge.id)
1241            .collect();
1242        if incident.len() < 4 {
1243            // A pinch needs at least two fans of >= 2 edges each.
1244            continue;
1245        }
1246        let index_of: HashMap<u64, usize> = incident
1247            .iter()
1248            .enumerate()
1249            .map(|(index, id)| (*id, index))
1250            .collect();
1251        let mut parent: Vec<usize> = (0..incident.len()).collect();
1252        fn root(parent: &mut [usize], index: usize) -> usize {
1253            if parent[index] != index {
1254                parent[index] = root(parent, parent[index]);
1255            }
1256            parent[index]
1257        }
1258        let edge_end = |edge_id: u64, forward: bool| -> Option<u64> {
1259            edge_of_id.get(&edge_id).map(|&index| {
1260                let edge = &solid.edges[index];
1261                if forward {
1262                    edge.end_vertex_id
1263                } else {
1264                    edge.start_vertex_id
1265                }
1266            })
1267        };
1268        for shell in &solid.shells {
1269            for face in &shell.faces {
1270                for loop_record in &face.loops {
1271                    let count = loop_record.coedges.len();
1272                    for index in 0..count {
1273                        let current = &loop_record.coedges[index];
1274                        let next = &loop_record.coedges[(index + 1) % count];
1275                        // The corner between current and next sits at
1276                        // current's traversal END vertex.
1277                        let Some(junction) = edge_end(current.edge_id, current.forward) else {
1278                            continue;
1279                        };
1280                        if junction != vertex_id {
1281                            continue;
1282                        }
1283                        let (Some(&a), Some(&b)) =
1284                            (index_of.get(&current.edge_id), index_of.get(&next.edge_id))
1285                        else {
1286                            continue;
1287                        };
1288                        let ra = root(&mut parent, a);
1289                        let rb = root(&mut parent, b);
1290                        if ra != rb {
1291                            parent[rb] = ra;
1292                        }
1293                    }
1294                }
1295            }
1296        }
1297        let mut component_of: HashMap<usize, usize> = HashMap::default();
1298        let mut components = 0usize;
1299        let mut assignment: Vec<usize> = vec![0; incident.len()];
1300        for index in 0..incident.len() {
1301            let r = root(&mut parent, index);
1302            let component = *component_of.entry(r).or_insert_with(|| {
1303                components += 1;
1304                components - 1
1305            });
1306            assignment[index] = component;
1307        }
1308        if components < 2 {
1309            continue;
1310        }
1311        // Keep the original record for component 0; every further fan gets a
1312        // duplicate vertex at the same point.
1313        let point = vertex_of_id
1314            .get(&vertex_id)
1315            .map(|&index| solid.vertices[index].point)
1316            .ok_or(KernelRefusal::internal(KernelStage::Sew, "pinched_vertex", "split_pinched_vertices: vertex vanished"))?;
1317        let mut replacement_ids = vec![vertex_id];
1318        for _ in 1..components {
1319            let id = next_id;
1320            next_id += 1;
1321            solid.vertices.push(VertexRecord { id, point });
1322            replacement_ids.push(id);
1323        }
1324        for (offset, edge_id) in incident.iter().enumerate() {
1325            let replacement = replacement_ids[assignment[offset]];
1326            if replacement == vertex_id {
1327                continue;
1328            }
1329            if let Some(edge) = solid.edges.iter_mut().find(|edge| edge.id == *edge_id) {
1330                if edge.start_vertex_id == vertex_id {
1331                    edge.start_vertex_id = replacement;
1332                }
1333                if edge.end_vertex_id == vertex_id {
1334                    edge.end_vertex_id = replacement;
1335                }
1336            }
1337        }
1338        split_count += components - 1;
1339    }
1340    Ok(split_count)
1341}
1342