Class-A surfacing 3/3: blend curves, curved-edge fillets, the G2 corner and continuity analysis (#1642)
Thanks @midasdf.
This commit is contained in:
@@ -88,7 +88,10 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.at("SKETCH", "MODIFY")
|
||||
.icon("blend")
|
||||
.enabled(in_sketch)
|
||||
.params(concat!("a, b: end points of two curves (\"l1.end\", \"a2.start\"): a smooth (tangent) spline joining them", created_doc!())),
|
||||
.params(concat!(
|
||||
"a, b: end points of two curves (\"l1.end\", \"a2.start\"), continuity?: g1|g2|g3|g4 (default g1: a tangent spline; g2…g4 match the reference curves' curvature, curvature rate and 4th derivative as well, as one Bézier of degree 5, 7 or 9)",
|
||||
created_doc!()
|
||||
)),
|
||||
CommandSpec::new("sketch.centerline", "Centerline", centerline)
|
||||
.at("SKETCH", "CREATE")
|
||||
.icon("centerline")
|
||||
@@ -399,8 +402,68 @@ fn end_of(sk: &Sketch, pi: usize) -> Option<(usize, Vec2)> {
|
||||
sk.curves.iter().enumerate().filter(|(_, c)| !c.construction).find_map(|(i, _)| leaving_dir(sk, i, pi).map(|d| (i, d)))
|
||||
}
|
||||
|
||||
/// The continuity a blend asks for: the number of derivatives of each reference curve it
|
||||
/// matches at both joints (g1 is the tangent construction the tool has always made).
|
||||
fn blend_order(p: &Value, cmd: &str) -> Result<usize> {
|
||||
match p.get("continuity") {
|
||||
None | Some(Value::Null) => Ok(1),
|
||||
Some(Value::String(v)) => match v.trim().to_ascii_lowercase().as_str() {
|
||||
"" | "g1" => Ok(1),
|
||||
"g2" => Ok(2),
|
||||
"g3" => Ok(3),
|
||||
"g4" => Ok(4),
|
||||
_ => Err(bad(cmd, "`continuity` must be g1, g2, g3 or g4")),
|
||||
},
|
||||
Some(_) => Err(bad(cmd, "`continuity` must be g1, g2, g3 or g4")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Negate the odd-order derivatives: how a curve's derivatives change when it is read backwards.
|
||||
fn flip_odd(d: &mut [Vec2]) {
|
||||
for (i, v) in d.iter_mut().enumerate() {
|
||||
if i % 2 == 0 {
|
||||
*v = -*v;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Derivatives 1…`order` of curve `ci`'s continuation through its end point `pi`, in the
|
||||
/// parameterisation the blend needs at that joint: at the blend's start (`leaving`) the curve's
|
||||
/// continuation runs away from it, at the blend's end the blend runs into the curve instead, which
|
||||
/// is the same curve read backwards. The derivatives are those of the one exact piece that ends
|
||||
/// at `pi`, evaluated at that piece's own end, so an arc gives its circular-motion terms (zero
|
||||
/// curvature rate included) and a conic the quotient rule's terms. Errors when the curve has no
|
||||
/// exact piece, when a derivative is not finite (a corrupt or degenerate reference), or when it
|
||||
/// has no tangent at all: no blend can meet the last case.
|
||||
fn joint_derivatives(sk: &Sketch, ci: usize, pi: usize, order: usize, leaving: bool, what: &str, cmd: &str) -> Result<Vec<Vec2>> {
|
||||
let id = sk.curves.get(ci).map(|c| c.id.as_str()).unwrap_or("?");
|
||||
let (start, end) = sk.curves.get(ci).and_then(|c| c.kind.ends()).ok_or_else(|| bad(cmd, format!("`{id}` has no end points")))?;
|
||||
let at_end = end == pi;
|
||||
if !at_end && start != pi {
|
||||
return Err(bad(cmd, format!("`{what}` is not an end point of `{id}`")));
|
||||
}
|
||||
let pieces = sk.exact_pieces(ci);
|
||||
let seg = if at_end { pieces.last() } else { pieces.first() }.ok_or_else(|| bad(cmd, format!("`{id}` has no exact geometry")))?;
|
||||
let mut d = seg
|
||||
.derivatives(if at_end { 1.0 } else { 0.0 }, order)
|
||||
.ok_or_else(|| bad(cmd, format!("`{id}` has no finite derivatives up to order {order} at `{what}`")))?;
|
||||
// Reading the piece against its own direction, or reading the continuation into the curve
|
||||
// rather than out of it, each reverse the parameterisation once and so flip the odd
|
||||
// derivatives: the blend's start wants the continuation away from the reference's end (no
|
||||
// flip) or backwards out of its start (flip); its end wants the mirror image of that, so a
|
||||
// joint needs a flip exactly when its two readings disagree.
|
||||
if at_end != leaving {
|
||||
flip_odd(&mut d);
|
||||
}
|
||||
if !d.first().is_some_and(|t| t.len() > 0.0) {
|
||||
return Err(bad(cmd, format!("`{id}` has no tangent at `{what}`")));
|
||||
}
|
||||
Ok(d)
|
||||
}
|
||||
|
||||
fn blend(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "sketch.blend_curve";
|
||||
let order = blend_order(p, cmd)?;
|
||||
let (out, info) = edit(s, p, cmd, false, |sk, _| {
|
||||
let pa = req_parg(sk, p, "a", cmd)?.idx().ok_or_else(|| bad(cmd, "`a` must be the end point of a curve"))?;
|
||||
let pb = req_parg(sk, p, "b", cmd)?.idx().ok_or_else(|| bad(cmd, "`b` must be the end point of a curve"))?;
|
||||
@@ -412,10 +475,34 @@ fn blend(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(cmd, "the ends must differ"));
|
||||
}
|
||||
let first_new = sk.points.len();
|
||||
let c1 = sk.add_point(qa + ta * (l / 3.0), None)?;
|
||||
let c2 = sk.add_point(qb + tb * (l / 3.0), None)?;
|
||||
let sp = sk.add_curve(CurveKind::Spline { pts: vec![pa, c1, c2, pb], control: true, degree: 3, periodic: false }, None)?;
|
||||
let cons = vec![add_c(sk, ConstraintKind::Tangent { a: ca, b: sp })?, add_c(sk, ConstraintKind::Tangent { a: cb, b: sp })?];
|
||||
let (sp, cons) = if order <= 1 {
|
||||
let c1 = sk.add_point(qa + ta * (l / 3.0), None)?;
|
||||
let c2 = sk.add_point(qb + tb * (l / 3.0), None)?;
|
||||
let sp = sk.add_curve(CurveKind::Spline { pts: vec![pa, c1, c2, pb], control: true, degree: 3, periodic: false }, None)?;
|
||||
let cons = vec![add_c(sk, ConstraintKind::Tangent { a: ca, b: sp })?, add_c(sk, ConstraintKind::Tangent { a: cb, b: sp })?];
|
||||
(sp, cons)
|
||||
} else {
|
||||
// One Bézier of degree 2·order + 1 whose controls are the Hermite interpolation of the
|
||||
// two references' derivatives, so its 1st…order-th derivatives are theirs at both
|
||||
// joints. Tangency comes from the construction, so it needs no tangent constraints.
|
||||
let da = joint_derivatives(sk, ca, pa, order, true, "a", cmd)?;
|
||||
let db = joint_derivatives(sk, cb, pb, order, false, "b", cmd)?;
|
||||
let mut pts: Vec<usize> = Vec::with_capacity(2 * order + 2);
|
||||
let cps = solidcraft_geom::hermite_bezier(qa, qb, &da, &db)
|
||||
.ok_or_else(|| bad(cmd, "the blend curve could not be built from the derivatives of `a` and `b`"))?;
|
||||
for (i, q) in cps.iter().enumerate() {
|
||||
pts.push(if i == 0 {
|
||||
pa
|
||||
} else if i + 1 == cps.len() {
|
||||
pb
|
||||
} else {
|
||||
sk.add_point(*q, None)?
|
||||
});
|
||||
}
|
||||
let degree = u8::try_from(cps.len().saturating_sub(1)).map_err(|_| bad(cmd, "the blend curve needs too many control points"))?;
|
||||
let sp = sk.add_curve(CurveKind::Spline { pts, control: true, degree, periodic: false }, None)?;
|
||||
(sp, Vec::new())
|
||||
};
|
||||
solve_new_only(sk, first_new);
|
||||
Ok((ids_of(sk, &[sp]), cons))
|
||||
})?;
|
||||
@@ -860,3 +947,391 @@ pub(super) fn solve_new_only(sk: &mut Sketch, first_new: usize) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod blend_tests {
|
||||
use serde_json::{Value, json};
|
||||
use solidcraft_geom::{Seg2, Vec2};
|
||||
use solidcraft_sketch::CurveKind;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
match s.execute(id, &p) {
|
||||
Ok(v) => v,
|
||||
Err(e) => panic!("{id} {p}: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn ids(v: &Value) -> Vec<String> {
|
||||
v.as_array().map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn new_sketch() -> Session {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY"}));
|
||||
s
|
||||
}
|
||||
|
||||
fn sketch(s: &Session) -> solidcraft_sketch::Sketch {
|
||||
let id = s.active_sketch.unwrap();
|
||||
s.model.state().sketch(id).unwrap().sketch.clone()
|
||||
}
|
||||
|
||||
fn factorial(n: usize) -> f64 {
|
||||
(1..=n).fold(1.0, |a, b| a * b as f64)
|
||||
}
|
||||
|
||||
/// The derivatives 1…`order` of exact piece `seg` at its end (`at_end`), from the piece's own
|
||||
/// geometry: what a blend must match, computed here independently of `Seg2::derivatives`.
|
||||
fn piece_derivatives(seg: &Seg2, at_end: bool, order: usize) -> Vec<Vec2> {
|
||||
let t = if at_end { 1.0 } else { 0.0 };
|
||||
let p = seg.point_at(t);
|
||||
let mut d = match *seg {
|
||||
Seg2::Line { a, b } => vec![b - a, Vec2::ZERO, Vec2::ZERO, Vec2::ZERO],
|
||||
Seg2::Arc { center, sweep, .. } => {
|
||||
let (v, s2) = (seg.derivative(t), sweep * sweep);
|
||||
vec![v, (p - center) * -s2, v * -s2, (p - center) * (s2 * s2)]
|
||||
}
|
||||
Seg2::Cubic { p0, p1, p2, p3 } => {
|
||||
let third = (p3 - p2 * 3.0 + p1 * 3.0 - p0) * 6.0;
|
||||
if at_end {
|
||||
vec![(p3 - p2) * 3.0, (p3 - p2 * 2.0 + p1) * 6.0, third, Vec2::ZERO]
|
||||
} else {
|
||||
vec![(p1 - p0) * 3.0, (p0 - p1 * 2.0 + p2) * 6.0, third, Vec2::ZERO]
|
||||
}
|
||||
}
|
||||
Seg2::Conic { a, apex, b, w } => {
|
||||
// The rational quadratic's numerator N and weight D as quadratics in the power
|
||||
// basis; dividing N's series by D's (constant term 1 at both ends) has to give the
|
||||
// Taylor coefficients of the curve.
|
||||
let (n0, n1, n2) = (a, apex * (2.0 * w) - a * 2.0, a - apex * (2.0 * w) + b);
|
||||
let (e1, e2) = (2.0 * (w - 1.0), 2.0 * (1.0 - w));
|
||||
let h = 1e-3;
|
||||
let series = |f: &dyn Fn(f64) -> Vec2| [f(t), (f(t + h) - f(t - h)) / (2.0 * h), (f(t + h) - f(t) * 2.0 + f(t - h)) / (2.0 * h * h)];
|
||||
let n = series(&|x| n0 + n1 * x + n2 * (x * x));
|
||||
let den = [1.0 + e1 * t + e2 * (t * t), e1 + e2 * (2.0 * t), e2];
|
||||
let mut x = vec![n[0] / den[0]];
|
||||
for j in 1..=order {
|
||||
let mut v = n.get(j).copied().unwrap_or(Vec2::ZERO);
|
||||
for i in 1..=j {
|
||||
v -= x[j - i] * den.get(i).copied().unwrap_or(0.0);
|
||||
}
|
||||
x.push(v / den[0]);
|
||||
}
|
||||
x.remove(0);
|
||||
x.into_iter().enumerate().map(|(i, v)| v * factorial(i + 1)).collect()
|
||||
}
|
||||
Seg2::Bezier { .. } => panic!("a test piece is not a high-degree Bézier"),
|
||||
};
|
||||
d.truncate(order);
|
||||
d
|
||||
}
|
||||
|
||||
/// The derivatives 1…`order` the blend's own control polygon carries at an end: the j-th
|
||||
/// difference of the controls, scaled by `n!/(n − j)!` (the Bézier endpoint identity).
|
||||
fn blend_derivatives(ctrl: &[Vec2], at_end: bool, order: usize) -> Vec<Vec2> {
|
||||
let c: Vec<Vec2> = if at_end { ctrl.iter().rev().copied().collect() } else { ctrl.to_vec() };
|
||||
let n = c.len() - 1;
|
||||
let (mut diffs, mut scale) = (c, 1.0);
|
||||
let mut out = Vec::new();
|
||||
for j in 1..=order {
|
||||
diffs = diffs.windows(2).map(|w| w[1] - w[0]).collect();
|
||||
scale *= (n + 1 - j) as f64;
|
||||
out.push(diffs.first().copied().unwrap_or_default() * scale);
|
||||
}
|
||||
if at_end {
|
||||
for (i, v) in out.iter_mut().enumerate() {
|
||||
if i % 2 == 0 {
|
||||
*v = -*v;
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The blend curve's control points, its degree and the one exact piece they make.
|
||||
fn blend_of(s: &Session, id: &str) -> (Vec<Vec2>, usize, Seg2) {
|
||||
let sk = sketch(s);
|
||||
let ci = sk.curve_index(id).unwrap();
|
||||
let ctrl: Vec<Vec2> = sk.curves[ci].kind.point_ids().iter().map(|i| sk.point(*i).unwrap()).collect();
|
||||
let degree = match sk.curves[ci].kind {
|
||||
CurveKind::Spline { degree, .. } => usize::from(degree),
|
||||
ref other => panic!("{other:?}"),
|
||||
};
|
||||
let pieces = sk.exact_pieces(ci);
|
||||
assert_eq!(pieces.len(), 1, "{pieces:?}");
|
||||
(ctrl, degree, pieces[0])
|
||||
}
|
||||
|
||||
/// The reference pair the tests build: a line `(0, 0)`–`(6, 0)` ending at `a` and a three-point
|
||||
/// control spline starting at `b`, so the blend runs out of the first and into the second with
|
||||
/// no reversal at either joint.
|
||||
fn two_references(s: &mut Session) -> (String, String, [Vec2; 4]) {
|
||||
let a = ids(&run(s, "sketch.line", json!({"points": [[0, 0], [6, 0]]}))["curves"])[0].clone();
|
||||
let bctrl = [Vec2::new(20.0, 10.0), Vec2::new(24.0, 14.0), Vec2::new(30.0, 9.0), Vec2::new(34.0, 6.0)];
|
||||
let b = ids(&run(s, "sketch.spline.control_point", json!({"points": [[20, 10], [24, 14], [30, 9], [34, 6]]}))["curves"])[0].clone();
|
||||
(a, b, bctrl)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_curve_matches_both_references_through_the_requested_order() {
|
||||
for order in 1..=4usize {
|
||||
let mut s = new_sketch();
|
||||
let (a, b, bctrl) = two_references(&mut s);
|
||||
let r = run(
|
||||
&mut s,
|
||||
"sketch.blend_curve",
|
||||
json!({
|
||||
"a": format!("{a}.end"),
|
||||
"b": format!("{b}.start"),
|
||||
"continuity": format!("g{order}"),
|
||||
}),
|
||||
);
|
||||
let sp = ids(&r["curves"])[0].clone();
|
||||
let (ctrl, degree, piece) = blend_of(&s, &sp);
|
||||
assert_eq!(degree, 2 * order + 1, "g{order} is one Bézier of degree 2k+1");
|
||||
assert_eq!(ctrl.len(), 2 * order + 2, "g{order} control count");
|
||||
assert!(r["sketch"]["solved"].as_bool().unwrap_or(false), "{r}");
|
||||
assert!(piece.start().dist(Vec2::new(6.0, 0.0)) < 1e-12 && piece.end().dist(bctrl[0]) < 1e-12, "the blend joins `a` and `b`");
|
||||
|
||||
// What each reference supplies at the joint: the line's own derivative at its end (and
|
||||
// nothing higher) and the cubic's at its start.
|
||||
let line = piece_derivatives(&Seg2::Line { a: Vec2::ZERO, b: Vec2::new(6.0, 0.0) }, true, 4);
|
||||
let cubic = piece_derivatives(&Seg2::Cubic { p0: bctrl[0], p1: bctrl[1], p2: bctrl[2], p3: bctrl[3] }, false, 4);
|
||||
let got0 = blend_derivatives(&ctrl, false, 4);
|
||||
let got1 = blend_derivatives(&ctrl, true, 4);
|
||||
// g1 is the tangent construction of the tool: the first derivative is parallel to the
|
||||
// reference's (that is what G1 is), with the tool's own chord-scaled magnitude. g2 and
|
||||
// up match the reference's derivative vectors themselves.
|
||||
let tan_line = line[0].normalized().unwrap();
|
||||
let tan_cubic = cubic[0].normalized().unwrap();
|
||||
assert!(got0[0].cross(tan_line).abs() < 1e-9 && got0[0].dot(tan_line) > 0.0, "g{order} leaves `a` along {tan_line:?}, not {:?}", got0[0]);
|
||||
assert!(
|
||||
got1[0].cross(tan_cubic).abs() < 1e-9 && got1[0].dot(tan_cubic) > 0.0,
|
||||
"g{order} enters `b` along {tan_cubic:?}, not {:?}",
|
||||
got1[0]
|
||||
);
|
||||
for j in 1..order {
|
||||
assert!(got0[j].dist(line[j]) < 1e-9, "g{order} at a, order {}: {:?} vs {:?}", j + 1, got0[j], line[j]);
|
||||
assert!(got1[j].dist(cubic[j]) < 1e-9, "g{order} at b, order {}: {:?} vs {:?}", j + 1, got1[j], cubic[j]);
|
||||
}
|
||||
if order >= 2 {
|
||||
for (got, want) in [(got0[0], line[0]), (got1[0], cubic[0])] {
|
||||
assert!(got.dist(want) < 1e-9, "g{order} matches the reference's own derivative: {got:?} vs {want:?}");
|
||||
}
|
||||
}
|
||||
// The next order up is not met: the line has no derivative there at all, while a blend of
|
||||
// degree 2k+1 has.
|
||||
if order < 4 {
|
||||
let next = got0[order];
|
||||
assert!(next.dist(line[order]) > 1e-6, "g{order} matched one order too many at a: {next:?}");
|
||||
}
|
||||
// Curvature itself (orientation-free, from finite differences of the samples) agrees at
|
||||
// both joints once the order asks for it.
|
||||
if order >= 2 {
|
||||
let curve = |x: f64| piece.point_at(x.clamp(0.0, 1.0));
|
||||
let line_f = |x: f64| Vec2::new(6.0 * x, 0.0);
|
||||
let cubic_f = |x: f64| Seg2::Cubic { p0: bctrl[0], p1: bctrl[1], p2: bctrl[2], p3: bctrl[3] }.point_at(x);
|
||||
let k0 = solidcraft_sketch::end_curvature(&curve, false);
|
||||
let ka = solidcraft_sketch::end_curvature(&line_f, true);
|
||||
let k1 = solidcraft_sketch::end_curvature(&curve, true);
|
||||
let kb = solidcraft_sketch::end_curvature(&cubic_f, false);
|
||||
assert!(k0.dist(ka) < 1e-3, "g{order} curvature at a: {k0:?} vs {ka:?}");
|
||||
assert!(k1.dist(kb) < 1e-3, "g{order} curvature at b: {k1:?} vs {kb:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_curve_g1_is_the_tangent_construction_with_its_constraints() {
|
||||
let mut s = new_sketch();
|
||||
let (a, b, bctrl) = two_references(&mut s);
|
||||
let r = run(&mut s, "sketch.blend_curve", json!({"a": format!("{a}.end"), "b": format!("{b}.start")}));
|
||||
let sp = ids(&r["curves"])[0].clone();
|
||||
let (ctrl, degree, _) = blend_of(&s, &sp);
|
||||
assert_eq!(degree, 3, "the default is the cubic tangent spline");
|
||||
let (qa, qb) = (Vec2::new(6.0, 0.0), bctrl[0]);
|
||||
let l = qa.dist(qb);
|
||||
let tb = (qb - bctrl[1]).normalized().unwrap();
|
||||
let want = [qa, qa + Vec2::X * (l / 3.0), qb + tb * (l / 3.0), qb];
|
||||
for (i, q) in want.iter().enumerate() {
|
||||
assert!(ctrl[i].dist(*q) < 1e-9, "g1 control {i}: {:?} vs {q:?}", ctrl[i]);
|
||||
}
|
||||
assert_eq!(ids(&r["constraints"]).len(), 2, "the two tangents are kept: {r}");
|
||||
// g2…g4 meet the derivatives by construction and need no constraint of their own.
|
||||
for order in 2..=4usize {
|
||||
let mut s = new_sketch();
|
||||
let (a, b, _) = two_references(&mut s);
|
||||
let r = run(
|
||||
&mut s,
|
||||
"sketch.blend_curve",
|
||||
json!({
|
||||
"a": format!("{a}.end"),
|
||||
"b": format!("{b}.start"),
|
||||
"continuity": format!("g{order}"),
|
||||
}),
|
||||
);
|
||||
assert!(ids(&r["constraints"]).is_empty(), "g{order}: {r}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_curve_between_two_lines_is_curvature_free_to_the_requested_order() {
|
||||
// Two lines meeting at a right angle: from G2 on, the blend has the lines' own zero
|
||||
// curvature at both joints (a corner with no curvature jump).
|
||||
for order in 2..=4usize {
|
||||
let mut s = new_sketch();
|
||||
let a = ids(&run(&mut s, "sketch.line", json!({"points": [[0, 0], [2, 0]]}))["curves"])[0].clone();
|
||||
let b = ids(&run(&mut s, "sketch.line", json!({"points": [[20, 10], [20, 12]]}))["curves"])[0].clone();
|
||||
let r = run(
|
||||
&mut s,
|
||||
"sketch.blend_curve",
|
||||
json!({
|
||||
"a": format!("{a}.end"),
|
||||
"b": format!("{b}.start"),
|
||||
"continuity": format!("g{order}"),
|
||||
}),
|
||||
);
|
||||
let sp = ids(&r["curves"])[0].clone();
|
||||
let (ctrl, degree, piece) = blend_of(&s, &sp);
|
||||
assert_eq!(degree, 2 * order + 1);
|
||||
let got0 = blend_derivatives(&ctrl, false, 4);
|
||||
let got1 = blend_derivatives(&ctrl, true, 4);
|
||||
assert!(got0[0].dist(Vec2::new(2.0, 0.0)) < 1e-12, "g{order} leaves `a` along +x: {:?}", got0[0]);
|
||||
assert!(got1[0].dist(Vec2::new(0.0, 2.0)) < 1e-12, "g{order} enters `b` along +y: {:?}", got1[0]);
|
||||
for j in 1..order {
|
||||
assert!(got0[j].len() < 1e-12, "g{order}: a line has no order-{} derivative", j + 1);
|
||||
assert!(got1[j].len() < 1e-12, "g{order}: a line has no order-{} derivative", j + 1);
|
||||
}
|
||||
if order < 4 {
|
||||
assert!(got0[order].len() > 1e-6, "g{order}: the blend curves, the line does not");
|
||||
}
|
||||
assert!(piece.start().dist(Vec2::new(2.0, 0.0)) < 1e-12 && piece.end().dist(Vec2::new(20.0, 10.0)) < 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_curve_matches_a_conic_reference() {
|
||||
for order in 2..=4usize {
|
||||
let mut s = new_sketch();
|
||||
let a = ids(&run(&mut s, "sketch.line", json!({"points": [[0, 0], [2, 0]]}))["curves"])[0].clone();
|
||||
let b = ids(&run(&mut s, "sketch.conic", json!({"start": [20, 10], "apex": [26, 16], "end": [30, 10], "rho": 0.7}))["curves"])[0].clone();
|
||||
let r = run(
|
||||
&mut s,
|
||||
"sketch.blend_curve",
|
||||
json!({
|
||||
"a": format!("{a}.end"),
|
||||
"b": format!("{b}.start"),
|
||||
"continuity": format!("g{order}"),
|
||||
}),
|
||||
);
|
||||
let sp = ids(&r["curves"])[0].clone();
|
||||
let (ctrl, degree, _) = blend_of(&s, &sp);
|
||||
assert_eq!(degree, 2 * order + 1);
|
||||
// The conic's own derivatives at its start: `w` comes from the sketch's `rho`, and the
|
||||
// series division in `piece_derivatives` is the expectation.
|
||||
let w = 0.7 / (1.0 - 0.7);
|
||||
let conic = Seg2::Conic { a: Vec2::new(20.0, 10.0), apex: Vec2::new(26.0, 16.0), b: Vec2::new(30.0, 10.0), w };
|
||||
let want = piece_derivatives(&conic, false, order);
|
||||
let got = blend_derivatives(&ctrl, true, order);
|
||||
for j in 0..order {
|
||||
assert!(got[j].dist(want[j]) < 1e-8 * want[j].len().max(1.0), "g{order} order {}: {:?} vs {:?}", j + 1, got[j], want[j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_curve_refuses_hostile_orders_and_degenerate_references() {
|
||||
let mut s = new_sketch();
|
||||
let (a, b, _) = two_references(&mut s);
|
||||
let ends = json!({"a": format!("{a}.end"), "b": format!("{b}.start")});
|
||||
for (order, want) in [("g0", true), ("g9", true), ("G9", true), ("curvature", true), ("", false), ("g2", false), ("G4", false)] {
|
||||
let mut p = ends.clone();
|
||||
p["continuity"] = json!(order);
|
||||
let r = s.execute("sketch.blend_curve", &p);
|
||||
assert_eq!(r.is_err(), want, "continuity {order:?}: {r:?}");
|
||||
assert!(r.is_ok() || r.unwrap_err().to_string().contains("continuity"), "continuity {order:?} needs a clear error");
|
||||
}
|
||||
let mut numbered = ends.clone();
|
||||
numbered["continuity"] = json!(3);
|
||||
assert!(s.execute("sketch.blend_curve", &numbered).is_err(), "a number is not a continuity");
|
||||
// A point that is not an end of a curve, and the same end twice.
|
||||
let p = ids(&run(&mut s, "sketch.point", json!({"point": [50, 50]}))["created"]["points"])[0].clone();
|
||||
let e = s.execute("sketch.blend_curve", &json!({"a": p, "b": format!("{b}.start")})).unwrap_err().to_string();
|
||||
assert!(e.contains("no curve ends at `a`"), "{e}");
|
||||
let e = s.execute("sketch.blend_curve", &json!({"a": format!("{a}.end"), "b": format!("{a}.end")})).unwrap_err().to_string();
|
||||
assert!(e.contains("ends must differ"), "{e}");
|
||||
// The helper behind the command refuses a corrupt (non-finite) reference and a reference
|
||||
// with no tangent at all, never guessing at them.
|
||||
let mut broken = solidcraft_sketch::Sketch::new();
|
||||
let p0 = broken.add_point(Vec2::new(1.0, 1.0), None).unwrap();
|
||||
let p1 = broken.add_point(Vec2::ZERO, None).unwrap();
|
||||
let l = broken.add_curve(CurveKind::Spline { pts: vec![p1, p0], control: true, degree: 1, periodic: false }, None).unwrap();
|
||||
broken.points[p0].pos = Vec2::new(f64::NAN, 4.0);
|
||||
assert!(super::joint_derivatives(&broken, l, p1, 2, true, "a", "sketch.blend_curve").is_err(), "non-finite geometry");
|
||||
let mut flat = solidcraft_sketch::Sketch::new();
|
||||
let q0 = flat.add_point(Vec2::new(3.0, 3.0), None).unwrap();
|
||||
let q1 = flat.add_point(Vec2::new(3.0, 3.0), None).unwrap();
|
||||
let d = flat.add_curve(CurveKind::Spline { pts: vec![q0, q1], control: true, degree: 1, periodic: false }, None).unwrap();
|
||||
let e = super::joint_derivatives(&flat, d, q0, 2, true, "a", "sketch.blend_curve").unwrap_err().to_string();
|
||||
assert!(e.contains("no tangent"), "{e}");
|
||||
assert!(solidcraft_geom::hermite_bezier(Vec2::ZERO, Vec2::X, &[Vec2::Y; 5], &[Vec2::Y; 5]).is_none(), "no order above g4");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_curve_with_g4_closes_a_profile_that_measures_exactly() {
|
||||
// A quarter-turn blend from (2, 0) into a line at (20, 10), closed by the chord between its
|
||||
// ends: the region's area comes from the degree-9 curve, not from its chord.
|
||||
let mut s = new_sketch();
|
||||
let a = ids(&run(&mut s, "sketch.line", json!({"points": [[0, 0], [2, 0]]}))["curves"])[0].clone();
|
||||
let b = ids(&run(&mut s, "sketch.line", json!({"points": [[20, 10], [20, 12]]}))["curves"])[0].clone();
|
||||
let r = run(
|
||||
&mut s,
|
||||
"sketch.blend_curve",
|
||||
json!({
|
||||
"a": format!("{a}.end"),
|
||||
"b": format!("{b}.start"),
|
||||
"continuity": "g4",
|
||||
}),
|
||||
);
|
||||
let sp = ids(&r["curves"])[0].clone();
|
||||
let (ctrl, degree, piece) = blend_of(&s, &sp);
|
||||
assert_eq!(degree, 9, "G4 is one degree-9 Bézier");
|
||||
assert_eq!(ctrl.len(), 10);
|
||||
// The command still reports what it added, with stable ids: ten controls of which the two
|
||||
// joints are the references' own points, so eight new points, and no new constraint.
|
||||
assert_eq!(ids(&r["created"]["curves"]), vec![sp.clone()], "{r}");
|
||||
assert_eq!(ids(&r["created"]["points"]).len(), 8, "{r}");
|
||||
assert!(ids(&r["created"]["constraints"]).is_empty() && ids(&r["created"]["dimensions"]).is_empty(), "{r}");
|
||||
run(&mut s, "sketch.line", json!({"points": [[20, 10], [2, 0]], "id": "chord"}));
|
||||
// Drop the two references: what is left is the blend and its chord, one closed region.
|
||||
run(&mut s, "sketch.delete", json!({"entities": [a, b]}));
|
||||
let id = s.active_sketch.unwrap();
|
||||
let state = s.model.state();
|
||||
let profiles = &state.sketch(id).unwrap().profiles;
|
||||
assert_eq!(profiles.len(), 1, "the blend and the chord close one region");
|
||||
let area = profiles[0].area;
|
||||
// A fine sampling of the exact piece plus the straight chord reproduces the area; the chord
|
||||
// alone (what a polyline approximation would give) is exactly zero.
|
||||
let n = 20_000;
|
||||
let mut sampled = 0.0;
|
||||
for i in 0..n {
|
||||
let (t0, t1) = (i as f64 / n as f64, (i + 1) as f64 / n as f64);
|
||||
sampled += 0.5 * piece.point_at(t0).cross(piece.point_at(t1));
|
||||
}
|
||||
// The chord back from (20, 10) to (2, 0) contributes its own shoelace term; together they
|
||||
// are the region.
|
||||
sampled += 0.5 * Vec2::new(20.0, 10.0).cross(Vec2::new(2.0, 0.0));
|
||||
assert!((area - sampled.abs()).abs() < 1e-4, "{area} vs {sampled}");
|
||||
assert!(area > 1e-2, "the blend curves away from the chord: {area}");
|
||||
// And the degree-9 profile still extrudes to its area times the height (the kernel's
|
||||
// volume of a free-form body is a numerical integration, so this is the same 2e-4 the
|
||||
// neighbouring free-form extrusion test allows).
|
||||
run(&mut s, "solid.extrude", json!({"distance": 5}));
|
||||
let m = run(&mut s, "inspect.measure", json!({}));
|
||||
let volume = m["total"]["volume_mm3"].as_f64().unwrap_or(f64::NAN);
|
||||
assert!((volume - area * 5.0).abs() / (area * 5.0) < 2e-4, "volume {volume} vs {}", area * 5.0);
|
||||
assert!(m["bodies"][0]["faces"].as_u64().unwrap_or(0) >= 3, "a solid with the blend as a side: {m}");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user