BREP_construction 0.34.1

Rust B-rep CAD kernel (next.BREP.io): solid construction: extrusions, revolutions, sweeps and lofts.
Documentation
//! A cone (a point and a flat base) TURNED about a line that crosses its
//! axis inside it, aslant or square (`BREP_SWEEP_CONE_ACROSS`, default on; a
//! rescue: it answers only where the general route refuses, and `=0` restores
//! that refusal).
//!
//! Let O be where the turn's axis meets the cone's, between its point and its
//! base. Every point of the base's rim lies at one distance R from O, so fill
//! the cone out to the ball of radius R about O: K* is the cone with its flat
//! base replaced by the cap of that sphere (K* = the cone's nappe within R of
//! O, a solid of revolution about the cone's axis). The turn's axis e and the
//! cone's axis lie in one plane P, so K* is symmetric in P; write a circle
//! about e by its angle φ from the half of P that the cone's axis leans into
//! (φ = 0) and the other half (φ = π).
//!
//! - Where K* meets every circle about e in arcs that each hold φ = 0 or
//!   φ = π, an arc [−b, b] turned by up to θ covers [−b, b + θ] = [−b, b] ∪
//!   [0, θ] ∪ [θ − b, θ + b]: so K* sweeps K* where it starts, K* where it
//!   stops, and its section by P's two halves, each revolved about e
//!   through θ.
//! - K* sweeps what the cone sweeps where every point K* adds is reached by
//!   the cone within the turn (the gap the cone leaves on such a circle is
//!   narrower than θ).
//!
//! Both are read on a grid of circles about e (each circle sampled round,
//! from the two solids' closed-form membership) before anything is built;
//! where either fails, or the motion is not one turn short of a whole one, or
//! the tool is not such a cone with the axes meeting inside it, the route
//! declines (None) and the refusal stands. The sweep is then the union of the
//! four solids of revolution: cones, spheres and planes.
use super::*;

/// The switch (default on; `BREP_SWEEP_CONE_ACROSS=0` restores the refusal).
pub(super) fn cone_across_on() -> bool {
    crate::switch!("BREP_SWEEP_CONE_ACROSS", true)
}

/// Circles of the check: heights along e and radii about it, and the samples round each.
const GRID: usize = 48;
const ROUND: usize = 720;

/// The cone in its own meridian coordinates: its point at axial `apex`, its
/// base at axial `base` with radius `rim` (radial ≥ 0).
#[derive(Clone, Copy, Debug)]
struct Cone {
    apex: f64,
    base: f64,
    rim: f64,
}

/// A cone's meridian, if `meridian` is one: three lines closing a triangle
/// with two corners on the axis (the point and the base's centre) and the
/// base square to the axis.
fn cone_of(meridian: &[OutlinePiece]) -> Option<Cone> {
    if meridian.len() != 3 {
        return None;
    }
    let mut corners = Vec::with_capacity(3);
    for (k, piece) in meridian.iter().enumerate() {
        let OutlinePiece::Line { from, to } = piece else { return None };
        let OutlinePiece::Line { from: next, .. } = &meridian[(k + 1) % 3] else { return None };
        let scale = from[0].abs().max(from[1].abs()).max(to[0].abs()).max(to[1].abs()).max(1e-300);
        if (to[0] - next[0]).abs() > 1e-12 * scale || (to[1] - next[1]).abs() > 1e-12 * scale {
            return None;
        }
        corners.push(*from);
    }
    let scale = corners.iter().map(|c| c[0].abs().max(c[1].abs())).fold(0.0f64, f64::max);
    if !(scale > 0.0 && scale.is_finite()) {
        return None;
    }
    let tiny = 1e-12 * scale;
    let rims: Vec<_> = corners.iter().filter(|c| c[0] > tiny).collect();
    let axial: Vec<_> = corners.iter().filter(|c| c[0].abs() <= tiny).collect();
    let ([rim], [p, q]) = (rims.as_slice(), axial.as_slice()) else { return None };
    // The base's centre shares the rim's axial coordinate; the point does not.
    let (apex, base) = if (p[1] - rim[1]).abs() <= tiny { (q[1], p[1]) } else if (q[1] - rim[1]).abs() <= tiny { (p[1], q[1]) } else { return None };
    if (apex - base).abs() <= tiny {
        return None;
    }
    Some(Cone { apex, base, rim: rim[0] })
}

/// The cone turned about a line crossing its axis inside it, if the tool and
/// the motion are such and the check holds (module docs); `None` otherwise.
pub(super) fn cone_across_axis(screw: &Screw, origin: Vec3, axis: Vec3, meridian: &[OutlinePiece]) -> Result<Option<BrepSolid>, KernelRefusal> {
    if screw.frame.is_some() || screw.turns.is_some() || screw.omega == 0.0 || screw.c != 0.0 || screw.c2 != 0.0 {
        return Ok(None);
    }
    let Some(cone) = cone_of(meridian) else { return Ok(None) };
    let Ok(w) = axis.normalized() else { return Ok(None) };
    let e = screw.e;
    let theta = screw.omega.abs() * (screw.t1 - screw.t0);
    if !(theta > 1e-9 && theta < TAU * (1.0 - 1e-9)) {
        return Ok(None);
    }
    // Where the two axes meet: they must be coplanar and not parallel.
    let scale = cone.apex.abs().max(cone.base.abs()).max(cone.rim).max(origin.sub(screw.a).length());
    let normal = w.cross(e);
    let sine = normal.length();
    if !(sine > 1e-9) {
        return Ok(None);
    }
    let gap = screw.a.sub(origin);
    if gap.dot(normal).abs() / sine > 1e-12 * scale.max(1e-300) {
        return Ok(None);
    }
    // origin + s w = a + k e: solve along the plane's in-plane normal to e.
    let across = e.cross(normal); // in the plane, square to e
    let s = gap.dot(across) / w.dot(across);
    let (lo, hi) = (cone.apex.min(cone.base), cone.apex.max(cone.base));
    if !(s > lo + 1e-9 * scale && s < hi - 1e-9 * scale) {
        return Ok(None);
    }
    // At the start: the meeting point holds still under the turn.
    let o = screw.apply(screw.t0, origin.add(w.scale(s)));
    let w0 = screw.apply(screw.t0, origin.add(w.scale(s + 1.0))).sub(o);
    let Ok(w0) = w0.normalized() else { return Ok(None) };
    // P's half the cone's axis leans into: x square to e (φ = 0), y = e × x.
    let Ok(x) = w0.sub(e.scale(w0.dot(e))).normalized() else { return Ok(None) };
    let y = e.cross(x);
    let toward = (cone.base - cone.apex).signum();
    let (point, base) = (cone.apex - s, cone.base - s); // axial, from O
    let big = base.hypot(cone.rim);
    // Membership of a point d (from O) in the cone and in K*, closed form.
    let inside = |d: Vec3, filled: bool| -> bool {
        let along = d.dot(w0);
        let radial = d.sub(w0.scale(along)).length();
        let f = (along - point) / (base - point);
        if !(f >= 0.0 && radial <= cone.rim * f) {
            return false;
        }
        if filled { d.length() <= big } else { f <= 1.0 }
    };
    let sigma = screw.omega.signum();
    let reach = big.max(point.abs());
    let step = TAU / ROUND as f64;
    // The turn in samples, kept two short so a sampled cover is a true one.
    let window = ((theta / step).floor() as usize).saturating_sub(2);
    let mut cone_at = vec![false; ROUND];
    let mut filled_at = vec![false; ROUND];
    for i in 0..GRID {
        let h = reach * (2.0 * (i as f64 + 0.5) / GRID as f64 - 1.0);
        for j in 0..GRID {
            let rho = reach * (j as f64 + 0.5) / GRID as f64;
            for k in 0..ROUND {
                let phi = step * k as f64;
                let d = e.scale(h).add(x.scale(rho * phi.cos())).add(y.scale(rho * phi.sin()));
                cone_at[k] = inside(d, false);
                filled_at[k] = inside(d, true);
            }
            // K* holds φ = 0 or φ = π in every arc: on [0, π] it runs in, out, in at most.
            let half = ROUND / 2;
            let mut runs = 1;
            for k in 1..=half {
                if filled_at[k] != filled_at[k - 1] {
                    runs += 1;
                }
            }
            if runs > 3 || (runs == 3 && !filled_at[0]) {
                return Ok(None);
            }
            // Every point K* adds is reached by the cone within the turn. What K* adds is the
            // lens between the base and the cap; off the cap's sphere it is bounded only by the
            // base, so a circle about e (all at one distance from O) leaves the lens only into
            // the cone, through a band that can be thinner than a sample next to the rim. So a
            // lens sample is reached when, going back by φ − σ τ for τ in the window, the circle
            // leaves the lens.
            if h.hypot(rho) >= big {
                continue;
            }
            for k in 0..ROUND {
                if !filled_at[k] || cone_at[k] {
                    continue;
                }
                let reached = (0..=window).any(|m| {
                    let back = if sigma > 0.0 { (k + ROUND * 2 - m) % ROUND } else { (k + m) % ROUND };
                    cone_at[back] || !filled_at[back]
                });
                if !reached {
                    return Ok(None);
                }
            }
        }
    }
    let arc = |centre: Vec3, from: Vec3, normal: Vec3, angle: f64| -> Result<NurbsCurve, KernelRefusal> {
        let surface = frag(make_revolution(centre, normal, &frag(make_line(from, from.add(normal)), "line")?, angle), "cone_across")?;
        frag(surface.iso_curve_v(0.0), "cone_across")
    };
    let line = |a: Vec3, b: Vec3| frag(make_line(a, b), "cone_across");
    // K* at a pose whose axis is `axis` (from O): point -> rim -> cap's arc -> back along the axis.
    let filled = |axis: Vec3| -> Result<BrepSolid, KernelRefusal> {
        let side = axis.cross(e).normalized().map_err(|_| refuse("cone_across", "the cone's axis lies along the turn's".into()))?.cross(axis);
        let tip = o.add(axis.scale(point));
        let rim = o.add(axis.scale(base)).add(side.scale(cone.rim));
        let top = o.add(axis.scale(big * toward));
        let opening = (rim.sub(o).dot(top.sub(o)) / (big * big)).clamp(-1.0, 1.0).acos();
        let turn_normal = rim.sub(o).cross(top.sub(o)).normalized().map_err(|_| refuse("cone_across", "the base's rim lies on the cone's axis".into()))?;
        let profile = [line(tip, rim)?, arc(o, rim, turn_normal, opening)?, line(top, tip)?];
        frag(crate::revolve_profile_brep(&profile, o, axis, TAU), "cone_across")
    };
    let start = filled(w0)?;
    let w1 = w0.rotate_about(e, screw.omega * (screw.t1 - screw.t0));
    let end = filled(w1)?;
    // K*'s section by P in (X along x, Z along e) from O: its boundary is the point, a rim,
    // the cap's arc to the other rim, back to the point; split by the turn's axis X = 0.
    let w2 = [w0.dot(x), w0.dot(e)];
    let u2 = [-w2[1], w2[0]];
    let at = |a: f64, b: f64| [a * w2[0] + b * u2[0], a * w2[1] + b * u2[1]];
    let tip2 = at(point, 0.0);
    let (rim_a, rim_b) = (at(base, cone.rim), at(base, -cone.rim));
    let angle = |q: [f64; 2]| q[1].atan2(q[0]);
    // The cap's arc from rim_a to rim_b through the axis' far point, as a signed sweep.
    let far = angle(at(big * toward, 0.0));
    let wrap = |a: f64| (a + PI).rem_euclid(TAU) - PI;
    let (a0, a1) = (angle(rim_a), angle(rim_b));
    let sweep = {
        let d = wrap(a1 - a0);
        // The arc that holds `far`.
        let holds = |d: f64| {
            let m = wrap(far - a0);
            if d > 0.0 { m > 0.0 && m < d } else { m < 0.0 && m > d }
        };
        if holds(d) { d } else { d - TAU * d.signum() }
    };
    #[derive(Clone, Copy)]
    enum Piece2 {
        Line([f64; 2], [f64; 2]),
        Arc(f64, f64), // start angle, signed sweep (radius `big` about O)
    }
    let point_of = |p: &Piece2, t: f64| -> [f64; 2] {
        match *p {
            Piece2::Line(a, b) => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t],
            Piece2::Arc(a, d) => [big * (a + d * t).cos(), big * (a + d * t).sin()],
        }
    };
    let boundary = [Piece2::Line(tip2, rim_a), Piece2::Arc(a0, sweep), Piece2::Line(rim_b, tip2)];
    // The two crossings of X = 0: (piece, parameter).
    let mut hits: Vec<(usize, f64)> = Vec::new();
    for (k, piece) in boundary.iter().enumerate() {
        match *piece {
            Piece2::Line(a, b) => {
                if (a[0] < 0.0) != (b[0] < 0.0) {
                    hits.push((k, a[0] / (a[0] - b[0])));
                }
            }
            Piece2::Arc(a, d) => {
                for target in [FRAC_PI_2, -FRAC_PI_2] {
                    let m = wrap(target - a);
                    let m = if d > 0.0 { m.rem_euclid(TAU) } else { -(-m).rem_euclid(TAU) };
                    if m.abs() < d.abs() {
                        hits.push((k, m / d));
                    }
                }
            }
        }
    }
    let clear = |t: f64| t > 1e-9 && t < 1.0 - 1e-9;
    if hits.len() != 2 || !hits.iter().all(|&(_, t)| clear(t)) {
        return Ok(None);
    }
    hits.sort_by(|p, q| (p.0, p.1).partial_cmp(&(q.0, q.1)).unwrap_or(std::cmp::Ordering::Equal));
    let world = |q: [f64; 2]| o.add(x.scale(q[0])).add(e.scale(q[1]));
    let plane_normal = x.cross(e);
    let curve_of = |p: &Piece2, t0: f64, t1: f64| -> Result<NurbsCurve, KernelRefusal> {
        match *p {
            Piece2::Line(..) => line(world(point_of(p, t0)), world(point_of(p, t1))),
            Piece2::Arc(_, d) => arc(o, world(point_of(p, t0)), plane_normal.scale(d.signum()), d.abs() * (t1 - t0)),
        }
    };
    // The boundary from one crossing on to the other, closed by the chord along X = 0.
    let path = |from: (usize, f64), to: (usize, f64)| -> Result<Vec<NurbsCurve>, KernelRefusal> {
        let mut curves = Vec::new();
        let (mut k, mut t) = from;
        loop {
            if k == to.0 && t <= to.1 {
                curves.push(curve_of(&boundary[k], t, to.1)?);
                break;
            }
            curves.push(curve_of(&boundary[k], t, 1.0)?);
            k = (k + 1) % boundary.len();
            t = 0.0;
        }
        curves.push(line(world(point_of(&boundary[to.0], to.1)), world(point_of(&boundary[from.0], from.1)))?);
        Ok(curves)
    };
    let turn_axis = e.scale(sigma);
    let halves = [path(hits[0], hits[1])?, path(hits[1], hits[0])?];
    let mut revolved = Vec::with_capacity(2);
    for half in &halves {
        revolved.push(frag(crate::revolve_profile_brep(half, o, turn_axis, theta), "cone_across")?);
    }
    // The revolved halves first (the n-ary union refuses the same four given a cone first).
    let parts = [revolved.swap_remove(0), revolved.swap_remove(0), end, start];
    // A rescue answers only with a sound body: anything else leaves the refusal standing.
    let body = crate::boolean_operation_nary(&parts, crate::BooleanOperation::Union)?;
    Ok((!body.validate().iter().any(|issue| issue.severity == "error")).then_some(body))
}