Skip to main content

brep_kernel/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, String> {
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("ruled_between: rows are not representation-compatible".into());
15    }
16    let grid = bottom
17        .control_points
18        .iter()
19        .zip(&top.control_points)
20        .map(|(a, b)| vec![*a, *b])
21        .collect();
22    NurbsSurface::new(
23        bottom.degree,
24        1,
25        bottom.knots.clone(),
26        vec![0.0, 0.0, 1.0, 1.0],
27        grid,
28    )
29}
30
31/// Subrange of a wall ROW curve between the projections of two junction
32/// points.  Splitting (instead of rebuilding with `make_arc`) preserves the
33/// row's parameterization exactly, so the edge is the surface's own boundary
34/// restriction and its parameter-line pcurve is pointwise exact.
35pub(super) fn arc_window_subrange(row: &NurbsCurve, start: Vec3, end: Vec3) -> Result<NurbsCurve, String> {
36    let [d0, d1] = row.domain()?;
37    let span = d1 - d0;
38    let u0 = project_point_to_curve(row, start)?.u;
39    let u1 = project_point_to_curve(row, end)?.u;
40    if u1 <= u0 + 1e-12 {
41        return Err("draftExtrude: a drafted arc's boundary trim inverted".into());
42    }
43    let epsilon = span * 1e-9;
44    let mut current = row.clone();
45    if u0 > d0 + epsilon {
46        current = current.split(u0)?.1;
47    }
48    let domain = current.domain()?;
49    if u1 < domain[1] - epsilon && u1 > domain[0] + epsilon {
50        current = current.split(u1)?.0;
51    }
52    Ok(current)
53}
54
55/// Gradient (unnormalized surface normal direction) of a drafted WALL's
56/// implicit surface at a point on it: for a line wall the tilted plane's
57/// normal; for an arc wall the cone's ∇(ρ − r(z)) = ρ̂ + (d·turn/h)·ẑ.  Exact
58/// closed forms — the junction-conic end tangents come from their cross
59/// products.
60fn wall_gradient(
61    seg: &SegGeom,
62    point: Vec3,
63    zh: Vec3,
64    height: f64,
65    signed_d: f64,
66) -> Result<Vec3, String> {
67    match seg {
68        SegGeom::Line { dir, normal, .. } => dir
69            .cross(normal.scale(signed_d).add(zh.scale(height)))
70            .normalized(),
71        SegGeom::Arc {
72            center, turn, ..
73        } => {
74            let rel = point.sub(*center);
75            let radial = rel.sub(zh.scale(rel.dot(zh)));
76            let rho = radial.normalized()?;
77            rho.add(zh.scale(signed_d * turn / height)).normalized()
78        }
79    }
80}
81
82/// The EXACT junction edge between two adjacent drafted walls, from bottom
83/// junction `a` to top junction `b` with mid-height witness `m` (all three are
84/// exact offset-primitive intersections).  Straight when `m` is collinear
85/// (plane∧plane miter edges, tangent-junction cone rulings); otherwise the
86/// exact CONIC through `a`/`b` with the walls' analytic gradient-cross end
87/// tangents, its rational-quadratic weight solved from `m` (a conic is
88/// uniquely determined by that data, and every drafted wall∧wall intersection
89/// IS a conic — both squared implicits shrink linearly at the same rate, so
90/// their difference is a plane).
91#[allow(clippy::too_many_arguments)]
92pub(super) fn junction_edge_curve(
93    prev: &SegGeom,
94    next: &SegGeom,
95    a: Vec3,
96    m: Vec3,
97    b: Vec3,
98    zh: Vec3,
99    height: f64,
100    signed_d: f64,
101) -> Result<NurbsCurve, String> {
102    let chord = b.sub(a);
103    let length = chord.length();
104    if length <= 1e-12 {
105        return Err("draftExtrude: a junction edge collapsed to a point".into());
106    }
107    let along = m.sub(a).dot(chord) / (length * length);
108    let deviation = m.sub(a).sub(chord.scale(along)).length();
109    if deviation <= length * 1e-9 {
110        return make_line(a, b);
111    }
112    // 2D frame in the conic's plane (it contains a, b, m by construction).
113    let e1 = chord.scale(1.0 / length);
114    let plane_normal = chord.cross(m.sub(a)).normalized()?;
115    let e2 = plane_normal.cross(e1).normalized()?;
116    let orient = |tangent: Vec3| {
117        if tangent.dot(zh) < 0.0 {
118            tangent.scale(-1.0)
119        } else {
120            tangent
121        }
122    };
123    let t0 = orient(wall_gradient(prev, a, zh, height, signed_d)?
124        .cross(wall_gradient(next, a, zh, height, signed_d)?));
125    let t2 = orient(wall_gradient(prev, b, zh, height, signed_d)?
126        .cross(wall_gradient(next, b, zh, height, signed_d)?));
127    let d0 = (t0.dot(e1), t0.dot(e2));
128    let d2 = (t2.dot(e1), t2.dot(e2));
129    let denom = d0.0 * d2.1 - d0.1 * d2.0;
130    let scale0 = d0.0.hypot(d0.1);
131    let scale2 = d2.0.hypot(d2.1);
132    if denom.abs() <= 1e-14 * scale0 * scale2 {
133        return Err("draftExtrude: junction end tangents are parallel — no conic apex".into());
134    }
135    // Apex: a + s·t0 = b + r·t2 solved in 2D (a = origin, b = (length, 0)).
136    let s = length * d2.1 / denom;
137    let apex = (s * d0.0, s * d0.1);
138    if apex.1.abs() <= f64::EPSILON * length {
139        return Err("draftExtrude: junction conic apex is degenerate".into());
140    }
141    // Barycentric coordinates of m over (a, apex, b): m = α·a + β·apex + γ·b.
142    let mq = (m.sub(a).dot(e1), m.sub(a).dot(e2));
143    let beta = mq.1 / apex.1;
144    let gamma = (mq.0 - beta * apex.0) / length;
145    let alpha = 1.0 - beta - gamma;
146    if !(alpha > 0.0 && beta > 0.0 && gamma > 0.0) {
147        return Err(format!(
148            "draftExtrude: junction conic witness fell outside its control triangle \
149             (α={alpha:.3e} β={beta:.3e} γ={gamma:.3e})"
150        ));
151    }
152    let weight = beta / (2.0 * (alpha * gamma).sqrt());
153    let apex_3d = a.add(e1.scale(apex.0)).add(e2.scale(apex.1));
154    NurbsCurve::new(
155        2,
156        vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0],
157        vec![
158            Vec4::from_point(a, 1.0),
159            Vec4::from_point(apex_3d, weight),
160            Vec4::from_point(b, 1.0),
161        ],
162    )
163}
164
165/// In-plane circumcircle of three coplanar points (projected onto `ex`/`ey`,
166/// `np = ex×ey`).  Returns `None` when the three points are collinear.
167fn circumcircle(a: Vec3, b: Vec3, c: Vec3, ex: Vec3, ey: Vec3, np: Vec3) -> Option<(Vec3, f64)> {
168    let (ax, ay) = (a.dot(ex), a.dot(ey));
169    let (bx, by) = (b.dot(ex), b.dot(ey));
170    let (cx, cy) = (c.dot(ex), c.dot(ey));
171    let d = 2.0 * (ax * (by - cy) + bx * (cy - ay) + cx * (ay - by));
172    if d.abs() < 1e-12 {
173        return None;
174    }
175    let a2 = ax * ax + ay * ay;
176    let b2 = bx * bx + by * by;
177    let c2 = cx * cx + cy * cy;
178    let ux = (a2 * (by - cy) + b2 * (cy - ay) + c2 * (ay - by)) / d;
179    let uy = (a2 * (cx - bx) + b2 * (ax - cx) + c2 * (bx - ax)) / d;
180    let plane_off = a.dot(np);
181    let center = ex.scale(ux).add(ey.scale(uy)).add(np.scale(plane_off));
182    let radius = a.sub(center).length();
183    Some((center, radius))
184}
185
186/// Intersect an offset LINE (through `line_point`, direction `line_dir`) with an
187/// offset CIRCLE (`center`, `radius`), returning the root nearest `near` (the
188/// original junction).  A clear Err when they no longer meet (offset too large).
189fn intersect_offset_line_circle(
190    line_point: Vec3,
191    line_dir: Vec3,
192    center: Vec3,
193    radius: f64,
194    near: Vec3,
195) -> Result<Vec3, String> {
196    let dir = line_dir.normalized()?;
197    let f = line_point.sub(center);
198    let b = f.dot(dir);
199    let c = f.dot(f) - radius * radius;
200    let disc = b * b - c;
201    if disc < -1e-9 {
202        return Err("an offset line and arc no longer meet (offset too large)".into());
203    }
204    let root = disc.max(0.0).sqrt();
205    let p1 = line_point.add(dir.scale(-b + root));
206    let p2 = line_point.add(dir.scale(-b - root));
207    Ok(if p1.sub(near).length() <= p2.sub(near).length() {
208        p1
209    } else {
210        p2
211    })
212}
213
214/// Intersect two offset CIRCLES (in the plane whose normal is `plane_normal`),
215/// returning the root nearest `near`.  A clear Err when they are concentric or no
216/// longer meet.
217fn intersect_offset_circles(
218    c1: Vec3,
219    r1: f64,
220    c2: Vec3,
221    r2: f64,
222    plane_normal: Vec3,
223    near: Vec3,
224) -> Result<Vec3, String> {
225    let between = c2.sub(c1);
226    let d = between.length();
227    if d < 1e-9 {
228        return Err("concentric offset arcs do not meet".into());
229    }
230    let axis = between.scale(1.0 / d);
231    let a = (d * d + r1 * r1 - r2 * r2) / (2.0 * d);
232    let h2 = r1 * r1 - a * a;
233    if h2 < -1e-9 {
234        return Err("offset arcs no longer meet (offset too large)".into());
235    }
236    let h = h2.max(0.0).sqrt();
237    let base = c1.add(axis.scale(a));
238    let perp = plane_normal.cross(axis).normalized()?;
239    let p1 = base.add(perp.scale(h));
240    let p2 = base.sub(perp.scale(h));
241    Ok(if p1.sub(near).length() <= p2.sub(near).length() {
242        p1
243    } else {
244        p2
245    })
246}
247
248/// Geometry class of one profile segment, shared by the draft-extrude builder
249/// and the in-plane offset engine: a straight LINE or a circular ARC in the
250/// plane with normal `plane_normal`.
251pub(super) enum SegGeom {
252    Line {
253        start: Vec3,
254        end: Vec3,
255        /// Unit chord direction.
256        dir: Vec3,
257        /// In-plane offset normal `plane_normal × dir` (inward on a CCW loop).
258        normal: Vec3,
259    },
260    Arc {
261        center: Vec3,
262        radius: f64,
263        /// +1 when the arc bends CCW about the plane normal (a convex arc on a
264        /// CCW loop, which SHRINKS under a positive inward offset), −1 when CW.
265        turn: f64,
266        /// ±plane_normal — the axis the arc sweeps CCW about.
267        arc_normal: Vec3,
268        start: Vec3,
269        end: Vec3,
270    },
271}
272
273impl SegGeom {
274    fn start(&self) -> Vec3 {
275        match self {
276            SegGeom::Line { start, .. } | SegGeom::Arc { start, .. } => *start,
277        }
278    }
279
280    fn end(&self) -> Vec3 {
281        match self {
282            SegGeom::Line { end, .. } | SegGeom::Arc { end, .. } => *end,
283        }
284    }
285
286    /// Naive offset image of a point ON this segment's primitive: lines
287    /// translate along their normal; arc points scale radially onto the
288    /// concentric offset circle (Err when a concave arc collapses).
289    fn offset_point(&self, point: Vec3, signed_d: f64) -> Result<Vec3, String> {
290        match self {
291            SegGeom::Line { normal, .. } => Ok(point.add(normal.scale(signed_d))),
292            SegGeom::Arc {
293                center,
294                radius,
295                turn,
296                ..
297            } => {
298                let r_offset = radius - signed_d * turn;
299                if r_offset <= 1e-6 {
300                    return Err("offset: distance is too large — a concave arc collapses".into());
301                }
302                Ok(center.add(point.sub(*center).scale(r_offset / radius)))
303            }
304        }
305    }
306}
307
308/// Classify every profile segment as a LINE (all interior samples on the
309/// chord) or a circular ARC (circumcircle through start/mid/end confirmed by
310/// on-circle samples), with its turning direction about `plane_normal`.
311/// Anything else is a clear Err — the offset/draft machinery is exact for
312/// lines and circles only.
313pub(super) fn classify_profile_segments(
314    profile: &[NurbsCurve],
315    plane_normal: Vec3,
316) -> Result<Vec<SegGeom>, String> {
317    let tol = 1e-6;
318    if profile.is_empty() {
319        return Err("offset: profile has no segments".into());
320    }
321    let np = plane_normal.normalized()?;
322    let ex = np.perpendicular()?;
323    let ey = np.cross(ex).normalized()?;
324    let mut segs = Vec::with_capacity(profile.len());
325    for curve in profile {
326        let [t0, t1] = curve.domain()?;
327        let start = curve.evaluate(t0)?;
328        let end = curve.evaluate(t1)?;
329        let chord = end.sub(start);
330        let chord_len = chord.length();
331        if chord_len <= tol {
332            return Err("offset: profile has a degenerate (zero-length) segment".into());
333        }
334        let dir = chord.scale(1.0 / chord_len);
335        // A straight LINE if every interior sample lies on the chord.
336        let mut is_line = true;
337        for k in 1..8 {
338            let point = curve.evaluate(t0 + (t1 - t0) * k as f64 / 8.0)?;
339            let rel = point.sub(start);
340            let perpendicular = rel.sub(dir.scale(rel.dot(dir))).length();
341            if perpendicular > tol * 10.0 {
342                is_line = false;
343                break;
344            }
345        }
346        if is_line {
347            segs.push(SegGeom::Line {
348                start,
349                end,
350                dir,
351                normal: np.cross(dir).normalized()?,
352            });
353            continue;
354        }
355        // Otherwise it must be a circular ARC: fit a circle through start/mid/end.
356        let mid = curve.evaluate((t0 + t1) * 0.5)?;
357        let (center, radius) = circumcircle(start, mid, end, ex, ey, np).ok_or_else(|| {
358            "offset: only straight lines and circular arcs are supported".to_string()
359        })?;
360        for k in 0..=8 {
361            let point = curve.evaluate(t0 + (t1 - t0) * k as f64 / 8.0)?;
362            if (point.sub(center).length() - radius).abs() > tol * 10.0 {
363                return Err("offset: only straight lines and circular arcs are supported".into());
364            }
365        }
366        // Turning direction about the plane normal (CCW ⇒ +1 ⇒ shrink inward).
367        let bend = np.dot(mid.sub(start).cross(end.sub(mid)));
368        let (arc_normal, turn) = if bend >= 0.0 {
369            (np, 1.0)
370        } else {
371            (np.scale(-1.0), -1.0)
372        };
373        segs.push(SegGeom::Arc {
374            center,
375            radius,
376            turn,
377            arc_normal,
378            start,
379            end,
380        });
381    }
382    Ok(segs)
383}
384
385/// The junction between two consecutive segments' OFFSET primitives at signed
386/// in-plane distance `signed_d`:
387///   • offset 0 → the original shared vertex, exactly;
388///   • a TANGENT (G1) junction degenerates to the shared offset point
389///     (coincident-naive-offsets fast path);
390///   • line∧line → the exact miter V' = V + signed_d/(1+nₐ·n_b)·(nₐ+n_b);
391///   • line∧arc  → the offset line ∩ the offset circle, root nearest V;
392///   • arc∧arc   → the two offset circles ∩, root nearest V.
393/// Offsets that no longer meet (too large for the local feature) are a clear
394/// Err.
395pub(super) fn offset_junction(
396    prev: &SegGeom,
397    next: &SegGeom,
398    plane_normal: Vec3,
399    signed_d: f64,
400) -> Result<Vec3, String> {
401    let vertex = prev.end();
402    if signed_d == 0.0 {
403        return Ok(vertex);
404    }
405    let prev_offset = prev.offset_point(prev.end(), signed_d)?;
406    let next_offset = next.offset_point(next.start(), signed_d)?;
407    if prev_offset.sub(next_offset).length() <= 1e-6 {
408        return Ok(prev_offset.add(next_offset).scale(0.5));
409    }
410    match (prev, next) {
411        (SegGeom::Line { normal: na, .. }, SegGeom::Line { normal: nb, .. }) => {
412            let denom = 1.0 + na.dot(*nb);
413            if denom.abs() < 1e-6 {
414                return Err("offset: degenerate (near-reversal) polyline corner".into());
415            }
416            Ok(vertex.add(na.add(*nb).scale(signed_d / denom)))
417        }
418        (
419            SegGeom::Line { dir, .. },
420            SegGeom::Arc {
421                center,
422                radius,
423                turn,
424                ..
425            },
426        ) => intersect_offset_line_circle(
427            prev_offset,
428            *dir,
429            *center,
430            radius - signed_d * turn,
431            vertex,
432        ),
433        (
434            SegGeom::Arc {
435                center,
436                radius,
437                turn,
438                ..
439            },
440            SegGeom::Line { dir, .. },
441        ) => intersect_offset_line_circle(
442            next_offset,
443            *dir,
444            *center,
445            radius - signed_d * turn,
446            vertex,
447        ),
448        (
449            SegGeom::Arc {
450                center: c1,
451                radius: r1,
452                turn: turn1,
453                ..
454            },
455            SegGeom::Arc {
456                center: c2,
457                radius: r2,
458                turn: turn2,
459                ..
460            },
461        ) => intersect_offset_circles(
462            *c1,
463            r1 - signed_d * turn1,
464            *c2,
465            r2 - signed_d * turn2,
466            plane_normal,
467            vertex,
468        ),
469    }
470}
471
472/// Offset a planar profile CHAIN (a sequence of LINE and circular-ARC segments)
473/// IN-PLANE by the SIGNED distance `signed_d` along the per-segment offset normal
474/// n = (plane_normal × tangent).normalized().  Lines move to a parallel line;
475/// circular arcs move to a CONCENTRIC arc (radius r' = r − signed_d·turn — a
476/// convex-outward arc shrinks, a convex-inward arc grows).  Consecutive offset
477/// segments are re-joined at their [`offset_junction`].  `closed` treats the
478/// chain as a loop (every junction re-joined); an OPEN chain leaves its two end
479/// offsets un-joined.  Returns one reconstructed NurbsCurve per input segment
480/// (make_line / make_arc).  A self-intersecting offset (signed_d too large for
481/// a concave corner or arc) surfaces as a clear Err.
482fn offset_profile_segments(
483    profile: &[NurbsCurve],
484    plane_normal: Vec3,
485    signed_d: f64,
486    closed: bool,
487) -> Result<Vec<NurbsCurve>, String> {
488    let tol = 1e-6;
489    let np = plane_normal.normalized()?;
490    let segs = classify_profile_segments(profile, np)?;
491    let n = segs.len();
492
493    // Naive per-segment offsets, then re-join consecutive ones exactly.
494    let mut offsets: Vec<(Vec3, Vec3)> = segs
495        .iter()
496        .map(|seg| {
497            Ok((
498                seg.offset_point(seg.start(), signed_d)?,
499                seg.offset_point(seg.end(), signed_d)?,
500            ))
501        })
502        .collect::<Result<_, String>>()?;
503    let junctions = if closed { n } else { n.saturating_sub(1) };
504    for i in 0..junctions {
505        let j = (i + 1) % n;
506        let point = offset_junction(&segs[i], &segs[j], np, signed_d)?;
507        offsets[i].1 = point;
508        offsets[j].0 = point;
509    }
510
511    // --- Reconstruct each offset segment as a NurbsCurve.
512    let mut out = Vec::with_capacity(n);
513    for (seg, (off_start, off_end)) in segs.iter().zip(&offsets) {
514        match seg {
515            SegGeom::Line { .. } => out.push(make_line(*off_start, *off_end)?),
516            SegGeom::Arc {
517                center, arc_normal, ..
518            } => {
519                let radial = off_start.sub(*center);
520                let r2 = radial.length();
521                if r2 <= tol {
522                    return Err("offset: reconstructed arc has a zero radius".into());
523                }
524                let ax = radial.scale(1.0 / r2);
525                let ay = arc_normal.cross(ax).normalized()?;
526                let ve = off_end.sub(*center);
527                let mut angle = ve.dot(ay).atan2(ve.dot(ax));
528                if angle <= 1e-9 {
529                    angle += std::f64::consts::TAU;
530                }
531                out.push(make_arc(*center, ax, ay, r2, 0.0, angle)?);
532            }
533        }
534    }
535    Ok(out)
536}
537
538/// Which way a rib grows out of its sketch — SolidWorks' **Extrusion Direction**
539/// control, and the same two choices it offers.
540///
541/// The two are not variants of one construction: they SWAP which axis carries the
542/// thickness and which carries the growth, which is why a rib built in the wrong
543/// one lies down where it should stand up.
544#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
545#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
546pub enum RibExtrusion {
547    /// **Parallel to Sketch** (SolidWorks' default, and what everyone means by a
548    /// rib or a gusset): the material grows PARALLEL to the sketch plane and the
549    /// thickness is applied NORMAL to it. A line drawn between two walls becomes a
550    /// thin fin standing ON the sketch plane, growing across it until it lands on
551    /// the part.
552    #[default]
553    ParallelToSketch,
554    /// **Normal to Sketch**: the material grows NORMAL to the sketch plane and the
555    /// thickness is applied IN it. The chain is thickened inside its own plane and
556    /// that ribbon is driven off the plane — walls hanging under a sketch.
557    NormalToSketch,
558}
559
560/// Rib / stiffener (§6.6) — SolidWorks' Rib, both extrusion directions, with its
561/// **Up To Next** end condition.
562///
563/// The chain is thickened by `thickness` and grown along `extrude_dir` until it
564/// LANDS ON THE PART. Which axis carries which is [`RibExtrusion`]'s whole
565/// purpose: `ParallelToSketch` offsets ±thickness/2 along the plane NORMAL and
566/// sweeps the chain IN the plane; `NormalToSketch` offsets ±thickness/2 INSIDE
567/// the plane (miter-joined, straight caps across the open ends) and sweeps that
568/// ribbon along the plane normal.
569///
570/// # Up To Next
571///
572/// There is no depth. SolidWorks' rib has exactly one end condition — the rib
573/// develops until it meets the next faces and the feature FAILS if any part of it
574/// meets nothing — and this reproduces it exactly rather than approximating it:
575/// the chain is swept a generous `reach` (twice the part's bounding diagonal, so
576/// it certainly crosses the part), the sweep is CUT BY THE PART
577/// (`slab − solid`), and the piece that grew out of the sketch is kept. Its
578/// termination surface is therefore the part's own faces, whatever shape they are.
579/// A piece still running at `reach` never landed, and that is the documented
580/// failure — not a silently truncated rib.
581///
582/// `plane_normal` is the profile's own plane when the caller knows it (a sketch
583/// publishes the plane it was drawn on). `None` falls back to deriving the plane
584/// from the chain's bends, which no single straight segment can supply.
585///
586/// V1 SCOPE: POLYLINE profiles only — arcs/curves return a clear Err.
587pub fn rib_from_profile(
588    solid: &BrepSolid,
589    profile: &[NurbsCurve],
590    thickness: f64,
591    extrude_dir: Vec3,
592    plane_normal: Option<Vec3>,
593    extrusion: RibExtrusion,
594    name: Option<&str>,
595) -> Result<BrepSolid, String> {
596    // The union carries face names from its operands; accept `name` for ABI
597    // symmetry with the other builders (the app stamps names post-hoc).
598    let _ = name;
599    let tolerance = 1e-6;
600    if profile.is_empty() {
601        return Err("rib: profile needs at least 1 curve forming an open chain".into());
602    }
603    if !(thickness > 0.0) {
604        return Err("rib: thickness must be positive".into());
605    }
606
607    // --- 1. Extract the ordered chain vertices (segment endpoints) and verify the
608    //        chain is connected end→start.  Segments may be LINES or circular ARCS.
609    let mut vertices = Vec::with_capacity(profile.len() + 1);
610    let mut samples = Vec::new();
611    for (index, curve) in profile.iter().enumerate() {
612        let [start, end] = curve.domain()?;
613        let v_start = curve.evaluate(start)?;
614        let v_end = curve.evaluate(end)?;
615        if v_end.sub(v_start).length() <= tolerance {
616            return Err("rib: profile has a degenerate (zero-length) segment".into());
617        }
618        if index == 0 {
619            vertices.push(v_start);
620        } else if v_start.sub(*vertices.last().unwrap()).length() > tolerance {
621            return Err(format!(
622                "rib: profile chain is not connected at curve {index}"
623            ));
624        }
625        vertices.push(v_end);
626        // Skip k = 0 after the first segment: it duplicates the previous
627        // segment's endpoint, which would otherwise inject a zero-length step
628        // and cancel the corner bend used to derive the plane normal.
629        let first_k = if index == 0 { 0 } else { 1 };
630        for k in first_k..=8 {
631            samples.push(curve.evaluate(start + (end - start) * k as f64 / 8.0)?);
632        }
633    }
634    let count = vertices.len();
635    if count < 2 {
636        return Err("rib: profile needs at least 2 distinct vertices".into());
637    }
638
639    // --- 2. A rib thickens an OPEN profile; a closed loop is an ordinary
640    //        extrude, not a rib.
641    if vertices[count - 1].sub(vertices[0]).length() <= tolerance {
642        return Err("rib: profile chain is closed; rib expects an open chain".into());
643    }
644
645    // --- 3. The profile plane normal np.  A caller-supplied plane wins: it is the
646    //        plane the profile was AUTHORED on (a sketch publishes it), so it is
647    //        both unambiguous in sign and defined for a chain with no bend at all.
648    //        Otherwise derive it from the sampled chain's bends (robust for arc
649    //        segments), which a fully collinear chain cannot yield.  Either way
650    //        the chain must lie in the plane.
651    let np = match plane_normal {
652        Some(supplied) => supplied
653            .normalized()
654            .map_err(|_| "rib: the supplied profile plane normal is degenerate".to_string())?,
655        None => {
656            let mut normal = Vec3::default();
657            for i in 1..samples.len() - 1 {
658                let a = samples[i].sub(samples[i - 1]);
659                let b = samples[i + 1].sub(samples[i]);
660                normal = normal.add(a.cross(b));
661            }
662            normal.normalized().map_err(|_| {
663                "rib: profile is collinear and no profile plane was supplied; cannot determine \
664                 its plane"
665                    .to_string()
666            })?
667        }
668    };
669    let origin = vertices[0];
670    if samples
671        .iter()
672        .any(|point| point.sub(origin).dot(np).abs() > tolerance * 100.0)
673    {
674        return Err(if plane_normal.is_some() {
675            "rib: profile does not lie in the supplied plane".into()
676        } else {
677            "rib: profile is not planar".to_string()
678        });
679    }
680
681    // --- 4. How far to sweep before the part cuts the rib back: twice the part's
682    //        bounding diagonal certainly crosses it from anywhere on the chain, so
683    //        the CUT decides the rib's extent, never this number.
684    let reach = sweep_reach(solid, &vertices)?;
685
686    // --- 5. Build the over-long slab for the requested extrusion direction.  The
687    //        two arms differ only in which axis carries the thickness.
688    let slab = match extrusion {
689        RibExtrusion::ParallelToSketch => {
690            // The growth direction lies IN the plane; anything out of plane is a
691            // caller error, not something to silently project away.
692            let along = extrude_dir.sub(np.scale(extrude_dir.dot(np)));
693            let along = along.normalized().map_err(|_| {
694                "rib: a Parallel-to-Sketch rib grows INSIDE its sketch plane, but the requested \
695                 direction is perpendicular to it"
696                    .to_string()
697            })?;
698            parallel_slab(profile, &vertices, np, along, thickness, reach)?
699        }
700        RibExtrusion::NormalToSketch => {
701            let along = extrude_dir
702                .normalized()
703                .map_err(|_| "rib: extrude direction is degenerate".to_string())?;
704            normal_slab(profile, np, along, thickness, reach)?
705        }
706    };
707
708    // --- 6. Up To Next: cut the over-long slab by the part and keep the piece the
709    //        sketch grew.  That piece is the rib; its far end IS the part's faces.
710    let along = match extrusion {
711        RibExtrusion::ParallelToSketch => {
712            let along = extrude_dir.sub(np.scale(extrude_dir.dot(np)));
713            along.normalized()?
714        }
715        RibExtrusion::NormalToSketch => extrude_dir.normalized()?,
716    };
717    let seeds = chain_probe_seeds(profile)?;
718    let rib = up_to_next(solid, &slab, &seeds, along, reach)?;
719    let Some(rib) = rib else {
720        // Every bit of the sweep was already material: the rib adds nothing, and
721        // the part is its own answer.  Not an error — the same document with a
722        // thicker wall would build exactly this.
723        return Ok(solid.clone());
724    };
725
726    boolean_operation(
727        solid,
728        &rib,
729        BooleanOperation::Union,
730        &BooleanOptions::default(),
731    )
732    .map_err(|error| format!("rib: union of the rib into the part failed: {error}"))
733}
734
735/// Twice the part's bounding diagonal, measured from the chain too so a sketch
736/// standing off the part still sweeps across it.  The rib's real extent is decided
737/// by the cut in [`up_to_next`]; this only has to be generous.
738fn sweep_reach(solid: &BrepSolid, chain: &[Vec3]) -> Result<f64, String> {
739    let mut min = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
740    let mut max = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
741    let mut extend = |point: Vec3| {
742        min = Vec3::new(min.x.min(point.x), min.y.min(point.y), min.z.min(point.z));
743        max = Vec3::new(max.x.max(point.x), max.y.max(point.y), max.z.max(point.z));
744    };
745    for vertex in &solid.vertices {
746        extend(vertex.point);
747    }
748    for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
749        for row in &face.surface.control_points {
750            for point in row {
751                extend(point.point()?);
752            }
753        }
754    }
755    for point in chain {
756        extend(*point);
757    }
758    let diagonal = max.sub(min).length();
759    if !(diagonal > 0.0) || !diagonal.is_finite() {
760        return Err("rib: the target solid has no extent to grow the rib against".into());
761    }
762    Ok(diagonal * 2.0)
763}
764
765/// Points ON the chain, one per segment — where the rib starts, and so where the
766/// search for its free-space piece begins.
767///
768/// It has to be the chain ITSELF, not the average of its vertices: for a bent
769/// chain that average is off the chain entirely (an L's vertex centroid lands
770/// exactly on the thickened ribbon's inner corner, a knife-edge the classifier
771/// can only answer "on"), and a probe that starts on a boundary finds no piece.
772fn chain_probe_seeds(profile: &[NurbsCurve]) -> Result<Vec<Vec3>, String> {
773    let mut seeds = Vec::with_capacity(profile.len());
774    for curve in profile {
775        let [start, end] = curve.domain()?;
776        seeds.push(curve.evaluate(start + (end - start) * 0.5)?);
777    }
778    if seeds.is_empty() {
779        return Err("rib: profile has no points to grow from".into());
780    }
781    Ok(seeds)
782}
783
784/// **Parallel to Sketch**: the chain swept `reach` along the IN-PLANE direction
785/// `along` gives a closed region inside the sketch plane; that region, offset to
786/// −thickness/2 and extruded `thickness` along the plane normal, is the fin.
787///
788/// The loop must be simple, so a chain that doubles back across its own sweep
789/// self-intersects here and the extrude refuses — the documented V1 limit.
790fn parallel_slab(
791    profile: &[NurbsCurve],
792    vertices: &[Vec3],
793    np: Vec3,
794    along: Vec3,
795    thickness: f64,
796    reach: f64,
797) -> Result<BrepSolid, String> {
798    let offset = along.scale(reach);
799    let chain_start = vertices[0];
800    let chain_end = *vertices.last().expect("chain has vertices");
801    let mut region: Vec<NurbsCurve> = Vec::with_capacity(profile.len() * 2 + 2);
802    for curve in profile {
803        region.push(curve.clone());
804    }
805    region.push(make_line(chain_end, chain_end.add(offset))?);
806    for curve in profile.iter().rev() {
807        region.push(super::extrude::translated_curve(&curve.reversed()?, offset)?);
808    }
809    region.push(make_line(chain_start.add(offset), chain_start)?);
810
811    // Centre the thickness on the sketch plane: start half a thickness under it
812    // and extrude a full thickness back through.
813    let base = region
814        .iter()
815        .map(|curve| super::extrude::translated_curve(curve, np.scale(-thickness * 0.5)))
816        .collect::<Result<Vec<_>, String>>()?;
817    extrude_profile_brep(&base, np, thickness)
818        .map_err(|error| format!("rib: sweeping the profile inside its plane failed: {error}"))
819}
820
821/// **Normal to Sketch**: the chain thickened INSIDE its own plane (miter-offset
822/// ±thickness/2, straight caps across the two open ends → a closed thin loop),
823/// extruded `reach` along `along` (the plane normal).
824fn normal_slab(
825    profile: &[NurbsCurve],
826    np: Vec3,
827    along: Vec3,
828    thickness: f64,
829    reach: f64,
830) -> Result<BrepSolid, String> {
831    let half = thickness * 0.5;
832    let left = offset_profile_segments(profile, np, half, false)
833        .map_err(|error| format!("rib: {error}"))?;
834    let right = offset_profile_segments(profile, np, -half, false)
835        .map_err(|error| format!("rib: {error}"))?;
836    let left_first = &left[0];
837    let left_last = &left[left.len() - 1];
838    let right_first = &right[0];
839    let right_last = &right[right.len() - 1];
840    let left_start = left_first.evaluate(left_first.domain()?[0])?;
841    let left_end = left_last.evaluate(left_last.domain()?[1])?;
842    let right_start = right_first.evaluate(right_first.domain()?[0])?;
843    let right_end = right_last.evaluate(right_last.domain()?[1])?;
844    let mut thin_loop: Vec<NurbsCurve> = Vec::with_capacity(left.len() + right.len() + 2);
845    for curve in &left {
846        thin_loop.push(curve.clone());
847    }
848    thin_loop.push(make_line(left_end, right_end)?);
849    for curve in right.iter().rev() {
850        thin_loop.push(curve.reversed()?);
851    }
852    thin_loop.push(make_line(right_start, left_start)?);
853    extrude_profile_brep(&thin_loop, along, reach)
854        .map_err(|error| format!("rib: extrude of the thickened profile failed: {error}"))
855}
856
857/// SolidWorks' **Up To Next**, exactly: cut the over-long `slab` by the part and
858/// keep the piece the sketch grew into.
859///
860/// `slab − solid` leaves the sweep's free-space pieces, and the boolean assembler
861/// already groups a disconnected result into ONE SHELL PER PIECE (it unions faces
862/// by shared edges), so the pieces are the result's shells. The piece containing
863/// the sketch is the rib; anything past the part is a different piece and is
864/// dropped — that, not a bounding box, is what makes the rib stop at the part's
865/// own faces whatever shape they are.
866///
867/// `Ok(None)` means the sweep was entirely inside existing material: there is
868/// nothing to add. A piece still running at `reach` never landed on anything, and
869/// that is SolidWorks' documented failure ("if any portion of the solid feature
870/// generated does not hit a Next face it fails").
871fn up_to_next(
872    solid: &BrepSolid,
873    slab: &BrepSolid,
874    seeds: &[Vec3],
875    along: Vec3,
876    reach: f64,
877) -> Result<Option<BrepSolid>, String> {
878    let free = match boolean_operation(
879        slab,
880        solid,
881        BooleanOperation::Subtract,
882        &BooleanOptions::default(),
883    ) {
884        Ok(free) => free,
885        // A subtract that refuses because the operands are disjoint means the
886        // sweep never reached the part at all — the Up To Next failure, reported
887        // as itself rather than as a boolean's internal complaint.
888        Err(error) => {
889            // ESSENTIAL REFUSAL (see the sibling below): the cut refusing because
890            // the operands are disjoint IS "the rib met nothing".
891            return Err(format!(
892                "rib: RIB_UP_TO_NEXT_UNBOUNDED — the rib never reaches the part, so it has \
893                 nothing to stop against (SolidWorks' Up To Next requires every part of a rib \
894                 to meet a face); check the rib's direction — the cut reported: {error}"
895            ))
896        }
897    };
898    if free.shells.is_empty() {
899        return Ok(None);
900    }
901
902    // Where the rib actually begins: the first point along the sweep from each
903    // seed that is NOT already material. The chain can be drawn inside a wall, and
904    // the rib is then the free space just beyond it.
905    let classifier = SolidClassifier::new(solid, 1e-6)?;
906    let steps = 64;
907    let mut probes = Vec::new();
908    for seed in seeds {
909        for step in 1..=steps {
910            let point = seed.add(along.scale(reach * step as f64 / steps as f64 * 0.5));
911            if classifier.classify(point)?.class == PointClass::Out {
912                probes.push(point);
913                break;
914            }
915        }
916    }
917    if probes.is_empty() {
918        // Every sample along the sweep sits inside the part: nothing to add.
919        return Ok(None);
920    }
921
922    let mut kept: Option<BrepSolid> = None;
923    for shell in &free.shells {
924        let piece = solid_from_shell(&free, shell);
925        let grown_here = probes
926            .iter()
927            .map(|probe| classify_point(*probe, &piece, 1e-6))
928            .collect::<Result<Vec<_>, String>>()?
929            .into_iter()
930            .any(|classification| classification.class == PointClass::In);
931        if !grown_here {
932            continue;
933        }
934        // SolidWorks' cardinal rule for Up To Next: a piece that is still going at
935        // the end of the sweep never met a face.
936        let overrun = piece
937            .vertices
938            .iter()
939            .map(|vertex| vertex.point.sub(seeds[0]).dot(along))
940            .fold(f64::NEG_INFINITY, f64::max);
941        if overrun >= reach * 0.99 {
942            // ESSENTIAL REFUSAL — do not "open" this one. Unlike a gate that
943            // refuses data the machinery could already answer, this is the
944            // feature's DEFINITION: SolidWorks' rib has one end condition, and
945            // "if any portion of the solid feature generated does not hit a Next
946            // face it fails" is the rule, not a limitation of ours. Accepting it
947            // would ship a rib hanging in space with a far end at an arbitrary
948            // sweep distance, which is exactly the bug this feature was reported
949            // for. The right repair is always the rib's DIRECTION, never this
950            // check.
951            return Err(
952                "rib: RIB_UP_TO_NEXT_UNBOUNDED — part of the rib never lands on the part, so \
953                 it has no face to stop against (SolidWorks' Up To Next requires the whole rib \
954                 to terminate on a face). Turn the rib around with `direction`, or move the \
955                 profile so its sweep meets the part"
956                    .into(),
957            );
958        }
959        kept = Some(match kept {
960            None => piece,
961            Some(previous) => boolean_operation(
962                &previous,
963                &piece,
964                BooleanOperation::Union,
965                &BooleanOptions::default(),
966            )
967            .map_err(|error| format!("rib: joining the rib's own pieces failed: {error}"))?,
968        });
969    }
970    Ok(kept)
971}
972
973/// One shell of `source` as a solid in its own right, carrying only the edges and
974/// vertices its faces use — how a disconnected boolean result is taken apart into
975/// the pieces the assembler already separated.
976fn solid_from_shell(source: &BrepSolid, shell: &ShellRecord) -> BrepSolid {
977    let edge_ids: std::collections::HashSet<u64> = shell
978        .faces
979        .iter()
980        .flat_map(|face| &face.loops)
981        .flat_map(|loop_record| &loop_record.coedges)
982        .map(|coedge| coedge.edge_id)
983        .collect();
984    let edges: Vec<EdgeRecord> = source
985        .edges
986        .iter()
987        .filter(|edge| edge_ids.contains(&edge.id))
988        .cloned()
989        .collect();
990    let vertex_ids: std::collections::HashSet<u64> = edges
991        .iter()
992        .flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id])
993        .collect();
994    BrepSolid {
995        id: source.id,
996        vertices: source
997            .vertices
998            .iter()
999            .filter(|vertex| vertex_ids.contains(&vertex.id))
1000            .cloned()
1001            .collect(),
1002        edges,
1003        shells: vec![shell.clone()],
1004        genus: 0,
1005    }
1006}