Skip to main content

brep_construction/construction/sweep_topology/
rib.rs

1use super::*;
2use crate::{classify_point, PointClass, SolidClassifier};
3use serde::{Deserialize, Serialize};
4
5/// Rational ruled surface between two curves with IDENTICAL degree, knots and
6/// weight pattern (the drafted-arc rows share one `make_arc` window, so this
7/// yields the EXACT cone patch: each ruling blends radially-corresponding
8/// points at equal weights).
9pub(super) fn ruled_between(bottom: &NurbsCurve, top: &NurbsCurve) -> Result<NurbsSurface, KernelRefusal> {
10    if bottom.degree != top.degree
11        || bottom.control_points.len() != top.control_points.len()
12        || bottom.knots.len() != top.knots.len()
13    {
14        return Err(KernelRefusal::internal(
15            KernelStage::Fragment,
16            "ruled_rows",
17            "ruled_between: rows are not representation-compatible",
18        ));
19    }
20    let grid = bottom
21        .control_points
22        .iter()
23        .zip(&top.control_points)
24        .map(|(a, b)| vec![*a, *b])
25        .collect();
26    NurbsSurface::new(
27        bottom.degree,
28        1,
29        bottom.knots.clone(),
30        vec![0.0, 0.0, 1.0, 1.0],
31        grid,
32    )
33    .or_refuse(KernelStage::Fragment, "surface_new")
34}
35
36/// Subrange of a wall ROW curve between the projections of two junction
37/// points.  Splitting (instead of rebuilding with `make_arc`) preserves the
38/// row's parameterization exactly, so the edge is the surface's own boundary
39/// restriction and its parameter-line pcurve is pointwise exact.
40pub(super) fn arc_window_subrange(row: &NurbsCurve, start: Vec3, end: Vec3) -> Result<NurbsCurve, KernelRefusal> {
41    let [d0, d1] = row.domain().or_refuse(KernelStage::Fragment, "domain")?;
42    let span = d1 - d0;
43    let u0 = project_point_to_curve(row, start).or_refuse(KernelStage::Fragment, "project_point")?.u;
44    let u1 = project_point_to_curve(row, end).or_refuse(KernelStage::Fragment, "project_point")?.u;
45    if u1 <= u0 + 1e-12 {
46        return Err(KernelRefusal::internal(
47            KernelStage::Fragment,
48            "arc_trim",
49            "draftExtrude: a drafted arc's boundary trim inverted",
50        ));
51    }
52    let epsilon = span * 1e-9;
53    let mut current = row.clone();
54    if u0 > d0 + epsilon {
55        current = current.split(u0).or_refuse(KernelStage::Fragment, "split")?.1;
56    }
57    let domain = current.domain().or_refuse(KernelStage::Fragment, "domain")?;
58    if u1 < domain[1] - epsilon && u1 > domain[0] + epsilon {
59        current = current.split(u1).or_refuse(KernelStage::Fragment, "split")?.0;
60    }
61    Ok(current)
62}
63
64/// Gradient (unnormalized surface normal direction) of a drafted WALL's
65/// implicit surface at a point on it: for a line wall the tilted plane's
66/// normal; for an arc wall the cone's ∇(ρ − r(z)) = ρ̂ + (d·turn/h)·ẑ.  Exact
67/// closed forms — the junction-conic end tangents come from their cross
68/// products.
69fn wall_gradient(
70    seg: &SegGeom,
71    point: Vec3,
72    zh: Vec3,
73    height: f64,
74    signed_d: f64,
75) -> Result<Vec3, KernelRefusal> {
76    match seg {
77        SegGeom::Line { dir, normal, .. } => dir
78            .cross(normal.scale(signed_d).add(zh.scale(height)))
79            .normalized()
80            .or_refuse(KernelStage::Fragment, "normalized"),
81        SegGeom::Arc {
82            center, turn, ..
83        } => {
84            let rel = point.sub(*center);
85            let radial = rel.sub(zh.scale(rel.dot(zh)));
86            let rho = radial.normalized().or_refuse(KernelStage::Fragment, "normalized")?;
87            rho.add(zh.scale(signed_d * turn / height))
88                .normalized()
89                .or_refuse(KernelStage::Fragment, "normalized")
90        }
91    }
92}
93
94/// The EXACT junction edge between two adjacent drafted walls, from bottom
95/// junction `a` to top junction `b` with mid-height witness `m` (all three are
96/// exact offset-primitive intersections).  Straight when `m` is collinear
97/// (plane∧plane miter edges, tangent-junction cone rulings); otherwise the
98/// exact CONIC through `a`/`b` with the walls' analytic gradient-cross end
99/// tangents, its rational-quadratic weight solved from `m` (a conic is
100/// uniquely determined by that data, and every drafted wall∧wall intersection
101/// IS a conic — both squared implicits shrink linearly at the same rate, so
102/// their difference is a plane).
103#[allow(clippy::too_many_arguments)]
104pub(super) fn junction_edge_curve(
105    prev: &SegGeom,
106    next: &SegGeom,
107    a: Vec3,
108    m: Vec3,
109    b: Vec3,
110    zh: Vec3,
111    height: f64,
112    signed_d: f64,
113) -> Result<NurbsCurve, KernelRefusal> {
114    let chord = b.sub(a);
115    let length = chord.length();
116    if length <= 1e-12 {
117        return Err(KernelRefusal::internal(
118            KernelStage::Fragment,
119            "junction_collapsed",
120            "draftExtrude: a junction edge collapsed to a point",
121        ));
122    }
123    let along = m.sub(a).dot(chord) / (length * length);
124    let deviation = m.sub(a).sub(chord.scale(along)).length();
125    if deviation <= length * 1e-9 {
126        return make_line(a, b).or_refuse(KernelStage::Fragment, "make_line");
127    }
128    // 2D frame in the conic's plane (it contains a, b, m by construction).
129    let e1 = chord.scale(1.0 / length);
130    let plane_normal = chord
131        .cross(m.sub(a))
132        .normalized()
133        .or_refuse(KernelStage::Fragment, "normalized")?;
134    let e2 = plane_normal
135        .cross(e1)
136        .normalized()
137        .or_refuse(KernelStage::Fragment, "normalized")?;
138    let orient = |tangent: Vec3| {
139        if tangent.dot(zh) < 0.0 {
140            tangent.scale(-1.0)
141        } else {
142            tangent
143        }
144    };
145    let t0 = orient(wall_gradient(prev, a, zh, height, signed_d)?
146        .cross(wall_gradient(next, a, zh, height, signed_d)?));
147    let t2 = orient(wall_gradient(prev, b, zh, height, signed_d)?
148        .cross(wall_gradient(next, b, zh, height, signed_d)?));
149    let d0 = (t0.dot(e1), t0.dot(e2));
150    let d2 = (t2.dot(e1), t2.dot(e2));
151    let denom = d0.0 * d2.1 - d0.1 * d2.0;
152    let scale0 = d0.0.hypot(d0.1);
153    let scale2 = d2.0.hypot(d2.1);
154    if denom.abs() <= 1e-14 * scale0 * scale2 {
155        return Err(KernelRefusal::internal(
156            KernelStage::Fragment,
157            "conic_apex",
158            "draftExtrude: junction end tangents are parallel — no conic apex",
159        ));
160    }
161    // Apex: a + s·t0 = b + r·t2 solved in 2D (a = origin, b = (length, 0)).
162    let s = length * d2.1 / denom;
163    let apex = (s * d0.0, s * d0.1);
164    if apex.1.abs() <= f64::EPSILON * length {
165        return Err(KernelRefusal::internal(
166            KernelStage::Fragment,
167            "conic_apex_degenerate",
168            "draftExtrude: junction conic apex is degenerate",
169        ));
170    }
171    // Barycentric coordinates of m over (a, apex, b): m = α·a + β·apex + γ·b.
172    let mq = (m.sub(a).dot(e1), m.sub(a).dot(e2));
173    let beta = mq.1 / apex.1;
174    let gamma = (mq.0 - beta * apex.0) / length;
175    let alpha = 1.0 - beta - gamma;
176    if !(alpha > 0.0 && beta > 0.0 && gamma > 0.0) {
177        return Err(KernelRefusal::internal(
178            KernelStage::Fragment,
179            "conic_witness",
180            format!(
181            "draftExtrude: junction conic witness fell outside its control triangle \
182             (α={alpha:.3e} β={beta:.3e} γ={gamma:.3e})"
183            ),
184        ));
185    }
186    let weight = beta / (2.0 * (alpha * gamma).sqrt());
187    let apex_3d = a.add(e1.scale(apex.0)).add(e2.scale(apex.1));
188    NurbsCurve::new(
189        2,
190        vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0],
191        vec![
192            Vec4::from_point(a, 1.0),
193            Vec4::from_point(apex_3d, weight),
194            Vec4::from_point(b, 1.0),
195        ],
196    )
197    .or_refuse(KernelStage::Fragment, "curve_new")
198}
199
200/// In-plane circumcircle of three coplanar points (projected onto `ex`/`ey`,
201/// `np = ex×ey`).  Returns `None` when the three points are collinear.
202fn circumcircle(a: Vec3, b: Vec3, c: Vec3, ex: Vec3, ey: Vec3, np: Vec3) -> Option<(Vec3, f64)> {
203    let [ux, uy] = crate::circumcenter_2d([a.dot(ex), a.dot(ey)], [b.dot(ex), b.dot(ey)], [c.dot(ex), c.dot(ey)])?;
204    let plane_off = a.dot(np);
205    let center = ex.scale(ux).add(ey.scale(uy)).add(np.scale(plane_off));
206    Some((center, a.sub(center).length()))
207}
208
209/// Intersect an offset LINE (through `line_point`, direction `line_dir`) with an
210/// offset CIRCLE (`center`, `radius`), returning the root nearest `near` (the
211/// original junction).  A clear Err when they no longer meet (offset too large).
212fn intersect_offset_line_circle(
213    line_point: Vec3,
214    line_dir: Vec3,
215    center: Vec3,
216    radius: f64,
217    near: Vec3,
218) -> Result<Vec3, KernelRefusal> {
219    let dir = line_dir.normalized().or_refuse(KernelStage::Classify, "normalized")?;
220    let f = line_point.sub(center);
221    let b = f.dot(dir);
222    let c = f.dot(f) - radius * radius;
223    let disc = b * b - c;
224    if disc < -1e-9 {
225        return Err(KernelRefusal::input(
226            KernelStage::Classify,
227            "offset_too_large",
228            "an offset line and arc no longer meet (offset too large)",
229        ));
230    }
231    let root = disc.max(0.0).sqrt();
232    let p1 = line_point.add(dir.scale(-b + root));
233    let p2 = line_point.add(dir.scale(-b - root));
234    Ok(if p1.sub(near).length() <= p2.sub(near).length() {
235        p1
236    } else {
237        p2
238    })
239}
240
241/// Intersect two offset CIRCLES (in the plane whose normal is `plane_normal`),
242/// returning the root nearest `near`.  A clear Err when they are concentric or no
243/// longer meet.
244fn intersect_offset_circles(
245    c1: Vec3,
246    r1: f64,
247    c2: Vec3,
248    r2: f64,
249    plane_normal: Vec3,
250    near: Vec3,
251) -> Result<Vec3, KernelRefusal> {
252    let between = c2.sub(c1);
253    let d = between.length();
254    if d < 1e-9 {
255        return Err(KernelRefusal::internal(
256            KernelStage::Classify,
257            "concentric_arcs",
258            "concentric offset arcs do not meet",
259        ));
260    }
261    let axis = between.scale(1.0 / d);
262    let a = (d * d + r1 * r1 - r2 * r2) / (2.0 * d);
263    let h2 = r1 * r1 - a * a;
264    if h2 < -1e-9 {
265        return Err(KernelRefusal::input(
266            KernelStage::Classify,
267            "offset_arcs_too_large",
268            "offset arcs no longer meet (offset too large)",
269        ));
270    }
271    let h = h2.max(0.0).sqrt();
272    let base = c1.add(axis.scale(a));
273    let perp = plane_normal.cross(axis).normalized().or_refuse(KernelStage::Classify, "normalized")?;
274    let p1 = base.add(perp.scale(h));
275    let p2 = base.sub(perp.scale(h));
276    Ok(if p1.sub(near).length() <= p2.sub(near).length() {
277        p1
278    } else {
279        p2
280    })
281}
282
283/// Geometry class of one profile segment, shared by the draft-extrude builder
284/// and the in-plane offset engine: a straight LINE or a circular ARC in the
285/// plane with normal `plane_normal`.
286#[derive(Clone)]
287pub(super) enum SegGeom {
288    Line {
289        start: Vec3,
290        end: Vec3,
291        /// Unit chord direction.
292        dir: Vec3,
293        /// In-plane offset normal `plane_normal × dir` (inward on a CCW loop).
294        normal: Vec3,
295    },
296    Arc {
297        center: Vec3,
298        radius: f64,
299        /// +1 when the arc bends CCW about the plane normal (a convex arc on a
300        /// CCW loop, which SHRINKS under a positive inward offset), −1 when CW.
301        turn: f64,
302        /// ±plane_normal — the axis the arc sweeps CCW about.
303        arc_normal: Vec3,
304        start: Vec3,
305        end: Vec3,
306    },
307}
308
309impl SegGeom {
310    fn start(&self) -> Vec3 {
311        match self {
312            SegGeom::Line { start, .. } | SegGeom::Arc { start, .. } => *start,
313        }
314    }
315
316    fn end(&self) -> Vec3 {
317        match self {
318            SegGeom::Line { end, .. } | SegGeom::Arc { end, .. } => *end,
319        }
320    }
321
322    /// Naive offset image of a point ON this segment's primitive: lines
323    /// translate along their normal; arc points scale radially onto the
324    /// concentric offset circle (Err when a concave arc collapses).
325    fn offset_point(&self, point: Vec3, signed_d: f64) -> Result<Vec3, KernelRefusal> {
326        match self {
327            SegGeom::Line { normal, .. } => Ok(point.add(normal.scale(signed_d))),
328            SegGeom::Arc {
329                center,
330                radius,
331                turn,
332                ..
333            } => {
334                let r_offset = radius - signed_d * turn;
335                if r_offset <= 1e-6 {
336                    return Err(KernelRefusal::input(
337                        KernelStage::Classify,
338                        "arc_collapse",
339                        "offset: distance is too large — a concave arc collapses",
340                    ));
341                }
342                Ok(center.add(point.sub(*center).scale(r_offset / radius)))
343            }
344        }
345    }
346}
347
348/// Classify every profile segment as a LINE (all interior samples on the
349/// chord) or a circular ARC (circumcircle through start/mid/end confirmed by
350/// on-circle samples), with its turning direction about `plane_normal`.
351/// Anything else is a clear Err — the offset/draft machinery is exact for
352/// lines and circles only.
353pub(super) fn classify_profile_segments(
354    profile: &[NurbsCurve],
355    plane_normal: Vec3,
356) -> Result<Vec<SegGeom>, KernelRefusal> {
357    let tol = 1e-6;
358    if profile.is_empty() {
359        return Err(KernelRefusal::input(
360            KernelStage::Collect,
361            "profile_empty",
362            "offset: profile has no segments",
363        ));
364    }
365    let np = plane_normal.normalized().or_refuse(KernelStage::Classify, "normalized")?;
366    let ex = np.perpendicular().or_refuse(KernelStage::Classify, "perpendicular")?;
367    let ey = np.cross(ex).normalized().or_refuse(KernelStage::Classify, "normalized")?;
368    let mut segs = Vec::with_capacity(profile.len());
369    for curve in profile {
370        let [t0, t1] = curve.domain().or_refuse(KernelStage::Classify, "domain")?;
371        let start = curve.evaluate(t0).or_refuse(KernelStage::Classify, "evaluate")?;
372        let end = curve.evaluate(t1).or_refuse(KernelStage::Classify, "evaluate")?;
373        let chord = end.sub(start);
374        let chord_len = chord.length();
375        if chord_len <= tol {
376            return Err(KernelRefusal::input(
377                KernelStage::Collect,
378                "segment_length",
379                "offset: profile has a degenerate (zero-length) segment",
380            ));
381        }
382        let dir = chord.scale(1.0 / chord_len);
383        // A straight LINE if every interior sample lies on the chord.
384        let mut is_line = true;
385        for k in 1..8 {
386            let point = curve.evaluate(t0 + (t1 - t0) * k as f64 / 8.0).or_refuse(KernelStage::Classify, "evaluate")?;
387            let rel = point.sub(start);
388            let perpendicular = rel.sub(dir.scale(rel.dot(dir))).length();
389            if perpendicular > tol * 10.0 {
390                is_line = false;
391                break;
392            }
393        }
394        if is_line {
395            segs.push(SegGeom::Line {
396                start,
397                end,
398                dir,
399                normal: np.cross(dir).normalized().or_refuse(KernelStage::Classify, "normalized")?,
400            });
401            continue;
402        }
403        // Otherwise it must be a circular ARC: fit a circle through start/mid/end.
404        let mid = curve.evaluate((t0 + t1) * 0.5).or_refuse(KernelStage::Classify, "evaluate")?;
405        let (center, radius) = circumcircle(start, mid, end, ex, ey, np).ok_or_else(|| {
406            KernelRefusal::unsupported(
407                KernelStage::Classify,
408                "segment_kind",
409                "offset: only straight lines and circular arcs are supported",
410            )
411        })?;
412        for k in 0..=8 {
413            let point = curve.evaluate(t0 + (t1 - t0) * k as f64 / 8.0).or_refuse(KernelStage::Classify, "evaluate")?;
414            if (point.sub(center).length() - radius).abs() > tol * 10.0 {
415                return Err(KernelRefusal::unsupported(
416                    KernelStage::Classify,
417                    "segment_kind",
418                    "offset: only straight lines and circular arcs are supported",
419                ));
420            }
421        }
422        // Turning direction about the plane normal (CCW ⇒ +1 ⇒ shrink inward).
423        let bend = np.dot(mid.sub(start).cross(end.sub(mid)));
424        let (arc_normal, turn) = if bend >= 0.0 {
425            (np, 1.0)
426        } else {
427            (np.scale(-1.0), -1.0)
428        };
429        segs.push(SegGeom::Arc {
430            center,
431            radius,
432            turn,
433            arc_normal,
434            start,
435            end,
436        });
437    }
438    Ok(segs)
439}
440
441/// The junction between two consecutive segments' OFFSET primitives at signed
442/// in-plane distance `signed_d`:
443///   • offset 0 → the original shared vertex, exactly;
444///   • a TANGENT (G1) junction degenerates to the shared offset point
445///     (coincident-naive-offsets fast path);
446///   • line∧line → the exact miter V' = V + signed_d/(1+nₐ·n_b)·(nₐ+n_b);
447///   • line∧arc  → the offset line ∩ the offset circle, root nearest V;
448///   • arc∧arc   → the two offset circles ∩, root nearest V.
449/// Offsets that no longer meet (too large for the local feature) are a clear
450/// Err.
451pub(super) fn offset_junction(
452    prev: &SegGeom,
453    next: &SegGeom,
454    plane_normal: Vec3,
455    signed_d: f64,
456) -> Result<Vec3, KernelRefusal> {
457    let vertex = prev.end();
458    if signed_d == 0.0 {
459        return Ok(vertex);
460    }
461    let prev_offset = prev.offset_point(prev.end(), signed_d)?;
462    let next_offset = next.offset_point(next.start(), signed_d)?;
463    if prev_offset.sub(next_offset).length() <= 1e-6 {
464        return Ok(prev_offset.add(next_offset).scale(0.5));
465    }
466    match (prev, next) {
467        (SegGeom::Line { normal: na, .. }, SegGeom::Line { normal: nb, .. }) => {
468            let denom = 1.0 + na.dot(*nb);
469            if denom.abs() < 1e-6 {
470                return Err(KernelRefusal::input(
471                    KernelStage::Classify,
472                    "reversal_corner",
473                    "offset: degenerate (near-reversal) polyline corner",
474                ));
475            }
476            Ok(vertex.add(na.add(*nb).scale(signed_d / denom)))
477        }
478        (
479            SegGeom::Line { dir, .. },
480            SegGeom::Arc {
481                center,
482                radius,
483                turn,
484                ..
485            },
486        ) => intersect_offset_line_circle(
487            prev_offset,
488            *dir,
489            *center,
490            radius - signed_d * turn,
491            vertex,
492        ),
493        (
494            SegGeom::Arc {
495                center,
496                radius,
497                turn,
498                ..
499            },
500            SegGeom::Line { dir, .. },
501        ) => intersect_offset_line_circle(
502            next_offset,
503            *dir,
504            *center,
505            radius - signed_d * turn,
506            vertex,
507        ),
508        (
509            SegGeom::Arc {
510                center: c1,
511                radius: r1,
512                turn: turn1,
513                ..
514            },
515            SegGeom::Arc {
516                center: c2,
517                radius: r2,
518                turn: turn2,
519                ..
520            },
521        ) => intersect_offset_circles(
522            *c1,
523            r1 - signed_d * turn1,
524            *c2,
525            r2 - signed_d * turn2,
526            plane_normal,
527            vertex,
528        ),
529    }
530}
531
532/// Offset a planar profile CHAIN (a sequence of LINE and circular-ARC segments)
533/// IN-PLANE by the SIGNED distance `signed_d` along the per-segment offset normal
534/// n = (plane_normal × tangent).normalized().  Lines move to a parallel line;
535/// circular arcs move to a CONCENTRIC arc (radius r' = r − signed_d·turn — a
536/// convex-outward arc shrinks, a convex-inward arc grows).  Consecutive offset
537/// segments are re-joined at their [`offset_junction`].  `closed` treats the
538/// chain as a loop (every junction re-joined); an OPEN chain leaves its two end
539/// offsets un-joined.  Returns one reconstructed NurbsCurve per input segment
540/// (make_line / make_arc).  A self-intersecting offset (signed_d too large for
541/// a concave corner or arc) surfaces as a clear Err.
542fn offset_profile_segments(
543    profile: &[NurbsCurve],
544    plane_normal: Vec3,
545    signed_d: f64,
546    closed: bool,
547) -> Result<Vec<NurbsCurve>, KernelRefusal> {
548    let np = plane_normal.normalized().or_refuse(KernelStage::Fragment, "normalized")?;
549    let segs = classify_profile_segments(profile, np)?;
550    let n = segs.len();
551
552    // Naive per-segment offsets, then re-join consecutive ones exactly.
553    let mut offsets: Vec<(Vec3, Vec3)> = segs
554        .iter()
555        .map(|seg| {
556            Ok((
557                seg.offset_point(seg.start(), signed_d)?,
558                seg.offset_point(seg.end(), signed_d)?,
559            ))
560        })
561        .collect::<Result<_, KernelRefusal>>()?;
562    let junctions = if closed { n } else { n.saturating_sub(1) };
563    for i in 0..junctions {
564        let j = (i + 1) % n;
565        let point = offset_junction(&segs[i], &segs[j], np, signed_d)?;
566        offsets[i].1 = point;
567        offsets[j].0 = point;
568    }
569
570    // --- Reconstruct each offset segment as a NurbsCurve.
571    let mut out = Vec::with_capacity(n);
572    for (seg, (off_start, off_end)) in segs.iter().zip(&offsets) {
573        out.push(rebuild_offset_segment(seg, *off_start, *off_end)?);
574    }
575    Ok(out)
576}
577
578/// One LINE or ARC segment's offset rebuilt between its re-joined offset ends:
579/// a line between them, or the concentric arc from one to the other.
580fn rebuild_offset_segment(seg: &SegGeom, off_start: Vec3, off_end: Vec3) -> Result<NurbsCurve, KernelRefusal> {
581    let tol = 1e-6;
582    match seg {
583        SegGeom::Line { .. } => make_line(off_start, off_end).or_refuse(KernelStage::Fragment, "make_line"),
584        SegGeom::Arc {
585            center, arc_normal, ..
586        } => {
587            let radial = off_start.sub(*center);
588            let r2 = radial.length();
589            if r2 <= tol {
590                return Err(KernelRefusal::internal(
591                    KernelStage::Fragment,
592                    "arc_radius",
593                    "offset: reconstructed arc has a zero radius",
594                ));
595            }
596            let ax = radial.scale(1.0 / r2);
597            let ay = arc_normal.cross(ax).normalized().or_refuse(KernelStage::Fragment, "normalized")?;
598            let ve = off_end.sub(*center);
599            let mut angle = ve.dot(ay).atan2(ve.dot(ax));
600            if angle <= 1e-9 {
601                angle += std::f64::consts::TAU;
602            }
603            make_arc(*center, ax, ay, r2, 0.0, angle).or_refuse(KernelStage::Fragment, "make_arc")
604        }
605    }
606}
607
608/// One segment of a Normal-to-Sketch rib's chain: a LINE or circular ARC the
609/// exact offset engine handles, or any other planar curve (a sketch spline),
610/// whose offset is fitted.
611enum RibSegment<'a> {
612    Exact(SegGeom),
613    Free(&'a NurbsCurve),
614}
615
616/// How a free segment's fitted offset is cut back or lengthened to meet its
617/// neighbour at one end.
618#[derive(Clone, Copy)]
619enum OffsetEnd {
620    /// The offsets already meet (a tangent joint, or a chain end).
621    Keep,
622    /// The concave side of a corner: the offsets cross, cut back to the crossing
623    /// at this parameter of the fitted offset.
624    Trim(f64),
625    /// The convex side of a corner: the offsets part, extended along the
626    /// curve's end tangent to the mitre point.
627    Extend(Vec3),
628}
629
630/// The in-plane offset of a rib's OPEN chain by `signed_d` (same sign
631/// convention as [`offset_profile_segments`]: along `plane_normal × tangent`).
632///
633/// A chain of lines and circular arcs goes through [`offset_profile_segments`]
634/// unchanged — exact lines and concentric arcs, re-joined at their exact
635/// junctions. A chain holding any other curve (a sketch spline) offsets that
636/// curve by [`offset_free_curve`] and joins it to its neighbours like a mitre:
637///
638/// - a TANGENT joint: both offsets end at one point;
639/// - the CONCAVE side of a corner: the two offsets cross near the vertex and
640///   are both cut back to the crossing;
641/// - the CONVEX side: the offsets part, so each is continued along its end
642///   tangent (a line's own extension, an arc's offset circle) to where they
643///   meet — the straight-line mitre the line/arc engine builds, with the spline
644///   standing in as its end tangent.
645pub fn offset_rib_chain(
646    profile: &[NurbsCurve],
647    plane_normal: Vec3,
648    signed_d: f64,
649) -> Result<Vec<NurbsCurve>, KernelRefusal> {
650    let np = plane_normal.normalized().or_refuse(KernelStage::Fragment, "normalized")?;
651    let mut segments = Vec::with_capacity(profile.len());
652    for curve in profile {
653        segments.push(match classify_profile_segments(std::slice::from_ref(curve), np) {
654            Ok(mut one) if exact_everywhere(&one[0], curve)? => RibSegment::Exact(one.remove(0)),
655            Ok(_) => RibSegment::Free(curve),
656            Err(refusal)
657                if matches!(
658                    &refusal.class,
659                    crate::RefusalClass::UnsupportedGeometry { what } if what == "segment_kind"
660                ) =>
661            {
662                RibSegment::Free(curve)
663            }
664            Err(refusal) => return Err(refusal),
665        });
666    }
667    if segments.iter().all(|segment| matches!(segment, RibSegment::Exact(_))) {
668        return offset_profile_segments(profile, np, signed_d, false);
669    }
670
671    // Every segment's whole offset, not yet joined, and its two ends.
672    let mut offsets = Vec::with_capacity(segments.len());
673    let mut ends = Vec::with_capacity(segments.len());
674    for segment in &segments {
675        let (offset, start, end) = match segment {
676            RibSegment::Exact(seg) => {
677                let start = seg.offset_point(seg.start(), signed_d)?;
678                let end = seg.offset_point(seg.end(), signed_d)?;
679                (rebuild_offset_segment(seg, start, end)?, start, end)
680            }
681            RibSegment::Free(curve) => {
682                let offset = offset_free_curve(curve, np, signed_d)?;
683                let [t0, t1] = offset.domain().or_refuse(KernelStage::Fragment, "domain")?;
684                let start = offset.evaluate(t0).or_refuse(KernelStage::Fragment, "evaluate")?;
685                let end = offset.evaluate(t1).or_refuse(KernelStage::Fragment, "evaluate")?;
686                (offset, start, end)
687            }
688        };
689        offsets.push(offset);
690        ends.push((start, end));
691    }
692
693    let mut fixes = vec![(OffsetEnd::Keep, OffsetEnd::Keep); segments.len()];
694    for index in 0..segments.len().saturating_sub(1) {
695        let (prev, next) = (&segments[index], &segments[index + 1]);
696        let point = if let (RibSegment::Exact(prev), RibSegment::Exact(next)) = (prev, next) {
697            offset_junction(prev, next, np, signed_d)?
698        } else {
699            let vertex = profile[index + 1]
700                .evaluate(profile[index + 1].domain().or_refuse(KernelStage::Fragment, "domain")?[0])
701                .or_refuse(KernelStage::Fragment, "evaluate")?;
702            let prev_tangent = end_tangent(&profile[index], true)?;
703            let next_tangent = end_tangent(&profile[index + 1], false)?;
704            let (point, at_end, at_start) = mitre_join(
705                &tangent_stand_in(prev, np, vertex, prev_tangent, true)?,
706                &tangent_stand_in(next, np, vertex, next_tangent, false)?,
707                (&offsets[index], &offsets[index + 1]),
708                (ends[index].1, ends[index + 1].0),
709                np,
710                signed_d,
711            )?;
712            fixes[index].1 = at_end;
713            fixes[index + 1].0 = at_start;
714            point
715        };
716        ends[index].1 = point;
717        ends[index + 1].0 = point;
718    }
719
720    let mut out = Vec::with_capacity(segments.len());
721    for (index, segment) in segments.iter().enumerate() {
722        let (start, end) = ends[index];
723        out.push(match segment {
724            RibSegment::Exact(seg) => rebuild_offset_segment(seg, start, end)?,
725            RibSegment::Free(_) => {
726                join_free_offset(offsets[index].clone(), fixes[index], start, end)?
727            }
728        });
729    }
730    Ok(out)
731}
732
733/// Where two consecutive offsets meet, and how each is cut back or carried on
734/// to get there. `prev_line` / `next_line` are what each offset continues as
735/// past the vertex ([`tangent_stand_in`]); `offsets` are the two whole offsets
736/// and `ends` the end of the first and the start of the second.
737///
738/// - The offsets already meet (a tangent joint): there.
739/// - The CONCAVE side of a corner (the chain turns toward this offset): they
740///   overlap, so both are cut back to where they cross nearest the corner.
741/// - The CONVEX side: they part, so both are carried on to the mitre point.
742fn mitre_join(
743    prev_line: &SegGeom,
744    next_line: &SegGeom,
745    offsets: (&NurbsCurve, &NurbsCurve),
746    (a, b): (Vec3, Vec3),
747    np: Vec3,
748    signed_d: f64,
749) -> Result<(Vec3, OffsetEnd, OffsetEnd), KernelRefusal> {
750    if a.sub(b).length() <= 1e-6 {
751        return Ok((a.add(b).scale(0.5), OffsetEnd::Keep, OffsetEnd::Keep));
752    }
753    let tangent = |line: &SegGeom, at_end: bool| -> Result<Vec3, KernelRefusal> {
754        match line {
755            SegGeom::Line { dir, .. } => Ok(*dir),
756            SegGeom::Arc { center, arc_normal, start, end, .. } => {
757                let point = if at_end { *end } else { *start };
758                arc_normal.cross(point.sub(*center)).normalized().or_refuse(KernelStage::Fragment, "normalized")
759            }
760        }
761    };
762    let turn = np.dot(tangent(prev_line, true)?.cross(tangent(next_line, false)?));
763    if turn * signed_d > 0.0 {
764        let crossing = crate::intersect_curves(offsets.0, offsets.1, 1e-9)
765            .or_refuse(KernelStage::Fragment, "intersect_curves")?
766            .into_iter()
767            .min_by(|p, q| {
768                let reach = |hit: &crate::CurveCurveIntersection| {
769                    hit.point.sub(a).length() + hit.point.sub(b).length()
770                };
771                reach(p).total_cmp(&reach(q))
772            })
773            .ok_or_else(rib_curve_corner_refusal)?;
774        Ok((crossing.point, OffsetEnd::Trim(crossing.s), OffsetEnd::Trim(crossing.t)))
775    } else {
776        let point = offset_junction(prev_line, next_line, np, signed_d)?;
777        Ok((point, OffsetEnd::Extend(point), OffsetEnd::Extend(point)))
778    }
779}
780
781/// Whether `curve` really is the line or arc `seg` says, checked at every
782/// eighth of every knot span: the classifier samples the whole curve's eighths
783/// only, and a spline with several spans can pass through all of them (a wave
784/// crossing its chord at each) without being straight; nor is a collinear
785/// curve that runs back over itself its chord. A degree-1 curve is a
786/// line by construction.
787fn exact_everywhere(seg: &SegGeom, curve: &NurbsCurve) -> Result<bool, KernelRefusal> {
788    if curve.degree <= 1 {
789        return Ok(true);
790    }
791    let (center, radius) = match seg {
792        SegGeom::Line { start, dir, .. } => {
793            // Exactly, not by samples: a curve lies on its chord and runs forward
794            // along it when its CONTROL POINTS do (it stays in their hull, and a
795            // monotone control polygon gives a monotone curve).
796            let mut previous = f64::NEG_INFINITY;
797            for point in &curve.control_points {
798                let rel = point.point().or_refuse(KernelStage::Classify, "control_point")?.sub(*start);
799                let along = rel.dot(*dir);
800                if rel.sub(dir.scale(along)).length() > 1e-5 || along < previous {
801                    return Ok(false);
802                }
803                previous = along;
804            }
805            return Ok(true);
806        }
807        SegGeom::Arc { center, radius, .. } => (*center, *radius),
808    };
809    let [t0, t1] = curve.domain().or_refuse(KernelStage::Classify, "domain")?;
810    let mut breaks: Vec<f64> = curve.knots.iter().copied().filter(|knot| *knot > t0 && *knot < t1).collect();
811    breaks.insert(0, t0);
812    breaks.push(t1);
813    breaks.dedup();
814    for window in breaks.windows(2) {
815        for k in 1..8 {
816            let point = curve
817                .evaluate(window[0] + (window[1] - window[0]) * k as f64 / 8.0)
818                .or_refuse(KernelStage::Classify, "evaluate")?;
819            if (point.sub(center).length() - radius).abs() > 1e-5 {
820                return Ok(false);
821            }
822        }
823    }
824    // ...and it must SWEEP the arc it will be rebuilt as: the angle it turns
825    // through about the arc's axis, summed over fine steps, equals the rebuilt
826    // arc's sweep from its start to its end. A curve winding past a full turn,
827    // or running round the other way, lies on the circle without being that arc.
828    let SegGeom::Arc { arc_normal, start, end, .. } = seg else {
829        return Ok(true);
830    };
831    let ax = start.sub(center).normalized().or_refuse(KernelStage::Classify, "normalized")?;
832    let ay = arc_normal.cross(ax);
833    let ve = end.sub(center);
834    let mut sweep = ve.dot(ay).atan2(ve.dot(ax));
835    if sweep <= 1e-9 {
836        sweep += std::f64::consts::TAU;
837    }
838    let mut turned = 0.0;
839    let mut previous = start.sub(center);
840    for window in breaks.windows(2) {
841        for k in 1..=32 {
842            let radial = curve
843                .evaluate(window[0] + (window[1] - window[0]) * k as f64 / 32.0)
844                .or_refuse(KernelStage::Classify, "evaluate")?
845                .sub(center);
846            turned += arc_normal.dot(previous.cross(radial)).atan2(previous.dot(radial));
847            previous = radial;
848        }
849    }
850    Ok((turned - sweep).abs() <= 1e-6)
851}
852
853/// A curve's unit tangent at its end (`at_end`) or start.
854fn end_tangent(curve: &NurbsCurve, at_end: bool) -> Result<Vec3, KernelRefusal> {
855    let [t0, t1] = curve.domain().or_refuse(KernelStage::Fragment, "domain")?;
856    let ders = curve
857        .derivatives(if at_end { t1 } else { t0 }, 1)
858        .or_refuse(KernelStage::Fragment, "derivatives")?;
859    ders[1].normalized().or_refuse(KernelStage::Fragment, "normalized")
860}
861
862/// What a segment's offset continues as past `vertex` on the convex side of a
863/// corner: a line or arc is itself (its offset line or circle extends); a free
864/// curve stands in as its end tangent line.
865fn tangent_stand_in(
866    segment: &RibSegment,
867    np: Vec3,
868    vertex: Vec3,
869    tangent: Vec3,
870    ends_at_vertex: bool,
871) -> Result<SegGeom, KernelRefusal> {
872    match segment {
873        RibSegment::Exact(seg) => Ok(seg.clone()),
874        RibSegment::Free(_) => {
875            let (start, end) = if ends_at_vertex {
876                (vertex.sub(tangent), vertex)
877            } else {
878                (vertex, vertex.add(tangent))
879            };
880            Ok(SegGeom::Line {
881                start,
882                end,
883                dir: tangent,
884                normal: np.cross(tangent).normalized().or_refuse(KernelStage::Fragment, "normalized")?,
885            })
886        }
887    }
888}
889
890/// A free segment's fitted offset cut back or extended at each end as its
891/// junctions decided, with its two ends then pinned exactly onto the junction
892/// points its neighbours share.
893fn join_free_offset(
894    offset: NurbsCurve,
895    (at_start, at_end): (OffsetEnd, OffsetEnd),
896    start: Vec3,
897    end: Vec3,
898) -> Result<NurbsCurve, KernelRefusal> {
899    let mut curve = offset;
900    if let OffsetEnd::Trim(parameter) = at_end {
901        curve = trim_at(&curve, parameter, true)?;
902    }
903    if let OffsetEnd::Trim(parameter) = at_start {
904        curve = trim_at(&curve, parameter, false)?;
905    }
906    let last = curve.control_points.len() - 1;
907    if !matches!(at_start, OffsetEnd::Extend(_)) {
908        curve.control_points[0] = Vec4::from_point(start, 1.0);
909    }
910    if !matches!(at_end, OffsetEnd::Extend(_)) {
911        curve.control_points[last] = Vec4::from_point(end, 1.0);
912    }
913    if let OffsetEnd::Extend(point) = at_start {
914        let [t0, _] = curve.domain().or_refuse(KernelStage::Fragment, "domain")?;
915        let from = curve.evaluate(t0).or_refuse(KernelStage::Fragment, "evaluate")?;
916        if point.sub(from).length() > 1e-9 {
917            curve = join_c0(&cubic_line(point, from, t0 - 1.0, t0)?, &curve)?;
918        }
919    }
920    if let OffsetEnd::Extend(point) = at_end {
921        let [_, t1] = curve.domain().or_refuse(KernelStage::Fragment, "domain")?;
922        let from = curve.evaluate(t1).or_refuse(KernelStage::Fragment, "evaluate")?;
923        if point.sub(from).length() > 1e-9 {
924            curve = join_c0(&curve, &cubic_line(from, point, t1, t1 + 1.0)?)?;
925        }
926    }
927    Ok(curve)
928}
929
930/// `curve` cut at `parameter`, keeping the part before it (`keep_before`) or
931/// after it. A crossing on the wrong side of a junction's own segment (the cut
932/// would consume the whole segment) is the corner the rib cannot join.
933fn trim_at(curve: &NurbsCurve, parameter: f64, keep_before: bool) -> Result<NurbsCurve, KernelRefusal> {
934    let [t0, t1] = curve.domain().or_refuse(KernelStage::Fragment, "domain")?;
935    let nudge = (t1 - t0) * 1e-9;
936    if keep_before && parameter >= t1 - nudge || !keep_before && parameter <= t0 + nudge {
937        return Ok(curve.clone());
938    }
939    if !(parameter > t0 + nudge && parameter < t1 - nudge) {
940        return Err(rib_curve_corner_refusal());
941    }
942    let (before, after) = curve.split(parameter).or_refuse(KernelStage::Fragment, "split")?;
943    Ok(if keep_before { before } else { after })
944}
945
946/// The straight segment `from → to` as a clamped cubic over `[t0, t1]`.
947fn cubic_line(from: Vec3, to: Vec3, t0: f64, t1: f64) -> Result<NurbsCurve, KernelRefusal> {
948    let step = to.sub(from).scale(1.0 / 3.0);
949    NurbsCurve::new(
950        3,
951        vec![t0, t0, t0, t0, t1, t1, t1, t1],
952        vec![
953            Vec4::from_point(from, 1.0),
954            Vec4::from_point(from.add(step), 1.0),
955            Vec4::from_point(from.add(step.scale(2.0)), 1.0),
956            Vec4::from_point(to, 1.0),
957        ],
958    )
959    .or_refuse(KernelStage::Fragment, "curve_new")
960}
961
962/// Two clamped non-rational cubics end to start as one curve, C0 at the joint
963/// (the joint knot at multiplicity three). `second` must start where `first`
964/// ends in space; its parameter is shifted to follow on.
965fn join_c0(first: &NurbsCurve, second: &NurbsCurve) -> Result<NurbsCurve, KernelRefusal> {
966    if first.degree != 3 || second.degree != 3 {
967        return Err(KernelRefusal::internal(
968            KernelStage::Fragment,
969            "rib_offset_join",
970            "rib offset pieces are not cubic",
971        ));
972    }
973    // Shift `second` to start where `first` ends: the joined parameter only has
974    // to increase (a piece cut back or carried on no longer abuts in parameter).
975    let shift = first.knots[first.knots.len() - 1] - second.knots[0];
976    let mut knots = first.knots[..first.knots.len() - 1].to_vec();
977    knots.extend(second.knots[4..].iter().map(|knot| knot + shift));
978    let mut points = first.control_points.clone();
979    points.extend_from_slice(&second.control_points[1..]);
980    NurbsCurve::new(3, knots, points).or_refuse(KernelStage::Fragment, "curve_new")
981}
982
983fn rib_curve_corner_refusal() -> KernelRefusal {
984    KernelRefusal::unsupported(
985        KernelStage::Classify,
986        "rib_curve_corner",
987        "RIB_CURVE_CORNER — the walls of a Normal-to-Sketch rib cannot be joined at a corner of a \
988         spline segment: its two offsets neither cross nor meet near the corner (the rib is too \
989         thick for that corner); thin the rib, or build it Parallel to Sketch",
990    )
991}
992
993/// The offset of `curve` at parameter `t` by `signed_d` along
994/// `plane_normal × tangent`, and that offset curve's first derivative.
995///
996/// With `T` the unit tangent and `n = plane_normal × T`, the offset is
997/// `o = p + d·n` and, because `n' = −(p''·n / |p'|)·T` for a planar curve,
998/// `o' = (|p'| − d·p''·n / |p'|)·T`: the offset runs parallel to the curve,
999/// slower on the side it bends toward. Where that speed reaches zero the
1000/// thickness is at least the curve's radius of curvature there and the wall
1001/// would fold over itself — a named refusal, not a cusped face.
1002fn free_offset_at(
1003    curve: &NurbsCurve,
1004    t: f64,
1005    plane_normal: Vec3,
1006    signed_d: f64,
1007) -> Result<(Vec3, Vec3), KernelRefusal> {
1008    let ders = curve.derivatives(t, 2).or_refuse(KernelStage::Fragment, "derivatives")?;
1009    let speed = ders[1].length();
1010    if !(speed > 1e-12) {
1011        return Err(KernelRefusal::input(
1012            KernelStage::Classify,
1013            "rib_curve_tangent",
1014            "a profile spline has a point with no tangent, so its wall has no direction there",
1015        ));
1016    }
1017    let tangent = ders[1].scale(1.0 / speed);
1018    let normal = plane_normal.cross(tangent);
1019    let stretch = speed - signed_d * ders[2].dot(normal) / speed;
1020    if !(stretch > 1e-9 * speed) {
1021        return Err(KernelRefusal::input(
1022            KernelStage::Classify,
1023            "rib_offset_cusp",
1024            "RIB_OFFSET_CUSP — the rib is thicker than a profile spline's tightest bend allows \
1025             (half the thickness reaches its radius of curvature), so a wall would fold over \
1026             itself; thin the rib or ease the bend",
1027        ));
1028    }
1029    Ok((ders[0].add(normal.scale(signed_d)), tangent.scale(stretch)))
1030}
1031
1032/// The offset of a free planar curve, FITTED. The curve is cut at every
1033/// distinct interior knot (a sketch Bézier chain is C0 there, so its offset's
1034/// derivative may jump), and each piece's offset is a clamped cubic
1035/// interpolating the exact offset at stations spread evenly over the piece,
1036/// with the piece's own exact end derivatives, refined (stations doubled)
1037/// until it is within `1e-7` (relative to the curve's size, absolute below
1038/// unit size) of the exact offset at the quarter points between stations. The
1039/// pieces are joined C0 into one curve that keeps the source's parameter.
1040///
1041/// Where the pieces meet at a sharp kink (a broken tangent inside the spline)
1042/// they are mitred as two segments' offsets are ([`mitre_join`]).
1043fn offset_free_curve(
1044    curve: &NurbsCurve,
1045    plane_normal: Vec3,
1046    signed_d: f64,
1047) -> Result<NurbsCurve, KernelRefusal> {
1048    let [t0, t1] = curve.domain().or_refuse(KernelStage::Fragment, "domain")?;
1049    let nudge = (t1 - t0) * 1e-9;
1050    let mut breaks = vec![t0];
1051    for &knot in &curve.knots {
1052        if knot > breaks[breaks.len() - 1] + nudge && knot < t1 - nudge {
1053            breaks.push(knot);
1054        }
1055    }
1056    breaks.push(t1);
1057    let mut size = 0.0f64;
1058    let first = curve.evaluate(t0).or_refuse(KernelStage::Fragment, "evaluate")?;
1059    for point in &curve.control_points {
1060        let point = point.point().or_refuse(KernelStage::Fragment, "control_point")?;
1061        size = size.max(point.sub(first).length());
1062    }
1063    let tolerance = 1e-7 * size.max(1.0);
1064
1065    let mut rest = curve.clone();
1066    let mut sources = Vec::with_capacity(breaks.len() - 1);
1067    for index in 0..breaks.len() - 1 {
1068        if index + 2 < breaks.len() {
1069            let (piece, after) = rest.split(breaks[index + 1]).or_refuse(KernelStage::Fragment, "split")?;
1070            rest = after;
1071            sources.push(piece);
1072        } else {
1073            sources.push(rest.clone());
1074        }
1075    }
1076    let fitted = sources
1077        .iter()
1078        .map(|piece| offset_piece(piece, plane_normal, signed_d, tolerance))
1079        .collect::<Result<Vec<_>, KernelRefusal>>()?;
1080    let ends_of = |curve: &NurbsCurve| -> Result<(Vec3, Vec3), KernelRefusal> {
1081        let [t0, t1] = curve.domain().or_refuse(KernelStage::Fragment, "domain")?;
1082        Ok((
1083            curve.evaluate(t0).or_refuse(KernelStage::Fragment, "evaluate")?,
1084            curve.evaluate(t1).or_refuse(KernelStage::Fragment, "evaluate")?,
1085        ))
1086    };
1087    let mut ends = fitted.iter().map(ends_of).collect::<Result<Vec<_>, KernelRefusal>>()?;
1088    let mut fixes = vec![(OffsetEnd::Keep, OffsetEnd::Keep); fitted.len()];
1089    // A kink inside the spline (a sketch Bézier chain with a broken tangent) is
1090    // mitred exactly like a corner between two segments, each side standing in
1091    // as its end tangent.
1092    for index in 0..fitted.len().saturating_sub(1) {
1093        let vertex = ends_of(&sources[index])?.1;
1094        let prev_tangent = end_tangent(&sources[index], true)?;
1095        let next_tangent = end_tangent(&sources[index + 1], false)?;
1096        let free = |curve| RibSegment::Free(curve);
1097        let (point, at_end, at_start) = mitre_join(
1098            &tangent_stand_in(&free(&sources[index]), plane_normal, vertex, prev_tangent, true)?,
1099            &tangent_stand_in(&free(&sources[index + 1]), plane_normal, vertex, next_tangent, false)?,
1100            (&fitted[index], &fitted[index + 1]),
1101            (ends[index].1, ends[index + 1].0),
1102            plane_normal,
1103            signed_d,
1104        )?;
1105        fixes[index].1 = at_end;
1106        fixes[index + 1].0 = at_start;
1107        ends[index].1 = point;
1108        ends[index + 1].0 = point;
1109    }
1110    let mut joined: Option<NurbsCurve> = None;
1111    for ((piece, fix), (start, end)) in fitted.into_iter().zip(fixes).zip(ends) {
1112        let piece = join_free_offset(piece, fix, start, end)?;
1113        joined = Some(match joined {
1114            None => piece,
1115            Some(previous) => join_c0(&previous, &piece)?,
1116        });
1117    }
1118    joined.ok_or_else(|| {
1119        KernelRefusal::internal(KernelStage::Fragment, "rib_offset_pieces", "a spline with no pieces")
1120    })
1121}
1122
1123/// One knot span's offset fitted to `tolerance` (see [`offset_free_curve`]).
1124fn offset_piece(
1125    piece: &NurbsCurve,
1126    plane_normal: Vec3,
1127    signed_d: f64,
1128    tolerance: f64,
1129) -> Result<NurbsCurve, KernelRefusal> {
1130    let [t0, t1] = piece.domain().or_refuse(KernelStage::Fragment, "domain")?;
1131    // The fold check first, for BOTH walls, densely, and sharpened where the
1132    // offset is slowest: a bend tight enough to fold a wall can sit between
1133    // fitting stations, and it must be refused as itself, not as a fit that
1134    // will not converge (on the outside of the same bend).
1135    let samples = 256;
1136    // A curve that turns back on itself (its tangent reversing, as a collinear
1137    // spline running back over its own line does) has no wall on either side.
1138    // Two samples whose tangents point apart are only a suspect (a smooth
1139    // hairpin can turn that far between samples): a reversal is where the
1140    // curve STOPS, so the speed between them is searched down to its minimum.
1141    let reversal = || {
1142        KernelRefusal::input(
1143            KernelStage::Classify,
1144            "rib_curve_tangent",
1145            "a profile spline turns back on itself, so its walls have no side to stand on",
1146        )
1147    };
1148    let rate_at = |t: f64| -> Result<Vec3, KernelRefusal> {
1149        Ok(piece.derivatives(t, 1).or_refuse(KernelStage::Fragment, "derivatives")?[1])
1150    };
1151    let mut previous: Option<(f64, Vec3)> = None;
1152    for step in 0..=samples {
1153        let t = t0 + (t1 - t0) * step as f64 / samples as f64;
1154        let rate = rate_at(t)?;
1155        if !(rate.length() > 1e-12) {
1156            return Err(reversal());
1157        }
1158        if let Some((before_t, before)) = previous.filter(|(_, before)| before.dot(rate) <= 0.0) {
1159            let (mut low, mut high) = (before_t, t);
1160            for _ in 0..80 {
1161                let third = (high - low) / 3.0;
1162                if rate_at(low + third)?.length() < rate_at(high - third)?.length() {
1163                    high -= third;
1164                } else {
1165                    low += third;
1166                }
1167            }
1168            let slowest = rate_at(0.5 * (low + high))?.length();
1169            if slowest <= 1e-9 * before.length().max(rate.length()) {
1170                return Err(reversal());
1171            }
1172        }
1173        previous = Some((t, rate));
1174    }
1175    for side in [signed_d, -signed_d] {
1176        let speed_at = |t: f64| free_offset_at(piece, t, plane_normal, side).map(|(_, rate)| rate.length());
1177        let mut slowest = (f64::INFINITY, t0);
1178        for step in 0..=samples {
1179            let t = t0 + (t1 - t0) * step as f64 / samples as f64;
1180            let speed = speed_at(t)?;
1181            if speed < slowest.0 {
1182                slowest = (speed, t);
1183            }
1184        }
1185        let width = (t1 - t0) / samples as f64;
1186        let (mut low, mut high) = ((slowest.1 - width).max(t0), (slowest.1 + width).min(t1));
1187        for _ in 0..60 {
1188            let third = (high - low) / 3.0;
1189            if speed_at(low + third)? < speed_at(high - third)? {
1190                high -= third;
1191            } else {
1192                low += third;
1193            }
1194        }
1195        speed_at(0.5 * (low + high))?;
1196    }
1197    let start_tangent = free_offset_at(piece, t0, plane_normal, signed_d)?.1;
1198    let end_tangent = free_offset_at(piece, t1, plane_normal, signed_d)?.1;
1199    let mut stations = 8usize;
1200    loop {
1201        let parameters: Vec<f64> = (0..=stations)
1202            .map(|step| {
1203                if step == stations {
1204                    t1
1205                } else {
1206                    t0 + (t1 - t0) * step as f64 / stations as f64
1207                }
1208            })
1209            .collect();
1210        let points = parameters
1211            .iter()
1212            .map(|&t| free_offset_at(piece, t, plane_normal, signed_d).map(|(point, _)| point))
1213            .collect::<Result<Vec<_>, KernelRefusal>>()?;
1214        let fit = crate::interpolate_curve_with_end_tangents(
1215            &points,
1216            &parameters,
1217            start_tangent,
1218            end_tangent,
1219        )
1220        .or_refuse(KernelStage::Fragment, "offset_fit")?;
1221        let mut worst = 0.0f64;
1222        for window in parameters.windows(2) {
1223            for fraction in [0.25, 0.5, 0.75] {
1224                let t = window[0] + (window[1] - window[0]) * fraction;
1225                let exact = free_offset_at(piece, t, plane_normal, signed_d)?.0;
1226                let fitted = fit.evaluate(t).or_refuse(KernelStage::Fragment, "evaluate")?;
1227                worst = worst.max(fitted.sub(exact).length());
1228            }
1229        }
1230        if worst <= tolerance {
1231            return Ok(fit);
1232        }
1233        if stations >= 256 {
1234            return Err(KernelRefusal::non_convergence(
1235                KernelStage::Fragment,
1236                "rib_offset_fit",
1237                format!(
1238                    "the offset of a profile spline could not be fitted within {tolerance:.1e} \
1239                     (best {worst:.1e})"
1240                ),
1241            ));
1242        }
1243        stations *= 2;
1244    }
1245}
1246
1247/// Which way a rib grows out of its sketch — SolidWorks' **Extrusion Direction**
1248/// control, and the same two choices it offers.
1249///
1250/// The two are not variants of one construction: they SWAP which axis carries the
1251/// thickness and which carries the growth, which is why a rib built in the wrong
1252/// one lies down where it should stand up.
1253#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
1254#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
1255pub enum RibExtrusion {
1256    /// **Parallel to Sketch** (SolidWorks' default, and what everyone means by a
1257    /// rib or a gusset): the material grows PARALLEL to the sketch plane and the
1258    /// thickness is applied NORMAL to it. A line drawn between two walls becomes a
1259    /// thin fin standing ON the sketch plane, growing across it until it lands on
1260    /// the part.
1261    #[default]
1262    ParallelToSketch,
1263    /// **Normal to Sketch**: the material grows NORMAL to the sketch plane and the
1264    /// thickness is applied IN it. The chain is thickened inside its own plane and
1265    /// that ribbon is driven off the plane — walls hanging under a sketch.
1266    NormalToSketch,
1267}
1268
1269/// Rib / stiffener (§6.6) — SolidWorks' Rib, both extrusion directions, with its
1270/// **Up To Next** end condition.
1271///
1272/// The chain is thickened by `thickness` and grown along `extrude_dir` until it
1273/// LANDS ON THE PART. Which axis carries which is [`RibExtrusion`]'s whole
1274/// purpose: `ParallelToSketch` offsets ±thickness/2 along the plane NORMAL and
1275/// sweeps the chain IN the plane; `NormalToSketch` offsets ±thickness/2 INSIDE
1276/// the plane (miter-joined, straight caps across the open ends) and sweeps that
1277/// ribbon along the plane normal.
1278///
1279/// # Up To Next
1280///
1281/// There is no depth. SolidWorks' rib has exactly one end condition — the rib
1282/// develops until it meets the next faces and the feature FAILS if any part of it
1283/// meets nothing — and this reproduces it exactly rather than approximating it:
1284/// the chain is swept a generous `reach` (twice the part's bounding diagonal, so
1285/// it certainly crosses the part), the sweep is CUT BY THE PART
1286/// (`slab − solid`), and the piece that grew out of the sketch is kept. Its
1287/// termination surface is therefore the part's own faces, whatever shape they are.
1288/// A piece still running at `reach` never landed, and that is the documented
1289/// failure — not a silently truncated rib.
1290///
1291/// `plane_normal` is the profile's own plane when the caller knows it (a sketch
1292/// publishes the plane it was drawn on). `None` falls back to deriving the plane
1293/// from the chain's bends, which no single straight segment can supply.
1294///
1295/// # Face names
1296///
1297/// Every face of the result is named, and every name is a pure function of
1298/// `names` and the geometry — never of the order the booleans met the faces in.
1299/// See [`RibNames`] for the table.
1300///
1301/// # Profiles
1302///
1303/// Any open planar chain: lines, circular arcs and free curves (sketch
1304/// splines), meeting tangentially or at corners. A Parallel-to-Sketch rib
1305/// sweeps the chain itself, so every curve is exact. A Normal-to-Sketch rib
1306/// offsets the chain in its plane: lines and arcs exactly, a spline by a
1307/// fitted offset, every corner mitred (see `offset_rib_chain`).
1308pub fn rib_from_profile(
1309    solid: &BrepSolid,
1310    profile: &[NurbsCurve],
1311    thickness: f64,
1312    extrude_dir: Vec3,
1313    plane_normal: Option<Vec3>,
1314    extrusion: RibExtrusion,
1315    names: &RibNames,
1316) -> Result<BrepSolid, KernelRefusal> {
1317    let tolerance = 1e-6;
1318    if profile.is_empty() {
1319        return Err(KernelRefusal::input(
1320            KernelStage::Collect,
1321            "profile_count",
1322            "rib: profile needs at least 1 curve forming an open chain",
1323        ));
1324    }
1325    if names.segments.len() != profile.len() {
1326        return Err(KernelRefusal::input(
1327            KernelStage::Collect,
1328            "segment_names",
1329            format!(
1330                "rib: {} segment names for {} profile curves",
1331                names.segments.len(),
1332                profile.len()
1333            ),
1334        ));
1335    }
1336    if !(thickness > 0.0) {
1337        return Err(KernelRefusal::input(
1338            KernelStage::Collect,
1339            "thickness",
1340            "rib: thickness must be positive",
1341        ));
1342    }
1343
1344    // --- 0. A curve with a sharp corner INSIDE it (a sketch Bézier chain whose
1345    //        tangent breaks at a joint) becomes one segment per side of the
1346    //        corner, so each side gets its own faces and the corner its mitre;
1347    //        a single face creased through the corner is fragile in every
1348    //        boolean after. Pieces after the first are named `{segment}.2`, ….
1349    let geometric = profile.iter().map(geometric_parameter).collect::<Result<Vec<_>, _>>()?;
1350    let (split_profile, split_names) = split_at_kinks(&geometric, names)?;
1351    let (profile, names) = (split_profile.as_slice(), &split_names);
1352
1353    // --- 1. Extract the ordered chain vertices (segment endpoints) and verify the
1354    //        chain is connected end→start.  Segments may be LINES or circular ARCS.
1355    let mut vertices = Vec::with_capacity(profile.len() + 1);
1356    let mut samples = Vec::new();
1357    for (index, curve) in profile.iter().enumerate() {
1358        let [start, end] = curve.domain().or_refuse(KernelStage::Collect, "domain")?;
1359        let v_start = curve.evaluate(start).or_refuse(KernelStage::Collect, "evaluate")?;
1360        let v_end = curve.evaluate(end).or_refuse(KernelStage::Collect, "evaluate")?;
1361        if v_end.sub(v_start).length() <= tolerance {
1362            return Err(KernelRefusal::input(
1363                KernelStage::Collect,
1364                "segment_length",
1365                "rib: profile has a degenerate (zero-length) segment",
1366            ));
1367        }
1368        if index == 0 {
1369            vertices.push(v_start);
1370        } else if v_start.sub(*vertices.last().unwrap()).length() > tolerance {
1371            return Err(KernelRefusal::input(
1372                KernelStage::Collect,
1373                "chain_connected",
1374                format!("rib: profile chain is not connected at curve {index}"),
1375            ));
1376        }
1377        vertices.push(v_end);
1378        // Skip k = 0 after the first segment: it duplicates the previous
1379        // segment's endpoint, which would otherwise inject a zero-length step
1380        // and cancel the corner bend used to derive the plane normal.
1381        let first_k = if index == 0 { 0 } else { 1 };
1382        for k in first_k..=8 {
1383            samples.push(curve.evaluate(start + (end - start) * k as f64 / 8.0).or_refuse(KernelStage::Collect, "evaluate")?);
1384        }
1385    }
1386    let count = vertices.len();
1387    if count < 2 {
1388        return Err(KernelRefusal::input(
1389            KernelStage::Collect,
1390            "vertex_count",
1391            "rib: profile needs at least 2 distinct vertices",
1392        ));
1393    }
1394
1395    // --- 2. A rib thickens an OPEN profile; a closed loop is an ordinary
1396    //        extrude, not a rib.
1397    if vertices[count - 1].sub(vertices[0]).length() <= tolerance {
1398        return Err(KernelRefusal::input(
1399            KernelStage::Collect,
1400            "chain_closed",
1401            "rib: profile chain is closed; rib expects an open chain",
1402        ));
1403    }
1404
1405    // --- 3. The profile plane normal np.  A caller-supplied plane wins: it is the
1406    //        plane the profile was AUTHORED on (a sketch publishes it), so it is
1407    //        both unambiguous in sign and defined for a chain with no bend at all.
1408    //        Otherwise derive it from the sampled chain's bends (robust for arc
1409    //        segments), which a fully collinear chain cannot yield.  Either way
1410    //        the chain must lie in the plane.
1411    let np = match plane_normal {
1412        Some(supplied) => supplied.normalized().map_err(|_| {
1413            KernelRefusal::input(
1414                KernelStage::Collect,
1415                "plane_normal",
1416                "rib: the supplied profile plane normal is degenerate",
1417            )
1418        })?,
1419        None => {
1420            let mut normal = Vec3::default();
1421            for i in 1..samples.len() - 1 {
1422                let a = samples[i].sub(samples[i - 1]);
1423                let b = samples[i + 1].sub(samples[i]);
1424                normal = normal.add(a.cross(b));
1425            }
1426            // A collinear chain lies in every plane through its line: the
1427            // input does not pick one, so the rib refuses rather than choosing.
1428            normal.normalized().map_err(|_| {
1429                KernelRefusal::ill_posed(
1430                    KernelStage::Classify,
1431                    "plane_undetermined",
1432                    "rib: profile is collinear and no profile plane was supplied; cannot determine \
1433                 its plane",
1434                )
1435            })?
1436        }
1437    };
1438    let origin = vertices[0];
1439    if samples
1440        .iter()
1441        .any(|point| point.sub(origin).dot(np).abs() > tolerance * 100.0)
1442    {
1443        return Err(KernelRefusal::input(
1444            KernelStage::Collect,
1445            "profile_planar",
1446            if plane_normal.is_some() {
1447                "rib: profile does not lie in the supplied plane"
1448            } else {
1449                "rib: profile is not planar"
1450            },
1451        ));
1452    }
1453
1454    // --- 4. How far to sweep before the part cuts the rib back: twice the part's
1455    //        bounding diagonal certainly crosses it from anywhere on the chain, so
1456    //        the CUT decides the rib's extent, never this number.
1457    let reach = sweep_reach(solid, &vertices, profile)?;
1458
1459    // --- 5. Build the over-long slab for the requested extrusion direction.  The
1460    //        two arms differ only in which axis carries the thickness.
1461    let mut slab = match extrusion {
1462        RibExtrusion::ParallelToSketch => {
1463            // The growth direction lies IN the plane; anything out of plane is a
1464            // caller error, not something to silently project away.
1465            let along = extrude_dir.sub(np.scale(extrude_dir.dot(np)));
1466            let along = along.normalized().map_err(|_| {
1467                KernelRefusal::input(
1468                    KernelStage::Collect,
1469                    "direction_in_plane",
1470                    "rib: a Parallel-to-Sketch rib grows INSIDE its sketch plane, but the requested \
1471                 direction is perpendicular to it",
1472                )
1473            })?;
1474            parallel_slab(profile, &vertices, np, along, thickness, reach)?
1475        }
1476        RibExtrusion::NormalToSketch => {
1477            let along = extrude_dir.normalized().map_err(|_| {
1478                KernelRefusal::input(
1479                    KernelStage::Collect,
1480                    "direction",
1481                    "rib: extrude direction is degenerate",
1482                )
1483            })?;
1484            normal_slab(profile, np, along, thickness, reach)?
1485        }
1486    };
1487
1488    // --- 6. Up To Next: cut the over-long slab by the part and keep the piece the
1489    //        sketch grew.  That piece is the rib; its far end IS the part's faces.
1490    let along = match extrusion {
1491        RibExtrusion::ParallelToSketch => {
1492            let along = extrude_dir.sub(np.scale(extrude_dir.dot(np)));
1493            along.normalized().or_refuse(KernelStage::Collect, "normalized")?
1494        }
1495        RibExtrusion::NormalToSketch => extrude_dir.normalized().or_refuse(KernelStage::Collect, "normalized")?,
1496    };
1497
1498    // Both operands go through the cut and the fuse carrying SOURCE TOKENS, not
1499    // names: the booleans number split fragments in the order they meet them,
1500    // and a part may already hold a `Floor` and a `Floor_1`, so a propagated name
1501    // cannot say which face a fragment came from. The tokens can, and
1502    // `restamp_rib_faces` turns them into names once the result exists.
1503    let roles = slab_face_names(names, extrusion, profile.len());
1504    let slab_faces: usize = slab.shells.iter().map(|shell| shell.faces.len()).sum();
1505    if slab_faces != roles.len() {
1506        return Err(KernelRefusal::internal(
1507            KernelStage::Fragment,
1508            "slab_faces",
1509            format!(
1510                "rib: the slab builder produced {slab_faces} faces, expected {}",
1511                roles.len()
1512            ),
1513        ));
1514    }
1515    let (part, part_names) = tokenised(solid, TARGET_TOKEN);
1516    for (index, face) in slab.shells.iter_mut().flat_map(|shell| shell.faces.iter_mut()).enumerate() {
1517        face.name = Some(format!("{SOURCE_TOKEN}{RIB_TOKEN}{index}"));
1518    }
1519    let sources = FaceSources {
1520        part: part_names,
1521        rib: roles,
1522    };
1523
1524    let seeds = chain_probe_seeds(profile)?;
1525    // A CURVED profile is not spoken for by one probe per segment: a lobe of an
1526    // arc or spline can run out past the part while its midpoint stays over it.
1527    // There every free piece that holds a piece of the slab's NEAR face (the
1528    // face the sketch lies on) grew from the sketch, and is held to Up To Next.
1529    // A polyline keeps its probes alone, exactly as before.
1530    // Likewise a piece holding a piece of the slab's FAR face is still going at
1531    // the end of the sweep, wherever along the curve it started.
1532    let segments = profile.len();
1533    let slab_ends = match extrusion {
1534        RibExtrusion::ParallelToSketch => SlabEnds {
1535            near: (0..segments).collect(),
1536            far: (segments + 1..2 * segments + 1).collect(),
1537        },
1538        RibExtrusion::NormalToSketch => SlabEnds {
1539            near: vec![2 * segments + 2],
1540            far: vec![2 * segments + 3],
1541        },
1542    };
1543    let curved = profile.iter().any(|curve| curve.degree > 1);
1544    let rib = up_to_next(&part, &slab, &seeds, curved.then_some(&slab_ends), along, reach)
1545        .map_err(|error| error.with_message(|error| sources.detokenise(error)))?;
1546    let Some(rib) = rib else {
1547        // Every bit of the sweep was already material: the rib adds nothing, and
1548        // the part is its own answer.  Not an error — the same document with a
1549        // thicker wall would build exactly this.
1550        return Ok(solid.clone());
1551    };
1552
1553    let mut fused = boolean_operation(
1554        &part,
1555        &rib,
1556        BooleanOperation::Union,
1557        &BooleanOptions::default(),
1558    )
1559    .map_err(|error| {
1560        error.with_message(|error| {
1561            format!(
1562                "rib: union of the rib into the part failed: {}",
1563                sources.detokenise(error)
1564            )
1565        })
1566    })?;
1567    let chord = vertices[count - 1].sub(vertices[0]).normalized().or_refuse(KernelStage::Collect, "normalized")?;
1568    let frame = RibFrame {
1569        origin: vertices[0],
1570        thickness: match extrusion {
1571            RibExtrusion::ParallelToSketch => np,
1572            RibExtrusion::NormalToSketch => np.cross(chord).normalized().or_refuse(KernelStage::Collect, "normalized")?,
1573        },
1574        chord,
1575        growth: along,
1576        quantum: 1e-7 * reach.max(1.0),
1577    };
1578    restamp_rib_faces(&mut fused, &sources, &names.feature, &frame);
1579    crate::face_names::stamp_derived_edge_names(&mut fused);
1580    Ok(fused)
1581}
1582
1583/// A curved profile segment re-parameterized over `[0, L]`, `L` the length of
1584/// its control polygon, so its parameter speed is of the order of its size and
1585/// every threshold on a derivative below is geometric, not a matter of the
1586/// units its knots were written in. The curve itself is unchanged (an affine
1587/// map of the knots), and a straight segment is returned as it came.
1588fn geometric_parameter(curve: &NurbsCurve) -> Result<NurbsCurve, KernelRefusal> {
1589    if curve.degree <= 1 {
1590        return Ok(curve.clone());
1591    }
1592    let mut length = 0.0;
1593    for pair in curve.control_points.windows(2) {
1594        let a = pair[0].point().or_refuse(KernelStage::Collect, "control_point")?;
1595        let b = pair[1].point().or_refuse(KernelStage::Collect, "control_point")?;
1596        length += b.sub(a).length();
1597    }
1598    let [t0, t1] = curve.domain().or_refuse(KernelStage::Collect, "domain")?;
1599    if !(length > 0.0) || !(t1 > t0) || !length.is_finite() {
1600        return Err(KernelRefusal::input(
1601            KernelStage::Collect,
1602            "segment_length",
1603            "rib: profile has a degenerate (zero-length) segment",
1604        ));
1605    }
1606    let scale = length / (t1 - t0);
1607    let knots = curve.knots.iter().map(|knot| (knot - t0) * scale).collect();
1608    NurbsCurve::new(curve.degree, knots, curve.control_points.clone()).or_refuse(KernelStage::Collect, "curve_new")
1609}
1610
1611/// Every profile curve cut at its interior knots where the tangent breaks, and
1612/// the names to match (see step 0 of [`rib_from_profile`]). A polyline, or any
1613/// curve smooth through its knots, comes back as it went in.
1614fn split_at_kinks(profile: &[NurbsCurve], names: &RibNames) -> Result<(Vec<NurbsCurve>, RibNames), KernelRefusal> {
1615    let mut curves = Vec::with_capacity(profile.len());
1616    let mut segments = Vec::with_capacity(profile.len());
1617    for (curve, name) in profile.iter().zip(&names.segments) {
1618        let mut rest = curve.clone();
1619        let mut piece = 1usize;
1620        if curve.degree > 1 {
1621            let [t0, t1] = curve.domain().or_refuse(KernelStage::Collect, "domain")?;
1622            let nudge = (t1 - t0) * 1e-9;
1623            let mut knots: Vec<f64> = curve.knots.iter().copied().filter(|knot| *knot > t0 + nudge && *knot < t1 - nudge).collect();
1624            knots.dedup_by(|a, b| (*a - *b).abs() <= nudge);
1625            for knot in knots {
1626                let (before, after) = rest.split(knot).or_refuse(KernelStage::Collect, "split")?;
1627                let turn = end_tangent(&before, true)?.dot(end_tangent(&after, false)?);
1628                if turn < 1.0 - 1e-12 {
1629                    curves.push(before);
1630                    segments.push(if piece == 1 { name.clone() } else { format!("{name}.{piece}") });
1631                    piece += 1;
1632                    rest = after;
1633                }
1634            }
1635        }
1636        curves.push(rest);
1637        segments.push(if piece == 1 { name.clone() } else { format!("{name}.{piece}") });
1638    }
1639    Ok((curves, RibNames { feature: names.feature.clone(), segments }))
1640}
1641
1642/// Twice the part's bounding diagonal, measured from the chain too so a sketch
1643/// standing off the part still sweeps across it.  The rib's real extent is decided
1644/// by the cut in [`up_to_next`]; this only has to be generous.
1645fn sweep_reach(solid: &BrepSolid, chain: &[Vec3], profile: &[NurbsCurve]) -> Result<f64, KernelRefusal> {
1646    let mut min = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
1647    let mut max = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
1648    let mut extend = |point: Vec3| {
1649        min = Vec3::new(min.x.min(point.x), min.y.min(point.y), min.z.min(point.z));
1650        max = Vec3::new(max.x.max(point.x), max.y.max(point.y), max.z.max(point.z));
1651    };
1652    for vertex in &solid.vertices {
1653        extend(vertex.point);
1654    }
1655    for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
1656        for row in &face.surface.control_points {
1657            for point in row {
1658                extend(point.point().or_refuse(KernelStage::Collect, "control_point")?);
1659            }
1660        }
1661    }
1662    for point in chain {
1663        extend(*point);
1664    }
1665    // A curve bulges past its end points; its control hull bounds it. (A
1666    // straight segment's controls are its ends, so a polyline measures as before.)
1667    for curve in profile.iter().filter(|curve| curve.degree > 1) {
1668        for point in &curve.control_points {
1669            extend(point.point().or_refuse(KernelStage::Collect, "control_point")?);
1670        }
1671    }
1672    let diagonal = max.sub(min).length();
1673    if !(diagonal > 0.0) || !diagonal.is_finite() {
1674        return Err(KernelRefusal::input(
1675            KernelStage::Collect,
1676            "target_extent",
1677            "rib: the target solid has no extent to grow the rib against",
1678        ));
1679    }
1680    Ok(diagonal * 2.0)
1681}
1682
1683/// Points ON the chain, one per segment — where the rib starts, and so where the
1684/// search for its free-space piece begins.
1685///
1686/// It has to be the chain ITSELF, not the average of its vertices: for a bent
1687/// chain that average is off the chain entirely (an L's vertex centroid lands
1688/// exactly on the thickened ribbon's inner corner, a knife-edge the classifier
1689/// can only answer "on"), and a probe that starts on a boundary finds no piece.
1690fn chain_probe_seeds(profile: &[NurbsCurve]) -> Result<Vec<Vec3>, KernelRefusal> {
1691    let mut seeds = Vec::with_capacity(profile.len());
1692    for curve in profile {
1693        let [start, end] = curve.domain().or_refuse(KernelStage::Collect, "domain")?;
1694        seeds.push(curve.evaluate(start + (end - start) * 0.5).or_refuse(KernelStage::Collect, "evaluate")?);
1695    }
1696    if seeds.is_empty() {
1697        return Err(KernelRefusal::input(
1698            KernelStage::Collect,
1699            "profile_empty",
1700            "rib: profile has no points to grow from",
1701        ));
1702    }
1703    Ok(seeds)
1704}
1705
1706/// **Parallel to Sketch**: the chain swept `reach` along the IN-PLANE direction
1707/// `along` gives a closed region inside the sketch plane; that region, offset to
1708/// −thickness/2 and extruded `thickness` along the plane normal, is the fin.
1709///
1710/// The loop must be simple, so a chain that doubles back across its own sweep
1711/// self-intersects here and the extrude refuses — the documented V1 limit.
1712fn parallel_slab(
1713    profile: &[NurbsCurve],
1714    vertices: &[Vec3],
1715    np: Vec3,
1716    along: Vec3,
1717    thickness: f64,
1718    reach: f64,
1719) -> Result<BrepSolid, KernelRefusal> {
1720    let offset = along.scale(reach);
1721    let chain_start = vertices[0];
1722    let chain_end = *vertices.last().expect("chain has vertices");
1723    let mut region: Vec<NurbsCurve> = Vec::with_capacity(profile.len() * 2 + 2);
1724    for curve in profile {
1725        region.push(curve.clone());
1726    }
1727    region.push(make_line(chain_end, chain_end.add(offset)).or_refuse(KernelStage::Fragment, "make_line")?);
1728    for curve in profile.iter().rev() {
1729        region.push(super::extrude::translated_curve(&curve.reversed().or_refuse(KernelStage::Fragment, "reversed")?, offset)?);
1730    }
1731    region.push(make_line(chain_start.add(offset), chain_start).or_refuse(KernelStage::Fragment, "make_line")?);
1732
1733    // Centre the thickness on the sketch plane: start half a thickness under it
1734    // and extrude a full thickness back through.
1735    let base = region
1736        .iter()
1737        .map(|curve| super::extrude::translated_curve(curve, np.scale(-thickness * 0.5)))
1738        .collect::<Result<Vec<_>, KernelRefusal>>()?;
1739    extrude_profile_brep(&base, np, thickness).map_err(|error| {
1740        error.with_message(|error| {
1741            format!("rib: sweeping the profile inside its plane failed: {error}")
1742        })
1743    })
1744}
1745
1746/// **Normal to Sketch**: the chain thickened INSIDE its own plane (miter-offset
1747/// ±thickness/2, straight caps across the two open ends → a closed thin loop),
1748/// extruded `reach` along `along` (the plane normal).
1749fn normal_slab(
1750    profile: &[NurbsCurve],
1751    np: Vec3,
1752    along: Vec3,
1753    thickness: f64,
1754    reach: f64,
1755) -> Result<BrepSolid, KernelRefusal> {
1756    let half = thickness * 0.5;
1757    let left = offset_rib_chain(profile, np, half)
1758        .map_err(|error| error.with_message(|error| format!("rib: {error}")))?;
1759    let right = offset_rib_chain(profile, np, -half)
1760        .map_err(|error| error.with_message(|error| format!("rib: {error}")))?;
1761    let left_first = &left[0];
1762    let left_last = &left[left.len() - 1];
1763    let right_first = &right[0];
1764    let right_last = &right[right.len() - 1];
1765    let left_start = left_first.evaluate(left_first.domain().or_refuse(KernelStage::Fragment, "domain")?[0]).or_refuse(KernelStage::Fragment, "evaluate")?;
1766    let left_end = left_last.evaluate(left_last.domain().or_refuse(KernelStage::Fragment, "domain")?[1]).or_refuse(KernelStage::Fragment, "evaluate")?;
1767    let right_start = right_first.evaluate(right_first.domain().or_refuse(KernelStage::Fragment, "domain")?[0]).or_refuse(KernelStage::Fragment, "evaluate")?;
1768    let right_end = right_last.evaluate(right_last.domain().or_refuse(KernelStage::Fragment, "domain")?[1]).or_refuse(KernelStage::Fragment, "evaluate")?;
1769    let mut thin_loop: Vec<NurbsCurve> = Vec::with_capacity(left.len() + right.len() + 2);
1770    for curve in &left {
1771        thin_loop.push(curve.clone());
1772    }
1773    thin_loop.push(make_line(left_end, right_end).or_refuse(KernelStage::Fragment, "make_line")?);
1774    for curve in right.iter().rev() {
1775        thin_loop.push(curve.reversed().or_refuse(KernelStage::Fragment, "reversed")?);
1776    }
1777    thin_loop.push(make_line(right_start, left_start).or_refuse(KernelStage::Fragment, "make_line")?);
1778    extrude_profile_brep(&thin_loop, along, reach).map_err(|error| {
1779        error.with_message(|error| {
1780            format!("rib: extrude of the thickened profile failed: {error}")
1781        })
1782    })
1783}
1784
1785/// SolidWorks' **Up To Next**, exactly: cut the over-long `slab` by the part and
1786/// keep the piece the sketch grew into.
1787///
1788/// `slab − solid` leaves the sweep's free-space pieces, and the boolean assembler
1789/// already groups a disconnected result into ONE SHELL PER PIECE (it unions faces
1790/// by shared edges), so the pieces are the result's shells. The piece containing
1791/// the sketch is the rib; anything past the part is a different piece and is
1792/// dropped — that, not a bounding box, is what makes the rib stop at the part's
1793/// own faces whatever shape they are.
1794///
1795/// `Ok(None)` means the sweep was entirely inside existing material: there is
1796/// nothing to add. A piece still running at `reach` never landed on anything, and
1797/// that is SolidWorks' documented failure ("if any portion of the solid feature
1798/// generated does not hit a Next face it fails").
1799fn up_to_next(
1800    solid: &BrepSolid,
1801    slab: &BrepSolid,
1802    seeds: &[Vec3],
1803    slab_ends: Option<&SlabEnds>,
1804    along: Vec3,
1805    reach: f64,
1806) -> Result<Option<BrepSolid>, KernelRefusal> {
1807    let free = match boolean_operation(
1808        slab,
1809        solid,
1810        BooleanOperation::Subtract,
1811        &BooleanOptions::default(),
1812    ) {
1813        Ok(free) => free,
1814        // A subtract that refuses because the operands are disjoint means the
1815        // sweep never reached the part at all — the Up To Next failure, reported
1816        // as itself rather than as a boolean's internal complaint.
1817        Err(error) => {
1818            // ESSENTIAL REFUSAL (see the sibling below): the cut refusing because
1819            // the operands are disjoint IS "the rib met nothing". The cut's own
1820            // class rides through under the rib's text.
1821            return Err(error.with_message(|error| {
1822                format!(
1823                "rib: RIB_UP_TO_NEXT_UNBOUNDED — the rib never reaches the part, so it has \
1824                 nothing to stop against (SolidWorks' Up To Next requires every part of a rib \
1825                 to meet a face); check the rib's direction — the cut reported: {error}"
1826                )
1827            }))
1828        }
1829    };
1830    if free.shells.is_empty() {
1831        return Ok(None);
1832    }
1833
1834    // Where the rib actually begins: the first point along the sweep from each
1835    // seed that is NOT already material. The chain can be drawn inside a wall, and
1836    // the rib is then the free space just beyond it.
1837    let classifier = SolidClassifier::new(solid, 1e-6).or_refuse(KernelStage::Select, "classifier")?;
1838    let steps = 64;
1839    let mut probes = Vec::new();
1840    for seed in seeds {
1841        for step in 1..=steps {
1842            let point = seed.add(along.scale(reach * step as f64 / steps as f64 * 0.5));
1843            if classifier.classify(point).or_refuse(KernelStage::Select, "classify")?.class == PointClass::Out {
1844                probes.push(point);
1845                break;
1846            }
1847        }
1848    }
1849    if probes.is_empty() && slab_ends.is_none() {
1850        // Every sample along the sweep sits inside the part: nothing to add.
1851        return Ok(None);
1852    }
1853
1854    let mut kept: Option<BrepSolid> = None;
1855    for shell in &free.shells {
1856        let piece = solid_from_shell(&free, shell);
1857        let grown_here = probes
1858            .iter()
1859            .map(|probe| classify_point(*probe, &piece, 1e-6))
1860            .collect::<Result<Vec<_>, String>>()
1861            .or_refuse(KernelStage::Select, "classify_point")?
1862            .into_iter()
1863            .any(|classification| classification.class == PointClass::In)
1864            || slab_ends.is_some_and(|ends| holds_slab_face(shell, &ends.near));
1865        if !grown_here {
1866            continue;
1867        }
1868        // SolidWorks' cardinal rule for Up To Next: a piece that is still going at
1869        // the end of the sweep never met a face.
1870        let overrun = piece
1871            .vertices
1872            .iter()
1873            .map(|vertex| vertex.point.sub(seeds[0]).dot(along))
1874            .fold(f64::NEG_INFINITY, f64::max);
1875        if overrun >= reach * 0.99 || slab_ends.is_some_and(|ends| holds_slab_face(shell, &ends.far)) {
1876            // ESSENTIAL REFUSAL — do not "open" this one. Unlike a gate that
1877            // refuses data the machinery could already answer, this is the
1878            // feature's DEFINITION: SolidWorks' rib has one end condition, and
1879            // "if any portion of the solid feature generated does not hit a Next
1880            // face it fails" is the rule, not a limitation of ours. Accepting it
1881            // would ship a rib hanging in space with a far end at an arbitrary
1882            // sweep distance, which is exactly the bug this feature was reported
1883            // for. The right repair is always the rib's DIRECTION, never this
1884            // check.
1885            return Err(KernelRefusal::input(
1886                KernelStage::Select,
1887                "up_to_next_unbounded",
1888                "rib: RIB_UP_TO_NEXT_UNBOUNDED — part of the rib never lands on the part, so \
1889                 it has no face to stop against (SolidWorks' Up To Next requires the whole rib \
1890                 to terminate on a face). Turn the rib around with `direction`, or move the \
1891                 profile so its sweep meets the part",
1892            ));
1893        }
1894        kept = Some(match kept {
1895            None => piece,
1896            Some(previous) => boolean_operation(
1897                &previous,
1898                &piece,
1899                BooleanOperation::Union,
1900                &BooleanOptions::default(),
1901            )
1902            .map_err(|error| {
1903                error.with_message(|error| {
1904                    format!("rib: joining the rib's own pieces failed: {error}")
1905                })
1906            })?,
1907        });
1908    }
1909    Ok(kept)
1910}
1911
1912/// The slab faces (indices into its token-named faces) at the sketch and at the
1913/// far end of the sweep.
1914struct SlabEnds {
1915    near: Vec<usize>,
1916    far: Vec<usize>,
1917}
1918
1919/// Whether `shell` holds a fragment of one of the slab's faces `indices`.
1920fn holds_slab_face(shell: &ShellRecord, indices: &[usize]) -> bool {
1921    shell.faces.iter().any(|face| {
1922        face.name
1923            .as_deref()
1924            .and_then(FaceSources::parse)
1925            .is_some_and(|(kind, index)| kind == RIB_TOKEN && indices.contains(&index))
1926    })
1927}
1928
1929/// One shell of `source` as a solid in its own right, carrying only the edges and
1930/// vertices its faces use — how a disconnected boolean result is taken apart into
1931/// the pieces the assembler already separated.
1932fn solid_from_shell(source: &BrepSolid, shell: &ShellRecord) -> BrepSolid {
1933    let edge_ids: std::collections::HashSet<u64> = shell
1934        .faces
1935        .iter()
1936        .flat_map(|face| &face.loops)
1937        .flat_map(|loop_record| &loop_record.coedges)
1938        .map(|coedge| coedge.edge_id)
1939        .collect();
1940    let edges: Vec<EdgeRecord> = source
1941        .edges
1942        .iter()
1943        .filter(|edge| edge_ids.contains(&edge.id))
1944        .cloned()
1945        .collect();
1946    let vertex_ids: std::collections::HashSet<u64> = edges
1947        .iter()
1948        .flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id])
1949        .collect();
1950    BrepSolid {
1951        mass_properties_cache: Default::default(),
1952        cells: Default::default(),
1953        id: source.id,
1954        vertices: source
1955            .vertices
1956            .iter()
1957            .filter(|vertex| vertex_ids.contains(&vertex.id))
1958            .cloned()
1959            .collect(),
1960        edges,
1961        shells: vec![shell.clone()],
1962        genus: 0,
1963        kind: crate::BodyKind::Solid,
1964    }
1965}
1966
1967// ===========================================================================
1968// Face names
1969// ===========================================================================
1970
1971/// What a rib calls its faces: the feature id every name starts with, and the
1972/// source name of each profile curve (`{sketchId}:G{gid}` for a sketch segment),
1973/// index-aligned with the profile.
1974///
1975/// | face | Parallel to Sketch | Normal to Sketch |
1976/// |---|---|---|
1977/// | the rib's two walls | `{id}:A` (−thickness axis), `{id}:B` (+) | `{id}:{segment}_A`, `{id}:{segment}_B` per segment |
1978/// | the rib's top (on the sketch) | `{id}:{segment}_TOP` per segment | `{id}:TOP` |
1979/// | its ends, at the chain's start and end | `{id}:START`, `{id}:END` | `{id}:START`, `{id}:END` |
1980/// | the far end (cut away by Up To Next) | `{id}:{segment}_FAR` | `{id}:FAR` |
1981///
1982/// The thickness axis is the sketch plane's authored normal for a Parallel rib,
1983/// and for a Normal rib the in-plane normal `plane normal × segment direction` —
1984/// the left of the chain seen from the side the normal points to.
1985///
1986/// A face the rib SPLITS is named by `restamp_rib_faces`: one fragment keeps
1987/// the name and the others are named after the rib and the side they are on.
1988#[derive(Clone, Debug, PartialEq, Eq)]
1989pub struct RibNames {
1990    pub feature: String,
1991    pub segments: Vec<String>,
1992}
1993
1994impl RibNames {
1995    /// Names for a caller with no segment identity to offer: `SEG{i}`.
1996    pub fn positional(feature: &str, count: usize) -> Self {
1997        Self {
1998            feature: feature.to_string(),
1999            segments: (0..count).map(|index| format!("SEG{index}")).collect(),
2000        }
2001    }
2002}
2003
2004/// The slab's face names in `extrude_profile_brep`'s face order: the region's
2005/// sides in input order, then the base cap, then the far cap.
2006///
2007/// Parallel region: `[segments…, end line, far segments reversed…, start line]`,
2008/// base cap at −thickness/2 along the normal. Normal region: `[+offset
2009/// segments…, end cap, −offset segments reversed…, start cap]`, base cap on the
2010/// sketch plane.
2011fn slab_face_names(names: &RibNames, extrusion: RibExtrusion, count: usize) -> Vec<String> {
2012    let id = &names.feature;
2013    let segment = |index: usize, role: &str| format!("{id}:{}_{role}", names.segments[index]);
2014    let mut faces = Vec::with_capacity(2 * count + 4);
2015    let (near, far, base, top) = match extrusion {
2016        RibExtrusion::ParallelToSketch => ("TOP", "FAR", format!("{id}:A"), format!("{id}:B")),
2017        RibExtrusion::NormalToSketch => ("B", "A", format!("{id}:TOP"), format!("{id}:FAR")),
2018    };
2019    faces.extend((0..count).map(|index| segment(index, near)));
2020    faces.push(format!("{id}:END"));
2021    faces.extend((0..count).rev().map(|index| segment(index, far)));
2022    faces.push(format!("{id}:START"));
2023    faces.push(base);
2024    faces.push(top);
2025    faces
2026}
2027
2028/// Leads every source token, so no authored or derived name can spell one.
2029const SOURCE_TOKEN: char = '\u{1}';
2030const TARGET_TOKEN: char = 'T';
2031const RIB_TOKEN: char = 'R';
2032
2033/// A copy of `solid` whose faces carry `{SOURCE_TOKEN}{kind}{index}` instead of
2034/// their names, plus the names, index-aligned.
2035fn tokenised(solid: &BrepSolid, kind: char) -> (BrepSolid, Vec<Option<String>>) {
2036    let mut copy = solid.clone();
2037    let mut names = Vec::new();
2038    for face in copy.shells.iter_mut().flat_map(|shell| shell.faces.iter_mut()) {
2039        names.push(face.name.take());
2040        face.name = Some(format!("{SOURCE_TOKEN}{kind}{}", names.len() - 1));
2041    }
2042    (copy, names)
2043}
2044
2045/// Where each token points: the part's own face names and the slab's roles.
2046struct FaceSources {
2047    part: Vec<Option<String>>,
2048    rib: Vec<String>,
2049}
2050
2051impl FaceSources {
2052    /// `(kind, index)` of a token-named face. The booleans append `_n` to the
2053    /// later fragments of a split face; the digits after the kind end the index.
2054    fn parse(name: &str) -> Option<(char, usize)> {
2055        let mut chars = name.strip_prefix(SOURCE_TOKEN)?.chars();
2056        let kind = chars.next()?;
2057        let digits: String = chars.take_while(|c| c.is_ascii_digit()).collect();
2058        Some((kind, digits.parse().ok()?))
2059    }
2060
2061    fn name(&self, kind: char, index: usize) -> Option<&str> {
2062        match kind {
2063            TARGET_TOKEN => self.part.get(index)?.as_deref(),
2064            RIB_TOKEN => self.rib.get(index).map(String::as_str),
2065            _ => None,
2066        }
2067    }
2068
2069    /// A boolean's refusal text with every token put back as the name it stands for.
2070    fn detokenise(&self, text: &str) -> String {
2071        let mut out = String::with_capacity(text.len());
2072        let mut chars = text.chars().peekable();
2073        while let Some(c) = chars.next() {
2074            if c != SOURCE_TOKEN {
2075                out.push(c);
2076                continue;
2077            }
2078            let kind = chars.next();
2079            let mut digits = String::new();
2080            while let Some(digit) = chars.peek().copied().filter(char::is_ascii_digit) {
2081                digits.push(digit);
2082                chars.next();
2083            }
2084            match (kind, digits.parse::<usize>()) {
2085                (Some(kind), Ok(index)) => out.push_str(self.name(kind, index).unwrap_or("<unnamed>")),
2086                _ => {
2087                    out.extend(kind);
2088                    out.push_str(&digits);
2089                }
2090            }
2091        }
2092        out
2093    }
2094}
2095
2096/// The rib's own frame, which orders the fragments of a split face: the
2097/// thickness axis first (which SIDE of the rib a fragment is on), then along
2098/// the chord from the chain's start, then along the growth direction.
2099struct RibFrame {
2100    origin: Vec3,
2101    thickness: Vec3,
2102    chord: Vec3,
2103    growth: Vec3,
2104    /// Coordinates closer than this are equal (a fragment's position is
2105    /// recomputed by every rebuild; its last bits are not its identity).
2106    quantum: f64,
2107}
2108
2109/// Replace every source token on `fused` with the face's final name.
2110///
2111/// A source face that reaches the result as ONE face keeps its name. A face
2112/// that arrives in several fragments keeps its name on ONE of them and names
2113/// the rest after the rib, by position in the rib's own frame rather than by
2114/// the order the boolean met them or by their sizes (both change with edits
2115/// that have nothing to do with the rib — moving a hole from one half of a
2116/// floor to the other swaps which half is larger):
2117///
2118/// - a PART face split by the rib: its fragments are sorted by side (the rib's
2119///   A side, straddling, then its B side), then along the chord, then along the
2120///   growth direction. The first keeps the part's name; every other is
2121///   `{id}:{name}_{side}{k}`, `k` counting that side's fragments from 1 in the
2122///   same order — so a floor a rib crosses stays `Floor` on the A side and
2123///   becomes `{id}:Floor_B1` on the B side.
2124/// - one of the rib's OWN faces in several pieces (the part interrupts the rib):
2125///   along the chord, then the growth direction; the first keeps the name and
2126///   the others are `{name}_2`, `{name}_3`, …
2127///
2128/// A part face that had no name keeps none.
2129fn restamp_rib_faces(fused: &mut BrepSolid, sources: &FaceSources, feature: &str, frame: &RibFrame) {
2130    use std::collections::{BTreeMap, HashMap};
2131    let points: HashMap<u64, Vec3> = fused.vertices.iter().map(|vertex| (vertex.id, vertex.point)).collect();
2132    let ends: HashMap<u64, (u64, u64)> = fused
2133        .edges
2134        .iter()
2135        .map(|edge| (edge.id, (edge.start_vertex_id, edge.end_vertex_id)))
2136        .collect();
2137    let quantise = |value: f64| (value / frame.quantum).round() as i64;
2138    // (shell, face) positions per source, each with its sort key.
2139    let mut groups: BTreeMap<(char, usize), Vec<((i64, i64, i64), (usize, usize))>> = BTreeMap::new();
2140    for (shell_index, shell) in fused.shells.iter().enumerate() {
2141        for (face_index, face) in shell.faces.iter().enumerate() {
2142            let Some(source) = face.name.as_deref().and_then(FaceSources::parse) else {
2143                continue;
2144            };
2145            let mut ids: Vec<u64> = face
2146                .loops
2147                .iter()
2148                .flat_map(|loop_record| &loop_record.coedges)
2149                .filter_map(|coedge| ends.get(&coedge.edge_id))
2150                .flat_map(|(start, end)| [*start, *end])
2151                .collect();
2152            ids.sort_unstable();
2153            ids.dedup();
2154            let mut centre = Vec3::default();
2155            for id in &ids {
2156                if let Some(point) = points.get(id) {
2157                    centre = centre.add(*point);
2158                }
2159            }
2160            let centre = centre.scale(1.0 / ids.len().max(1) as f64).sub(frame.origin);
2161            let key = (
2162                quantise(centre.dot(frame.thickness)),
2163                quantise(centre.dot(frame.chord)),
2164                quantise(centre.dot(frame.growth)),
2165            );
2166            groups.entry(source).or_default().push((key, (shell_index, face_index)));
2167        }
2168    }
2169    for ((kind, index), mut fragments) in groups {
2170        let original = sources.name(kind, index).map(str::to_string);
2171        let side = |key: &(i64, i64, i64)| match key.0.signum() {
2172            -1 => ('A', 0),
2173            0 => ('M', 1),
2174            _ => ('B', 2),
2175        };
2176        let named: Vec<((usize, usize), Option<String>)> = match &original {
2177            None => fragments.into_iter().map(|(_, at)| (at, None)).collect(),
2178            Some(name) if fragments.len() == 1 => vec![(fragments[0].1, Some(name.clone()))],
2179            Some(name) if kind == RIB_TOKEN => {
2180                fragments.sort_by_key(|(key, _)| (key.1, key.2, key.0));
2181                fragments
2182                    .into_iter()
2183                    .enumerate()
2184                    .map(|(rank, (_, at))| {
2185                        (at, Some(if rank == 0 { name.clone() } else { format!("{name}_{}", rank + 1) }))
2186                    })
2187                    .collect()
2188            }
2189            Some(name) => {
2190                fragments.sort_by_key(|(key, _)| (side(key).1, key.1, key.2, key.0));
2191                let mut per_side: BTreeMap<char, usize> = BTreeMap::new();
2192                fragments
2193                    .into_iter()
2194                    .enumerate()
2195                    .map(|(rank, (key, at))| {
2196                        let letter = side(&key).0;
2197                        let ordinal = per_side.entry(letter).or_insert(0);
2198                        *ordinal += 1;
2199                        let spelled = if rank == 0 {
2200                            name.clone()
2201                        } else {
2202                            format!("{feature}:{name}_{letter}{ordinal}")
2203                        };
2204                        (at, Some(spelled))
2205                    })
2206                    .collect()
2207            }
2208        };
2209        for ((shell_index, face_index), name) in named {
2210            fused.shells[shell_index].faces[face_index].name = name;
2211        }
2212    }
2213}