Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion crates/engine/src/cmd/canvas_sketch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,12 +74,15 @@ fn to_sketch(s: &mut Session, p: &Value) -> Result<Value> {
cur = seg.end();
}
}
// A cubic whose handle has no length (a vertex with no tangent, a span too short) has an end
// with no direction, which a sketch spline can't have: it comes in as curves that follow it.
let (geom, _, _) = super::sketch_import::split_nurbs(geom, super::sketch_import::DEFAULT_FIT_TOLERANCE / 2.0, 1.0).map_err(|e| bad(cmd, e))?;
let name = str_(p, "name").map(str::to_string).unwrap_or_else(|| format!("{} sketch", canvas.name));
let r = super::sketch::create_sketch_with_plane(s, &json!({ "name": name }), canvas.plane.clone(), None)?;
let id = r.get("sketch").and_then(Value::as_u64);
let tol = (sc * 0.01).max(1e-6);
let made = super::sketch::edit(s, &json!({}), cmd, false, |sk, _| {
let (cs, _) = super::sketch_import::add_geometry(sk, &geom, &|q| q, 1.0, tol)?;
let (cs, _, _) = super::sketch_import::add_geometry(sk, &geom, &|q| q, 1.0, tol)?;
Ok(cs.len())
});
let finish = super::find_command("sketch.finish").ok_or_else(|| bad(cmd, "sketch.finish"))?.run;
Expand Down
742 changes: 723 additions & 19 deletions crates/engine/src/cmd/sketch_import.rs

Large diffs are not rendered by default.

8 changes: 5 additions & 3 deletions crates/engine/src/cmd/sketch_modify_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3780,7 +3780,9 @@ fn freeform_offsets_trim_folds_and_round_chain_corners_into_an_extrudable_wall()
let mut s = new_sketch();
run(&mut s, "sketch.insert_svg", json!({"text": svg}));
let sources = sketch(&s).curves.iter().map(|c| c.id.clone()).collect::<Vec<_>>();
assert_eq!(sources.len(), 5);
// Five curves as written; the one with the zero-length handle comes in as several that
// have a direction at that end, which a sketch spline needs (Insert SVG), so more than five.
assert!(sources.len() > 5, "{sources:?}");
// Picking every curve of the chain makes one offset, not one per curve.
let out = run(&mut s, "sketch.offset", json!({"curves": sources, "distance": distance}));
let curves = ids(&out["curves"]);
Expand All @@ -3789,8 +3791,8 @@ fn freeform_offsets_trim_folds_and_round_chain_corners_into_an_extrudable_wall()
curves.iter().any(|c| matches!(sk.curves[sk.curve_index(c).unwrap()].kind, CurveKind::Arc { .. })),
"an outer corner is rounded: {out}"
);
assert_eq!(sk.curves.len(), 5 + curves.len());
let source: Vec<_> = (0..5).flat_map(|i| sk.exact_pieces(i)).collect();
assert_eq!(sk.curves.len(), sources.len() + curves.len());
let source: Vec<_> = (0..sources.len()).flat_map(|i| sk.exact_pieces(i)).collect();
for c in &curves {
for seg in sk.exact_pieces(sk.curve_index(c).unwrap()) {
for k in 0..=8 {
Expand Down
85 changes: 70 additions & 15 deletions crates/geom/src/bspline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,15 @@ use std::ops::{Add, AddAssign, Mul, Sub};

use solidcore_record::Vec3;

mod curve;
mod interval;

pub use curve::{Certified, CurvePiece, Fit, MIN_CONIC_RHO_GAP, MIN_CONTROL_GAP, NurbsCurve, follow};

/// Highest polynomial degree accepted in either direction: the B-rep record's own bound
/// (`Brep::validate`), so every spline a record may hold can be evaluated. A G4 blend is of
/// degree 9 (five conditions at each end).
/// degree 9 (five conditions at each end). A [`NurbsCurve`] has the same bound, which bounds
/// the work a hostile curve can ask for.
pub const MAX_SPLINE_DEGREE: usize = solidcore_record::brep::MAX_SPLINE_DEGREE;
/// Most knots accepted in one knot vector.
pub const MAX_KNOTS: usize = 1 << 14;
Expand Down Expand Up @@ -95,6 +101,33 @@ impl AddAssign for HPoint {
}
}

/// A homogeneous control point as knot insertion and de Casteljau combine it: in floating point
/// ([`HPoint`]), or enclosed in intervals that hold the exact result ([`interval::HInterval`]).
/// One implementation of each of those steps serves both.
pub(crate) trait Blend: Copy {
/// What a point is weighted by: a number, or an interval holding one.
type Factor: Copy;
const ZERO: Self;
/// The factors of the later and the earlier point for `u` between `lo < hi`:
/// `((u − lo)/(hi − lo), (hi − u)/(hi − lo))`, both from knot differences (`1 − α` loses α's
/// digits when α is near 1, and a weight of 10¹² beside one of 1 shows it).
fn factors(lo: f64, u: f64, hi: f64) -> (Self::Factor, Self::Factor);
/// `self·a + other·b`.
fn blend(self, a: Self::Factor, other: Self, b: Self::Factor) -> Self;
}

impl Blend for HPoint {
type Factor = f64;
const ZERO: HPoint = HPoint::ZERO;
fn factors(lo: f64, u: f64, hi: f64) -> (f64, f64) {
let den = hi - lo;
((u - lo) / den, (hi - u) / den)
}
fn blend(self, a: f64, other: HPoint, b: f64) -> HPoint {
self * a + other * b
}
}

/// A parameter direction: along s (u, the first) or along t (v, the second).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Dir {
Expand Down Expand Up @@ -341,6 +374,11 @@ pub fn find_span(knots: &[f64], p: usize, n: usize, u: f64) -> Option<usize> {
/// points (Boehm; NURBS Book eq. 5.10 / A5.1). `u` must lie in the domain `[knots[p],
/// knots[n]]`; the curve is unchanged.
pub fn insert_knot(p: usize, knots: &[f64], ctrl: &[HPoint], u: f64) -> SplineResult<(Vec<f64>, Vec<HPoint>)> {
insert_row(p, knots, ctrl, u)
}

/// [`insert_knot`] for either kind of point ([`Blend`]).
pub(crate) fn insert_row<P: Blend>(p: usize, knots: &[f64], ctrl: &[P], u: f64) -> SplineResult<(Vec<f64>, Vec<P>)> {
let n = ctrl.len();
if n <= p || knots.len() != n + p + 1 {
return invalid("knot and control point counts do not match the degree");
Expand All @@ -351,17 +389,18 @@ pub fn insert_knot(p: usize, knots: &[f64], ctrl: &[HPoint], u: f64) -> SplineRe
check_knots(knots)?;
let k = find_span(knots, p, n, u).ok_or_else(|| SplineError::Invalid(format!("knot {u} is outside the domain")))?;
let kn = |i: usize| knots.get(i).copied().unwrap_or(0.0);
let pt = |i: usize| ctrl.get(i).copied().unwrap_or(HPoint::ZERO);
let pt = |i: usize| ctrl.get(i).copied().unwrap_or(P::ZERO);
let mut q = Vec::with_capacity(n + 1);
for i in 0..=n {
q.push(if i + p <= k {
pt(i)
} else if i > k {
pt(i - 1)
} else if kn(i + p) > kn(i) {
let (alpha, beta) = P::factors(kn(i), u, kn(i + p));
pt(i).blend(alpha, pt(i - 1), beta)
} else {
let den = kn(i + p) - kn(i);
let alpha = if den > 0.0 { (u - kn(i)) / den } else { 1.0 };
pt(i) * alpha + pt(i - 1) * (1.0 - alpha)
pt(i)
});
}
let mut nk = knots.to_vec();
Expand Down Expand Up @@ -430,7 +469,7 @@ pub fn bernstein(p: usize, i: usize, x: f64) -> f64 {
/// basis functions that vanish on the domain dropped (a basis function's last span does not
/// depend on its first knot, so that knot moves to the domain end). The curve on the domain is
/// unchanged.
pub(crate) fn clamp_row(p: usize, knots: &[f64], row: &[HPoint]) -> SplineResult<(Vec<f64>, Vec<HPoint>)> {
pub(crate) fn clamp_row<P: Blend>(p: usize, knots: &[f64], row: &[P]) -> SplineResult<(Vec<f64>, Vec<P>)> {
let n = row.len();
let (Some(&a), Some(&b)) = (knots.get(p), knots.get(n)) else { return invalid("too few knots") };
let (mut knots, mut row) = (knots.to_vec(), row.to_vec());
Expand All @@ -439,10 +478,10 @@ pub(crate) fn clamp_row(p: usize, knots: &[f64], row: &[HPoint]) -> SplineResult
let mut guard = 0;
while mult(&knots) < p {
guard += 1;
if guard > MAX_SPLINE_DEGREE + 1 {
if guard > p + 1 {
return invalid("clamping did not converge");
}
(knots, row) = insert_knot(p, &knots, &row, x)?;
(knots, row) = insert_row(p, &knots, &row, x)?;
}
let n = row.len();
let (first, last) = if at_end {
Expand All @@ -461,15 +500,15 @@ pub(crate) fn clamp_row(p: usize, knots: &[f64], row: &[HPoint]) -> SplineResult
} else {
nk.first_mut().into_iter().for_each(|y| *y = x);
}
row = row.get(first..last).map(<[HPoint]>::to_vec).unwrap_or_default();
row = row.get(first..last).map(<[P]>::to_vec).unwrap_or_default();
knots = nk;
}
Ok((knots, row))
}

/// A Bézier curve's point at `x ∈ [0, 1]` (de Casteljau, NURBS Book §1.4).
pub fn bezier_point(ctrl: &[HPoint], x: f64) -> HPoint {
subdivide(ctrl, x).0.last().copied().unwrap_or(HPoint::ZERO)
subdivide(ctrl, x, 1.0 - x).0.last().copied().unwrap_or(HPoint::ZERO)
}

/// The control points of the piece of a Bézier curve over `[a, b] ⊂ [0, 1]` (two de Casteljau
Expand All @@ -479,19 +518,21 @@ pub fn bezier_segment(ctrl: &[HPoint], a: f64, b: f64) -> SplineResult<Vec<HPoin
return invalid("a Bézier segment must satisfy 0 ≤ a < b ≤ 1");
}
// Left part [0, b], then its right part from a/b.
let left = subdivide(ctrl, b).0;
Ok(subdivide(&left, a / b).1)
let left = subdivide(ctrl, b, 1.0 - b).0;
let t = a / b;
Ok(subdivide(&left, t, 1.0 - t).1)
}

/// Split a Bézier curve at `x` (de Casteljau): control points of `[0, x]` and `[x, 1]`.
fn subdivide(ctrl: &[HPoint], x: f64) -> (Vec<HPoint>, Vec<HPoint>) {
/// Split a Bézier curve where its parameter is `t` (and `1 − t` is `s`), by de Casteljau: control
/// points of `[0, t]` and `[t, 1]`.
pub(crate) fn subdivide<P: Blend>(ctrl: &[P], t: P::Factor, s: P::Factor) -> (Vec<P>, Vec<P>) {
let mut left = Vec::with_capacity(ctrl.len());
let mut right = Vec::with_capacity(ctrl.len());
let mut pts = ctrl.to_vec();
while let (Some(&f), Some(&l)) = (pts.first(), pts.last()) {
left.push(f);
right.push(l);
pts = pts.windows(2).map(|w| if let [a, b] = w { *a * (1.0 - x) + *b * x } else { HPoint::ZERO }).collect();
pts = pts.windows(2).map(|w| if let [a, b] = w { a.blend(s, *b, t) } else { P::ZERO }).collect();
}
right.reverse();
(left, right)
Expand Down Expand Up @@ -896,6 +937,20 @@ pub(crate) mod tests {
assert!(worst < 1e-13, "deviation {worst}");
assert!(insert_knot(p, &KNOTS, &ctrl, 1.5).is_err());
assert!(insert_knot(p, &KNOTS, &ctrl, f64::NAN).is_err());
// Beside a weight of 10¹², α = (1.5 − 2⁻⁵²)/1.5 is so near 1 that `1 − α` keeps a
// quarter of the other factor wrong; from knot differences it stays on the curve.
let ub = 1.5 - 2f64.powi(-52);
let heavy = [
HPoint::weighted(Vec3::new(0.0, 0.0, 0.0), 1.0),
HPoint::weighted(Vec3::new(10.0, 20.0, 0.0), 1e12),
HPoint::weighted(Vec3::new(20.0, 0.0, 0.0), 1.0),
];
let open = [0.0, 0.0, 0.0, 1.5, 1.5, 1.5];
let (kn, pts) = insert_knot(2, &open, &heavy, ub).unwrap();
for u in [0.75, 1.4, ub, 1.5] {
let off = curve(2, &open, &heavy, u).dist(curve(2, &kn, &pts, u));
assert!(off < 1e-9, "{off:e} off the curve at {u}");
}
}

pub(crate) fn random_surface(seed: u64, ku: Vec<f64>, kv: Vec<f64>, degree: [usize; 2]) -> NurbsSurface {
Expand Down
Loading
Loading