Merge pull request #2703 from 2ez4gcx/fix/spline-file-tangent-length

SPLINE: a file's end tangents count with their length, as in AutoCAD 2024
This commit is contained in:
FredApps authored and GitHub committed 2026-11-26 10:09:24 +01:00
commit b4ad0f3800
3 files changed
+234 -31

No files matched your search

+163 -29
View File
@@ -67,10 +67,12 @@ impl KnotParam {
pub struct FitOptions {
#[serde(default)]
pub knots: KnotParam,
/// Unit tangent direction at the first fit point; `None` lets the end follow the points.
/// Tangent at the first fit point; `None` lets the end follow the points. SPLINE, SPLINEDIT
/// and the JSON options give a unit direction; one read from a file keeps its length through
/// refits and transforms ([`Spline::fit_with_end_derivatives`]).
#[serde(default)]
pub start_tangent: Option<Vec2>,
/// Unit tangent direction at the last fit point.
/// Tangent at the last fit point, as the start one.
#[serde(default)]
pub end_tangent: Option<Vec2>,
/// Largest allowed distance between the curve and a fit point; 0 passes through them.
@@ -79,14 +81,22 @@ pub struct FitOptions {
}
impl FitOptions {
/// Normalised tangents (zero or non-finite directions dropped) and a finite, non-negative
/// tolerance: what a spline stores.
/// Normalised tangents (non-finite directions and those too short to normalise dropped) and a
/// finite, non-negative tolerance: what [`Spline::fit_with`] stores.
pub fn sanitized(self) -> FitOptions {
let dir = |t: Option<Vec2>| t.filter(|v| v.x.is_finite() && v.y.is_finite() && v.len() > 1e-12).map(Vec2::normalized);
let o = self.sanitized_keeping_length();
// `normalized` gives zero for a direction too short to scale to a unit.
let unit = |t: Option<Vec2>| t.map(Vec2::normalized).filter(|d| d.len() > 0.5);
FitOptions { start_tangent: unit(o.start_tangent), end_tangent: unit(o.end_tangent), ..o }
}
/// As [`FitOptions::sanitized`], but the tangents keep their length.
pub fn sanitized_keeping_length(self) -> FitOptions {
let valid = |t: Option<Vec2>| t.filter(|v| v.x.is_finite() && v.y.is_finite() && v.len() > 1e-12);
FitOptions {
knots: self.knots,
start_tangent: dir(self.start_tangent),
end_tangent: dir(self.end_tangent),
start_tangent: valid(self.start_tangent),
end_tangent: valid(self.end_tangent),
tolerance: if self.tolerance.is_finite() { self.tolerance.max(0.0) } else { 0.0 },
}
}
@@ -108,26 +118,23 @@ impl Spline {
/// curve passes through it with a corner (a knot of full multiplicity) and the pieces on
/// either side are fitted on their own.
pub fn fit_with(fit: &[Vec2], closed: bool, opts: FitOptions) -> Spline {
let opts = opts.sanitized();
let kinked = if fit.len() <= MAX_KINK_POINTS { kinked_fit(fit, closed, opts) } else { None };
let mut s = if let Some(s) = kinked {
s
} else {
// Repeats at the ends of an open curve are no corners: fit without them.
let (pts, _) = kinks(fit, false);
let mut s = if closed { closed_fit(&pts, opts.knots, opts.tolerance) } else { open_fit(&pts, opts) };
if pts.len() != fit.len() && !closed {
s.fit = fit.to_vec();
}
s
};
s.fit_opts = if closed { FitOptions { start_tangent: None, end_tangent: None, ..opts } } else { opts };
s
fit_sanitized(fit, closed, opts.sanitized())
}
/// As [`Spline::fit_with`], but an end tangent is the end derivative itself, length included
/// (per unit of chord with chord-length knots), as AutoCAD 2024 rebuilds a SPLINE stored with
/// fit data only (DXF 12/13): with 12 = (0, 3) the second control point is three times as far
/// from the first as with (0, 1). `fit_with`, behind SPLINE and the JSON options, takes
/// tangents as directions.
pub fn fit_with_end_derivatives(fit: &[Vec2], closed: bool, opts: FitOptions) -> Spline {
fit_sanitized(fit, closed, opts.sanitized_keeping_length())
}
/// Rebuild from new fit points with this spline's knot parametrisation, tangents and tolerance.
/// The tangents count as stored, so one read from a file keeps its length, as in AutoCAD's
/// SPLINEDIT Fit data Move.
pub fn refit(&self, fit: &[Vec2], closed: bool) -> Spline {
Spline::fit_with(fit, closed, self.fit_opts)
Spline::fit_with_end_derivatives(fit, closed, self.fit_opts)
}
/// Which knot parametrisation produced this spline's knots from its fit points (DXF files
@@ -190,12 +197,26 @@ impl Spline {
.unwrap_or(KnotParam::Chord)
}
/// Apply an affine map to the control and fit points and turn the end tangents with it.
/// Apply an affine map to the control and fit points and turn the end tangents with it. A
/// tangent keeps its length, as in AutoCAD, where SCALE 2 leaves 12 = (0, 3) as it is. A map
/// that flattens a tangent's direction (to under EPS of the map's largest axis scale) drops it.
pub fn transform(&mut self, m: &Mat3) {
for c in self.control.iter_mut().chain(self.fit.iter_mut()) {
*c = m.apply(*c);
}
let turn = |t: Option<Vec2>| t.map(|v| m.apply_vec(v).normalized()).filter(|v| v.len() > 0.5);
// The map's largest axis scale: a direction it shrinks to under EPS of that is flattened.
// Not `scale_factor`, which is 0 for a singular map and would keep rounding noise.
let scale = Vec2::new(m.a, m.b).len().max(Vec2::new(m.c, m.d).len());
let turn = |t: Option<Vec2>| {
t.and_then(|v| {
let w = m.apply_vec(v);
let (lv, lw) = (v.len(), w.len());
// Scaled by lengths, not through `normalized`, which zeroes a short tangent. A map
// that flattens the tangent's direction drops it; an invertible uniform scale,
// however small, does not.
(lw.is_finite() && lw > crate::EPS * scale * lv).then(|| w / lw * lv)
})
};
self.fit_opts.start_tangent = turn(self.fit_opts.start_tangent);
self.fit_opts.end_tangent = turn(self.fit_opts.end_tangent);
}
@@ -224,6 +245,24 @@ fn chord_length(pts: &[Vec2]) -> f64 {
pts.windows(2).map(|w| w.first().zip(w.get(1)).map_or(0.0, |(a, b)| a.dist(*b))).sum()
}
/// [`Spline::fit_with`] with `opts` already sanitized.
fn fit_sanitized(fit: &[Vec2], closed: bool, opts: FitOptions) -> Spline {
let kinked = if fit.len() <= MAX_KINK_POINTS { kinked_fit(fit, closed, opts) } else { None };
let mut s = if let Some(s) = kinked {
s
} else {
// Repeats at the ends of an open curve are no corners: fit without them.
let (pts, _) = kinks(fit, false);
let mut s = if closed { closed_fit(&pts, opts.knots, opts.tolerance) } else { open_fit(&pts, opts) };
if pts.len() != fit.len() && !closed {
s.fit = fit.to_vec();
}
s
};
s.fit_opts = if closed { FitOptions { start_tangent: None, end_tangent: None, ..opts } } else { opts };
s
}
fn open_fit(fit: &[Vec2], opts: FitOptions) -> Spline {
let n = fit.len();
let tangents = opts.start_tangent.is_some() || opts.end_tangent.is_some();
@@ -240,7 +279,8 @@ fn open_fit(fit: &[Vec2], opts: FitOptions) -> Spline {
return s;
}
let u = params(fit, opts.knots, false);
// Tangents are directions; the derivative's length is the curve length in parameter space.
// A tangent is the derivative per unit of chord (a unit direction unless read from a file):
// per unit of the normalised parameter it is that times the chord length.
let len = chord_length(fit).max(1e-12);
let d0 = opts.start_tangent.map(|t| t * len);
let d1 = opts.end_tangent.map(|t| t * len);
@@ -269,9 +309,9 @@ fn open_fit(fit: &[Vec2], opts: FitOptions) -> Spline {
/// AutoCAD 2024's cubic through fit points with chord-length parameters, as it builds a fit-point
/// spline: the parameters are the running chord length, not normalised, and they are the interior
/// knots themselves; two control points more than fit points meet the end conditions. An end with
/// a tangent (a unit direction) has it as its first derivative, so its length is one per unit of
/// chord; an end without one has no curvature (second derivative 0). `None` for fewer than two
/// points or two in the same place.
/// a tangent has it as its first derivative, length included (one per unit of chord for a unit
/// direction); an end without one has no curvature (second derivative 0). `None` for fewer than
/// two points or two in the same place.
fn chord_interpolate(fit: &[Vec2], d0: Option<Vec2>, d1: Option<Vec2>) -> Option<Spline> {
let n = fit.len();
if n < 2 {
@@ -1086,6 +1126,19 @@ mod tests {
}
let tight: Vec<Vec2> = (0..8).map(|i| Vec2::new(f64::from(i) * 1e-13, 0.0)).collect();
let _ = Spline::fit_with(&tight, true, FitOptions { tolerance: 1.0, ..FitOptions::default() });
// A file's tangent keeps its length, however extreme.
let kept = Spline::fit_with_end_derivatives(&fit, false, bad);
assert!(kept.is_valid() && kept.fit_opts.start_tangent.is_none() && kept.fit_opts.end_tangent.is_none());
for len in [1e-11, 1e150, 1e308, f64::MAX] {
for knots in KnotParam::ALL {
for tolerance in [0.0, 0.5] {
let t = Some(Vec2::new(len, -len));
let mut s = Spline::fit_with_end_derivatives(&fit, false, FitOptions { knots, start_tangent: t, end_tangent: t, tolerance });
s.transform(&Mat3::scale(2.0, 0.5));
let _ = s.refit(&fit, false);
}
}
}
}
/// Above the interpolation cap the fit points become control points instead of a dense
@@ -1122,6 +1175,87 @@ mod tests {
s.transform(&Mat3::rotate(std::f64::consts::FRAC_PI_2));
assert!(s.fit_opts.start_tangent.is_some_and(|t| t.near(Vec2::Y, 1e-12)));
}
#[test]
fn a_stored_tangent_keeps_its_length_through_edits_as_in_autocad() {
// AutoCAD 2024 (accoreconsole) on a SPLINE stored with these fit points and 12 = (0, 3).
let fit = [Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(8.0, 2.0), Vec2::new(12.0, 1.0), Vec2::new(15.0, 4.0)];
let t0 = Some(Vec2::new(0.0, 3.0));
let s = Spline::fit_with_end_derivatives(&fit, false, FitOptions { start_tangent: t0, ..FitOptions::default() });
// SPLINEDIT Fit data Move of the third fit point to (8, 3) refits with (0, 3) as stored.
let moved = [Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(8.0, 3.0), Vec2::new(12.0, 1.0), Vec2::new(15.0, 4.0)];
let r = s.refit(&moved, false);
let autocad = [
(0.0, 0.0),
(0.0, 4.0),
(5.412665758603298, -3.5553537661153),
(7.3671281655678, 5.7160776616114),
(12.24746922455167, -0.8468238208691),
(14.09874022239649, 2.4130068961106),
(15.0, 4.0),
];
assert_eq!(r.control.len(), autocad.len());
for (c, (x, y)) in r.control.iter().zip(autocad) {
assert!(c.near(Vec2::new(x, y), 1e-9), "{c:?} vs ({x}, {y})");
}
assert_eq!(r.fit_opts.start_tangent, t0);
// MOVE, ROTATE 90, SCALE 2 and MIRROR about y = x turn 12 and keep its length, so a refit
// of the moved fit points gives the moved curve.
for (m, t) in [
(Mat3::translate(Vec2::new(10.0, 0.0)), Vec2::new(0.0, 3.0)),
(Mat3::rotate(std::f64::consts::FRAC_PI_2), Vec2::new(-3.0, 0.0)),
(Mat3::scale(2.0, 2.0), Vec2::new(0.0, 3.0)),
(Mat3::mirror(Vec2::ZERO, Vec2::new(1.0, 1.0)), Vec2::new(3.0, 0.0)),
] {
let mut e = s.clone();
e.transform(&m);
assert!(e.fit_opts.start_tangent.is_some_and(|v| v.near(t, 1e-12)), "{:?} vs {t:?}", e.fit_opts.start_tangent);
let again = e.refit(&e.fit, false);
assert!(again.control.iter().zip(&e.control).all(|(a, b)| a.near(*b, 1e-9)), "{:?} vs {:?}", again.control, e.control);
}
}
#[test]
fn short_tangents_are_no_zero_directions() {
let fit = pts();
// A direction too short to scale to a unit is no tangent, not a zero one.
let short = Some(Vec2::new(0.0, 1e-10));
let s = Spline::fit_with(&fit, false, FitOptions { start_tangent: short, end_tangent: short, ..FitOptions::default() });
assert_eq!((s.fit_opts.start_tangent, s.fit_opts.end_tangent), (None, None));
// A file's short tangent is kept, and a transform turns it rather than dropping it.
let mut f = Spline::fit_with_end_derivatives(&fit, false, FitOptions { start_tangent: short, ..FitOptions::default() });
assert_eq!(f.fit_opts.start_tangent, short);
f.transform(&Mat3::rotate(std::f64::consts::FRAC_PI_2));
assert!(f.fit_opts.start_tangent.is_some_and(|t| t.near(Vec2::new(-1e-10, 0.0), 1e-24)), "{:?}", f.fit_opts.start_tangent);
// A map that flattens its direction drops it.
f.transform(&Mat3::scale(0.0, 1.0));
assert_eq!(f.fit_opts.start_tangent, None);
}
#[test]
fn a_small_uniform_scale_keeps_the_tangent_and_a_singular_map_drops_it() {
let fit = pts();
let t = Some(Vec2::new(100.0, 0.0));
let mut s = Spline::fit_with_end_derivatives(&fit, false, FitOptions { start_tangent: t, ..FitOptions::default() });
// Invertible, however small: the tangent stays, with its length.
s.transform(&Mat3::scale(1e-10, 1e-10));
assert!(s.fit_opts.start_tangent.is_some_and(|v| v.near(Vec2::new(100.0, 0.0), 1e-9)), "{:?}", s.fit_opts.start_tangent);
// A singular map that flattens the direction to rounding noise (0.1 + 0.2 - 0.3) drops it.
let flat = Some(Vec2::new(0.1 + 0.2, -0.3));
let mut s = Spline::fit_with_end_derivatives(&fit, false, FitOptions { start_tangent: flat, ..FitOptions::default() });
s.transform(&Mat3 { a: 1.0, b: 1.0, c: 1.0, d: 1.0, e: 0.0, f: 0.0 });
assert_eq!(s.fit_opts.start_tangent, None);
// So does one that squashes it to under 1e-9 of its largest axis scale, along either axis.
for (t, m) in [(Vec2::new(0.0, 3.0), Mat3::scale(1.0, 1e-12)), (Vec2::new(3.0, 0.0), Mat3::scale(1e-12, 1.0))] {
let mut s = Spline::fit_with_end_derivatives(&fit, false, FitOptions { start_tangent: Some(t), ..FitOptions::default() });
s.transform(&m);
assert_eq!(s.fit_opts.start_tangent, None, "{t:?}");
}
// A turned length that overflows gives no tangent rather than NaN.
let mut s = Spline::fit_with_end_derivatives(&fit, false, FitOptions { start_tangent: Some(Vec2::new(1e10, 0.0)), ..FitOptions::default() });
s.transform(&Mat3::scale(1e300, 1e300));
assert_eq!(s.fit_opts.start_tangent, None);
}
}
#[cfg(test)]
+3 -2
View File
@@ -108,13 +108,14 @@ fn spline(t: &T) -> Spline {
let weights = t.all_f(41);
let fit = t.pts(11);
let tangent = |c: i32| t.f(c).map(|_| t.p(c).xy());
// AutoCAD takes a 12/13 tangent with its length, and writes it back as it read it.
let fit_opts =
cadcraft_geom::FitOptions { knots: Default::default(), start_tangent: tangent(12), end_tangent: tangent(13), tolerance: t.fd(44, 0.0) }
.sanitized();
.sanitized_keeping_length();
let closed = t.i(70).unwrap_or(0) & 1 != 0;
let mut sp = Spline { degree, knots, control, weights, fit: fit.clone(), closed, fit_opts };
if !sp.is_valid() && fit.len() >= 2 {
sp = Spline::fit_with(&fit, sp.closed, fit_opts);
sp = Spline::fit_with_end_derivatives(&fit, sp.closed, fit_opts);
} else if !sp.is_valid() && sp.control.len() >= 2 {
sp = Spline::from_control(sp.control.clone(), degree);
} else if fit.len() >= 3 {
+68
View File
@@ -68,3 +68,71 @@ fn fit_data_is_written_with_the_documented_groups() {
// derivative, as AutoCAD 2024 builds it.
assert!(r.is_valid() && r.fit_opts.start_tangent == Some(Vec2::Y) && r.control.len() == 5);
}
/// A SPLINE stored with fit points and end tangents only.
fn fit_only_dxf(fit: &[(f64, f64)], start: Option<(f64, f64)>, end: Option<(f64, f64)>) -> String {
let mut s =
format!("0\r\nSECTION\r\n2\r\nENTITIES\r\n0\r\nSPLINE\r\n8\r\n0\r\n100\r\nAcDbSpline\r\n70\r\n8\r\n71\r\n3\r\n74\r\n{}\r\n", fit.len());
for (code, t) in [(12, start), (13, end)] {
if let Some((x, y)) = t {
s += &format!("{code}\r\n{x:?}\r\n{}\r\n{y:?}\r\n{}\r\n0.0\r\n", code + 10, code + 20);
}
}
for (x, y) in fit {
s += &format!("11\r\n{x:?}\r\n21\r\n{y:?}\r\n31\r\n0.0\r\n");
}
s + "0\r\nENDSEC\r\n0\r\nEOF\r\n"
}
#[test]
fn a_fit_only_spline_takes_its_end_tangents_with_their_length() {
// AutoCAD 2024 (accoreconsole, entget of the spline it builds): each stored tangent is the end
// derivative as it stands, so 12 = (0, 3) is not 12 = (0, 1), and 13 = (1, -1) is not a unit.
let fit = [(0.0, 0.0), (4.0, 0.0), (8.0, 2.0), (12.0, 1.0), (15.0, 4.0)];
let total = 16.83788226773652;
let knots = [0.0, 0.0, 0.0, 0.0, 4.0, 8.47213595499958, 12.59524158061724, total, total, total, total];
let cases = [
(
Some((0.0, 3.0)),
None,
[
(0.0, 0.0),
(0.0, 4.0),
(5.032653247327764, -2.9587578599554),
(7.49793879823205, 3.8423576404002),
(12.40378970003823, -0.4300472739512),
(14.12639202373297, 2.5093177413937),
(15.0, 4.0),
],
),
(
Some((0.0, 2.0)),
Some((1.0, -1.0)),
[
(0.0, 0.0),
(0.0, 2.6666666666666),
(5.051273572432346, -2.3615552390813),
(7.426977592306234, 4.0442234834397),
(12.64672696003663, -1.6844325426585),
(13.5857864376269, 5.4142135623731),
(15.0, 4.0),
],
),
];
let v = |t: Option<(f64, f64)>| t.map(|(x, y)| Vec2::new(x, y));
for (start, end, control) in cases {
let back = cadcraft_io::read(fit_only_dxf(&fit, start, end).as_bytes(), "c.dxf").unwrap();
let Some(EntityKind::Spline(r)) = back.model.iter().map(|e| e.kind.clone()).next() else { panic!("no spline") };
assert_eq!(r.knots.len(), knots.len());
assert!(r.knots.iter().zip(knots).all(|(a, b)| (a - b).abs() < 1e-9), "{:?}", r.knots);
assert_eq!(r.control.len(), control.len());
for (c, (x, y)) in r.control.iter().zip(control) {
assert!(c.near(Vec2::new(x, y), 1e-9), "{start:?} {end:?}: {c:?} vs ({x}, {y})");
}
// The tangents are kept as stored, and written back so.
assert_eq!((r.fit_opts.start_tangent, r.fit_opts.end_tangent), (v(start), v(end)));
let again = roundtrip(&r);
assert_eq!((again.fit_opts.start_tangent, again.fit_opts.end_tangent), (v(start), v(end)));
assert!(again.control.iter().zip(&r.control).all(|(a, b)| a.near(*b, 1e-12)));
}
}