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