Skip to main content

brep_boolean/healing/
face_merge.rs

1use crate::analytic_surface::circumcenter;
2pub use crate::mass_properties::{face_area, face_volume_contribution, parameter_space_area};
3pub use crate::topology::{BrepSolid, CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord};
4pub use crate::{
5    build_pcurve_on_surface, make_line, make_plane, make_revolution, KnotVector, NurbsCurve,
6    NurbsSurface, Vec3, Vec4,
7};
8use crate::{KernelRefusal, KernelStage, OrRefuse, RefusalClass};
9pub use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
10
11fn controls_match(first: Vec4, second: Vec4, tolerance: f64) -> bool {
12    (first.x - second.x).abs() <= tolerance
13        && (first.y - second.y).abs() <= tolerance
14        && (first.z - second.z).abs() <= tolerance
15        && (first.w - second.w).abs() <= tolerance
16}
17
18/// Whether two faces ride the SAME carrier patch — identical degrees, knots
19/// and control points inside `tolerance`. `pub` because the direct-edit
20/// cap lane asks the same question for the same reason this module does: when
21/// two faces share one carrier their coedges' pcurves are interchangeable, so
22/// loops can move between them with nothing refit.
23pub fn same_surface(first: &NurbsSurface, second: &NurbsSurface, tolerance: f64) -> bool {
24    first.degree_u == second.degree_u
25        && first.degree_v == second.degree_v
26        && first.knots_u.len() == second.knots_u.len()
27        && first.knots_v.len() == second.knots_v.len()
28        && first.control_points.len() == second.control_points.len()
29        && first
30            .control_points
31            .iter()
32            .zip(&second.control_points)
33            .all(|(a, b)| {
34                a.len() == b.len()
35                    && a.iter()
36                        .zip(b)
37                        .all(|(a, b)| controls_match(*a, *b, tolerance))
38            })
39        && first
40            .knots_u
41            .iter()
42            .zip(&second.knots_u)
43            .all(|(a, b)| (a - b).abs() <= tolerance)
44        && first
45            .knots_v
46            .iter()
47            .zip(&second.knots_v)
48            .all(|(a, b)| (a - b).abs() <= tolerance)
49}
50
51fn surface_domains(surface: &NurbsSurface) -> Result<([f64; 2], [f64; 2]), KernelRefusal> {
52    Ok((
53        KnotVector::new(surface.knots_u.clone(), surface.degree_u)
54            .or_refuse(KernelStage::Sew, "new")?
55            .domain(),
56        KnotVector::new(surface.knots_v.clone(), surface.degree_v)
57            .or_refuse(KernelStage::Sew, "new")?
58            .domain(),
59    ))
60}
61
62pub fn outward_normal(face: &FaceRecord) -> Result<Vec3, KernelRefusal> {
63    let (u, v) = surface_domains(&face.surface)?;
64    let normal = face
65        .surface
66        .normal((u[0] + u[1]) / 2.0, (v[0] + v[1]) / 2.0)
67        .or_refuse(KernelStage::Sew, "healing.face_merge")?;
68    Ok(if face.same_sense {
69        normal
70    } else {
71        normal.scale(-1.0)
72    })
73}
74
75fn planar_support(
76    face: &FaceRecord,
77    tolerance: f64,
78) -> Result<Option<(Vec3, Vec3)>, KernelRefusal> {
79    let (u, v) = surface_domains(&face.surface)?;
80    let midpoint_u = (u[0] + u[1]) / 2.0;
81    let midpoint_v = (v[0] + v[1]) / 2.0;
82    let origin = face
83        .surface
84        .evaluate(midpoint_u, midpoint_v)
85        .or_refuse(KernelStage::Sew, "evaluate")?;
86    // No normal at the domain centre (a cusp, pinch or fold line through the
87    // carrier): no plane (`BREP_SINGULAR_CENTRE_NOT_PLANAR`, default off).
88    let normal = match face.surface.normal(midpoint_u, midpoint_v) {
89        Ok(normal) => normal,
90        Err(error) => {
91            if crate::imprint::support::singular_centre_not_planar(|| format!("face_merge: face {}", face.id), &error) {
92                return Ok(None);
93            }
94            return Err(error).or_refuse(KernelStage::Sew, "normal");
95        }
96    };
97    let controls = face
98        .surface
99        .control_points
100        .iter()
101        .flatten()
102        .map(|control| control.point())
103        .collect::<Result<Vec<_>, _>>()
104        .or_refuse(KernelStage::Sew, "healing.face_merge")?;
105    let scale = controls
106        .iter()
107        .map(|point| point.sub(origin).length())
108        .fold(1.0f64, f64::max);
109    let plane_tolerance = (tolerance * 100.0).max(1e-7) * scale;
110    if controls
111        .iter()
112        .all(|point| point.sub(origin).dot(normal).abs() <= plane_tolerance)
113    {
114        Ok(Some((origin, normal)))
115    } else {
116        Ok(None)
117    }
118}
119
120fn coplanar_with_same_outward_normal(
121    first: &FaceRecord,
122    second: &FaceRecord,
123    tolerance: f64,
124) -> Result<bool, KernelRefusal> {
125    let Some((first_origin, first_geometric_normal)) = planar_support(first, tolerance)? else {
126        return Ok(false);
127    };
128    let Some((_, second_geometric_normal)) = planar_support(second, tolerance)? else {
129        return Ok(false);
130    };
131    if first_geometric_normal.dot(second_geometric_normal).abs() < 1.0 - 1e-7 {
132        return Ok(false);
133    }
134    let first_normal = outward_normal(first)?;
135    let second_normal = outward_normal(second)?;
136    if first_normal.dot(second_normal) < 1.0 - 1e-7 {
137        return Ok(false);
138    }
139    let (second_u, second_v) = surface_domains(&second.surface)?;
140    // The merged face is emitted carrying `first`'s plane, so every point of
141    // `second` has to lie ON that plane, not merely near it.  The band is the
142    // caller's coplanarity tolerance, floored where a caller asks for less
143    // than its own fitting noise and CAPPED at the assembler weld: past that
144    // the assembler holds a point and this plane apart, so the merged face is
145    // one nothing exact downstream can consume — the STEP importer's phase
146    // 1.75 ear-clips precisely such a face back into planar triangles.
147    //
148    // The cap replaces a `* (1.0 + first_origin.length())` factor that
149    // charged the band by how far the plane's origin sits from the WORLD
150    // origin — where the part happens to have been modelled, not a property
151    // of its geometry.  On a 190-unit part 50 units out it opened a 1.9e-7
152    // request to a 9.7e-4 band, wide enough to merge adjacent facets of a
153    // tessellated curve into one "plane" whose own corners sat 5.4e-4 off it.
154    let plane_tolerance = (tolerance * 100.0)
155        .max(1e-6)
156        .min(crate::tolerance::assembler_weld(tolerance));
157    for u in second_u {
158        for v in second_v {
159            if second
160                .surface
161                .evaluate(u, v)
162                .or_refuse(KernelStage::Sew, "evaluate")?
163                .sub(first_origin)
164                .dot(first_normal)
165                .abs()
166                > plane_tolerance
167            {
168                return Ok(false);
169            }
170        }
171    }
172    Ok(true)
173}
174
175/// Circular-arc support of a curve, detected by sampling: circumcenter of
176/// three spread samples, validated against all samples for constant radius
177/// and planarity. Returns (center, unit plane normal, radius).
178fn arc_circle_support(
179    curve: &NurbsCurve,
180    tolerance: f64,
181) -> Result<Option<(Vec3, Vec3, f64)>, KernelRefusal> {
182    let [t0, t1] = curve.domain().or_refuse(KernelStage::Sew, "domain")?;
183    let samples = (0..=8)
184        .map(|index| curve.evaluate(t0 + (t1 - t0) * index as f64 / 8.0))
185        .collect::<Result<Vec<_>, _>>()
186        .or_refuse(KernelStage::Sew, "healing.face_merge")?;
187    // A full-circle carrier evaluates identical endpoints, so the sample
188    // triple must avoid (start, end); fall back across spreads until one is
189    // non-degenerate.
190    let Some(center) = circumcenter(samples[0], samples[2], samples[5])
191        .or_else(|| circumcenter(samples[0], samples[4], samples[8]))
192        .or_else(|| circumcenter(samples[1], samples[4], samples[7]))
193    else {
194        return Ok(None);
195    };
196    let radius = samples[0].sub(center).length();
197    if radius <= tolerance {
198        return Ok(None);
199    }
200    let normal = match samples[2]
201        .sub(samples[0])
202        .cross(samples[5].sub(samples[0]))
203        .normalized()
204        .or_else(|_| {
205            samples[4]
206                .sub(samples[0])
207                .cross(samples[8].sub(samples[0]))
208                .normalized()
209        }) {
210        Ok(normal) => normal,
211        Err(_) => return Ok(None),
212    };
213    let band = tolerance.max(1e-9 * radius);
214    for sample in &samples {
215        let delta = sample.sub(center);
216        if (delta.length() - radius).abs() > band || delta.dot(normal).abs() > band {
217            if std::env::var("BREP_DEBUG_MERGE").is_ok() {
218                eprintln!(
219                    "    arc reject: radius={radius} dr={} dplane={} band={band}",
220                    (delta.length() - radius).abs(),
221                    delta.dot(normal).abs()
222                );
223            }
224            return Ok(None);
225        }
226    }
227    Ok(Some((center, normal, radius)))
228}
229
230/// Merge lanes a caller opts into beyond what the solid-wide merge does.
231///
232/// The solid-wide merge runs after every boolean and keeps every face it does
233/// not have to join: the default (all off) is exactly its behaviour. A caller
234/// joining faces the USER selected together (Push Face on the halves of an
235/// imported bore) asks for more: those faces are one region of one carrier by
236/// the user's own reading, and a face the merge leaves split is a face the
237/// edit cannot move.
238#[derive(Clone, Copy, Debug, Default)]
239pub struct MergeLanes<'a> {
240    /// Admit a CONE (a ruled revolution whose two boundary circles differ in
241    /// radius) wherever the cylinder lanes run. Only the full-turn lane builds
242    /// its carrier from the radius at each end; the partial-turn lane stays
243    /// cylinder-only.
244    pub cones: bool,
245    /// Let the full-turn lane seam a ring closed by two half-turn patches on
246    /// a SHARED axial edge (the halves of a bore written as two faces). The
247    /// solid-wide merge keeps such pairs apart (see `merge_cylinder_full_turn`).
248    pub shared_seam_ring: bool,
249    /// Among equally ranked seam candidates, prefer an axial edge ending at one
250    /// of these vertices: the seam a coaxial neighbour of the same selection
251    /// already kept, so the rim the two faces share meets both seams at ONE
252    /// vertex and closes into one circle.
253    pub seam_vertices: Option<&'a HashSet<u64>>,
254    /// The re-seam lane ([`rejoin_seam_split_pairs`]): join only two pieces
255    /// of ONE cylinder or frustum carrier whose only shared edges are the
256    /// carrier's own seam, on a carrier seamed in their union's angular gap,
257    /// and decline every other pair.
258    pub reseam: bool,
259}
260
261pub struct CylinderSupport {
262    origin: Vec3,
263    axis: Vec3,
264    /// The radius at `origin`.
265    radius: f64,
266    /// dρ per unit of axial travel along `axis`: zero for a cylinder, the
267    /// cone's slope for a cone (admitted only under `MergeLanes::cones`).
268    slope: f64,
269    /// +1 when the face's outward normal points radially away from the
270    /// axis, -1 when it points inward.
271    outward_radial_sign: f64,
272}
273
274impl CylinderSupport {
275    /// The carrier's radius `axial` along `axis` from `origin`.
276    fn radius_at(&self, axial: f64) -> f64 {
277        self.radius + self.slope * axial
278    }
279}
280
281/// Detect a ruled cylinder patch: quadratic circular arc in one parameter
282/// direction, linear in the other, both boundary arcs sharing an axis and
283/// radius. Covers extruded arcs, revolved axis-parallel lines, and
284/// primitive cylinder walls regardless of parameterization. With
285/// `allow_cone`, two coaxial boundary arcs of DIFFERENT radii are a cone
286/// patch, admitted when the patch's midpoint lies on the cone they span.
287pub fn ruled_cylinder_support(
288    face: &FaceRecord,
289    tolerance: f64,
290    allow_cone: bool,
291    allow_apex: bool,
292) -> Result<Option<CylinderSupport>, KernelRefusal> {
293    let surface = &face.surface;
294    let debug = std::env::var("BREP_DEBUG_MERGE").is_ok();
295    let (arc_first, columns) = match (surface.degree_u, surface.degree_v) {
296        (2, 1) => (true, surface.control_points[0].len()),
297        (1, 2) => (false, surface.control_points.len()),
298        _ => {
299            if debug {
300                eprintln!(
301                    "  support face {}: degrees ({},{}) not ruled-arc",
302                    face.id, surface.degree_u, surface.degree_v
303                );
304            }
305            return Ok(None);
306        }
307    };
308    // Boolean splits can insert linear-direction knots, so a ruled carrier
309    // may hold more than two columns; the outermost columns still bound the
310    // patch and interior straightness is enforced by the final area check.
311    let last = columns - 1;
312    let iso_curve = |side: usize| -> Result<NurbsCurve, KernelRefusal> {
313        let controls = if arc_first {
314            surface
315                .control_points
316                .iter()
317                .map(|row| row[side])
318                .collect::<Vec<_>>()
319        } else {
320            surface.control_points[side].clone()
321        };
322        let knots = if arc_first {
323            surface.knots_u.clone()
324        } else {
325            surface.knots_v.clone()
326        };
327        NurbsCurve::new(2, knots, controls).or_refuse(KernelStage::Sew, "NurbsCurve::new")
328    };
329    let scale = surface
330        .control_points
331        .iter()
332        .flatten()
333        .map(|point| point.point().map(|p| p.length()).unwrap_or(0.0))
334        .fold(1.0f64, f64::max);
335    let circle_tolerance = (tolerance * 100.0).max(1e-7 * scale);
336    // An apex iso is one point: a circle of radius zero about it. Its plane is
337    // the far circle's, so the checks below read that normal against the axis.
338    let apex_of = |curve: &NurbsCurve| -> Result<Option<Vec3>, KernelRefusal> {
339        if !allow_apex {
340            return Ok(None);
341        }
342        let [t0, t1] = curve.domain().or_refuse(KernelStage::Sew, "domain")?;
343        let first = curve.evaluate(t0).or_refuse(KernelStage::Sew, "evaluate")?;
344        for index in 1..=8 {
345            let point = curve.evaluate(t0 + (t1 - t0) * index as f64 / 8.0).or_refuse(KernelStage::Sew, "evaluate")?;
346            if point.sub(first).length() > circle_tolerance {
347                return Ok(None);
348            }
349        }
350        Ok(Some(first))
351    };
352    let (iso0, iso1) = (iso_curve(0)?, iso_curve(last)?);
353    let (apex0, apex1) = (apex_of(&iso0)?, apex_of(&iso1)?);
354    let far_circle = match (apex0, apex1) {
355        (Some(_), None) => arc_circle_support(&iso1, circle_tolerance)?,
356        (None, Some(_)) => arc_circle_support(&iso0, circle_tolerance)?,
357        _ => None,
358    };
359    let apex_circle = |apex: Vec3| far_circle.map(|(_, normal, _)| (apex, normal, 0.0));
360    let circle0 = match apex0 {
361        Some(apex) => apex_circle(apex),
362        None => arc_circle_support(&iso0, circle_tolerance)?,
363    };
364    let circle1 = match apex1 {
365        Some(apex) => apex_circle(apex),
366        None => arc_circle_support(&iso1, circle_tolerance)?,
367    };
368    let Some((center0, normal0, radius0)) = circle0
369    else {
370        if debug {
371            eprintln!("  support face {}: first iso not circular", face.id);
372        }
373        return Ok(None);
374    };
375    let Some((center1, normal1, radius1)) = circle1
376    else {
377        if debug {
378            eprintln!("  support face {}: last iso not circular", face.id);
379        }
380        return Ok(None);
381    };
382    let is_cone = (radius0 - radius1).abs() > circle_tolerance;
383    if is_cone && !allow_cone {
384        if debug {
385            eprintln!(
386                "  support face {}: radii differ {} vs {}",
387                face.id, radius0, radius1
388            );
389        }
390        return Ok(None);
391    }
392    let axial = center1.sub(center0);
393    if axial.length() <= circle_tolerance {
394        if debug {
395            eprintln!("  support face {}: zero axial extent", face.id);
396        }
397        return Ok(None);
398    }
399    let axis = axial
400        .normalized()
401        .or_refuse(KernelStage::Sew, "normalized")?;
402    if axis.dot(normal0).abs() < 1.0 - 1e-7 || axis.dot(normal1).abs() < 1.0 - 1e-7 {
403        if debug {
404            eprintln!(
405                "  support face {}: arc planes not perpendicular to axis",
406                face.id
407            );
408        }
409        return Ok(None);
410    }
411    let outward = outward_normal(face)?;
412    let (u, v) = surface_domains(surface)?;
413    let midpoint = surface
414        .evaluate((u[0] + u[1]) / 2.0, (v[0] + v[1]) / 2.0)
415        .or_refuse(KernelStage::Sew, "healing.face_merge")?;
416    let foot = center0.add(axis.scale(midpoint.sub(center0).dot(axis)));
417    let radial = match midpoint.sub(foot).normalized() {
418        Ok(radial) => radial,
419        Err(_) => return Ok(None),
420    };
421    let slope = if is_cone {
422        (radius1 - radius0) / axial.length()
423    } else {
424        0.0
425    };
426    if is_cone {
427        // A twisted ruling between the two circles is a hyperboloid, not a
428        // cone: the patch's own midpoint must sit on the cone they span.
429        let axial_mid = midpoint.sub(center0).dot(axis);
430        let off = (midpoint.sub(foot).length() - (radius0 + slope * axial_mid)).abs();
431        if off > circle_tolerance {
432            if debug {
433                eprintln!("  support face {}: midpoint {off:.3e} off the spanned cone", face.id);
434            }
435            return Ok(None);
436        }
437    }
438    let alignment = outward.dot(radial);
439    // A cone's normal leans off the radial by its half-angle.
440    if alignment.abs() < 0.9 / (1.0 + slope * slope).sqrt() {
441        if debug {
442            eprintln!(
443                "  support face {}: outward not radial ({alignment})",
444                face.id
445            );
446        }
447        return Ok(None);
448    }
449    Ok(Some(CylinderSupport {
450        origin: center0,
451        axis,
452        radius: radius0,
453        slope,
454        outward_radial_sign: alignment.signum(),
455    }))
456}
457
458fn cosurface_cylinder_pair(
459    first: &FaceRecord,
460    second: &FaceRecord,
461    tolerance: f64,
462    lanes: MergeLanes<'_>,
463) -> Result<Option<CylinderSupport>, KernelRefusal> {
464    let debug = std::env::var("BREP_DEBUG_MERGE").is_ok();
465    let Some(support_a) = ruled_cylinder_support(first, tolerance, lanes.cones, false)? else {
466        if debug {
467            eprintln!(
468                "merge {}x{}: first not a ruled cylinder",
469                first.id, second.id
470            );
471        }
472        return Ok(None);
473    };
474    let Some(support_b) = ruled_cylinder_support(second, tolerance, lanes.cones, false)? else {
475        if debug {
476            eprintln!(
477                "merge {}x{}: second not a ruled cylinder",
478                first.id, second.id
479            );
480        }
481        return Ok(None);
482    };
483    let scale = 1.0f64
484        .max(support_a.origin.length())
485        .max(support_b.origin.length())
486        .max(support_a.radius);
487    let band = (tolerance * 100.0).max(1e-7 * scale);
488    // Both radii read at A's origin and one radius-length further along A's
489    // axis: equal for two cylinders of one radius, and for two patches of
490    // one cone (whose slopes agree once B's axis is turned to A's).
491    let radius_mismatch = {
492        let station = support_a.radius.max(1.0);
493        let b_axial = |axial_on_a: f64| {
494            support_a
495                .origin
496                .add(support_a.axis.scale(axial_on_a))
497                .sub(support_b.origin)
498                .dot(support_b.axis)
499        };
500        (support_a.radius - support_b.radius_at(b_axial(0.0)))
501            .abs()
502            .max((support_a.radius_at(station) - support_b.radius_at(b_axial(station))).abs())
503    };
504    if support_a.axis.dot(support_b.axis).abs() < 1.0 - 1e-7
505        || radius_mismatch > band
506        || support_a.outward_radial_sign != support_b.outward_radial_sign
507    {
508        if debug {
509            eprintln!(
510                "merge {}x{}: axis/radius/sign mismatch dot={} dr={} signs=({},{})",
511                first.id,
512                second.id,
513                support_a.axis.dot(support_b.axis),
514                radius_mismatch,
515                support_a.outward_radial_sign,
516                support_b.outward_radial_sign
517            );
518        }
519        return Ok(None);
520    }
521    let offset = support_b.origin.sub(support_a.origin);
522    let perpendicular = offset.sub(support_a.axis.scale(offset.dot(support_a.axis)));
523    if perpendicular.length() > band {
524        if debug {
525            eprintln!(
526                "merge {}x{}: axes offset {}",
527                first.id,
528                second.id,
529                perpendicular.length()
530            );
531        }
532        return Ok(None);
533    }
534    if debug {
535        eprintln!(
536            "merge {}x{}: MATCH r={} axis=({:.4},{:.4},{:.4})",
537            first.id,
538            second.id,
539            support_a.radius,
540            support_a.axis.x,
541            support_a.axis.y,
542            support_a.axis.z
543        );
544    }
545    Ok(Some(support_a))
546}
547
548struct ExtrusionSupport {
549    /// Profile iso curve at the sweep start, in its actual 3D position.
550    base: NurbsCurve,
551    /// Unit sweep direction (from column 0 toward the last column).
552    direction: Vec3,
553    /// Axial interval the patch occupies along `direction`.
554    interval: [f64; 2],
555}
556
557/// Detect a linear sweep of an arbitrary profile curve: one parameter
558/// direction is degree 1 with every profile control translated by the SAME
559/// vector (weights unchanged), and the profile lies in a plane perpendicular
560/// to the sweep. This is exact at the control-point level, so it also merges
561/// swept faces whose profile is only approximately circular.
562fn ruled_extrusion_support(
563    face: &FaceRecord,
564    tolerance: f64,
565) -> Result<Option<ExtrusionSupport>, KernelRefusal> {
566    let surface = &face.surface;
567    // Planar faces are the coplanar path's business; a plane recognized as
568    // an "extrusion of a line" here could merge across a knife edge.
569    if planar_support(face, tolerance)?.is_some() {
570        return Ok(None);
571    }
572    let profile_first = if surface.degree_v == 1 && surface.degree_u >= 1 {
573        true
574    } else if surface.degree_u == 1 && surface.degree_v >= 1 {
575        false
576    } else {
577        return Ok(None);
578    };
579    let (profile_count, linear_count) = if profile_first {
580        (
581            surface.control_points.len(),
582            surface.control_points[0].len(),
583        )
584    } else {
585        (
586            surface.control_points[0].len(),
587            surface.control_points.len(),
588        )
589    };
590    if linear_count < 2 {
591        return Ok(None);
592    }
593    let control = |profile_index: usize, linear_index: usize| -> Vec4 {
594        if profile_first {
595            surface.control_points[profile_index][linear_index]
596        } else {
597            surface.control_points[linear_index][profile_index]
598        }
599    };
600    let scale = surface
601        .control_points
602        .iter()
603        .flatten()
604        .map(|point| point.point().map(|p| p.length()).unwrap_or(0.0))
605        .fold(1.0f64, f64::max);
606    let band = (tolerance * 100.0).max(1e-7 * scale);
607    let mut translation: Option<Vec3> = None;
608    for profile_index in 0..profile_count {
609        let first = control(profile_index, 0);
610        let last = control(profile_index, linear_count - 1);
611        if (first.w - last.w).abs() > 1e-9 * first.w.abs().max(1.0) {
612            return Ok(None);
613        }
614        let step = last
615            .point()
616            .or_refuse(KernelStage::Sew, "point")?
617            .sub(first.point().or_refuse(KernelStage::Sew, "point")?);
618        if let Some(reference) = translation {
619            if step.sub(reference).length() > band {
620                return Ok(None);
621            }
622        } else {
623            translation = Some(step);
624        }
625        let start = first.point().or_refuse(KernelStage::Sew, "point")?;
626        for linear_index in 1..linear_count - 1 {
627            let middle = control(profile_index, linear_index);
628            if (middle.w - first.w).abs() > 1e-9 * first.w.abs().max(1.0) {
629                return Ok(None);
630            }
631            let offset = middle
632                .point()
633                .or_refuse(KernelStage::Sew, "point")?
634                .sub(start);
635            let along = offset.dot(step) / step.dot(step).max(1e-30);
636            if offset.sub(step.scale(along)).length() > band
637                || !(-1e-9..=1.0 + 1e-9).contains(&along)
638            {
639                return Ok(None);
640            }
641        }
642    }
643    let translation = translation.ok_or_else(|| {
644        KernelRefusal::internal(
645            KernelStage::Sew,
646            "face_merge",
647            "extrusion support: empty net",
648        )
649    })?;
650    if translation.length() <= band {
651        return Ok(None);
652    }
653    let direction = translation
654        .normalized()
655        .or_refuse(KernelStage::Sew, "normalized")?;
656    let base_controls = (0..profile_count).map(|index| control(index, 0)).collect();
657    let base_knots = if profile_first {
658        surface.knots_u.clone()
659    } else {
660        surface.knots_v.clone()
661    };
662    let base_degree = if profile_first {
663        surface.degree_u
664    } else {
665        surface.degree_v
666    };
667    let base = NurbsCurve::new(base_degree, base_knots, base_controls)
668        .or_refuse(KernelStage::Sew, "new")?;
669    let [t0, t1] = base.domain().or_refuse(KernelStage::Sew, "domain")?;
670    let mut axial = [f64::INFINITY, f64::NEG_INFINITY];
671    for index in 0..=8 {
672        let z = base
673            .evaluate(t0 + (t1 - t0) * index as f64 / 8.0)
674            .or_refuse(KernelStage::Sew, "evaluate")?
675            .dot(direction);
676        axial[0] = axial[0].min(z);
677        axial[1] = axial[1].max(z);
678    }
679    if axial[1] - axial[0] > band {
680        // Slanted profiles sweep skewed slabs whose axial union is not an
681        // interval; keep the merge to perpendicular profiles.
682        return Ok(None);
683    }
684    let start = (axial[0] + axial[1]) / 2.0;
685    Ok(Some(ExtrusionSupport {
686        base,
687        direction,
688        interval: [start, start + translation.length()],
689    }))
690}
691
692fn perpendicular_profile(curve: &NurbsCurve, direction: Vec3) -> Result<NurbsCurve, KernelRefusal> {
693    let controls = curve
694        .control_points
695        .iter()
696        .map(|control| {
697            let point = control.point().or_refuse(KernelStage::Sew, "point")?;
698            Ok(Vec4::from_point(
699                point.sub(direction.scale(point.dot(direction))),
700                control.w,
701            ))
702        })
703        .collect::<Result<Vec<_>, KernelRefusal>>()?;
704    NurbsCurve::new(curve.degree, curve.knots.clone(), controls)
705        .or_refuse(KernelStage::Sew, "NurbsCurve::new")
706}
707
708fn curves_coincide(
709    first: &NurbsCurve,
710    second: &NurbsCurve,
711    band: f64,
712) -> Result<bool, KernelRefusal> {
713    for (from, to) in [(first, second), (second, first)] {
714        let [t0, t1] = from.domain().or_refuse(KernelStage::Sew, "domain")?;
715        for index in 0..=8 {
716            let point = from
717                .evaluate(t0 + (t1 - t0) * index as f64 / 8.0)
718                .or_refuse(KernelStage::Sew, "evaluate")?;
719            let projection = match crate::project_point_to_curve(to, point) {
720                Ok(projection) => projection,
721                Err(_) => return Ok(false),
722            };
723            if projection.distance > band {
724                return Ok(false);
725            }
726        }
727    }
728    Ok(true)
729}
730
731/// Matching linear sweeps: parallel directions, identical perpendicular
732/// profile, adjacent (or touching) axial intervals.
733fn coextrusion_pair(
734    older: &FaceRecord,
735    newer: &FaceRecord,
736    tolerance: f64,
737) -> Result<Option<(ExtrusionSupport, [f64; 2])>, KernelRefusal> {
738    let debug = std::env::var("BREP_DEBUG_MERGE").is_ok();
739    let Some(support_a) = ruled_extrusion_support(older, tolerance)? else {
740        return Ok(None);
741    };
742    let Some(support_b) = ruled_extrusion_support(newer, tolerance)? else {
743        return Ok(None);
744    };
745    let alignment = support_a.direction.dot(support_b.direction);
746    if alignment.abs() < 1.0 - 1e-9 {
747        if debug {
748            eprintln!(
749                "coextrusion {}x{}: directions differ (dot {alignment})",
750                older.id, newer.id
751            );
752        }
753        return Ok(None);
754    }
755    let scale = 1.0f64
756        .max(support_a.interval[1].abs())
757        .max(support_b.interval[1].abs());
758    let band = (tolerance * 100.0).max(1e-7 * scale);
759    let profile_a = perpendicular_profile(&support_a.base, support_a.direction)?;
760    let profile_b = perpendicular_profile(&support_b.base, support_a.direction)?;
761    if !curves_coincide(&profile_a, &profile_b, band)? {
762        if debug {
763            eprintln!("coextrusion {}x{}: profiles differ", older.id, newer.id);
764        }
765        return Ok(None);
766    }
767    // Express B's interval along A's direction regardless of B's own sweep
768    // orientation: anti-parallel sweeps negate the axial coordinate.
769    let interval_b = if alignment < 0.0 {
770        [-support_b.interval[1], -support_b.interval[0]]
771    } else {
772        support_b.interval
773    };
774    if interval_b[0] > support_a.interval[1] + band || support_a.interval[0] > interval_b[1] + band
775    {
776        if debug {
777            eprintln!(
778                "coextrusion {}x{}: axial gap {:?} vs {:?}",
779                older.id, newer.id, support_a.interval, interval_b
780            );
781        }
782        return Ok(None);
783    }
784    let certified_on = crate::switch!("BREP_COEXTRUSION_CERTIFIED_APART", true);
785    let certified_check = crate::switch!("BREP_COEXTRUSION_CERTIFIED_APART_CHECK", false);
786    if (certified_on || certified_check) && profile_a.degree > 1 && profile_b.degree > 1 {
787        // A finite complete profile-crossing cover excludes a shared arc.
788        // The sampling band can call two shallowly crossing profiles equal;
789        // merging them would replace distinct wall patches by one carrier.
790        let crossings = match (older.surface.linear_extrusion(), newer.surface.linear_extrusion()) {
791            (Some(a), Some(b)) => crate::analytic_surface::certified_parallel_extrusion_sections(a, b, tolerance),
792            _ => None,
793        };
794        if let Some(crossings) = crossings {
795            if certified_check {
796                eprintln!("COEXTRUSION_CERTIFIED_APART faces={}x{} crossings={} applied={certified_on}",
797                    older.id, newer.id, crossings.len());
798            }
799            if certified_on { return Ok(None); }
800        }
801    }
802    let union = [
803        support_a.interval[0].min(interval_b[0]),
804        support_a.interval[1].max(interval_b[1]),
805    ];
806    Ok(Some((support_a, union)))
807}
808
809fn trimmed_curve(curve: &NurbsCurve, t0: f64, t1: f64) -> Result<NurbsCurve, KernelRefusal> {
810    crate::curve_helpers::trimmed_curve(curve, t0, t1, "face_merge trimmed")
811}
812
813/// The axial extent of `curve` about `support`'s axis, read off its control
814/// polygon: the axial coordinate is an affine functional of position and
815/// the weights are positive, so the curve's own extent lies inside its
816/// control points'. Nine samples per edge missed a sphere-cut rim's peak by
817/// 0.14 (BadBoolean, master's gate of 2026-10-13); the carrier built that
818/// short had the projector fold the rim onto its top boundary, and the body
819/// read 0.14 low in volume with the validator none the wiser.
820fn axial_hull(curve: &NurbsCurve, support: &CylinderSupport) -> [f64; 2] {
821    let origin_axial = support.origin.dot(support.axis);
822    let mut range = [f64::INFINITY, f64::NEG_INFINITY];
823    for point in &curve.control_points {
824        let axial = Vec3::new(point.x / point.w, point.y / point.w, point.z / point.w)
825            .dot(support.axis)
826            - origin_axial;
827        range[0] = range[0].min(axial);
828        range[1] = range[1].max(axial);
829    }
830    range
831}
832
833/// An affine plane chart, proven from its complete bilinear control net.
834/// Rational or warped charts need the general projection path instead.
835struct AffinePlaneChart {
836    origin: Vec3,
837    du: Vec3,
838    dv: Vec3,
839    u0: f64,
840    v0: f64,
841}
842
843fn affine_plane_chart(surface: &NurbsSurface) -> Option<AffinePlaneChart> {
844    if surface.degree_u != 1 || surface.degree_v != 1
845        || surface.control_points.len() != 2
846        || surface.control_points.iter().any(|row| row.len() != 2)
847        || surface.knots_u.len() != 4 || surface.knots_v.len() != 4
848    { return None; }
849    let ku = &surface.knots_u;
850    let kv = &surface.knots_v;
851    if ku[0] != ku[1] || ku[2] != ku[3] || kv[0] != kv[1] || kv[2] != kv[3]
852        || ku[2] <= ku[1] || kv[2] <= kv[1]
853    { return None; }
854    let weight = surface.control_points[0][0].w;
855    if !weight.is_finite() || weight.abs() <= 1e-300
856        || surface.control_points.iter().flatten().any(|point| point.w != weight)
857    { return None; }
858    let p00 = surface.control_points[0][0].point().ok()?;
859    let p10 = surface.control_points[1][0].point().ok()?;
860    let p01 = surface.control_points[0][1].point().ok()?;
861    let p11 = surface.control_points[1][1].point().ok()?;
862    let u = p10.sub(p00);
863    let v = p01.sub(p00);
864    let scale = u.length().max(v.length()).max(1.0);
865    if p11.sub(p10).sub(v).length() > 1e-12 * scale { return None; }
866    let du = u.scale(1.0 / (ku[2] - ku[1]));
867    let dv = v.scale(1.0 / (kv[2] - kv[1]));
868    let determinant = du.dot(du) * dv.dot(dv) - du.dot(dv).powi(2);
869    if !determinant.is_finite() || determinant <= 1e-12 * du.dot(du) * dv.dot(dv) {
870        return None;
871    }
872    Some(AffinePlaneChart { origin: p00, du, dv, u0: ku[1], v0: kv[1] })
873}
874
875/// Transfer the existing trimmed locus, rather than replacing it with the
876/// shared edge's potentially displaced fitted curve. Affine reparameterization
877/// preserves every rational weight, knot and degree, including controls outside
878/// the surface's finite patch.
879pub fn transfer_affine_planar_pcurve(
880    source: &NurbsSurface,
881    target: &NurbsSurface,
882    curve: &NurbsCurve,
883    tolerance: f64,
884) -> Option<NurbsCurve> {
885    let source = affine_plane_chart(source)?;
886    let target = affine_plane_chart(target)?;
887    let uu = target.du.dot(target.du);
888    let uv = target.du.dot(target.dv);
889    let vv = target.dv.dot(target.dv);
890    let determinant = uu * vv - uv * uv;
891    let mut transferred = curve.clone();
892    for control in &mut transferred.control_points {
893        if !control.w.is_finite() || control.w.abs() <= 1e-300 { return None; }
894        let point = source.origin
895            .add(source.du.scale(control.x / control.w - source.u0))
896            .add(source.dv.scale(control.y / control.w - source.v0));
897        let relative = point.sub(target.origin);
898        let a = relative.dot(target.du);
899        let b = relative.dot(target.dv);
900        let u = (a * vv - b * uv) / determinant;
901        let v = (b * uu - a * uv) / determinant;
902        let reconstructed = target.origin.add(target.du.scale(u)).add(target.dv.scale(v));
903        if !u.is_finite() || !v.is_finite()
904            || reconstructed.sub(point).length() > tolerance.max(1e-12)
905        { return None; }
906        control.x = (target.u0 + u) * control.w;
907        control.y = (target.v0 + v) * control.w;
908        control.z = 0.0;
909    }
910    Some(transferred)
911}
912
913fn transfer_planar_loops(
914    target: &NurbsSurface,
915    loops: &[LoopRecord],
916    older: &FaceRecord,
917    newer: &FaceRecord,
918    tolerance: f64,
919) -> Option<Vec<LoopRecord>> {
920    let mut transferred = loops.to_vec();
921    for loop_record in &mut transferred {
922        for coedge in &mut loop_record.coedges {
923            let source = [older, newer].into_iter().find(|face| {
924                face.loops.iter().flat_map(|lp| &lp.coedges)
925                    .any(|original| original.id == coedge.id && original.edge_id == coedge.edge_id)
926            })?;
927            coedge.pcurve = transfer_affine_planar_pcurve(
928                &source.surface, target, &coedge.pcurve, tolerance,
929            )?;
930        }
931    }
932    Some(transferred)
933}
934
935fn reproject_loops(
936    surface: &NurbsSurface,
937    loops: Vec<LoopRecord>,
938    edges: &HashMap<u64, &EdgeRecord>,
939) -> Result<Vec<LoopRecord>, KernelRefusal> {
940    let mut projected_loops = Vec::new();
941    for (loop_index, loop_record) in loops.into_iter().enumerate() {
942        let mut projected = Vec::new();
943        for mut coedge in loop_record.coedges {
944            let edge = edges[&coedge.edge_id];
945            let mut curve = trimmed_curve(&edge.curve, edge.t0, edge.t1)?;
946            if !coedge.forward {
947                curve = curve.reversed().or_refuse(KernelStage::Sew, "reversed")?;
948            }
949            coedge.pcurve = build_pcurve_on_surface(surface, &curve)
950                .or_refuse(KernelStage::Sew, "build_pcurve_on_surface")?;
951            projected.push(coedge);
952        }
953        projected_loops.push(LoopRecord {
954            id: loop_index as u64 + 1,
955            coedges: projected,
956        });
957    }
958    Ok(projected_loops)
959}
960
961/// Put the one degenerate `apex` coedge back into the loop that passes through
962/// its vertex: a parameter line at the pole from the arriving trim's longitude
963/// to the leaving trim's. Each trim's pole end takes the longitude of its next
964/// control point, since projection cannot read a longitude at the pole. False
965/// when no single loop passes through the apex.
966fn stitch_cone_apex(
967    surface: &NurbsSurface,
968    loops: &mut [LoopRecord],
969    apex: &CoedgeRecord,
970    edges: &HashMap<u64, &EdgeRecord>,
971) -> Result<bool, KernelRefusal> {
972    let vertex = edges[&apex.edge_id].start_vertex_id;
973    let mut sites = Vec::new();
974    for (loop_index, loop_record) in loops.iter().enumerate() {
975        for (index, coedge) in loop_record.coedges.iter().enumerate() {
976            let next = &loop_record.coedges[(index + 1) % loop_record.coedges.len()];
977            if traversal_vertices(edges[&coedge.edge_id], coedge).1 == vertex
978                && traversal_vertices(edges[&next.edge_id], next).0 == vertex
979            {
980                sites.push((loop_index, index));
981            }
982        }
983    }
984    let [(loop_index, index)] = sites[..] else {
985        return Ok(false);
986    };
987    let coedges = &mut loops[loop_index].coedges;
988    let next_index = (index + 1) % coedges.len();
989    let (u_domain, _) = surface_domains(surface)?;
990    let [_, t1] = coedges[index].pcurve.domain().or_refuse(KernelStage::Sew, "domain")?;
991    let pole = coedges[index].pcurve.evaluate(t1).or_refuse(KernelStage::Sew, "evaluate")?;
992    let apex_point = surface.evaluate(pole.x, pole.y).or_refuse(KernelStage::Sew, "evaluate")?;
993    let across = surface
994        .evaluate((u_domain[0] + u_domain[1]) / 2.0, pole.y)
995        .or_refuse(KernelStage::Sew, "evaluate")?;
996    let angle_is_u = across.sub(apex_point).length() <= 1e-7 * (1.0 + apex_point.length());
997    let snapped = |pcurve: &mut NurbsCurve, at_end: bool| -> Result<Vec3, KernelRefusal> {
998        let count = pcurve.control_points.len();
999        if count < 2 {
1000            return Err(KernelRefusal::internal(KernelStage::Sew, "face_merge", "cone apex: trim has one control point"));
1001        }
1002        let (slot, inner) = if at_end { (count - 1, count - 2) } else { (0, 1) };
1003        let from = pcurve.control_points[inner].point().or_refuse(KernelStage::Sew, "point")?;
1004        let weight = pcurve.control_points[slot].w;
1005        let mut point = pcurve.control_points[slot].point().or_refuse(KernelStage::Sew, "point")?;
1006        if angle_is_u {
1007            point.x = from.x;
1008        } else {
1009            point.y = from.y;
1010        }
1011        pcurve.control_points[slot] = Vec4::from_point(point, weight);
1012        Ok(point)
1013    };
1014    let arriving = snapped(&mut coedges[index].pcurve, true)?;
1015    let leaving = snapped(&mut coedges[next_index].pcurve, false)?;
1016    let mut bridge = apex.clone();
1017    bridge.pcurve = make_line(arriving, leaving).or_refuse(KernelStage::Sew, "healing.face_merge")?;
1018    coedges.insert(index + 1, bridge);
1019    Ok(true)
1020}
1021
1022fn traversal_vertices(edge: &EdgeRecord, coedge: &CoedgeRecord) -> (u64, u64) {
1023    if coedge.forward {
1024        (edge.start_vertex_id, edge.end_vertex_id)
1025    } else {
1026        (edge.end_vertex_id, edge.start_vertex_id)
1027    }
1028}
1029
1030/// The parameter space every leftover coedge's pcurve lives in, when the merged
1031/// faces share ONE carrier. Only then can a merge read a loop's parameter-space
1032/// continuity; a reprojecting lane walks before its pcurves share a space.
1033pub struct SharedParameterSpace<'a> {
1034    pub surface: &'a NurbsSurface,
1035    /// The radius that made two fitted endpoints one vertex.
1036    pub weld: f64,
1037}
1038
1039impl SharedParameterSpace<'_> {
1040    fn coincide(&self, first: Vec3, second: Vec3) -> bool {
1041        let band = crate::classification::surface_uv_band(self.surface, first.x, first.y, self.weld);
1042        (first.x - second.x).abs() <= band && (first.y - second.y).abs() <= band
1043    }
1044}
1045
1046pub fn shared_trim_certificate_enabled() -> bool {
1047    switch!(live "BREP_FACE_MERGE_TRIM_CERT", true)
1048}
1049
1050/// `BREP_FACE_MERGE_RESEAM` (default on, `0` off): after a feature's boolean,
1051/// two pieces of ONE cylinder or frustum carrier whose only shared edge is
1052/// the carrier's own seam (their union is a partial turn that straddles the
1053/// seam, so in the carrier's chart it is two regions a period apart) are
1054/// joined on a revolution carrier seamed in the union's angular gap
1055/// ([`rejoin_seam_split_pairs`]). The boolean keeps its body as it was when a
1056/// later feature names something the join would change (see the boolean's
1057/// `seam_rejoin_later_references`). A cone with an apex, a sphere and a
1058/// torus are not read here. Off by default: a later offset shell of a joined
1059/// wall under a rim fillet closes on fewer turns of the cylinder than it
1060/// does on the split wall (the offset shell's own sensitivity to where the
1061/// rim blend's carrier starts; it already fails some turns of the split one).
1062pub fn seam_reseam_enabled() -> bool {
1063    switch!(live "BREP_FACE_MERGE_RESEAM", true)
1064}
1065
1066/// Prove closure of the complete boundary isocurves. Clamping makes these
1067/// the first/last control rows; their common positive rational basis bounds
1068/// the entire difference by the largest paired control-point displacement.
1069fn closed_control_boundary(surface: &NurbsSurface, along_u: bool, weld: f64) -> bool {
1070    let (degree, knots, lo, hi) = if along_u {
1071        let Ok([lo,hi]) = surface.domain_u() else { return false; };
1072        (surface.degree_u, &surface.knots_u, lo, hi)
1073    } else {
1074        let Ok([lo,hi]) = surface.domain_v() else { return false; };
1075        (surface.degree_v, &surface.knots_v, lo, hi)
1076    };
1077    if knots.len() < 2*(degree+1)
1078        || !knots[..=degree].iter().all(|k| *k == lo)
1079        || !knots[knots.len()-degree-1..].iter().all(|k| *k == hi)
1080    { return false; }
1081    let agree = |a: Vec4, b: Vec4| {
1082        if a.w <= 0.0 || !a.w.is_finite() || a.w != b.w { return false; }
1083        let (Ok(a), Ok(b)) = (a.point(), b.point()) else { return false; };
1084        a.sub(b).length() <= weld
1085    };
1086    if along_u {
1087        let (Some(first), Some(last)) = (surface.control_points.first(), surface.control_points.last()) else { return false; };
1088        first.len() == last.len() && first.iter().zip(last).all(|(a,b)| agree(*a,*b))
1089    } else {
1090        surface.control_points.iter().all(|row| match (row.first(), row.last()) {
1091            (Some(a), Some(b)) => agree(*a,*b),
1092            _ => false,
1093        })
1094    }
1095}
1096
1097/// Linear pcurves on affine boundary isocurves compose to polylines.
1098/// Matched positive-weight polygon controls therefore bound the COMPLETE
1099/// paired images by their largest 3D displacement, even when the other UV
1100/// coordinate differs by roundoff. No UV band or station sample is used.
1101fn affine_boundary_trim_pair(
1102    surface: &NurbsSurface,
1103    along_u: bool,
1104    first_at_low: bool,
1105    first: &NurbsCurve,
1106    reverse: &NurbsCurve,
1107    weld: f64,
1108) -> bool {
1109    let (degree, knots, bounds) = if along_u {
1110        (surface.degree_v, &surface.knots_v, surface.domain_v())
1111    } else {
1112        (surface.degree_u, &surface.knots_u, surface.domain_u())
1113    };
1114    let Ok([lo,hi]) = bounds else { return false; };
1115    if degree != 1 || knots.as_slice() != [lo,lo,hi,hi] || hi <= lo { return false; }
1116    let ends = if along_u {
1117        let (Some(a),Some(b)) = (surface.control_points.first(),surface.control_points.last()) else { return false; };
1118        if a.len()!=2 || b.len()!=2 { return false; }
1119        [a[0],a[1],b[0],b[1]]
1120    } else {
1121        if surface.control_points.len()!=2 { return false; }
1122        let (a,b) = (&surface.control_points[0],&surface.control_points[1]);
1123        let (Some(a0),Some(a1),Some(b0),Some(b1)) = (a.first(),a.last(),b.first(),b.last()) else { return false; };
1124        [*a0,*b0,*a1,*b1]
1125    };
1126    if ends[0].w<=0.0 || ends[0].w!=ends[1].w || ends[2].w<=0.0 || ends[2].w!=ends[3].w {
1127        return false;
1128    }
1129    let (Ok(a0),Ok(a1),Ok(b0),Ok(b1)) = (ends[0].point(),ends[1].point(),ends[2].point(),ends[3].point()) else { return false; };
1130    let (a0,a1,b0,b1) = if first_at_low { (a0,a1,b0,b1) } else { (b0,b1,a0,a1) };
1131    let image = |p: &Vec4, a: Vec3, b: Vec3| {
1132        let t = if along_u { p.y/p.w } else { p.x/p.w };
1133        a.add(b.sub(a).scale((t-lo)/(hi-lo)))
1134    };
1135    first.control_points.iter().zip(&reverse.control_points).all(|(a,b)| {
1136        let distance = image(a,a0,a1).sub(image(b,b0,b1)).length();
1137        distance.is_finite() && distance <= weld
1138    })
1139}
1140
1141/// Prove that a retained shared pair is a periodic seam over its whole
1142/// trim. Positive common rational bases match the other parameter, or
1143/// affine boundary images bound matched linear polygons. Every periodic
1144/// coordinate control lies on opposite closed domain sides.
1145/// This qualifies retention after the existing coincidence check fails. It
1146/// does not change cancellation policy or widen a UV band. Work is linear
1147/// in the existing control arrays, with no sampling or refinement search.
1148pub fn periodic_shared_trim(
1149    space: &SharedParameterSpace,
1150    first: &CoedgeRecord,
1151    second: &CoedgeRecord,
1152) -> bool {
1153    if first.forward == second.forward { return false; }
1154    let Ok(reverse) = second.pcurve.reversed() else { return false; };
1155    let curve = &first.pcurve;
1156    if curve.degree != reverse.degree || curve.control_points.len() != reverse.control_points.len()
1157        || curve.control_points.is_empty()
1158    { return false; }
1159    let polygon = |c: &NurbsCurve| {
1160        c.degree == 1 && c.knots.len() == c.control_points.len()+2
1161            && c.knots[0] == c.knots[1]
1162            && c.knots[c.knots.len()-1] == c.knots[c.knots.len()-2]
1163            && c.knots[1..c.knots.len()-1].windows(2).all(|k| k[1] > k[0])
1164    };
1165    let polygon = polygon(curve) && polygon(&reverse);
1166    if (!polygon && curve.knots != reverse.knots)
1167        || !curve.control_points.iter().zip(&reverse.control_points).all(|(a,b)| {
1168            [a,b].iter().all(|p| p.w > 0.0 && p.w.is_finite()
1169                && (p.x/p.w).is_finite() && (p.y/p.w).is_finite())
1170                && (polygon || a.w == b.w)
1171        })
1172    { return false; }
1173    let coordinate = |p: &Vec4, u: bool| if u { p.x/p.w } else { p.y/p.w };
1174    let same_coordinate = |u: bool| curve.control_points.iter().zip(&reverse.control_points)
1175        .all(|(a,b)| if polygon { coordinate(a,u) == coordinate(b,u) }
1176            else if u { a.x == b.x } else { a.y == b.y });
1177    for u in [true,false] {
1178        let bounds = if u { space.surface.domain_u() } else { space.surface.domain_v() };
1179        let Ok([lo,hi]) = bounds else { continue; };
1180        let other_bounds = if u { space.surface.domain_v() } else { space.surface.domain_u() };
1181        let Ok([other_lo,other_hi]) = other_bounds else { continue; };
1182        // The closed-boundary control bound applies on its active domain.
1183        // Positive pcurve hulls must stay inside it; extrapolated traces
1184        // need a different proof and keep their existing face partition.
1185        if !curve.control_points.iter().chain(&reverse.control_points)
1186            .all(|p| coordinate(p,!u) >= other_lo && coordinate(p,!u) <= other_hi)
1187        { continue; }
1188        let opposite = [(lo,hi),(hi,lo)].iter().any(|(a,b)|
1189            curve.control_points.iter().all(|p| coordinate(p,u) == *a)
1190                && reverse.control_points.iter().all(|p| coordinate(p,u) == *b));
1191        if opposite && closed_control_boundary(space.surface, u, space.weld)
1192            && (same_coordinate(!u) || (polygon && affine_boundary_trim_pair(
1193                space.surface, u, coordinate(&curve.control_points[0],u)==lo,
1194                curve, &reverse, space.weld)))
1195        {
1196            return true;
1197        }
1198    }
1199    false
1200}
1201
1202/// A coedge's pcurve at its start, middle and end. The pcurve runs in the
1203/// coedge's own direction, so its domain start is where the traversal starts.
1204fn pcurve_stations(coedge: &CoedgeRecord) -> Option<[Vec3; 3]> {
1205    let [t0, t1] = coedge.pcurve.domain().ok()?;
1206    Some([
1207        coedge.pcurve.evaluate(t0).ok()?,
1208        coedge.pcurve.evaluate((t0 + t1) / 2.0).ok()?,
1209        coedge.pcurve.evaluate(t1).ok()?,
1210    ])
1211}
1212
1213/// SLIT DISSOLUTION. An edge whose two leftover uses run along the SAME
1214/// parameter-space segment, one each way, separates nothing: its ring on the
1215/// other side was the shared edge the merge just cancelled (a flanged hole's
1216/// annulus, slit to the ring it bridged to). Kept, the walk can only return
1217/// along it and close a loop of zero area. Two uses a PERIOD apart are a seam
1218/// the region wraps across, and stay.
1219fn dissolve_slits(
1220    remaining: &mut Vec<CoedgeRecord>,
1221    edges: &HashMap<u64, &EdgeRecord>,
1222    space: &SharedParameterSpace,
1223) {
1224    let mut uses = HashMap::<u64, Vec<usize>>::default();
1225    for (index, coedge) in remaining.iter().enumerate() {
1226        uses.entry(coedge.edge_id).or_default().push(index);
1227    }
1228    let slits = uses
1229        .iter()
1230        .filter(|(edge_id, indices)| {
1231            if indices.len() != 2 || edges[*edge_id].degenerate {
1232                return false;
1233            }
1234            let (first, second) = (&remaining[indices[0]], &remaining[indices[1]]);
1235            if first.forward == second.forward {
1236                return false;
1237            }
1238            let (Some(first), Some(second)) = (pcurve_stations(first), pcurve_stations(second)) else {
1239                return false;
1240            };
1241            space.coincide(first[0], second[2])
1242                && space.coincide(first[1], second[1])
1243                && space.coincide(first[2], second[0])
1244        })
1245        .map(|(edge_id, _)| *edge_id)
1246        .collect::<HashSet<_>>();
1247    remaining.retain(|coedge| !slits.contains(&coedge.edge_id));
1248}
1249
1250/// Stitch a merged face's leftover coedges into loops, or `None` when the
1251/// stitching is not determined.
1252///
1253/// A loop can pass one VERTEX twice — a bridge's foot on the ring it joins —
1254/// so reaching the start vertex does not by itself close the loop, and a vertex
1255/// with several unused coedges leaving it does not name the next one. There the
1256/// walk follows the loop's PARAMETER-SPACE continuity when the coedges share a
1257/// carrier (`space`): the successor starts where the current pcurve ends, and a
1258/// seam's two images of one vertex a period apart are two different places.
1259/// Without a shared space, or with no single successor, the merge is refused
1260/// and the faces stay as they were assembled.
1261fn walk_cycles(
1262    mut remaining: Vec<CoedgeRecord>,
1263    edges: &HashMap<u64, &EdgeRecord>,
1264    space: Option<&SharedParameterSpace>,
1265) -> Option<Vec<LoopRecord>> {
1266    let maximum_cycle_length = remaining.len();
1267    let mut loops = Vec::new();
1268    while !remaining.is_empty() {
1269        let first = remaining.remove(0);
1270        let (start, mut end) = traversal_vertices(edges[&first.edge_id], &first);
1271        let mut cycle = vec![first];
1272        loop {
1273            let leaving = remaining
1274                .iter()
1275                .enumerate()
1276                .filter_map(|(index, coedge)| {
1277                    (traversal_vertices(edges[&coedge.edge_id], coedge).0 == end).then_some(index)
1278                })
1279                .collect::<Vec<_>>();
1280            let closes = end == start;
1281            let successor = match (leaving.as_slice(), closes) {
1282                ([], true) => None,
1283                ([only], false) => Some(*only),
1284                ([], false) => return None,
1285                _ => {
1286                    let space = space?;
1287                    let here = pcurve_stations(cycle.last()?)?[2];
1288                    let closing = closes && space.coincide(here, pcurve_stations(&cycle[0])?[0]);
1289                    let mut continuing = Vec::new();
1290                    for index in leaving {
1291                        if space.coincide(here, pcurve_stations(&remaining[index])?[0]) {
1292                            continuing.push(index);
1293                        }
1294                    }
1295                    match (continuing.as_slice(), closing) {
1296                        ([], true) => None,
1297                        ([only], false) => Some(*only),
1298                        _ => return None,
1299                    }
1300                }
1301            };
1302            let Some(index) = successor else {
1303                break;
1304            };
1305            let next = remaining.remove(index);
1306            end = traversal_vertices(edges[&next.edge_id], &next).1;
1307            cycle.push(next);
1308            if cycle.len() > maximum_cycle_length {
1309                return None;
1310            }
1311        }
1312        // A cycle that traverses every one of its edges both ways encloses
1313        // nothing, however its parameter-space image reads.
1314        let mut counts = HashMap::<u64, usize>::default();
1315        for coedge in &cycle {
1316            *counts.entry(coedge.edge_id).or_default() += 1;
1317        }
1318        if counts.values().all(|count| *count == 2) {
1319            return None;
1320        }
1321        loops.push(LoopRecord {
1322            id: loops.len() as u64 + 1,
1323            coedges: cycle,
1324        });
1325    }
1326    Some(loops)
1327}
1328
1329/// Whether two faces ride ONE carrier — the same geometric surface, oriented
1330/// the same way out of the material — by any of the four readings this module
1331/// merges on: bit-identical patches, coplanar planes with the same outward
1332/// normal, cosurface cylinder patches, and coextruded profiles.
1333///
1334/// `pub` because the direct-edit rejoin asks the same question for the
1335/// same reason: a survivor face on the far side of a deleted band can only
1336/// take the near side's loops when the two are one carrier. It asks GEOMETRIC
1337/// cosurface rather than [`same_surface`] alone, because a mirrored twin is
1338/// the same surface reparametrized — reflected control points, flipped
1339/// `same_sense` — and bit-identity reads that as two.
1340pub fn faces_are_cosurface(
1341    first: &FaceRecord,
1342    second: &FaceRecord,
1343    tolerance: f64,
1344) -> Result<bool, KernelRefusal> {
1345    if first.same_sense == second.same_sense
1346        && same_surface(&first.surface, &second.surface, tolerance)
1347    {
1348        return Ok(true);
1349    }
1350    if coplanar_with_same_outward_normal(first, second, tolerance)? {
1351        return Ok(true);
1352    }
1353    if cosurface_cylinder_pair(first, second, tolerance, MergeLanes::default())?.is_some() {
1354        return Ok(true);
1355    }
1356    Ok(coextrusion_pair(first, second, tolerance)?.is_some())
1357}
1358
1359/// Degree-one clamped trims follow their control polygon regardless of knot
1360/// spacing. For higher degrees, equal positive rational bases make the
1361/// difference of the two affine images a convex combination of control-point
1362/// differences. Bound the whole
1363/// shared trim, rather than relying on cancellation of its area integral.
1364fn opposed_planar_trims_agree(
1365    older: &FaceRecord,
1366    first: &CoedgeRecord,
1367    newer: &FaceRecord,
1368    second: &CoedgeRecord,
1369    tolerance: f64,
1370) -> bool {
1371    let Ok(reverse) = second.pcurve.reversed() else {
1372        return false;
1373    };
1374    let curve = &first.pcurve;
1375    if curve.degree != reverse.degree || curve.control_points.len() != reverse.control_points.len()
1376    {
1377        return false;
1378    }
1379    let linear_polygon = |c: &NurbsCurve| {
1380        c.degree == 1
1381            && c.knots.len() == c.control_points.len() + 2
1382            && c.knots[0] == c.knots[1]
1383            && c.knots[c.knots.len() - 1] == c.knots[c.knots.len() - 2]
1384            && c.knots[1..c.knots.len() - 1]
1385                .windows(2)
1386                .all(|k| k[1] > k[0])
1387    };
1388    let polygon = linear_polygon(curve) && linear_polygon(&reverse);
1389    if !polygon && curve.knots != reverse.knots {
1390        return false;
1391    }
1392    curve
1393        .control_points
1394        .iter()
1395        .zip(&reverse.control_points)
1396        .all(|(a, b)| {
1397            if !a.w.is_finite()
1398                || !b.w.is_finite()
1399                || a.w <= 0.0
1400                || b.w <= 0.0
1401                || (!polygon && a.w != b.w)
1402            {
1403                return false;
1404            }
1405            let (Ok(a), Ok(b)) = (a.point(), b.point()) else {
1406                return false;
1407            };
1408            let (Ok(a), Ok(b)) = (
1409                older.surface.evaluate_extended(a.x, a.y),
1410                newer.surface.evaluate_extended(b.x, b.y),
1411            ) else {
1412                return false;
1413            };
1414            a.sub(b).length() <= tolerance
1415        })
1416}
1417
1418/// Like [`decline!`], but leaves a labelled lane instead of the whole pair
1419/// merge, so a later lane can read the same pair again.
1420macro_rules! fall_through {
1421    ($older:expr, $newer:expr, $label:lifetime) => {{
1422        if std::env::var("BREP_DEBUG_MERGE").is_ok() {
1423            eprintln!(
1424                "merge {}x{}: lane left at face_merge.rs:{}",
1425                $older.id,
1426                $newer.id,
1427                line!()
1428            );
1429        }
1430        break $label;
1431    }};
1432}
1433
1434/// Trace a declined pair merge under `BREP_DEBUG_MERGE` with the source line
1435/// that declined it, then return `Ok(None)`. A pair whose carriers MATCH can
1436/// still be declined a dozen lines later (shared-edge census, cycle walk,
1437/// area check); without the line the trace reads "MATCH" and then nothing,
1438/// which is how the E13 cosurface report (2026-10-13) hid its cause.
1439macro_rules! decline {
1440    ($older:expr, $newer:expr) => {{
1441        if std::env::var("BREP_DEBUG_MERGE").is_ok() {
1442            eprintln!(
1443                "merge {}x{}: declined at face_merge.rs:{}",
1444                $older.id,
1445                $newer.id,
1446                line!()
1447            );
1448        }
1449        return Ok(None);
1450    }};
1451}
1452
1453pub fn try_merge_pair(
1454    older: &FaceRecord,
1455    newer: &FaceRecord,
1456    edges: &HashMap<u64, &EdgeRecord>,
1457    tolerance: f64,
1458    same_carrier_area_tolerance_ratio: f64,
1459) -> Result<Option<FaceRecord>, KernelRefusal> {
1460    try_merge_pair_lanes(
1461        older,
1462        newer,
1463        edges,
1464        tolerance,
1465        same_carrier_area_tolerance_ratio,
1466        MergeLanes::default(),
1467    )
1468}
1469
1470/// [`try_merge_pair`] with the opt-in [`MergeLanes`].
1471pub fn try_merge_pair_lanes(
1472    older: &FaceRecord,
1473    newer: &FaceRecord,
1474    edges: &HashMap<u64, &EdgeRecord>,
1475    tolerance: f64,
1476    same_carrier_area_tolerance_ratio: f64,
1477    lanes: MergeLanes<'_>,
1478) -> Result<Option<FaceRecord>, KernelRefusal> {
1479    let mut same_carrier = older.same_sense == newer.same_sense
1480        && same_surface(&older.surface, &newer.surface, tolerance);
1481    // Oppositely oriented planar patches can form a folded, zero-thickness
1482    // overlap along a multi-edge seam. Cancelling that seam preserves the
1483    // signed region, not the sum of the two unsigned face areas.
1484    let cancel_planar_fold = older.same_sense != newer.same_sense
1485        && older.loops.len() == 1
1486        && newer.loops.len() == 1
1487        && same_surface(&older.surface, &newer.surface, tolerance)
1488        && older
1489            .surface
1490            .is_affine()
1491            .or_refuse(KernelStage::Sew, "is_affine")?
1492        && newer
1493            .surface
1494            .is_affine()
1495            .or_refuse(KernelStage::Sew, "is_affine")?;
1496    let coplanar_planar =
1497        !same_carrier && coplanar_with_same_outward_normal(older, newer, tolerance)?;
1498    let mut cosurface_cylinder = if !same_carrier && !coplanar_planar {
1499        cosurface_cylinder_pair(older, newer, tolerance, lanes)?
1500    } else {
1501        None
1502    };
1503    let cosurface_extrusion = if !same_carrier && !coplanar_planar && cosurface_cylinder.is_none() {
1504        coextrusion_pair(older, newer, tolerance)?
1505    } else {
1506        None
1507    };
1508    let older_coedges = older
1509        .loops
1510        .iter()
1511        .flat_map(|loop_record| &loop_record.coedges)
1512        .collect::<Vec<_>>();
1513    let newer_coedges = newer
1514        .loops
1515        .iter()
1516        .flat_map(|loop_record| &loop_record.coedges)
1517        .collect::<Vec<_>>();
1518    let mut space = (same_carrier || cancel_planar_fold).then(|| SharedParameterSpace {
1519        surface: &older.surface,
1520        weld: crate::tolerance::assembler_weld(tolerance),
1521    });
1522    let mut shared_older = HashSet::default();
1523    let mut shared_newer = HashSet::default();
1524    let mut shared_edges = HashSet::default();
1525    // Same-carrier pairs a period apart that `periodic_shared_trim` proves
1526    // are the carrier's seam (older coedge, newer coedge, edge), and whether
1527    // any noncoincident pair went unproved: the re-seam route reads them.
1528    let mut seam_pairs: Vec<(u64, u64, u64)> = Vec::new();
1529    let mut unproved_seam = false;
1530    // Shared edges the merged face keeps, both ways: on ONE carrier, a pair
1531    // whose two images lie a period apart is the carrier's seam (the
1532    // dissolve_slits doctrine), and the union wraps across it. Cancelling it
1533    // tore the seam out of a shelled cylinder's wall against its own strip
1534    // (the E13 report, 2026-10-13) and the area check declined the pair. A
1535    // pair that touches ONLY across the seam still declines below: its union
1536    // is two regions a period apart in this carrier's chart, one face record
1537    // holding two discs (the slab-corner mirror union read V−E+F = 1 so).
1538    for first in &older_coedges {
1539        if edges[&first.edge_id].degenerate {
1540            continue;
1541        }
1542        for second in &newer_coedges {
1543            if first.edge_id != second.edge_id {
1544                continue;
1545            }
1546            if first.forward == second.forward {
1547                decline!(older, newer);
1548            }
1549            if cancel_planar_fold
1550                && !opposed_planar_trims_agree(older, first, newer, second, tolerance)
1551            {
1552                decline!(older, newer);
1553            }
1554            if same_carrier && !cancel_planar_fold {
1555                if let (Some(space), Some(here), Some(there)) =
1556                    (&space, pcurve_stations(first), pcurve_stations(second))
1557                {
1558                    let retraced = space.coincide(here[0], there[2])
1559                        && space.coincide(here[1], there[1])
1560                        && space.coincide(here[2], there[0]);
1561                    if !retraced {
1562                        // A noncoincident pair may be retained only as a
1563                        // proved periodic seam. An interior partition stays
1564                        // between faces; retaining it here creates a slit.
1565                        let proved = periodic_shared_trim(space, first, second);
1566                        if shared_trim_certificate_enabled() && !proved
1567                        { decline!(older, newer); }
1568                        if proved {
1569                            seam_pairs.push((first.id, second.id, first.edge_id));
1570                        } else {
1571                            unproved_seam = true;
1572                        }
1573                        continue;
1574                    }
1575                } else if shared_trim_certificate_enabled() {
1576                    decline!(older, newer);
1577                }
1578            }
1579            shared_older.insert(first.id);
1580            shared_newer.insert(second.id);
1581            shared_edges.insert(first.edge_id);
1582        }
1583    }
1584    // The pieces touch ONLY across the carrier's seam: their union is one
1585    // region of the cylinder (or cone) that this chart cuts in two. Read the
1586    // pair as a cosurface cylinder pair instead, the seam uses cancelled as
1587    // shared edges, so the partial-turn lane seams a new carrier in the
1588    // union's angular gap. A union that wraps the whole turn finds no gap
1589    // there and declines as before.
1590    let mut reseamed = false;
1591    if shared_older.is_empty()
1592        && !seam_pairs.is_empty()
1593        && !unproved_seam
1594        && same_carrier
1595        && !cancel_planar_fold
1596        && lanes.reseam
1597    {
1598        let reseam_lanes = MergeLanes { cones: true, ..lanes };
1599        if let Some(support) = cosurface_cylinder_pair(older, newer, tolerance, reseam_lanes)? {
1600            for (first, second, edge) in &seam_pairs {
1601                shared_older.insert(*first);
1602                shared_newer.insert(*second);
1603                shared_edges.insert(*edge);
1604            }
1605            same_carrier = false;
1606            space = None;
1607            cosurface_cylinder = Some(support);
1608            reseamed = true;
1609        }
1610    }
1611    if lanes.reseam && !reseamed {
1612        decline!(older, newer);
1613    }
1614    if shared_older.is_empty() || shared_older.len() != shared_newer.len() {
1615        decline!(older, newer);
1616    }
1617    if cancel_planar_fold && shared_older.len() < 2 {
1618        decline!(older, newer);
1619    }
1620    if !same_carrier
1621        && !cancel_planar_fold
1622        && !coplanar_planar
1623        && cosurface_cylinder.is_none()
1624        && cosurface_extrusion.is_none()
1625    {
1626        decline!(older, newer);
1627    }
1628    let mut remaining = older_coedges
1629        .into_iter()
1630        .filter(|coedge| {
1631            !shared_older.contains(&coedge.id)
1632                && !(coplanar_planar && edges[&coedge.edge_id].degenerate)
1633        })
1634        .chain(newer_coedges.into_iter().filter(|coedge| {
1635            !shared_newer.contains(&coedge.id)
1636                && !(coplanar_planar && edges[&coedge.edge_id].degenerate)
1637        }))
1638        .cloned()
1639        .collect::<Vec<_>>();
1640    if cancel_planar_fold {
1641        // The opposite fold shares this affine chart too. A retraced slit
1642        // contributes no signed boundary, but three coincident samples do
1643        // not prove that: opposite bows can match there and enclose slivers.
1644        // Use the whole-curve control bound before discarding either use.
1645        let mut uses = HashMap::<u64, Vec<&CoedgeRecord>>::default();
1646        for coedge in &remaining {
1647            uses.entry(coedge.edge_id).or_default().push(coedge);
1648        }
1649        let mut slits = HashSet::default();
1650        for (id, uses) in uses {
1651            if uses.len() == 2
1652                && !edges[&id].degenerate
1653                && uses[0].forward != uses[1].forward
1654                && opposed_planar_trims_agree(older, uses[0], older, uses[1], tolerance)
1655            {
1656                slits.insert(id);
1657            }
1658        }
1659        remaining.retain(|coedge| !slits.contains(&coedge.edge_id));
1660    } else if let Some(space) = &space {
1661        dissolve_slits(&mut remaining, edges, space);
1662    }
1663    let Some(mut loops) = walk_cycles(remaining, edges, space.as_ref()) else {
1664        // Cancelling the shared edges of a cosurface cylinder pair whose
1665        // union wraps the full turn can strand one face's seam strip at a
1666        // fork the 3D walk cannot resolve (the E13 report, 2026-10-13); the
1667        // full-turn lane walks in the merged carrier's own parameter space.
1668        if let Some(support) = &cosurface_cylinder {
1669            if let Some(merged) =
1670                merge_cylinder_full_turn(older, newer, edges, tolerance, support, &shared_edges, lanes)?
1671            {
1672                return Ok(Some(merged));
1673            }
1674        }
1675        decline!(older, newer);
1676    };
1677    if loops.iter().any(|loop_record| {
1678        loop_record
1679            .coedges
1680            .iter()
1681            .all(|coedge| edges[&coedge.edge_id].degenerate)
1682    }) {
1683        decline!(older, newer);
1684    }
1685    if loops.is_empty() {
1686        decline!(older, newer);
1687    }
1688    loops.sort_by(|first, second| {
1689        let area = |loop_record: &LoopRecord| {
1690            parameter_space_area(&FaceRecord {
1691                id: older.id,
1692                surface: older.surface.clone(),
1693                same_sense: older.same_sense,
1694                loops: vec![loop_record.clone()],
1695                name: None,
1696            })
1697            .map(f64::abs)
1698        };
1699        match (area(first), area(second)) {
1700            (Ok(a), Ok(b)) => b.total_cmp(&a),
1701            _ => std::cmp::Ordering::Equal,
1702        }
1703    });
1704    if same_carrier || cancel_planar_fold {
1705        if cancel_planar_fold && loops.len() != 1 {
1706            decline!(older, newer);
1707        }
1708        let expected = parameter_space_area(older)
1709            .or_refuse(KernelStage::Sew, "parameter_space_area")?
1710            + parameter_space_area(newer).or_refuse(KernelStage::Sew, "parameter_space_area")?;
1711        if cancel_planar_fold && expected.abs() <= tolerance * tolerance {
1712            decline!(older, newer);
1713        }
1714        let merged = FaceRecord {
1715            id: older.id,
1716            surface: older.surface.clone(),
1717            same_sense: if cancel_planar_fold {
1718                expected > 0.0
1719            } else {
1720                older.same_sense
1721            },
1722            loops,
1723            name: older.name.clone(),
1724        };
1725
1726        let actual =
1727            parameter_space_area(&merged).or_refuse(KernelStage::Sew, "parameter_space_area")?;
1728        let area_ratio = if cancel_planar_fold {
1729            same_carrier_area_tolerance_ratio.min(1e-7)
1730        } else {
1731            same_carrier_area_tolerance_ratio
1732        };
1733        let area_tolerance = 1e-9f64.max(expected.abs() * area_ratio);
1734        if (actual - expected).abs() > area_tolerance
1735            || (actual.abs() > 1e-12 && actual.is_sign_positive() != merged.same_sense)
1736        {
1737            decline!(older, newer);
1738        }
1739        return Ok(Some(merged));
1740    }
1741
1742    if reseamed {
1743        // The re-seam route keeps the pieces' own carrier, turned whole spans
1744        // to start inside their union's gap, and every trim's own pcurve
1745        // shifted with it: the joined face is exactly the face a primitive
1746        // whose seam lay in that gap would have given, which every later
1747        // feature reads as it reads the primitive's. It reads the full-turn
1748        // lane's bars, never the partial-turn lane's 5e-3 area share (one
1749        // piece of a seam-split pair can be a sliver that share would lose).
1750        let support = cosurface_cylinder.as_ref().expect("the re-seam route reads a cylinder support");
1751        let weld = crate::tolerance::assembler_weld(tolerance);
1752        let Some((surface, loops)) = turn_carrier_into_gap(&older.surface, loops, weld) else {
1753            decline!(older, newer);
1754        };
1755        let merged = FaceRecord { id: older.id, surface, same_sense: older.same_sense, loops, name: older.name.clone() };
1756        if reseam_accepts(older, newer, &merged, edges, tolerance, support)? {
1757            return Ok(Some(merged));
1758        }
1759        decline!(older, newer);
1760    }
1761
1762    if let Some(support) = &cosurface_cylinder {
1763        // The partial-turn lane first: a union that leaves an angular gap
1764        // takes a carrier seamed in that gap and never crosses the seam.
1765        // Whatever it declines (a sampled gap that is not one, a region that
1766        // wraps the full turn) the full-turn lane reads again on a closed
1767        // carrier seamed along an existing axial edge.
1768        'partial_turn: {
1769            // The partial-turn carrier is built at one radius: a cone goes
1770            // straight to the full-turn lane, which reads it per end.
1771            if support.slope != 0.0 {
1772                fall_through!(older, newer, 'partial_turn);
1773            }
1774            // Build one revolution carrier covering both patches: seam at the
1775            // largest angular gap so the merged region never crosses it, then
1776            // reproject every loop onto the shared cylinder.
1777            let x_reference = {
1778                let seed = loops
1779                    .iter()
1780                    .flat_map(|loop_record| &loop_record.coedges)
1781                    .find_map(|coedge| {
1782                        let edge = edges[&coedge.edge_id];
1783                        edge.curve.evaluate(edge.t0).ok()
1784                    })
1785                    .ok_or_else(|| {
1786                        KernelRefusal::internal(
1787                            KernelStage::Sew,
1788                            "face_merge",
1789                            "cylinder merge: no boundary sample",
1790                        )
1791                    })?;
1792                let delta = seed.sub(support.origin);
1793                let radial = delta.sub(support.axis.scale(delta.dot(support.axis)));
1794                match radial.normalized() {
1795                    Ok(radial) => radial,
1796                    Err(_) => fall_through!(older, newer, 'partial_turn),
1797                }
1798            };
1799            let y_reference = support.axis.cross(x_reference);
1800            let mut angles = Vec::new();
1801            // The angular sweep between consecutive samples of ONE edge: the
1802            // edge itself covers it, so no gap can open inside it.
1803            let mut swept: Vec<(f64, f64)> = Vec::new();
1804            let mut axial_range = [f64::INFINITY, f64::NEG_INFINITY];
1805            for coedge in loops.iter().flat_map(|loop_record| &loop_record.coedges) {
1806                let edge = edges[&coedge.edge_id];
1807                let curve = trimmed_curve(&edge.curve, edge.t0, edge.t1)?;
1808                let [c0, c1] = curve.domain().or_refuse(KernelStage::Sew, "domain")?;
1809                let hull = axial_hull(&curve, support);
1810                axial_range[0] = axial_range[0].min(hull[0]);
1811                axial_range[1] = axial_range[1].max(hull[1]);
1812                let mut previous: Option<f64> = None;
1813                for index in 0..=8 {
1814                    let point = curve
1815                        .evaluate(c0 + (c1 - c0) * index as f64 / 8.0)
1816                        .or_refuse(KernelStage::Sew, "evaluate")?;
1817                    let delta = point.sub(support.origin);
1818                    let axial = delta.dot(support.axis);
1819                    let radial = delta.sub(support.axis.scale(axial));
1820                    if radial.length() <= support.radius * 1e-6 {
1821                        continue;
1822                    }
1823                    let mut angle = radial.dot(y_reference).atan2(radial.dot(x_reference));
1824                    if angle < 0.0 {
1825                        angle += std::f64::consts::TAU;
1826                    }
1827                    if let Some(previous) = previous {
1828                        swept.push((previous, angle_difference(previous, angle)));
1829                    }
1830                    previous = Some(angle);
1831                    angles.push(angle);
1832                }
1833            }
1834            if angles.len() < 3 || axial_range[1] - axial_range[0] <= tolerance {
1835                fall_through!(older, newer, 'partial_turn);
1836            }
1837            // The boundary sweeps the whole turn (two half-turn walls closing a
1838            // ring between them): the largest gap between SAMPLES below would
1839            // be one sample step inside an arc, not a gap in the region, and
1840            // the carrier seamed there only fails the area check after a full
1841            // reprojection. Leave for the full-turn lane at once.
1842            if largest_uncovered_turn(&swept) <= 1e-6 {
1843                fall_through!(older, newer, 'partial_turn);
1844            }
1845            angles.sort_by(f64::total_cmp);
1846            let mut gap_start = angles.len() - 1;
1847            let mut largest_gap = angles[0] + std::f64::consts::TAU - angles[angles.len() - 1];
1848            for index in 0..angles.len() - 1 {
1849                let gap = angles[index + 1] - angles[index];
1850                if gap > largest_gap {
1851                    largest_gap = gap;
1852                    gap_start = index;
1853                }
1854            }
1855            let span = std::f64::consts::TAU - largest_gap;
1856            if span <= tolerance || span >= std::f64::consts::TAU - 1e-6 {
1857                fall_through!(older, newer, 'partial_turn);
1858            }
1859            let start_angle = angles[(gap_start + 1) % angles.len()];
1860            let start_direction = x_reference
1861                .scale(start_angle.cos())
1862                .add(y_reference.scale(start_angle.sin()));
1863            let generatrix = make_line(
1864                support
1865                    .origin
1866                    .add(support.axis.scale(axial_range[0]))
1867                    .add(start_direction.scale(support.radius)),
1868                support
1869                    .origin
1870                    .add(support.axis.scale(axial_range[1]))
1871                    .add(start_direction.scale(support.radius)),
1872            )
1873            .or_refuse(KernelStage::Sew, "healing.face_merge")?;
1874            let surface = make_revolution(support.origin, support.axis, &generatrix, span)
1875                .or_refuse(KernelStage::Sew, "make_revolution")?;
1876            let (u_domain, v_domain) = surface_domains(&surface)?;
1877            let sample = surface
1878                .evaluate(
1879                    (u_domain[0] + u_domain[1]) / 2.0,
1880                    (v_domain[0] + v_domain[1]) / 2.0,
1881                )
1882                .or_refuse(KernelStage::Sew, "healing.face_merge")?;
1883            let geometric_normal = surface
1884                .normal(
1885                    (u_domain[0] + u_domain[1]) / 2.0,
1886                    (v_domain[0] + v_domain[1]) / 2.0,
1887                )
1888                .or_refuse(KernelStage::Sew, "healing.face_merge")?;
1889            let delta = sample.sub(support.origin);
1890            let radial = delta.sub(support.axis.scale(delta.dot(support.axis)));
1891            let radial = match radial.normalized() {
1892                Ok(radial) => radial,
1893                Err(_) => fall_through!(older, newer, 'partial_turn),
1894            };
1895            let same_sense = geometric_normal.dot(radial).signum() == support.outward_radial_sign;
1896            let mut projected_loops = reproject_loops(&surface, loops, edges)?;
1897            projected_loops.sort_by(|first, second| {
1898                let area = |loop_record: &LoopRecord| {
1899                    parameter_space_area(&FaceRecord {
1900                        id: older.id,
1901                        surface: surface.clone(),
1902                        same_sense,
1903                        loops: vec![loop_record.clone()],
1904                        name: None,
1905                    })
1906                    .map(f64::abs)
1907                };
1908                match (area(first), area(second)) {
1909                    (Ok(a), Ok(b)) => b.total_cmp(&a),
1910                    _ => std::cmp::Ordering::Equal,
1911                }
1912            });
1913            let merged = FaceRecord {
1914                id: older.id,
1915                surface,
1916                same_sense,
1917                loops: projected_loops,
1918                name: older.name.clone(),
1919            };
1920            let area =
1921                parameter_space_area(&merged).or_refuse(KernelStage::Sew, "parameter_space_area")?;
1922            if area.abs() <= tolerance * tolerance || area.is_sign_positive() != merged.same_sense {
1923                fall_through!(older, newer, 'partial_turn);
1924            }
1925            // The reprojected trims must reproduce the pieces' combined 3D
1926            // area; a projection or seam mistake shows up here immediately.
1927            if boundary_areas_agree(older, newer, &merged) {
1928                return Ok(Some(merged));
1929            }
1930            let expected = face_area(older).or_refuse(KernelStage::Sew, "face_area")?
1931                + face_area(newer).or_refuse(KernelStage::Sew, "face_area")?;
1932            let actual = face_area(&merged).or_refuse(KernelStage::Sew, "face_area")?;
1933            if (actual - expected).abs() > expected.abs().max(1e-9) * 5e-3 {
1934                fall_through!(older, newer, 'partial_turn);
1935            }
1936            return Ok(Some(merged));
1937        }
1938        if let Some(merged) =
1939            merge_cylinder_full_turn(older, newer, edges, tolerance, support, &shared_edges, lanes)?
1940        {
1941            return Ok(Some(merged));
1942        }
1943        decline!(older, newer);
1944    }
1945
1946    if let Some((support, union)) = cosurface_extrusion {
1947        // Shared linear-sweep carrier: the older profile translated to the
1948        // union's start plane, extruded across the union interval.
1949        let shift = support.direction.scale(union[0] - support.interval[0]);
1950        let step = support.direction.scale(union[1] - union[0]);
1951        let rows = support
1952            .base
1953            .control_points
1954            .iter()
1955            .map(|control| -> Result<Vec<Vec4>, KernelRefusal> {
1956                let point = control
1957                    .point()
1958                    .or_refuse(KernelStage::Sew, "point")?
1959                    .add(shift);
1960                Ok(vec![
1961                    Vec4::from_point(point, control.w),
1962                    Vec4::from_point(point.add(step), control.w),
1963                ])
1964            })
1965            .collect::<Result<Vec<_>, _>>()?;
1966        let surface = NurbsSurface::new(
1967            support.base.degree,
1968            1,
1969            support.base.knots.clone(),
1970            vec![0.0, 0.0, 1.0, 1.0],
1971            rows,
1972        )
1973        .or_refuse(KernelStage::Sew, "healing.face_merge")?;
1974        let (older_u, older_v) = surface_domains(&older.surface)?;
1975        let older_mid = older
1976            .surface
1977            .evaluate(
1978                (older_u[0] + older_u[1]) / 2.0,
1979                (older_v[0] + older_v[1]) / 2.0,
1980            )
1981            .or_refuse(KernelStage::Sew, "healing.face_merge")?;
1982        let projection = crate::project_point_to_surface(&surface, older_mid)
1983            .or_refuse(KernelStage::Sew, "project_point_to_surface")?;
1984        let carrier_normal = surface
1985            .normal(projection.u, projection.v)
1986            .or_refuse(KernelStage::Sew, "normal")?;
1987        let same_sense = carrier_normal.dot(outward_normal(older)?) > 0.0;
1988        let mut projected_loops = reproject_loops(&surface, loops, edges)?;
1989        projected_loops.sort_by(|first, second| {
1990            let area = |loop_record: &LoopRecord| {
1991                parameter_space_area(&FaceRecord {
1992                    id: older.id,
1993                    surface: surface.clone(),
1994                    same_sense,
1995                    loops: vec![loop_record.clone()],
1996                    name: None,
1997                })
1998                .map(f64::abs)
1999            };
2000            match (area(first), area(second)) {
2001                (Ok(a), Ok(b)) => b.total_cmp(&a),
2002                _ => std::cmp::Ordering::Equal,
2003            }
2004        });
2005        let merged = FaceRecord {
2006            id: older.id,
2007            surface,
2008            same_sense,
2009            loops: projected_loops,
2010            name: older.name.clone(),
2011        };
2012        let area =
2013            parameter_space_area(&merged).or_refuse(KernelStage::Sew, "parameter_space_area")?;
2014        if area.abs() <= tolerance * tolerance || area.is_sign_positive() != merged.same_sense {
2015            decline!(older, newer);
2016        }
2017        let expected = face_area(older).or_refuse(KernelStage::Sew, "face_area")?
2018            + face_area(newer).or_refuse(KernelStage::Sew, "face_area")?;
2019        let actual = face_area(&merged).or_refuse(KernelStage::Sew, "face_area")?;
2020        if (actual - expected).abs() > expected.abs().max(1e-9) * 5e-3 {
2021            if std::env::var("BREP_DEBUG_MERGE").is_ok() {
2022                eprintln!(
2023                    "coextrusion {}x{}: area mismatch {actual} vs {expected}",
2024                    older.id, newer.id
2025                );
2026            }
2027            decline!(older, newer);
2028        }
2029        return Ok(Some(merged));
2030    }
2031
2032    let (u_domain, v_domain) = surface_domains(&older.surface)?;
2033    let origin = older
2034        .surface
2035        .evaluate(u_domain[0], v_domain[0])
2036        .or_refuse(KernelStage::Sew, "evaluate")?;
2037    let derivatives = older
2038        .surface
2039        .derivatives(
2040            (u_domain[0] + u_domain[1]) / 2.0,
2041            (v_domain[0] + v_domain[1]) / 2.0,
2042            1,
2043        )
2044        .or_refuse(KernelStage::Sew, "healing.face_merge")?;
2045    let u_axis = derivatives[1][0]
2046        .normalized()
2047        .or_refuse(KernelStage::Sew, "normalized")?;
2048    let geometric_normal = derivatives[1][0]
2049        .cross(derivatives[0][1])
2050        .normalized()
2051        .or_refuse(KernelStage::Sew, "normalized")?;
2052    let v_axis = geometric_normal
2053        .cross(u_axis)
2054        .normalized()
2055        .or_refuse(KernelStage::Sew, "normalized")?;
2056    let mut bounds_u = [f64::INFINITY, f64::NEG_INFINITY];
2057    let mut bounds_v = [f64::INFINITY, f64::NEG_INFINITY];
2058    for coedge in loops.iter().flat_map(|loop_record| &loop_record.coedges) {
2059        let edge = edges[&coedge.edge_id];
2060        let curve = trimmed_curve(&edge.curve, edge.t0, edge.t1)?;
2061        for control in &curve.control_points {
2062            let relative = control
2063                .point()
2064                .or_refuse(KernelStage::Sew, "point")?
2065                .sub(origin);
2066            let u = relative.dot(u_axis);
2067            let v = relative.dot(v_axis);
2068            bounds_u[0] = bounds_u[0].min(u);
2069            bounds_u[1] = bounds_u[1].max(u);
2070            bounds_v[0] = bounds_v[0].min(v);
2071            bounds_v[1] = bounds_v[1].max(v);
2072        }
2073    }
2074    let extent_u = bounds_u[1] - bounds_u[0];
2075    let extent_v = bounds_v[1] - bounds_v[0];
2076    if extent_u <= tolerance || extent_v <= tolerance {
2077        decline!(older, newer);
2078    }
2079    let surface_origin = origin
2080        .add(u_axis.scale(bounds_u[0]))
2081        .add(v_axis.scale(bounds_v[0]));
2082    let surface = make_plane(surface_origin, u_axis, v_axis, extent_u, extent_v)
2083        .or_refuse(KernelStage::Sew, "make_plane")?;
2084    let mut projected_loops = match transfer_planar_loops(&surface, &loops, older, newer, tolerance)
2085    {
2086        Some(transferred) => transferred,
2087        None => reproject_loops(&surface, loops, edges)?,
2088    };
2089    projected_loops.sort_by(|first, second| {
2090        let area = |loop_record: &LoopRecord| {
2091            parameter_space_area(&FaceRecord {
2092                id: older.id,
2093                surface: surface.clone(),
2094                same_sense: older.same_sense,
2095                loops: vec![loop_record.clone()],
2096                name: None,
2097            })
2098            .map(f64::abs)
2099        };
2100        match (area(first), area(second)) {
2101            (Ok(a), Ok(b)) => b.total_cmp(&a),
2102            _ => std::cmp::Ordering::Equal,
2103        }
2104    });
2105    let merged = FaceRecord {
2106        id: older.id,
2107        surface,
2108        same_sense: older.same_sense,
2109        loops: projected_loops,
2110        name: older.name.clone(),
2111    };
2112    let area = parameter_space_area(&merged).or_refuse(KernelStage::Sew, "parameter_space_area")?;
2113    if area.abs() <= tolerance * tolerance || area.is_sign_positive() != merged.same_sense {
2114        decline!(older, newer);
2115    }
2116    Ok(Some(merged))
2117}
2118
2119/// Angle of `point` about `support`'s axis in the (`x_reference`,
2120/// `y_reference`) frame, in `[0, TAU)`; `None` on the axis.
2121fn cylinder_angle(
2122    support: &CylinderSupport,
2123    x_reference: Vec3,
2124    y_reference: Vec3,
2125    point: Vec3,
2126) -> Option<f64> {
2127    let delta = point.sub(support.origin);
2128    let radial = delta.sub(support.axis.scale(delta.dot(support.axis)));
2129    if radial.length() <= support.radius * 1e-6 {
2130        return None;
2131    }
2132    let mut angle = radial.dot(y_reference).atan2(radial.dot(x_reference));
2133    if angle < 0.0 {
2134        angle += std::f64::consts::TAU;
2135    }
2136    // An atan2 a few ulp below zero rounds to TAU itself after the shift; the
2137    // range is half-open, so that reading is the seam angle 0.
2138    if angle >= std::f64::consts::TAU {
2139        angle = 0.0;
2140    }
2141    Some(angle)
2142}
2143
2144
2145/// The widest angle, in radians, that no `(start, signed sweep)` arc of
2146/// `swept` covers; `TAU` for no arcs. Arcs are read the short way round, as
2147/// [`angle_difference`] reports a sweep between two nearby samples.
2148pub fn largest_uncovered_turn(swept: &[(f64, f64)]) -> f64 {
2149    let tau = std::f64::consts::TAU;
2150    let mut arcs: Vec<(f64, f64)> = Vec::with_capacity(swept.len() + 1);
2151    for &(start, sweep) in swept {
2152        let (low, length) = if sweep < 0.0 { (start + sweep, -sweep) } else { (start, sweep) };
2153        let low = low.rem_euclid(tau);
2154        if low + length > tau {
2155            arcs.push((low, tau));
2156            arcs.push((0.0, low + length - tau));
2157        } else {
2158            arcs.push((low, low + length));
2159        }
2160    }
2161    if arcs.is_empty() {
2162        return tau;
2163    }
2164    arcs.sort_by(|a, b| a.0.total_cmp(&b.0));
2165    let mut largest = 0.0f64;
2166    let mut reach = arcs[0].1;
2167    for arc in &arcs[1..] {
2168        largest = largest.max(arc.0 - reach);
2169        reach = reach.max(arc.1);
2170    }
2171    // The wrap from the last reach round to the first arc's start.
2172    largest.max(arcs[0].0 + tau - reach)
2173}
2174
2175/// Signed angular distance from `from` to `to`, in `(-PI, PI]`.
2176fn angle_difference(from: f64, to: f64) -> f64 {
2177    let turn = (to - from).rem_euclid(std::f64::consts::TAU);
2178    if turn > std::f64::consts::PI {
2179        turn - std::f64::consts::TAU
2180    } else {
2181        turn
2182    }
2183}
2184
2185/// `carrier` (closed in u) turned whole spans to start at a full-multiplicity
2186/// knot inside the widest u interval no trim of `loops` sweeps across (the
2187/// knot inserted at the interval's middle when it holds none), with every
2188/// trim's pcurve shifted in u to the turned chart: exact, since turning a
2189/// closed net at a knot of multiplicity `degree` moves no basis function and
2190/// each trim lies on one side of the new seam. `None` when the carrier is not
2191/// closed in u or no such interval exists (the trims sweep the whole turn).
2192fn turn_carrier_into_gap(
2193    carrier: &NurbsSurface,
2194    loops: Vec<LoopRecord>,
2195    weld: f64,
2196) -> Option<(NurbsSurface, Vec<LoopRecord>)> {
2197    let degree = carrier.degree_u;
2198    if degree == 0 || !closed_control_boundary(carrier, true, weld) {
2199        return None;
2200    }
2201    let (u_domain, _) = surface_domains(carrier).ok()?;
2202    // Each trim's u samples and the u intervals it sweeps between them.
2203    let mut samples: Vec<f64> = Vec::new();
2204    let mut swept: Vec<(f64, f64)> = Vec::new();
2205    for coedge in loops.iter().flat_map(|loop_record| &loop_record.coedges) {
2206        let [t0, t1] = coedge.pcurve.domain().ok()?;
2207        let mut previous: Option<f64> = None;
2208        for index in 0..=16 {
2209            let u = coedge.pcurve.evaluate(t0 + (t1 - t0) * index as f64 / 16.0).ok()?.x;
2210            if !u.is_finite() {
2211                return None;
2212            }
2213            samples.push(u);
2214            if let Some(previous) = previous {
2215                swept.push((previous.min(u), previous.max(u)));
2216            }
2217            previous = Some(u);
2218        }
2219    }
2220    samples.sort_by(f64::total_cmp);
2221    let (first, last) = (*samples.first()?, *samples.last()?);
2222    if first < u_domain[0] - weld || last > u_domain[1] + weld {
2223        return None;
2224    }
2225    // The widest interval between consecutive samples that no sweep covers
2226    // (the trims meet across the old seam, so the wrap-around interval is
2227    // covered by construction and never read).
2228    let mut gap: Option<(f64, f64)> = None;
2229    for pair in samples.windows(2) {
2230        let (low, high) = (pair[0], pair[1]);
2231        let middle = (low + high) / 2.0;
2232        if high - low <= weld || swept.iter().any(|&(a, b)| a < middle && middle < b) {
2233            continue;
2234        }
2235        if gap.is_none_or(|(a, b)| high - low > b - a) {
2236            gap = Some((low, high));
2237        }
2238    }
2239    let (low, high) = gap?;
2240    let middle = (low + high) / 2.0;
2241    let existing = crate::boolean::reseat::full_knots(&carrier.knots_u, degree)
2242        .into_iter()
2243        .map(|(knot, _)| knot)
2244        .filter(|&knot| knot > low && knot < high)
2245        .min_by(|a, b| (a - middle).abs().total_cmp(&(b - middle).abs()));
2246    let (refined, seam) = match existing {
2247        Some(knot) => (carrier.clone(), knot),
2248        None => {
2249            let present = carrier.knots_u.iter().filter(|&&knot| knot == middle).count();
2250            let refined = carrier
2251                .insert_knot(crate::KnotDirection::U, middle, degree.saturating_sub(present))
2252                .ok()?;
2253            (refined, middle)
2254        }
2255    };
2256    let (knots_u, rows) =
2257        crate::boolean::reseat::rotate_closed(&refined.knots_u, degree, &refined.control_points, seam)?;
2258    let surface = NurbsSurface::new(refined.degree_u, refined.degree_v, knots_u, refined.knots_v.clone(), rows).ok()?;
2259    // u at or past the seam moves down by (seam - u0); u before it moves up
2260    // by (u1 - seam), the rest of the turn.
2261    let mut turned = Vec::with_capacity(loops.len());
2262    for mut loop_record in loops {
2263        for coedge in &mut loop_record.coedges {
2264            let [t0, t1] = coedge.pcurve.domain().ok()?;
2265            let mid = coedge.pcurve.evaluate((t0 + t1) / 2.0).ok()?.x;
2266            let shift = if mid >= seam { u_domain[0] - seam } else { u_domain[1] - seam };
2267            for point in &mut coedge.pcurve.control_points {
2268                point.x += shift * point.w;
2269            }
2270        }
2271        turned.push(loop_record);
2272    }
2273    Some((surface, turned))
2274}
2275
2276/// The re-seamed face built from a seam-split pair (`seam_reseam_enabled`)
2277/// stands in for both pieces: every trim on its edge within the validator's
2278/// own pcurve acceptance on the pair's extent, and the pieces' combined 3D
2279/// area and volume term about the origin reproduced within what trims
2280/// admitted `band` off their edges can move along the whole boundary (the
2281/// full-turn lane's bars).
2282fn reseam_accepts(
2283    older: &FaceRecord,
2284    newer: &FaceRecord,
2285    merged: &FaceRecord,
2286    edges: &HashMap<u64, &EdgeRecord>,
2287    tolerance: f64,
2288    support: &CylinderSupport,
2289) -> Result<bool, KernelRefusal> {
2290    let debug = std::env::var("BREP_DEBUG_MERGE").is_ok();
2291    let mut perimeter = 0.0f64;
2292    let mut bbox_lo = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
2293    let mut bbox_hi = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
2294    for coedge in [older, newer]
2295        .iter()
2296        .flat_map(|face| face.loops.iter().flat_map(|loop_record| &loop_record.coedges))
2297    {
2298        let edge = edges[&coedge.edge_id];
2299        if edge.degenerate {
2300            continue;
2301        }
2302        perimeter += crate::mass_properties::edge_arc_length(edge).unwrap_or(0.0);
2303        let curve = trimmed_curve(&edge.curve, edge.t0, edge.t1)?;
2304        let [c0, c1] = curve.domain().or_refuse(KernelStage::Sew, "domain")?;
2305        for index in 0..=8 {
2306            let point = curve
2307                .evaluate(c0 + (c1 - c0) * index as f64 / 8.0)
2308                .or_refuse(KernelStage::Sew, "evaluate")?;
2309            bbox_lo = Vec3::new(bbox_lo.x.min(point.x), bbox_lo.y.min(point.y), bbox_lo.z.min(point.z));
2310            bbox_hi = Vec3::new(bbox_hi.x.max(point.x), bbox_hi.y.max(point.y), bbox_hi.z.max(point.z));
2311        }
2312    }
2313    // The bars read the pair's own size, never its distance from the world
2314    // origin: far from the origin an origin-scaled band would admit a
2315    // carrier a visible distance off the pieces' own.
2316    let diagonal = bbox_hi.sub(bbox_lo).length();
2317    let scale = 1.0f64.max(diagonal).max(support.radius);
2318    let band = (tolerance * 100.0).max(1e-7 * scale);
2319    // The support stands for the pieces' carrier itself: every station of
2320    // that carrier lies on it within `band`. The support's detection admits
2321    // a slight taper as a cylinder; a carrier rebuilt from such a support
2322    // would move the wall, so the pair stays split.
2323    let carrier = &older.surface;
2324    let (u_domain, v_domain) = surface_domains(carrier)?;
2325    let mut worst_off = 0.0f64;
2326    for i in 0..=8 {
2327        for j in 0..=4 {
2328            let point = carrier
2329                .evaluate(
2330                    u_domain[0] + (u_domain[1] - u_domain[0]) * i as f64 / 8.0,
2331                    v_domain[0] + (v_domain[1] - v_domain[0]) * j as f64 / 4.0,
2332                )
2333                .or_refuse(KernelStage::Sew, "evaluate")?;
2334            let delta = point.sub(support.origin);
2335            let axial = delta.dot(support.axis);
2336            let radial = delta.sub(support.axis.scale(axial)).length();
2337            worst_off = worst_off.max((radial - support.radius_at(axial)).abs());
2338        }
2339    }
2340    let pcurve_limit = crate::KernelTolerances::for_scale(scale, 1e-7).pcurve_acceptance(diagonal);
2341    let mut worst_trim = 0.0f64;
2342    for coedge in merged.loops.iter().flat_map(|loop_record| &loop_record.coedges) {
2343        let edge = edges[&coedge.edge_id];
2344        let error = crate::topology::coedge_error_floored(
2345            &merged.surface,
2346            &coedge.pcurve,
2347            &edge.curve,
2348            edge,
2349            coedge.forward,
2350            pcurve_limit,
2351        )
2352        .unwrap_or(f64::INFINITY);
2353        worst_trim = worst_trim.max(error);
2354    }
2355    let expected_area = face_area(older).or_refuse(KernelStage::Sew, "face_area")?
2356        + face_area(newer).or_refuse(KernelStage::Sew, "face_area")?;
2357    let expected_term = face_volume_contribution(older)
2358        .or_refuse(KernelStage::Sew, "face_volume_contribution")?
2359        + face_volume_contribution(newer).or_refuse(KernelStage::Sew, "face_volume_contribution")?;
2360    let actual = face_area(merged).or_refuse(KernelStage::Sew, "face_area")?;
2361    let actual_term =
2362        face_volume_contribution(merged).or_refuse(KernelStage::Sew, "face_volume_contribution")?;
2363    let area_bar = band * perimeter + 1e-9 * expected_area.abs();
2364    let reach = bbox_lo.length().max(bbox_hi.length());
2365    let term_bar = band * perimeter * reach / 3.0 + 1e-9 * expected_term.abs().max(expected_area.abs());
2366    let accepted = worst_off <= band
2367        && worst_trim <= pcurve_limit
2368        && (actual - expected_area).abs() <= area_bar
2369        && (actual_term - expected_term).abs() <= term_bar;
2370    if debug {
2371        eprintln!(
2372            "merge {}x{}: re-seam {}: carrier off its support {worst_off:.3e} (band {band:.3e}), trim {worst_trim:.3e} (limit {pcurve_limit:.3e}), area {actual:.9} vs {expected_area:.9} (bar {area_bar:.3e}), volume term {actual_term:.9} vs {expected_term:.9} (bar {term_bar:.3e})",
2373            older.id,
2374            newer.id,
2375            if accepted { "MERGE" } else { "declined" }
2376        );
2377    }
2378    Ok(accepted)
2379}
2380
2381/// Merge two cosurface cylinder patches whose union wraps the FULL turn.
2382///
2383/// The partial-turn lane seams its carrier in the union's largest angular
2384/// gap; a union with no gap (the shelled cylinder's full outer wall against
2385/// the half-walls of a coaxial extrude, the E13 report of 2026-10-13) has no
2386/// such seam, and cancelling every shared edge there strands the full face's
2387/// seam strip at a fork the 3D walk cannot resolve. This lane builds a closed
2388/// revolution carrier seamed along an existing AXIAL edge that both faces
2389/// already traverse twice — one face's own seam pair, or a shared pair — keeps
2390/// the shared edges on that line as seam pairs instead of cancelling them,
2391/// places every seam-line trim on the side of the seam its traversal puts the
2392/// material on, and walks the leftover uses in the carrier's own parameter
2393/// space. Only a seam one of the faces ALREADY has is a candidate: a face
2394/// that wraps the turn by itself carries its own seam pair, and the merged
2395/// face keeps that seam. Two half-turn patches closing a ring between them
2396/// have no such seam; they were two faces before any boolean touched them
2397/// (a sketch circle's two arcs, a tube piece's two halves, a plate hole's
2398/// two bore segments whose names a flange picks) and they stay two faces
2399/// here — master's battery of 2026-10-13 read four regressions from merging
2400/// them. Each candidate is tried in turn, and the merged face must close
2401/// every loop in parameter space, keep every trim on its edge within the
2402/// validator's own pcurve acceptance, and reproduce the pieces'
2403/// parameter-space sign and their combined 3D area, or the candidate is
2404/// dropped; with no candidate left the pair stays as assembled.
2405///
2406/// What this lane does NOT do: two full rings seamed at different angles
2407/// (a shelled cylinder's bore wall and a coaxial extrude's hole wall whose
2408/// profile circle happened to start opposite) have no axial edge spanning
2409/// both, and merging them means re-seaming one through its far rim and the
2410/// cap on it — a solid-wide edit the face merge does not make. Such a pair
2411/// declines here with its loops open in parameter space and keeps its
2412/// circular joint.
2413fn merge_cylinder_full_turn(
2414    older: &FaceRecord,
2415    newer: &FaceRecord,
2416    edges: &HashMap<u64, &EdgeRecord>,
2417    tolerance: f64,
2418    support: &CylinderSupport,
2419    shared_edges: &HashSet<u64>,
2420    lanes: MergeLanes<'_>,
2421) -> Result<Option<FaceRecord>, KernelRefusal> {
2422    let debug = std::env::var("BREP_DEBUG_MERGE").is_ok();
2423    // `BREP_FULL_TURN_MERGE=0` hatches the lane off, for attribution only.
2424    if std::env::var("BREP_FULL_TURN_MERGE").as_deref() == Ok("0") {
2425        return Ok(None);
2426    }
2427    // Every non-degenerate use of either face, tagged with which face it came
2428    // from (0 older, 1 newer) so an edge used twice by ONE face reads as its
2429    // own seam.
2430    let uses = [older, newer]
2431        .iter()
2432        .enumerate()
2433        .flat_map(|(side, face)| {
2434            face.loops
2435                .iter()
2436                .flat_map(|loop_record| &loop_record.coedges)
2437                .filter(|coedge| !edges[&coedge.edge_id].degenerate)
2438                .map(move |coedge| (side, coedge.clone()))
2439        })
2440        .collect::<Vec<_>>();
2441    let Some(x_reference) = uses.iter().find_map(|(_, coedge)| {
2442        let edge = edges[&coedge.edge_id];
2443        let seed = edge.curve.evaluate(edge.t0).ok()?;
2444        let delta = seed.sub(support.origin);
2445        let radial = delta.sub(support.axis.scale(delta.dot(support.axis)));
2446        radial.normalized().ok()
2447    }) else {
2448        return Ok(None);
2449    };
2450    let y_reference = support.axis.cross(x_reference);
2451    let scale = 1.0f64.max(support.origin.length()).max(support.radius);
2452    let band = (tolerance * 100.0).max(1e-7 * scale);
2453    // The smallest radius the patches reach bounds the angle `band` subtends
2454    // (a cylinder's one radius; a cone's radius at its narrow end, read once
2455    // the axial range is known below and checked positive there).
2456    let mut angular_band = band / support.radius;
2457
2458    // Each use's stations: axial coordinate and angle at nine samples, plus
2459    // the station of its start and end in traversal order.
2460    struct Station {
2461        angle: Option<f64>,
2462    }
2463    let station = |point: Vec3| Station {
2464        angle: cylinder_angle(support, x_reference, y_reference, point),
2465    };
2466    let mut axial_range = [f64::INFINITY, f64::NEG_INFINITY];
2467    let mut samples = Vec::with_capacity(uses.len());
2468    let mut bbox_lo = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
2469    let mut bbox_hi = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
2470    // The boundary length of both faces together: the most area a set of
2471    // trims admitted `band` off their edges can move, per unit of `band`.
2472    let mut perimeter = 0.0f64;
2473    for (_, coedge) in &uses {
2474        let edge = edges[&coedge.edge_id];
2475        let curve = trimmed_curve(&edge.curve, edge.t0, edge.t1)?;
2476        let [c0, c1] = curve.domain().or_refuse(KernelStage::Sew, "domain")?;
2477        let hull = axial_hull(&curve, support);
2478        axial_range[0] = axial_range[0].min(hull[0]);
2479        axial_range[1] = axial_range[1].max(hull[1]);
2480        perimeter += crate::mass_properties::edge_arc_length(edge).unwrap_or(0.0);
2481        let mut stations = Vec::with_capacity(9);
2482        for index in 0..=8 {
2483            let point = curve
2484                .evaluate(c0 + (c1 - c0) * index as f64 / 8.0)
2485                .or_refuse(KernelStage::Sew, "evaluate")?;
2486            bbox_lo = Vec3::new(bbox_lo.x.min(point.x), bbox_lo.y.min(point.y), bbox_lo.z.min(point.z));
2487            bbox_hi = Vec3::new(bbox_hi.x.max(point.x), bbox_hi.y.max(point.y), bbox_hi.z.max(point.z));
2488            stations.push(station(point));
2489        }
2490        samples.push(stations);
2491    }
2492    if axial_range[1] - axial_range[0] <= tolerance {
2493        return Ok(None);
2494    }
2495    if support.slope != 0.0 {
2496        let narrow = support
2497            .radius_at(axial_range[0])
2498            .min(support.radius_at(axial_range[1]));
2499        if narrow <= band {
2500            return Ok(None);
2501        }
2502        angular_band = band / narrow;
2503    }
2504    // An edge is an axial line at angle `theta` when every sample reads that
2505    // angle: a straight generatrix of the shared cylinder.
2506    let axial_angle = |stations: &[Station]| -> Option<f64> {
2507        let first = stations.first()?.angle?;
2508        stations
2509            .iter()
2510            .all(|station| {
2511                station
2512                    .angle
2513                    .is_some_and(|angle| angle_difference(first, angle).abs() <= angular_band)
2514            })
2515            .then_some(first)
2516    };
2517    let mut use_count = HashMap::<u64, usize>::default();
2518    for (_, coedge) in &uses {
2519        *use_count.entry(coedge.edge_id).or_default() += 1;
2520    }
2521    // Candidate seam angles, ranked: a face's own seam pair (both uses from
2522    // one face) before a shared pair; a line used once bounds the region on
2523    // one side only and cannot seam a wrap by itself.
2524    let mut candidates: Vec<(u8, f64)> = Vec::new();
2525    // Candidate angles whose edge ends at a vertex `lanes.seam_vertices` names.
2526    let mut preferred: Vec<f64> = Vec::new();
2527    for (index, (side, coedge)) in uses.iter().enumerate() {
2528        if use_count.get(&coedge.edge_id).copied() != Some(2) {
2529            continue;
2530        }
2531        let Some(theta) = axial_angle(&samples[index]) else {
2532            continue;
2533        };
2534        let own_seam = uses
2535            .iter()
2536            .any(|(other_side, other)| {
2537                other.edge_id == coedge.edge_id
2538                    && other.id != coedge.id
2539                    && other_side == side
2540                    && other.forward != coedge.forward
2541            });
2542        let rank = if own_seam { 0 } else { 1 };
2543        if let Some(vertices) = lanes.seam_vertices {
2544            let edge = edges[&coedge.edge_id];
2545            if vertices.contains(&edge.start_vertex_id) || vertices.contains(&edge.end_vertex_id) {
2546                preferred.push(theta);
2547            }
2548        }
2549        if !candidates
2550            .iter()
2551            .any(|(_, known)| angle_difference(*known, theta).abs() <= angular_band)
2552        {
2553            candidates.push((rank, theta));
2554        } else if let Some(known) = candidates
2555            .iter_mut()
2556            .find(|(_, known)| angle_difference(*known, theta).abs() <= angular_band)
2557        {
2558            known.0 = known.0.min(rank);
2559        }
2560    }
2561    let is_preferred = |theta: f64| {
2562        preferred
2563            .iter()
2564            .any(|known| angle_difference(*known, theta).abs() <= angular_band)
2565    };
2566    // `false` sorts first: a preferred seam leads its rank. With no
2567    // preference every key is `true` and the order is the plain one.
2568    candidates.sort_by(|a, b| {
2569        a.0.cmp(&b.0)
2570            .then(is_preferred(b.1).cmp(&is_preferred(a.1)))
2571            .then(a.1.total_cmp(&b.1))
2572    });
2573    if debug {
2574        eprintln!(
2575            "merge {}x{}: full-turn lane, {} seam candidate(s) {:?}",
2576            older.id,
2577            newer.id,
2578            candidates.len(),
2579            candidates
2580        );
2581    }
2582    // A shared pair alone (rank 1) is two half patches closing a ring between
2583    // them: neither face wraps, and the merged face would carry a seam no
2584    // input face had. Those pairs stay as assembled (see the doc comment).
2585    // A caller that opted into `shared_seam_ring` is joining faces the user
2586    // named as one region; there the shared pair seams the ring.
2587    if !lanes.shared_seam_ring {
2588        candidates.retain(|(rank, _)| *rank == 0);
2589    }
2590    if candidates.is_empty() {
2591        if debug {
2592            eprintln!(
2593                "merge {}x{}: full-turn lane: no face wraps the turn by itself, the halves stay apart",
2594                older.id, newer.id
2595            );
2596        }
2597        return Ok(None);
2598    }
2599    let weld = crate::tolerance::assembler_weld(tolerance);
2600    // The validator's own edge/pcurve acceptance on this pair's extent (its
2601    // size-coupled ceiling floors at `pcurve_consistency`); the pair's
2602    // diagonal is at most the solid's, so nothing admitted here is refused
2603    // by the closing validation on that count.
2604    let pcurve_limit = crate::KernelTolerances::for_scale(scale, 1e-7)
2605        .pcurve_acceptance(bbox_hi.sub(bbox_lo).length());
2606    let expected_area = face_area(older).or_refuse(KernelStage::Sew, "face_area")?
2607        + face_area(newer).or_refuse(KernelStage::Sew, "face_area")?;
2608    let expected_term = face_volume_contribution(older)
2609        .or_refuse(KernelStage::Sew, "face_volume_contribution")?
2610        + face_volume_contribution(newer).or_refuse(KernelStage::Sew, "face_volume_contribution")?;
2611
2612    'candidate: for (_, theta) in candidates {
2613        let on_seam = |index: usize| {
2614            axial_angle(&samples[index])
2615                .is_some_and(|angle| angle_difference(theta, angle).abs() <= angular_band)
2616        };
2617        // Closed carrier seamed at `theta`, spanning both patches axially.
2618        let start_direction = x_reference
2619            .scale(theta.cos())
2620            .add(y_reference.scale(theta.sin()));
2621        let generatrix = make_line(
2622            support
2623                .origin
2624                .add(support.axis.scale(axial_range[0]))
2625                .add(start_direction.scale(support.radius_at(axial_range[0]))),
2626            support
2627                .origin
2628                .add(support.axis.scale(axial_range[1]))
2629                .add(start_direction.scale(support.radius_at(axial_range[1]))),
2630        )
2631        .or_refuse(KernelStage::Sew, "healing.face_merge")?;
2632        let surface = make_revolution(
2633            support.origin,
2634            support.axis,
2635            &generatrix,
2636            std::f64::consts::TAU,
2637        )
2638        .or_refuse(KernelStage::Sew, "make_revolution")?;
2639        let (u_domain, v_domain) = surface_domains(&surface)?;
2640        let (u_mid, v_mid) = (
2641            (u_domain[0] + u_domain[1]) / 2.0,
2642            (v_domain[0] + v_domain[1]) / 2.0,
2643        );
2644        let sample = surface
2645            .evaluate(u_mid, v_mid)
2646            .or_refuse(KernelStage::Sew, "healing.face_merge")?;
2647        let geometric_normal = surface
2648            .normal(u_mid, v_mid)
2649            .or_refuse(KernelStage::Sew, "healing.face_merge")?;
2650        let delta = sample.sub(support.origin);
2651        let radial = delta.sub(support.axis.scale(delta.dot(support.axis)));
2652        let Ok(radial) = radial.normalized() else {
2653            continue;
2654        };
2655        let same_sense = geometric_normal.dot(radial).signum() == support.outward_radial_sign;
2656        let v_of = |axial: f64| {
2657            v_domain[0]
2658                + (axial - axial_range[0]) / (axial_range[1] - axial_range[0])
2659                    * (v_domain[1] - v_domain[0])
2660        };
2661
2662        // Leftover uses: a shared edge off the seam line is cancelled; one on
2663        // it stays, both ways, as the merged face's seam.
2664        let mut remaining = Vec::new();
2665        for (index, (_, coedge)) in uses.iter().enumerate() {
2666            let seam_line = on_seam(index);
2667            if shared_edges.contains(&coedge.edge_id) && !seam_line {
2668                continue;
2669            }
2670            let edge = edges[&coedge.edge_id];
2671            let mut coedge = coedge.clone();
2672            let mut curve = trimmed_curve(&edge.curve, edge.t0, edge.t1)?;
2673            if !coedge.forward {
2674                curve = curve.reversed().or_refuse(KernelStage::Sew, "reversed")?;
2675            }
2676            if seam_line {
2677                // The material lies to the LEFT of a same-sense loop's
2678                // traversal in uv (parameter-space area positive) and to the
2679                // right of an opposite-sense one. A seam-line trim running
2680                // +v with material on its left is the domain's far side
2681                // (u = u1); running -v, its near side (u = u0).
2682                let [c0, c1] = curve.domain().or_refuse(KernelStage::Sew, "domain")?;
2683                let start = curve.evaluate(c0).or_refuse(KernelStage::Sew, "evaluate")?;
2684                let end = curve.evaluate(c1).or_refuse(KernelStage::Sew, "evaluate")?;
2685                let rising = end.sub(start).dot(support.axis) > 0.0;
2686                let far_side = rising == same_sense;
2687                let u = if far_side { u_domain[1] } else { u_domain[0] };
2688                // The trim carries the edge's OWN parameterisation: the
2689                // axial coordinate is an affine functional of position, so
2690                // mapping each control point (dehomogenised) and keeping the
2691                // degree, knots and weights reproduces v(t) exactly. A
2692                // two-point line assumed the edge ran its axis at constant
2693                // speed, which a spline tube's straight Hermite piece does
2694                // not (max deviation 0.5 at the validator, 2026-10-13).
2695                let origin_axial = support.origin.dot(support.axis);
2696                let control_points = curve
2697                    .control_points
2698                    .iter()
2699                    .map(|point| {
2700                        let w = point.w;
2701                        let axial = Vec3::new(point.x / w, point.y / w, point.z / w)
2702                            .dot(support.axis)
2703                            - origin_axial;
2704                        Vec4 { x: u * w, y: v_of(axial) * w, z: 0.0, w }
2705                    })
2706                    .collect();
2707                coedge.pcurve = NurbsCurve::new(curve.degree, curve.knots.clone(), control_points)
2708                    .or_refuse(KernelStage::Sew, "NurbsCurve::new")?;
2709            } else {
2710                // The kernel's fit, with its report read: a station standing
2711                // off the carrier (`off_surface`) is an edge this carrier
2712                // does not hold — the projector folds such a station onto
2713                // the carrier's boundary and the face becomes the wrong
2714                // region on a body `validate()` passes — and a residual over
2715                // the band is a trim that misses its edge between stations.
2716                let fit = match crate::fit_pcurve_on_surface(&surface, &curve) {
2717                    Ok(fit) => fit,
2718                    Err(_) => continue 'candidate,
2719                };
2720                if fit.report.off_surface > band || fit.report.residual > band {
2721                    if debug {
2722                        eprintln!(
2723                            "merge {}x{}: full-turn seam {theta:.4}: edge {} stands {:.3e} off the carrier, fit residual {:.3e} (band {band:.3e})",
2724                            older.id, newer.id, coedge.edge_id, fit.report.off_surface, fit.report.residual
2725                        );
2726                    }
2727                    continue 'candidate;
2728                }
2729                coedge.pcurve = fit.curve;
2730            }
2731            remaining.push(coedge);
2732        }
2733        let space = SharedParameterSpace { surface: &surface, weld };
2734        dissolve_slits(&mut remaining, edges, &space);
2735        if debug {
2736            for coedge in &remaining {
2737                let stations = pcurve_stations(coedge)
2738                    .map(|[a, m, b]| format!("({:.4},{:.4})->({:.4},{:.4})->({:.4},{:.4})", a.x, a.y, m.x, m.y, b.x, b.y))
2739                    .unwrap_or_default();
2740                eprintln!(
2741                    "  seam {theta:.4} use coedge {} edge {} fwd={} shared={} same_sense={same_sense} uv {stations}",
2742                    coedge.id,
2743                    coedge.edge_id,
2744                    coedge.forward,
2745                    shared_edges.contains(&coedge.edge_id)
2746                );
2747            }
2748        }
2749        let Some(mut loops) = walk_cycles(remaining, edges, Some(&space)) else {
2750            if debug {
2751                eprintln!(
2752                    "merge {}x{}: full-turn seam {theta:.4}: walk undetermined",
2753                    older.id, newer.id
2754                );
2755            }
2756            continue;
2757        };
2758        if loops.is_empty() {
2759            continue;
2760        }
2761        // Every loop must CLOSE in the carrier's parameter space: the walk
2762        // closes a cycle on vertex identity when nothing else leaves its
2763        // end, which on a seamed carrier accepts a full circle running one
2764        // period from its own vertex, or a ring whose own seam pair (off the
2765        // chosen seam) just dissolved as a slit. The area oracles below
2766        // integrate per pcurve and cannot see the grouping.
2767        let closed = loops.iter().all(|loop_record| {
2768            let count = loop_record.coedges.len();
2769            (0..count).all(|index| {
2770                let next = &loop_record.coedges[(index + 1) % count];
2771                match (
2772                    pcurve_stations(&loop_record.coedges[index]),
2773                    pcurve_stations(next),
2774                ) {
2775                    (Some(here), Some(there)) => space.coincide(here[2], there[0]),
2776                    _ => false,
2777                }
2778            })
2779        });
2780        if !closed {
2781            if debug {
2782                eprintln!(
2783                    "merge {}x{}: full-turn seam {theta:.4}: a loop is open in parameter space",
2784                    older.id, newer.id
2785                );
2786            }
2787            continue;
2788        }
2789        if debug {
2790            for loop_record in &loops {
2791                eprintln!(
2792                    "  seam {theta:.4} loop {:?}",
2793                    loop_record.coedges.iter().map(|c| (c.edge_id, c.forward)).collect::<Vec<_>>()
2794                );
2795            }
2796        }
2797        loops.sort_by(|first, second| {
2798            let area = |loop_record: &LoopRecord| {
2799                parameter_space_area(&FaceRecord {
2800                    id: older.id,
2801                    surface: surface.clone(),
2802                    same_sense,
2803                    loops: vec![loop_record.clone()],
2804                    name: None,
2805                })
2806                .map(f64::abs)
2807            };
2808            match (area(first), area(second)) {
2809                (Ok(a), Ok(b)) => b.total_cmp(&a),
2810                _ => std::cmp::Ordering::Equal,
2811            }
2812        });
2813        let merged = FaceRecord {
2814            id: older.id,
2815            surface,
2816            same_sense,
2817            loops,
2818            name: older.name.clone(),
2819        };
2820        // Every trim must lie on its edge by the validator's own reading;
2821        // a candidate that fails here falls through and the pair stays,
2822        // instead of the refusal surfacing from the closing validation as a
2823        // feature failure (the spline tube, 2026-10-13).
2824        let mut worst_trim = 0.0f64;
2825        for coedge in merged.loops.iter().flat_map(|loop_record| &loop_record.coedges) {
2826            let edge = edges[&coedge.edge_id];
2827            let error = crate::topology::coedge_error_floored(
2828                &merged.surface,
2829                &coedge.pcurve,
2830                &edge.curve,
2831                edge,
2832                coedge.forward,
2833                pcurve_limit,
2834            )
2835            .unwrap_or(f64::INFINITY);
2836            worst_trim = worst_trim.max(error);
2837        }
2838        if worst_trim > pcurve_limit {
2839            if debug {
2840                eprintln!(
2841                    "merge {}x{}: full-turn seam {theta:.4}: a trim is {worst_trim:.6} off its edge (limit {pcurve_limit:.6})",
2842                    older.id, newer.id
2843                );
2844            }
2845            continue;
2846        }
2847        let area =
2848            parameter_space_area(&merged).or_refuse(KernelStage::Sew, "parameter_space_area")?;
2849        if area.abs() <= tolerance * tolerance || area.is_sign_positive() != merged.same_sense {
2850            if debug {
2851                eprintln!(
2852                    "merge {}x{}: full-turn seam {theta:.4}: parameter area {area:.3e} vs same_sense {same_sense}",
2853                    older.id, newer.id
2854                );
2855            }
2856            continue;
2857        }
2858        // The merged face must reproduce the pieces' combined 3D area and
2859        // their combined volume term about the origin. The bar is what the
2860        // admitted trims can move: `band` off their edges along the whole
2861        // boundary (and that much times the farthest point for the volume
2862        // term), plus the quadrature's drift. A 5e-3 share of the area let
2863        // a 0.24 sliver through (BadBoolean, 2026-10-13); the volume term
2864        // sees a region of the right area in the wrong place, which the
2865        // area cannot.
2866        let actual = face_area(&merged).or_refuse(KernelStage::Sew, "face_area")?;
2867        let area_bar = band * perimeter + 1e-9 * expected_area.abs();
2868        if (actual - expected_area).abs() > area_bar {
2869            if debug {
2870                eprintln!(
2871                    "merge {}x{}: full-turn seam {theta:.4}: area {actual:.9} vs expected {expected_area:.9} (bar {area_bar:.3e})",
2872                    older.id, newer.id
2873                );
2874            }
2875            continue;
2876        }
2877        let actual_term =
2878            face_volume_contribution(&merged).or_refuse(KernelStage::Sew, "face_volume_contribution")?;
2879        let reach = bbox_lo.length().max(bbox_hi.length());
2880        let term_bar = band * perimeter * reach / 3.0 + 1e-9 * expected_term.abs().max(expected_area.abs());
2881        if (actual_term - expected_term).abs() > term_bar {
2882            if debug {
2883                eprintln!(
2884                    "merge {}x{}: full-turn seam {theta:.4}: volume term {actual_term:.9} vs expected {expected_term:.9} (bar {term_bar:.3e})",
2885                    older.id, newer.id
2886                );
2887            }
2888            continue;
2889        }
2890        if debug {
2891            eprintln!(
2892                "merge {}x{}: full-turn MERGE at seam {theta:.4}, {} loop(s); area {actual:.9} vs {expected_area:.9} (bar {area_bar:.3e}), volume term {actual_term:.9} vs {expected_term:.9} (bar {term_bar:.3e})",
2893                older.id,
2894                newer.id,
2895                merged.loops.len()
2896            );
2897        }
2898        return Ok(Some(merged));
2899    }
2900    Ok(None)
2901}
2902
2903
2904pub fn try_merge_connected_group(
2905    faces: &[FaceRecord],
2906    edges: &HashMap<u64, &EdgeRecord>,
2907    tolerance: f64,
2908    same_carrier_area_tolerance_ratio: f64,
2909    keep_unmerged: &[String],
2910) -> Result<Option<(Vec<usize>, FaceRecord)>, KernelRefusal> {
2911    for seed in 0..faces.len() {
2912        // A pinned face never seeds or joins a merge group.
2913        if face_is_pinned(&faces[seed], keep_unmerged) {
2914            continue;
2915        }
2916        let mut component = [seed].into_iter().collect::<HashSet<_>>();
2917        loop {
2918            let mut changed = false;
2919            for candidate in 0..faces.len() {
2920                if component.contains(&candidate)
2921                    || face_is_pinned(&faces[candidate], keep_unmerged)
2922                    || faces[candidate].same_sense != faces[seed].same_sense
2923                    || !same_surface(&faces[candidate].surface, &faces[seed].surface, 1e-7)
2924                {
2925                    continue;
2926                }
2927                let candidate_uses = faces[candidate]
2928                    .loops
2929                    .iter()
2930                    .flat_map(|loop_record| &loop_record.coedges);
2931                let adjacent = candidate_uses.into_iter().any(|candidate_use| {
2932                    !edges[&candidate_use.edge_id].degenerate
2933                        && component.iter().any(|member| {
2934                            faces[*member]
2935                                .loops
2936                                .iter()
2937                                .flat_map(|loop_record| &loop_record.coedges)
2938                                .any(|member_use| {
2939                                    member_use.edge_id == candidate_use.edge_id
2940                                        && member_use.forward != candidate_use.forward
2941                                })
2942                        })
2943                });
2944                if adjacent {
2945                    component.insert(candidate);
2946                    changed = true;
2947                }
2948            }
2949            if !changed {
2950                break;
2951            }
2952        }
2953        if component.len() < 2 {
2954            continue;
2955        }
2956
2957        let mut uses_by_edge = HashMap::<u64, Vec<CoedgeRecord>>::default();
2958        for index in &component {
2959            for coedge in faces[*index]
2960                .loops
2961                .iter()
2962                .flat_map(|loop_record| &loop_record.coedges)
2963            {
2964                uses_by_edge
2965                    .entry(coedge.edge_id)
2966                    .or_default()
2967                    .push(coedge.clone());
2968            }
2969        }
2970        if uses_by_edge.values().any(|uses| uses.len() > 2) {
2971            continue;
2972        }
2973        let internal = uses_by_edge
2974            .iter()
2975            .filter_map(|(edge_id, uses)| {
2976                (uses.len() == 2
2977                    && !edges[edge_id].degenerate
2978                    && uses[0].forward != uses[1].forward)
2979                    .then_some(*edge_id)
2980            })
2981            .collect::<HashSet<_>>();
2982        let remaining = uses_by_edge
2983            .into_iter()
2984            .filter(|(edge_id, _)| !internal.contains(edge_id))
2985            .flat_map(|(_, uses)| uses)
2986            .collect::<Vec<_>>();
2987        let space = SharedParameterSpace {
2988            surface: &faces[seed].surface,
2989            weld: crate::tolerance::assembler_weld(tolerance),
2990        };
2991        let Some(mut loops) = walk_cycles(remaining, edges, Some(&space)) else {
2992            continue;
2993        };
2994        if loops.is_empty() {
2995            continue;
2996        }
2997        loops.sort_by(|first, second| {
2998            let area = |loop_record: &LoopRecord| {
2999                parameter_space_area(&FaceRecord {
3000                    id: faces[seed].id,
3001                    surface: faces[seed].surface.clone(),
3002                    same_sense: faces[seed].same_sense,
3003                    loops: vec![loop_record.clone()],
3004                    name: None,
3005                })
3006                .map(f64::abs)
3007            };
3008            match (area(first), area(second)) {
3009                (Ok(a), Ok(b)) => b.total_cmp(&a),
3010                _ => std::cmp::Ordering::Equal,
3011            }
3012        });
3013        let merged = FaceRecord {
3014            id: faces[seed].id,
3015            surface: faces[seed].surface.clone(),
3016            same_sense: faces[seed].same_sense,
3017            loops,
3018            name: faces[seed].name.clone(),
3019        };
3020        let expected = component
3021            .iter()
3022            .map(|index| parameter_space_area(&faces[*index]))
3023            .collect::<Result<Vec<_>, _>>()
3024            .or_refuse(KernelStage::Sew, "healing.face_merge")?
3025            .into_iter()
3026            .sum::<f64>();
3027        let actual =
3028            parameter_space_area(&merged).or_refuse(KernelStage::Sew, "parameter_space_area")?;
3029        let area_tolerance = 1e-9f64.max(expected.abs() * same_carrier_area_tolerance_ratio);
3030        if (actual - expected).abs() > area_tolerance
3031            || (actual.abs() > 1e-12 && actual.is_sign_positive() != merged.same_sense)
3032        {
3033            continue;
3034        }
3035        let mut indices = component.into_iter().collect::<Vec<_>>();
3036        indices.sort_unstable();
3037        return Ok(Some((indices, merged)));
3038    }
3039    Ok(None)
3040}
3041
3042/// A face is PINNED out of the merge when its `name` contains any substring in
3043/// `keep_unmerged`: it never coalesces with a neighbour (in any merge lane) and
3044/// is emitted unchanged. An empty `keep_unmerged` pins nothing — the historical
3045/// behavior.
3046fn face_is_pinned(face: &FaceRecord, keep_unmerged: &[String]) -> bool {
3047    match &face.name {
3048        Some(name) => keep_unmerged
3049            .iter()
3050            .any(|needle| name.contains(needle.as_str())),
3051        None => false,
3052    }
3053}
3054
3055// Pairwise merge driver for one shell.
3056//
3057// `try_merge_pair` returns `None` for any two faces that share no
3058// non-degenerate edge, so the only candidates are edge-adjacent pairs; they
3059// are kept in a set ordered by the faces' original positions and evaluated
3060// smallest first. Faces stay in their original slots (a merged face keeps
3061// the lower slot, the absorbed face's slot is emptied), so that order never
3062// shifts. A rejected pair is dropped for good: `try_merge_pair` is a pure
3063// function of the two face records and the constant edge map, and a pair is
3064// re-queued only when one of its faces changes. Hence each accepted merge is
3065// the lexicographically first accepting pair over all faces — the same pair
3066// the former full rescan found — and the result is the same face set, in
3067// the same order, reached without re-examining every pair per merge.
3068thread_local! {
3069    /// Pairs [`try_merge_pair`] declined, by [`pair_identity`]: everything the
3070    /// pair test reads. A boolean hands the face merge every edge-adjacent
3071    /// pair of its result, and all but the pairs it touched are the pairs the
3072    /// boolean before it declined (a bore's two half-turn walls reach the
3073    /// full-turn lane and stay apart, each time).
3074    static DECLINED_PAIRS: std::cell::RefCell<HashSet<[u64; 2]>> = std::cell::RefCell::new(HashSet::default());
3075    static DECLINES_SERVED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3076}
3077
3078thread_local! {
3079    /// Partial-turn area checks the boundary reading decided, and those it
3080    /// handed to the surface integration, since the thread started.
3081    static BOUNDARY_AREA_CHECKS: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0, 0)) };
3082}
3083
3084/// `(decided, handed on)` by [`boundary_areas_agree`] since the thread started.
3085pub fn boundary_area_checks() -> (usize, usize) {
3086    BOUNDARY_AREA_CHECKS.with(|counts| counts.get())
3087}
3088
3089/// `BREP_MERGE_AREA_BOUNDARY` (default on; `=0` restores the surface integration): the partial-turn lane's area
3090/// check reads the three areas as boundary integrals first
3091/// ([`translational_boundary_area`]) and integrates over the surfaces only
3092/// when that reading cannot admit the merge.
3093fn boundary_area_check_on() -> bool {
3094    switch!("BREP_MERGE_AREA_BOUNDARY", true)
3095}
3096
3097/// How far below the area check's 5e-3 the boundary reading must find the
3098/// merged face's area from the two parts' before it admits the merge unread
3099/// by the surface integration: a tenth of the bar. The boundary reading is
3100/// itself held to [`BOUNDARY_AREA_SETTLED`], four orders tighter.
3101const BOUNDARY_AREA_ADMIT: f64 = 5e-4;
3102
3103/// The relative agreement between the boundary reading's two resolutions
3104/// below which it is taken as settled.
3105const BOUNDARY_AREA_SETTLED: f64 = 1e-7;
3106
3107/// Whether the boundary reading admits `merged` as the two parts' combined
3108/// area: all three faces read, and the merged area within
3109/// [`BOUNDARY_AREA_ADMIT`] of the sum. `false` decides nothing; the caller
3110/// then integrates as it always did, so a merge is never declined here.
3111fn boundary_areas_agree(older: &FaceRecord, newer: &FaceRecord, merged: &FaceRecord) -> bool {
3112    if !boundary_area_check_on() {
3113        return false;
3114    }
3115    let agreed = (|| {
3116        let expected = translational_boundary_area(older)? + translational_boundary_area(newer)?;
3117        let actual = translational_boundary_area(merged)?;
3118        Some((actual - expected).abs() <= expected.abs().max(1e-9) * BOUNDARY_AREA_ADMIT)
3119    })()
3120    .unwrap_or(false);
3121    BOUNDARY_AREA_CHECKS.with(|counts| {
3122        let (decided, handed_on) = counts.get();
3123        counts.set(if agreed { (decided + 1, handed_on) } else { (decided, handed_on + 1) });
3124    });
3125    agreed
3126}
3127
3128/// The widest ratio between a carrier's u weights the boundary reading
3129/// accepts.
3130const BOUNDARY_CARRIER_WEIGHT_RATIO: f64 = 4.0;
3131
3132const BOUNDARY_GAUSS_X: [f64; 4] = [0.1834346424956498, 0.5255324099163290, 0.7966664774136267, 0.9602898564975363];
3133const BOUNDARY_GAUSS_W: [f64; 4] = [0.3626837833783620, 0.3137066458778873, 0.2223810344533745, 0.1012285362903763];
3134
3135/// The area of a face on a TRANSLATIONAL carrier, `S(u, v) = C(u) + s(v) D`
3136/// with `s` linear (a cylinder patch, a linear sweep), read on its trim
3137/// boundary alone. The area element there is `g(u) du dv` with
3138/// `g(u) = |C'(u) x D| s'`, a function of `u` only, so by Green's theorem
3139/// the area inside the loops is `-∮ v g(u) du`: one carrier derivative per
3140/// boundary station and no cell of the surface. `v` is read from the
3141/// domain's start, so the sum does not cancel against an offset of the
3142/// parameterization. Each joint that misses is closed by its straight
3143/// chord, as the trim polygons close it.
3144///
3145/// `None` (the caller integrates over the surface) unless every condition
3146/// the identity needs holds: the carrier is degree 1 across two control
3147/// columns that differ by one vector with equal weights, its u weights
3148/// within [`BOUNDARY_CARRIER_WEIGHT_RATIO`] of one another; it is closed in
3149/// neither direction, so no loop steps a seam; every pcurve is polynomial
3150/// (equal weights); every boundary station lies inside the carrier's domain; and the reading at eight stations per
3151/// pcurve span (cut where it crosses a knot line of the carrier, across
3152/// which `g` has a kink) agrees with the reading at sixteen to
3153/// [`BOUNDARY_AREA_SETTLED`].
3154fn translational_boundary_area(face: &FaceRecord) -> Option<f64> {
3155    let surface = &face.surface;
3156    if surface.degree_v != 1 || surface.control_points.len() < 2 || surface.knots_v.len() != 4 {
3157        return None;
3158    }
3159    let closed = surface.closed_directions().ok()?;
3160    if closed != (false, false) && !(boundary_area_closed_on() && loops_close_in_the_chart(face)?) {
3161        return None;
3162    }
3163    // One sweep vector, equal weights across each row, and along u weights
3164    // no further apart than a circular arc's (a span of 120 degrees weighs
3165    // its middle control 1/2): a carrier re-weighted beyond that can gather
3166    // g next to a knot, where no fixed rule finds it.
3167    let mut sweep: Option<Vec3> = None;
3168    let mut scale = 0.0f64;
3169    let (mut lightest, mut heaviest) = (f64::INFINITY, 0.0f64);
3170    for row in &surface.control_points {
3171        let [low, high] = row.as_slice() else { return None };
3172        if !(low.w > 0.0) || low.w != high.w {
3173            return None;
3174        }
3175        lightest = lightest.min(low.w);
3176        heaviest = heaviest.max(low.w);
3177        let (low, high) = (low.point().ok()?, high.point().ok()?);
3178        scale = scale.max(low.length()).max(high.length());
3179        let step = high.sub(low);
3180        match sweep {
3181            None => sweep = Some(step),
3182            Some(first) if step.sub(first).length() <= 1e-12 * scale.max(first.length()) => {}
3183            Some(_) => return None,
3184        }
3185    }
3186    let sweep = sweep?;
3187    if !(sweep.length() > 0.0) || heaviest > lightest * BOUNDARY_CARRIER_WEIGHT_RATIO {
3188        return None;
3189    }
3190    let [u0, u1] = surface.domain_u().ok()?;
3191    let [v0, v1] = surface.domain_v().ok()?;
3192    let (slack_u, slack_v) = ((u1 - u0) * 1e-9, (v1 - v0) * 1e-9);
3193    // The carrier's u knot lines: g has a kink across each, so a pcurve span
3194    // is cut where it crosses one.
3195    let mut levels = vec![u0];
3196    levels.extend(crate::curve::interior_knots(&surface.knots_u, surface.degree_u));
3197    levels.push(u1);
3198    // g(u): the carrier's u derivative on the first column crossed with the
3199    // sweep, per unit v.
3200    let density = |u: f64| -> Option<f64> {
3201        let (_, along, _) = surface.deriv1(u, v0).ok()?;
3202        Some(along.cross(sweep).length() / (v1 - v0))
3203    };
3204    // -∫ v g(u) du along one parameter-plane path, at `panels` eight-point
3205    // panels; `path(t)` returns `(u, v, du/dt)` on [a, b].
3206    let path_integral = |path: &dyn Fn(f64) -> Option<(f64, f64, f64)>, a: f64, b: f64, panels: usize| -> Option<f64> {
3207        let mut total = 0.0;
3208        let width = (b - a) / panels as f64;
3209        for panel in 0..panels {
3210            let middle = a + width * (panel as f64 + 0.5);
3211            let half = width * 0.5;
3212            for (x, w) in BOUNDARY_GAUSS_X.iter().zip(&BOUNDARY_GAUSS_W) {
3213                for side in [-1.0, 1.0] {
3214                    let (u, v, du) = path(middle + side * half * x)?;
3215                    if u < u0 - slack_u || u > u1 + slack_u || v < v0 - slack_v || v > v1 + slack_v {
3216                        return None;
3217                    }
3218                    total -= w * half * (v - v0) * density(u.clamp(u0, u1))? * du;
3219                }
3220            }
3221        }
3222        Some(total)
3223    };
3224    let read = |panels: usize| -> Option<f64> {
3225        let mut area = 0.0;
3226        for loop_record in &face.loops {
3227            let count = loop_record.coedges.len();
3228            for (index, coedge) in loop_record.coedges.iter().enumerate() {
3229                let pcurve = &coedge.pcurve;
3230                // A rational pcurve can gather its whole sweep next to one
3231                // end, where no fixed rule finds it: only polynomial trims
3232                // are read.
3233                let weight = pcurve.control_points.first()?.w;
3234                if pcurve.control_points.iter().any(|control| control.w != weight) {
3235                    return None;
3236                }
3237                let [start, end] = pcurve.domain().ok()?;
3238                let mut breaks = vec![start];
3239                breaks.extend(crate::curve::interior_knots(&pcurve.knots, pcurve.degree));
3240                breaks.push(end);
3241                let breaks = crate::mass_properties::split_at_surface_breaks(pcurve, breaks, &levels, u1 - u0, true, false).ok()?;
3242                let along = |t: f64| -> Option<(f64, f64, f64)> {
3243                    let (point, tangent) = pcurve.deriv1(t).ok()?;
3244                    Some((point.x, point.y, tangent.x))
3245                };
3246                for pair in breaks.windows(2) {
3247                    area += path_integral(&along, pair[0], pair[1], panels)?;
3248                }
3249                // The joint to the next coedge, closed by its chord.
3250                let next = &loop_record.coedges[(index + 1) % count].pcurve;
3251                let here = pcurve.evaluate(end).ok()?;
3252                let there = next.evaluate(next.domain().ok()?[0]).ok()?;
3253                if here.x != there.x || here.y != there.y {
3254                    let chord = |t: f64| -> Option<(f64, f64, f64)> {
3255                        Some((here.x + (there.x - here.x) * t, here.y + (there.y - here.y) * t, there.x - here.x))
3256                    };
3257                    let mut cuts = vec![0.0];
3258                    if there.x != here.x {
3259                        let mut crossings: Vec<f64> = levels.iter().map(|level| (level - here.x) / (there.x - here.x)).filter(|t| *t > 0.0 && *t < 1.0).collect();
3260                        crossings.sort_by(f64::total_cmp);
3261                        cuts.extend(crossings);
3262                    }
3263                    cuts.push(1.0);
3264                    for pair in cuts.windows(2) {
3265                        area += path_integral(&chord, pair[0], pair[1], panels)?;
3266                    }
3267                }
3268            }
3269        }
3270        Some(area.abs())
3271    };
3272    let (coarse, fine) = (read(1)?, read(2)?);
3273    ((fine - coarse).abs() <= fine.abs() * BOUNDARY_AREA_SETTLED && fine.is_finite()).then_some(fine)
3274}
3275
3276/// `BREP_MERGE_AREA_BOUNDARY_CLOSED` (default on since 2026-11-19; `=0` leaves
3277/// every closed carrier to the surface integration): [`translational_boundary_area`]
3278/// also reads a face on a carrier closed in u (a full cylinder) when every
3279/// one of its loops closes in the carrier's own chart
3280/// ([`loops_close_in_the_chart`]).
3281fn boundary_area_closed_on() -> bool {
3282    switch!("BREP_MERGE_AREA_BOUNDARY_CLOSED", true)
3283}
3284
3285/// Whether every loop of `face` closes in its carrier's parameter chart:
3286/// each coedge's pcurve ends within a billionth of the chart's width of
3287/// where the next one starts, in both parameters.
3288///
3289/// On a closed carrier that is what lets Green's theorem read the face on
3290/// its boundary as on an open one. A loop that winds around the closed
3291/// direction (a full-turn rim, whose end lies a period from its start) or
3292/// hops the carrier's implicit seam (one pcurve ends on one side of the
3293/// chart, the next starts on the other) has a joint a period wide; the chord
3294/// that closes a joint would cross the whole chart, and the surface
3295/// integral reads such faces on routes of their own (winding bands, caps,
3296/// walls, the unwrapped covering plane). Those are left to it: `Some(false)`.
3297/// A loop of plain joints bounds the region it encloses in the chart, which
3298/// the integral reads on its in-domain path.
3299fn loops_close_in_the_chart(face: &FaceRecord) -> Option<bool> {
3300    let [u0, u1] = face.surface.domain_u().ok()?;
3301    let [v0, v1] = face.surface.domain_v().ok()?;
3302    let (gap_u, gap_v) = ((u1 - u0) * 1e-9, (v1 - v0) * 1e-9);
3303    for loop_record in &face.loops {
3304        let count = loop_record.coedges.len();
3305        if count == 0 {
3306            return Some(false);
3307        }
3308        for (index, coedge) in loop_record.coedges.iter().enumerate() {
3309            let next = &loop_record.coedges[(index + 1) % count].pcurve;
3310            let here = coedge.pcurve.evaluate(coedge.pcurve.domain().ok()?[1]).ok()?;
3311            let there = next.evaluate(next.domain().ok()?[0]).ok()?;
3312            if !((here.x - there.x).abs() <= gap_u && (here.y - there.y).abs() <= gap_v) {
3313                return Some(false);
3314            }
3315        }
3316    }
3317    Some(true)
3318}
3319
3320/// `BREP_MERGE_DECLINE_MEMO` (default on, `0` off): a pair whose content was declined
3321/// before is declined unread. Off under the reading memo's hatch
3322/// (`BREP_READING_MEMO=0`) and the merge's own trace (`BREP_DEBUG_MERGE`).
3323/// The most coedges a pair may hold, both faces together, for the decline
3324/// memo to read its identity.
3325const DECLINE_MEMO_COEDGES: usize = 32;
3326
3327fn decline_memo_on() -> bool {
3328    switch!("BREP_MERGE_DECLINE_MEMO", true)
3329        && crate::reading_memo::memo_on()
3330        && std::env::var_os("BREP_DEBUG_MERGE").is_none()
3331}
3332
3333/// Drop every memoised decline (`reading_memo::clear`).
3334pub fn clear_decline_memo() {
3335    DECLINED_PAIRS.with(|memo| memo.borrow_mut().clear());
3336}
3337
3338/// Declines served from the memo since the thread started.
3339pub fn declines_served() -> usize {
3340    DECLINES_SERVED.with(|served| served.get())
3341}
3342
3343/// One face's content as the pair test reads it, ids apart: the carrier and
3344/// sense, and per loop each coedge's sense, pcurve and edge (curve, domain,
3345/// degenerate flag) in order.
3346fn face_merge_content(face: &FaceRecord, edges: &HashMap<u64, &EdgeRecord>) -> [u64; 2] {
3347    let mut lane = crate::mass_properties::TwoLane::new();
3348    crate::mass_properties::hash_surface(&mut lane, &face.surface);
3349    lane.bool(face.same_sense);
3350    lane.usize(face.loops.len());
3351    for loop_record in &face.loops {
3352        lane.usize(loop_record.coedges.len());
3353        for coedge in &loop_record.coedges {
3354            let edge = edges[&coedge.edge_id];
3355            lane.bool(coedge.forward);
3356            crate::mass_properties::hash_curve(&mut lane, &coedge.pcurve);
3357            crate::mass_properties::hash_curve(&mut lane, &edge.curve);
3358            lane.f64(edge.t0);
3359            lane.f64(edge.t1);
3360            lane.bool(edge.degenerate);
3361        }
3362    }
3363    lane.finish()
3364}
3365
3366/// The identity of one ordered pair for the pair test: the two contents, the
3367/// two tolerances, and every coedge, edge and vertex id of the pair replaced
3368/// by its rank among the pair's ids of that kind (which uses share an edge or
3369/// a vertex, and every order between ids, without the ids themselves, which
3370/// an assembly mints anew).
3371fn pair_identity(
3372    contents: [[u64; 2]; 2],
3373    faces: [&FaceRecord; 2],
3374    edges: &HashMap<u64, &EdgeRecord>,
3375    tolerance: f64,
3376    same_carrier_area_tolerance_ratio: f64,
3377) -> [u64; 2] {
3378    let uses = || faces.into_iter().flat_map(|face| face.loops.iter().flat_map(|loop_record| &loop_record.coedges));
3379    let ranked = |mut ids: Vec<u64>| {
3380        ids.sort_unstable();
3381        ids.dedup();
3382        ids
3383    };
3384    let coedge_ids = ranked(uses().map(|coedge| coedge.id).collect());
3385    let edge_ids = ranked(uses().map(|coedge| coedge.edge_id).collect());
3386    let vertex_ids = ranked(
3387        uses()
3388            .flat_map(|coedge| {
3389                let edge = edges[&coedge.edge_id];
3390                [edge.start_vertex_id, edge.end_vertex_id]
3391            })
3392            .collect(),
3393    );
3394    let rank = |ids: &[u64], id: u64| ids.binary_search(&id).unwrap_or(usize::MAX);
3395    let mut lane = crate::mass_properties::TwoLane::new();
3396    for content in contents {
3397        lane.u64(content[0]);
3398        lane.u64(content[1]);
3399    }
3400    lane.f64(tolerance);
3401    lane.f64(same_carrier_area_tolerance_ratio);
3402    // The two process switches the pair test reads: a decline stored under
3403    // one setting is not the reading under the other.
3404    lane.bool(shared_trim_certificate_enabled());
3405    lane.bool(std::env::var("BREP_FULL_TURN_MERGE").as_deref() == Ok("0"));
3406    lane.bool(boundary_area_check_on());
3407    for coedge in uses() {
3408        let edge = edges[&coedge.edge_id];
3409        lane.usize(rank(&coedge_ids, coedge.id));
3410        lane.usize(rank(&edge_ids, coedge.edge_id));
3411        lane.usize(rank(&vertex_ids, edge.start_vertex_id));
3412        lane.usize(rank(&vertex_ids, edge.end_vertex_id));
3413    }
3414    lane.finish()
3415}
3416
3417struct PairMerger<'a> {
3418    /// Each slot's [`face_merge_content`], read on first use and dropped when
3419    /// a merge rebuilds the slot.
3420    contents: Vec<Option<[u64; 2]>>,
3421    slots: Vec<Option<FaceRecord>>,
3422    pinned: Vec<bool>,
3423    edges: &'a HashMap<u64, &'a EdgeRecord>,
3424    /// Non-degenerate edge id → slots of the faces using it.
3425    uses: HashMap<u64, Vec<usize>>,
3426    /// Edge-adjacent pairs `(lower slot, higher slot)` not yet rejected.
3427    candidates: std::collections::BTreeSet<(usize, usize)>,
3428    /// Ids of the faces this merger built (the surviving id of each pair).
3429    merged_ids: Vec<u64>,
3430}
3431
3432impl<'a> PairMerger<'a> {
3433    fn new(
3434        faces: Vec<FaceRecord>,
3435        edges: &'a HashMap<u64, &'a EdgeRecord>,
3436        keep_unmerged: &[String],
3437    ) -> Self {
3438        let pinned = faces
3439            .iter()
3440            .map(|face| face_is_pinned(face, keep_unmerged))
3441            .collect::<Vec<_>>();
3442        let mut merger = Self {
3443            contents: vec![None; faces.len()],
3444            slots: faces.into_iter().map(Some).collect(),
3445            pinned,
3446            edges,
3447            uses: HashMap::default(),
3448            candidates: std::collections::BTreeSet::new(),
3449            merged_ids: Vec::new(),
3450        };
3451        for slot in 0..merger.slots.len() {
3452            merger.index_slot(slot);
3453        }
3454        merger
3455    }
3456
3457    fn slot_edge_ids(&self, slot: usize) -> Vec<u64> {
3458        let Some(face) = &self.slots[slot] else {
3459            return Vec::new();
3460        };
3461        let mut ids = face
3462            .loops
3463            .iter()
3464            .flat_map(|loop_record| &loop_record.coedges)
3465            .map(|coedge| coedge.edge_id)
3466            .filter(|edge_id| !self.edges[edge_id].degenerate)
3467            .collect::<Vec<_>>();
3468        ids.sort_unstable();
3469        ids.dedup();
3470        ids
3471    }
3472
3473    /// Register `slot`'s edges and queue it against every face already
3474    /// using one of them.
3475    fn index_slot(&mut self, slot: usize) {
3476        for edge_id in self.slot_edge_ids(slot) {
3477            let users = self.uses.entry(edge_id).or_default();
3478            for &other in users.iter() {
3479                if other != slot && !self.pinned[other] && !self.pinned[slot] {
3480                    self.candidates.insert((other.min(slot), other.max(slot)));
3481                }
3482            }
3483            users.push(slot);
3484        }
3485    }
3486
3487    fn unindex_slot(&mut self, slot: usize) {
3488        for edge_id in self.slot_edge_ids(slot) {
3489            if let Some(users) = self.uses.get_mut(&edge_id) {
3490                users.retain(|user| *user != slot);
3491            }
3492        }
3493        self.candidates
3494            .retain(|(lower, higher)| *lower != slot && *higher != slot);
3495    }
3496
3497    /// Perform up to `budget` merges; returns how many were made.
3498    fn run(
3499        &mut self,
3500        budget: usize,
3501        tolerance: f64,
3502        same_carrier_area_tolerance_ratio: f64,
3503    ) -> Result<usize, KernelRefusal> {
3504        let mut merged_count = 0;
3505        while merged_count < budget {
3506            let Some(&(lower, higher)) = self.candidates.iter().next() else {
3507                break;
3508            };
3509            self.candidates.remove(&(lower, higher));
3510            let (Some(older), Some(newer)) = (&self.slots[lower], &self.slots[higher]) else {
3511                continue;
3512            };
3513            // The identity walks every coedge of both faces, so it is read
3514            // only for a small pair: a face with a long boundary (a plate
3515            // around many holes) meets each neighbour in a pair the test
3516            // declines at once, more cheaply than the identity is hashed.
3517            let small = [older, newer].iter().map(|face| face.loops.iter().map(|loop_record| loop_record.coedges.len()).sum::<usize>()).sum::<usize>()
3518                <= DECLINE_MEMO_COEDGES;
3519            let identity = (small && decline_memo_on()).then(|| {
3520                let contents = [(lower, older), (higher, newer)]
3521                    .map(|(slot, face)| *self.contents[slot].get_or_insert_with(|| face_merge_content(face, self.edges)));
3522                pair_identity(contents, [older, newer], self.edges, tolerance, same_carrier_area_tolerance_ratio)
3523            });
3524            if identity.is_some_and(|identity| DECLINED_PAIRS.with(|memo| memo.borrow().contains(&identity))) {
3525                DECLINES_SERVED.with(|served| served.set(served.get() + 1));
3526                crate::reading_memo::note(true);
3527                continue;
3528            }
3529            let Some(merged) = try_merge_pair(
3530                older,
3531                newer,
3532                self.edges,
3533                tolerance,
3534                same_carrier_area_tolerance_ratio,
3535            )?
3536            else {
3537                if let Some(identity) = identity {
3538                    crate::reading_memo::note(false);
3539                    DECLINED_PAIRS.with(|memo| {
3540                        let mut memo = memo.borrow_mut();
3541                        if memo.len() >= crate::reading_memo::capacity() {
3542                            memo.clear();
3543                        }
3544                        memo.insert(identity);
3545                    });
3546                }
3547                continue;
3548            };
3549            self.contents[lower] = None;
3550            self.contents[higher] = None;
3551            self.unindex_slot(higher);
3552            self.unindex_slot(lower);
3553            self.slots[higher] = None;
3554            self.merged_ids.push(merged.id);
3555            self.slots[lower] = Some(merged);
3556            self.index_slot(lower);
3557            merged_count += 1;
3558        }
3559        Ok(merged_count)
3560    }
3561
3562    fn into_faces(self) -> Vec<FaceRecord> {
3563        self.slots.into_iter().flatten().collect()
3564    }
3565}
3566
3567/// Merge adjacent fragments that retain the exact same carrier surface.
3568///
3569/// Every shared edge is cancelled in opposite directions and the remaining
3570/// coedges are stitched into outer/hole cycles without refitting geometry.
3571fn merge_same_surface_faces_impl(
3572    solid: &BrepSolid,
3573    tolerance: f64,
3574    validate: bool,
3575    same_carrier_area_tolerance_ratio: f64,
3576    keep_unmerged: &[String],
3577    validation_scope: Option<&HashSet<u64>>,
3578) -> Result<BrepSolid, KernelRefusal> {
3579    let mut result = solid.clone();
3580    let mut merged_ids: Vec<u64> = Vec::new();
3581    // `result.edges` is not touched until the retain below, so the id map is
3582    // built once; every candidate pair sees the same edge records.
3583    let edges = result
3584        .edges
3585        .iter()
3586        .map(|edge| (edge.id, edge))
3587        .collect::<HashMap<_, _>>();
3588    for shell in &mut result.shells {
3589        loop {
3590            if !validate {
3591                if let Some((indices, merged)) = try_merge_connected_group(
3592                    &shell.faces,
3593                    &edges,
3594                    tolerance,
3595                    same_carrier_area_tolerance_ratio,
3596                    keep_unmerged,
3597                )? {
3598                    let first = indices[0];
3599                    shell.faces[first] = merged;
3600                    for index in indices.into_iter().skip(1).rev() {
3601                        shell.faces.remove(index);
3602                    }
3603                    continue;
3604                }
3605            }
3606            // The validating lane has no group phase, so it drains every pair
3607            // merge in one pass; the open lane merges one pair, then offers
3608            // the changed shell to the group phase again, exactly as before.
3609            let budget = if validate { usize::MAX } else { 1 };
3610            let mut merger = PairMerger::new(
3611                std::mem::take(&mut shell.faces),
3612                &edges,
3613                keep_unmerged,
3614            );
3615            let merged = merger.run(budget, tolerance, same_carrier_area_tolerance_ratio);
3616            merged_ids.extend(merger.merged_ids.iter().copied());
3617            shell.faces = merger.into_faces();
3618            if merged? == 0 || validate {
3619                break;
3620            }
3621        }
3622    }
3623    // The validation reads the geometry of the caller's scope and of every
3624    // face this merge built; a face outside both left this pass as it came.
3625    let validation_scope = validation_scope.map(|scope| {
3626        let mut scope = scope.clone();
3627        scope.extend(merged_ids);
3628        scope
3629    });
3630    finish_merge(solid, result, validate, validation_scope.as_ref())
3631}
3632
3633/// Merge each face in `absorbed` into an edge-adjacent face outside `absorbed`
3634/// that rides the same carrier — the pair [`merge_same_surface_faces`] would
3635/// merge, at the same `tolerance` — and nothing else.
3636///
3637/// The absorbing face keeps its id, its name and its slot in the shell, and
3638/// its carrier is the frame the merged face is built on; a face in `absorbed`
3639/// that shares a carrier with no such neighbour is left as it was. Two faces
3640/// outside `absorbed` are never merged with each other, however cosurface: the
3641/// caller is naming whose material a face is, not normalizing the solid, so a
3642/// coplanar pair the document kept apart stays apart. The result passes the
3643/// validating merge's Euler and `validate()` checks or the call refuses.
3644pub fn absorb_faces_into_carriers(
3645    solid: &BrepSolid,
3646    tolerance: f64,
3647    absorbed: &HashSet<u64>,
3648) -> Result<BrepSolid, KernelRefusal> {
3649    let mut result = solid.clone();
3650    let edges = result
3651        .edges
3652        .iter()
3653        .map(|edge| (edge.id, edge))
3654        .collect::<HashMap<_, _>>();
3655    let edge_ids = |face: &FaceRecord| -> HashSet<u64> {
3656        face.loops
3657            .iter()
3658            .flat_map(|loop_record| &loop_record.coedges)
3659            .map(|coedge| coedge.edge_id)
3660            .filter(|edge_id| !edges[edge_id].degenerate)
3661            .collect()
3662    };
3663    for shell in &mut result.shells {
3664        'merge: loop {
3665            for inner in 0..shell.faces.len() {
3666                if !absorbed.contains(&shell.faces[inner].id) {
3667                    continue;
3668                }
3669                let inner_edges = edge_ids(&shell.faces[inner]);
3670                for outer in 0..shell.faces.len() {
3671                    if outer == inner
3672                        || absorbed.contains(&shell.faces[outer].id)
3673                        || edge_ids(&shell.faces[outer]).is_disjoint(&inner_edges)
3674                    {
3675                        continue;
3676                    }
3677                    let Some(merged) =
3678                        try_merge_pair(&shell.faces[outer], &shell.faces[inner], &edges, tolerance, 1e-7)?
3679                    else {
3680                        continue;
3681                    };
3682                    shell.faces[outer] = merged;
3683                    shell.faces.remove(inner);
3684                    continue 'merge;
3685                }
3686            }
3687            break;
3688        }
3689    }
3690    finish_merge(solid, result, true, None)
3691}
3692
3693/// Rebuild the cone face `id` on one carrier holding all its trims, every trim
3694/// re-read from its 3D edge, with its apex pole stitched back. A blend end grows
3695/// such a face past its old chart. False when it is not a ruled cone patch or the
3696/// rebuilt face does not close.
3697pub fn recarry_cone_apex_face(solid: &mut BrepSolid, id: u64, tolerance: f64) -> Result<bool, KernelRefusal> {
3698    let Some(face) = solid.shells.iter().flat_map(|shell| &shell.faces).find(|face| face.id == id).cloned() else {
3699        return Ok(false);
3700    };
3701    let Some(support) = ruled_cylinder_support(&face, tolerance, true, true)? else {
3702        return Ok(false);
3703    };
3704    let edges = solid.edges.iter().map(|edge| (edge.id, edge)).collect::<HashMap<_, _>>();
3705    let mut apex = None;
3706    let mut loops = face.loops.clone();
3707    for loop_record in &mut loops {
3708        loop_record.coedges.retain(|coedge| {
3709            let pole = edges[&coedge.edge_id].degenerate;
3710            if pole && apex.is_none() {
3711                apex = Some(coedge.clone());
3712            }
3713            !pole
3714        });
3715    }
3716    let seed = {
3717        let Some(point) = loops.iter().flat_map(|l| &l.coedges).find_map(|coedge| {
3718            let edge = edges[&coedge.edge_id];
3719            let [a, b] = [edge.curve.evaluate(edge.t0).ok()?, edge.curve.evaluate(edge.t1).ok()?];
3720            let radial = |p: Vec3| { let d = p.sub(support.origin); d.sub(support.axis.scale(d.dot(support.axis))) };
3721            if radial(a).length() > radial(b).length() { Some(radial(a)) } else { Some(radial(b)) }
3722        }) else {
3723            return Ok(false);
3724        };
3725        point.normalized().or_refuse(KernelStage::Sew, "normalized")?
3726    };
3727    let y_reference = support.axis.cross(seed);
3728    let mut angles = Vec::new();
3729    let mut axial_range = [f64::INFINITY, f64::NEG_INFINITY];
3730    for coedge in loops.iter().flat_map(|l| &l.coedges) {
3731        let edge = edges[&coedge.edge_id];
3732        let curve = trimmed_curve(&edge.curve, edge.t0, edge.t1)?;
3733        let [c0, c1] = curve.domain().or_refuse(KernelStage::Sew, "domain")?;
3734        let hull = axial_hull(&curve, &support);
3735        axial_range[0] = axial_range[0].min(hull[0]);
3736        axial_range[1] = axial_range[1].max(hull[1]);
3737        for index in 0..=32 {
3738            let delta = curve.evaluate(c0 + (c1 - c0) * index as f64 / 32.0).or_refuse(KernelStage::Sew, "evaluate")?.sub(support.origin);
3739            let radial = delta.sub(support.axis.scale(delta.dot(support.axis)));
3740            if radial.length() > (support.radius * 1e-6).max(tolerance) {
3741                angles.push(radial.dot(y_reference).atan2(radial.dot(seed)).rem_euclid(std::f64::consts::TAU));
3742            }
3743        }
3744    }
3745    if angles.len() < 3 {
3746        return Ok(false);
3747    }
3748    angles.sort_by(f64::total_cmp);
3749    let (mut gap_start, mut largest) = (angles.len() - 1, angles[0] + std::f64::consts::TAU - angles[angles.len() - 1]);
3750    for index in 0..angles.len() - 1 {
3751        if angles[index + 1] - angles[index] > largest {
3752            largest = angles[index + 1] - angles[index];
3753            gap_start = index;
3754        }
3755    }
3756    let span = std::f64::consts::TAU - largest;
3757    if span <= tolerance || span >= std::f64::consts::TAU - 1e-6 {
3758        return Ok(false);
3759    }
3760    let start = angles[(gap_start + 1) % angles.len()];
3761    let direction = seed.scale(start.cos()).add(y_reference.scale(start.sin()));
3762    let end_radius = |axial: f64| { let radius = support.radius_at(axial); if radius.abs() <= tolerance { 0.0 } else { radius } };
3763    let at = |axial: f64| support.origin.add(support.axis.scale(axial)).add(direction.scale(end_radius(axial)));
3764    let generatrix = make_line(at(axial_range[0]), at(axial_range[1])).or_refuse(KernelStage::Sew, "healing.face_merge")?;
3765    let surface = make_revolution(support.origin, support.axis, &generatrix, span).or_refuse(KernelStage::Sew, "make_revolution")?;
3766    let (u_domain, v_domain) = surface_domains(&surface)?;
3767    let (mid_u, mid_v) = ((u_domain[0] + u_domain[1]) / 2.0, (v_domain[0] + v_domain[1]) / 2.0);
3768    let delta = surface.evaluate(mid_u, mid_v).or_refuse(KernelStage::Sew, "evaluate")?.sub(support.origin);
3769    let radial = delta.sub(support.axis.scale(delta.dot(support.axis))).normalized().or_refuse(KernelStage::Sew, "normalized")?;
3770    let same_sense = surface.normal(mid_u, mid_v).or_refuse(KernelStage::Sew, "normal")?.dot(radial).signum() == support.outward_radial_sign;
3771    let mut projected = reproject_loops(&surface, loops, &edges)?;
3772    if let Some(apex) = &apex {
3773        if !stitch_cone_apex(&surface, &mut projected, apex, &edges)? {
3774            return Ok(false);
3775        }
3776    }
3777    let rebuilt = FaceRecord { id, surface, same_sense, loops: projected, name: face.name.clone() };
3778    let area = parameter_space_area(&rebuilt).or_refuse(KernelStage::Sew, "parameter_space_area")?;
3779    if area.abs() <= tolerance * tolerance || area.is_sign_positive() != rebuilt.same_sense {
3780        return Ok(false);
3781    }
3782    drop(edges);
3783    for shell in &mut solid.shells {
3784        if let Some(slot) = shell.faces.iter_mut().find(|face| face.id == id) {
3785            *slot = rebuilt;
3786            return Ok(true);
3787        }
3788    }
3789    Ok(false)
3790}
3791
3792/// Merge edge-adjacent faces of `group` that ride the same carrier — the
3793/// pairs [`merge_same_surface_faces`] would merge, at the same `tolerance`,
3794/// plus two lanes only a user's selection opts into: cone patches, and two
3795/// half-turn patches closing a ring on a shared axial edge (see
3796/// `MergeLanes`) — and nothing else: a face outside `group` is never touched,
3797/// however cosurface with a neighbour.
3798///
3799/// Cancelling a shared edge leaves its end vertices between two pieces of one
3800/// rim (the two half circles a split bore's halves each bounded); those
3801/// pieces are joined into one edge where they continue each other exactly
3802/// (`merge_curve_continuation_edges_at`, at those vertices only), so the merged
3803/// face carries the closed rims a face built whole carries.
3804///
3805/// The surviving face of each merged pair is the one in the lower shell slot;
3806/// it keeps its id and name. Returns the merged solid and, for every face id
3807/// of `group` (sorted, deduplicated), the pair `(face, carrier)` naming the
3808/// face that now carries it (itself when it did not merge). The result passes
3809/// the validating merge's Euler and `validate()` checks, scoped to the merged
3810/// faces, or the call refuses.
3811///
3812/// Push Face uses it to treat the halves of a split carrier the user selected
3813/// together (an imported bore written as two half cylinders) as the one face
3814/// the push moves: a half pushed alone can never meet its unmoved sibling.
3815pub fn merge_faces_within(
3816    solid: &BrepSolid,
3817    tolerance: f64,
3818    group: &[u64],
3819) -> Result<(BrepSolid, Vec<(u64, u64)>), KernelRefusal> {
3820    let group: HashSet<u64> = group.iter().copied().collect();
3821    let mut carried_by: Vec<(u64, u64)> = group.iter().map(|id| (*id, *id)).collect();
3822    carried_by.sort_unstable();
3823    let mut result = solid.clone();
3824    let edges = result
3825        .edges
3826        .iter()
3827        .map(|edge| (edge.id, edge))
3828        .collect::<HashMap<_, _>>();
3829    let edge_ids = |face: &FaceRecord| -> HashSet<u64> {
3830        face.loops
3831            .iter()
3832            .flat_map(|loop_record| &loop_record.coedges)
3833            .map(|coedge| coedge.edge_id)
3834            .filter(|edge_id| !edges[edge_id].degenerate)
3835            .collect()
3836    };
3837    let mut merged_ids: HashSet<u64> = HashSet::default();
3838    let mut cancelled_edges: HashSet<u64> = HashSet::default();
3839    // End vertices of the shared edges merged faces kept as their seams.
3840    let mut seam_vertices: HashSet<u64> = HashSet::default();
3841    for shell in &mut result.shells {
3842        'merge: loop {
3843            // Only the group's own slots are read: a 1 200-face import pays
3844            // for its four selected faces, not for every pair of the shell.
3845            let slots: Vec<usize> = (0..shell.faces.len())
3846                .filter(|slot| group.contains(&shell.faces[*slot].id))
3847                .collect();
3848            for (index, &lower) in slots.iter().enumerate() {
3849                let lower_edges = edge_ids(&shell.faces[lower]);
3850                for &higher in &slots[index + 1..] {
3851                    let higher_edges = edge_ids(&shell.faces[higher]);
3852                    if higher_edges.is_disjoint(&lower_edges) {
3853                        continue;
3854                    }
3855                    let lanes = MergeLanes {
3856                        cones: true,
3857                        shared_seam_ring: true,
3858                        seam_vertices: Some(&seam_vertices),
3859                        reseam: false,
3860                    };
3861                    let Some(mut merged) = try_merge_pair_lanes(
3862                        &shell.faces[lower],
3863                        &shell.faces[higher],
3864                        &edges,
3865                        tolerance,
3866                        1e-7,
3867                        lanes,
3868                    )?
3869                    else {
3870                        continue;
3871                    };
3872                    let survivor = shell.faces[lower].id;
3873                    let absorbed = shell.faces[higher].id;
3874                    merged.id = survivor;
3875                    merged.name = shell.faces[lower].name.clone();
3876                    let kept = edge_ids(&merged);
3877                    for edge_id in lower_edges.intersection(&higher_edges) {
3878                        if kept.contains(edge_id) {
3879                            let edge = edges[edge_id];
3880                            seam_vertices.insert(edge.start_vertex_id);
3881                            seam_vertices.insert(edge.end_vertex_id);
3882                        } else {
3883                            cancelled_edges.insert(*edge_id);
3884                        }
3885                    }
3886                    for (_, carrier) in carried_by.iter_mut() {
3887                        if *carrier == absorbed {
3888                            *carrier = survivor;
3889                        }
3890                    }
3891                    merged_ids.insert(survivor);
3892                    shell.faces[lower] = merged;
3893                    shell.faces.remove(higher);
3894                    continue 'merge;
3895                }
3896            }
3897            break;
3898        }
3899    }
3900    if merged_ids.is_empty() {
3901        return Ok((result, carried_by));
3902    }
3903    let joints: HashSet<u64> = cancelled_edges
3904        .iter()
3905        .flat_map(|edge_id| {
3906            let edge = edges[edge_id];
3907            [edge.start_vertex_id, edge.end_vertex_id]
3908        })
3909        .collect();
3910    let result = finish_merge(solid, result, true, Some(&merged_ids))?;
3911    if joints.is_empty() {
3912        return Ok((result, carried_by));
3913    }
3914    let result = crate::coalesce::merge_curve_continuation_edges_at(&result, tolerance, &joints)?;
3915    Ok((result, carried_by))
3916}
3917
3918/// The tail every merge shares: drop the edges and vertices no face uses any
3919/// more and, on the validating lane, recount the genus and validate.
3920fn finish_merge(
3921    solid: &BrepSolid,
3922    mut result: BrepSolid,
3923    validate: bool,
3924    validation_scope: Option<&HashSet<u64>>,
3925) -> Result<BrepSolid, KernelRefusal> {
3926    let used_edges = result
3927        .shells
3928        .iter()
3929        .flat_map(|shell| &shell.faces)
3930        .flat_map(|face| &face.loops)
3931        .flat_map(|loop_record| &loop_record.coedges)
3932        .map(|coedge| coedge.edge_id)
3933        .collect::<HashSet<_>>();
3934    result.edges.retain(|edge| used_edges.contains(&edge.id));
3935    let used_vertices = result
3936        .edges
3937        .iter()
3938        .flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id])
3939        .collect::<HashSet<_>>();
3940    result
3941        .vertices
3942        .retain(|vertex| used_vertices.contains(&vertex.id));
3943    if !validate {
3944        return Ok(result);
3945    }
3946    if std::env::var("BREP_DEBUG_MERGE").is_ok() {
3947        let entry_faces: i64 = solid.shells.iter().map(|s| s.faces.len() as i64).sum();
3948        let entry_holes: i64 = solid
3949            .shells
3950            .iter()
3951            .flat_map(|s| &s.faces)
3952            .map(|f| f.loops.len().saturating_sub(1) as i64)
3953            .sum();
3954        let entry_edges = solid.edges.iter().filter(|e| !e.degenerate).count() as i64;
3955        let entry_used: std::collections::HashSet<u64> = solid
3956            .shells
3957            .iter()
3958            .flat_map(|s| &s.faces)
3959            .flat_map(|f| &f.loops)
3960            .flat_map(|l| &l.coedges)
3961            .map(|c| c.edge_id)
3962            .collect();
3963        eprintln!(
3964            "merge entry census: V={} E={entry_edges} (coedge-referenced {}) F={entry_faces} H={entry_holes} S={} stored_genus={}",
3965            solid.vertices.len(),
3966            entry_used.len(),
3967            solid.shells.len(),
3968            solid.genus
3969        );
3970    }
3971    let face_count = result
3972        .shells
3973        .iter()
3974        .map(|shell| shell.faces.len() as i64)
3975        .sum::<i64>();
3976    let hole_count = result.bounding_hole_count();
3977    let edge_count = result.edges.iter().filter(|edge| !edge.degenerate).count() as i64;
3978    // Count only LIVE vertices (referenced by a non-degenerate edge): the
3979    // merge removes edges and faces, orphaning vertices that then must not
3980    // participate in the Euler census — mirroring refresh_derived_genus
3981    // (boolean.rs). Counting stale vertices inflated V and rejected valid
3982    // merges as "non-integral genus" (the helmet report's final layer).
3983    let live_vertices: std::collections::HashSet<u64> = result
3984        .edges
3985        .iter()
3986        .filter(|edge| !edge.degenerate)
3987        .flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id])
3988        .collect();
3989    let vertex_count = result
3990        .vertices
3991        .iter()
3992        .filter(|vertex| live_vertices.contains(&vertex.id))
3993        .count() as i64;
3994    let euler = vertex_count - edge_count + face_count - hole_count;
3995    let numerator = result.shells.len() as i64 * 2 - euler;
3996    // Mirror validate()'s convention (topology.rs): the reduced V−E+F−H
3997    // formula does not model parameter-space POLE COLLAPSES reliably, so on a
3998    // complex carrying degenerate edges the parity check must not reject —
3999    // the helmet result holds 17 legitimate degenerate (pole) edges and its
4000    // odd numerator here is a formula artifact, not a defect; validate()
4001    // below performs the real integrity checks either way. With no
4002    // degenerate edges the strict behavior is unchanged.
4003    let has_degenerate = result.edges.iter().any(|edge| edge.degenerate);
4004    if numerator < 0 || numerator % 2 != 0 {
4005        if std::env::var("BREP_DEBUG_MERGE").is_ok() {
4006            eprintln!(
4007                "merge euler reject: V={vertex_count} E={edge_count} F={face_count} H={hole_count} S={} euler={euler} numerator={numerator} degenerate={has_degenerate}",
4008                result.shells.len()
4009            );
4010        }
4011        if !has_degenerate
4012            || std::env::var("BREP_MERGE_DEGENERATE_EULER_STRICT").as_deref() == Ok("1")
4013        {
4014            return Err(KernelRefusal::new(
4015                RefusalClass::NonIntegralGenus {
4016                    shells: result.shells.len() as u32,
4017                    euler: euler as i64,
4018                },
4019                KernelStage::Validate,
4020                "merge_same_surface_faces produced non-integral genus",
4021            ));
4022        }
4023    } else {
4024        result.genus = numerator / 2;
4025    }
4026    let issues = match validation_scope {
4027        Some(scope) => result.validate_scoped(scope),
4028        None => result.validate(),
4029    };
4030    if !issues.is_empty() {
4031        return Err(KernelRefusal::new(
4032            RefusalClass::DegenerateArrangement {
4033                open_edges: 0,
4034                issues: issues.len() as u32,
4035            },
4036            KernelStage::Validate,
4037            format!("merge_same_surface_faces produced invalid topology: {issues:?}"),
4038        ));
4039    }
4040    Ok(result)
4041}
4042
4043/// Join every pair of faces the re-seam lane admits ([`MergeLanes::reseam`])
4044/// and nothing else, pair by pair: `(the body, (surviving face id, absorbed
4045/// face id) per join)`, or `None` when no pair joins or the joined body fails
4046/// the merge's closing Euler and `validate()` checks.
4047pub fn rejoin_seam_split_pairs(
4048    solid: &BrepSolid,
4049    tolerance: f64,
4050    keep_unmerged: &[String],
4051) -> Result<Option<(BrepSolid, Vec<(u64, u64)>)>, KernelRefusal> {
4052    let mut result = solid.clone();
4053    let edges = solid.edges.iter().map(|edge| (edge.id, edge)).collect::<HashMap<_, _>>();
4054    let lanes = MergeLanes { reseam: true, ..MergeLanes::default() };
4055    let mut joins = Vec::new();
4056    let edge_ids = |face: &FaceRecord| {
4057        face.loops
4058            .iter()
4059            .flat_map(|loop_record| &loop_record.coedges)
4060            .filter(|coedge| !edges[&coedge.edge_id].degenerate)
4061            .map(|coedge| coedge.edge_id)
4062            .collect::<HashSet<u64>>()
4063    };
4064    for shell in &mut result.shells {
4065        'restart: loop {
4066            for lower in 0..shell.faces.len() {
4067                let lower_edges = edge_ids(&shell.faces[lower]);
4068                for higher in lower + 1..shell.faces.len() {
4069                    let (older, newer) = (&shell.faces[lower], &shell.faces[higher]);
4070                    if older.same_sense != newer.same_sense
4071                        || face_is_pinned(older, keep_unmerged)
4072                        || face_is_pinned(newer, keep_unmerged)
4073                        || edge_ids(newer).is_disjoint(&lower_edges)
4074                        || !same_surface(&older.surface, &newer.surface, tolerance)
4075                    {
4076                        continue;
4077                    }
4078                    if let Some(merged) = try_merge_pair_lanes(older, newer, &edges, tolerance, 1e-7, lanes)? {
4079                        joins.push((older.id, newer.id));
4080                        shell.faces[lower] = merged;
4081                        shell.faces.remove(higher);
4082                        continue 'restart;
4083                    }
4084                }
4085            }
4086            break;
4087        }
4088    }
4089    if joins.is_empty() {
4090        return Ok(None);
4091    }
4092    match finish_merge(solid, result, true, None) {
4093        Ok(result) => Ok(Some((result, joins))),
4094        Err(_) => Ok(None),
4095    }
4096}
4097
4098pub fn merge_same_surface_faces(
4099    solid: &BrepSolid,
4100    tolerance: f64,
4101) -> Result<BrepSolid, KernelRefusal> {
4102    merge_same_surface_faces_impl(solid, tolerance, true, 1e-7, &[], None)
4103}
4104
4105/// [`merge_same_surface_faces_excluding`] whose closing validation reads
4106/// the geometry of the faces in `scope` and of the faces the merge built;
4107/// every pair still merges exactly as the plain call merges it (an operand's
4108/// own coplanar neighbours included: the 2026-10-10 census found a mesh
4109/// import whose five such pairs the boolean fuses). A boolean passes the
4110/// faces its operation touched and their neighbours
4111/// (`BooleanOptions::untouched_passthrough`); the rest were validated by the
4112/// assembler and left this pass as they came.
4113pub fn merge_same_surface_faces_scoped(
4114    solid: &BrepSolid,
4115    tolerance: f64,
4116    keep_unmerged: &[String],
4117    scope: &HashSet<u64>,
4118) -> Result<BrepSolid, KernelRefusal> {
4119    merge_same_surface_faces_impl(solid, tolerance, true, 1e-7, keep_unmerged, Some(scope))
4120}
4121
4122/// Like [`merge_same_surface_faces`], but any face whose `name` CONTAINS one of
4123/// `keep_unmerged` is pinned: it never merges with a coplanar/cosurface
4124/// neighbour and is emitted unchanged, while every other face merges exactly as
4125/// [`merge_same_surface_faces`] would. An empty `keep_unmerged` is identical to
4126/// the plain call.
4127pub fn merge_same_surface_faces_excluding(
4128    solid: &BrepSolid,
4129    tolerance: f64,
4130    keep_unmerged: &[String],
4131) -> Result<BrepSolid, KernelRefusal> {
4132    merge_same_surface_faces_impl(solid, tolerance, true, 1e-7, keep_unmerged, None)
4133}
4134
4135pub fn merge_same_surface_faces_open(
4136    solid: &BrepSolid,
4137    tolerance: f64,
4138) -> Result<BrepSolid, KernelRefusal> {
4139    merge_same_surface_faces_impl(solid, tolerance, false, 5e-3, &[], None)
4140}
4141
4142
4143