Merge remote-tracking branch 'origin/main' into feat/profiles-by-curve-ids
# Conflicts: # crates/doc/src/lib.rs # crates/sketch/src/lib.rs
This commit is contained in:
commit
184e301c46
180 files changed
+29315
-1568
No files matched your search
@@ -168,6 +168,64 @@ pub fn fit_beziers(p: &[Vec2]) -> Vec<[Vec2; 4]> {
|
||||
fit_spans(p).into_iter().map(|(p0, p1, t0, t1)| [p0, p0 + t0 / 3.0, p1 - t1 / 3.0, p1]).collect()
|
||||
}
|
||||
|
||||
/// Fit pieces in the explicitly selected interpolation mode.
|
||||
pub fn fit_beziers_mode(p: &[Vec2], periodic: bool) -> crate::model::Result<Vec<[Vec2; 4]>> {
|
||||
if periodic { crate::periodic_beziers(p) } else { Ok(fit_beziers(p)) }
|
||||
}
|
||||
pub fn spline_point_mode(p: &[Vec2], control: bool, degree: u8, periodic: bool, t: f64) -> Vec2 {
|
||||
if !periodic {
|
||||
return spline_point(p, control, degree, t);
|
||||
}
|
||||
let Ok(pieces) = crate::periodic_beziers(p) else {
|
||||
return p.first().copied().unwrap_or_default();
|
||||
};
|
||||
let lengths: Vec<f64> = p.windows(2).map(|p| p[0].dist(p[1])).collect();
|
||||
let total = lengths.iter().sum::<f64>();
|
||||
let mut remaining = t.clamp(0.0, 1.0) * total;
|
||||
let mut i = 0;
|
||||
while i + 1 < pieces.len() && remaining > lengths[i] {
|
||||
remaining -= lengths[i];
|
||||
i += 1;
|
||||
}
|
||||
let Some([a, b, c, d]) = pieces.get(i).copied() else {
|
||||
return Vec2::ZERO;
|
||||
};
|
||||
let t = (remaining / lengths[i]).clamp(0.0, 1.0);
|
||||
a * (1.0 - t).powi(3) + b * (3.0 * t * (1.0 - t).powi(2)) + c * (3.0 * t * t * (1.0 - t)) + d * t.powi(3)
|
||||
}
|
||||
pub fn spline_polyline_mode(p: &[Vec2], control: bool, degree: u8, periodic: bool) -> Vec<Vec2> {
|
||||
if !periodic {
|
||||
return spline_polyline(p, control, degree);
|
||||
}
|
||||
let Ok(pieces) = crate::periodic_beziers(p) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut out = Vec::with_capacity(pieces.len() * SPAN_SAMPLES + 1);
|
||||
for [a, b, c, d] in pieces {
|
||||
for i in 0..SPAN_SAMPLES {
|
||||
let t = i as f64 / SPAN_SAMPLES as f64;
|
||||
out.push(a * (1.0 - t).powi(3) + b * (3.0 * t * (1.0 - t).powi(2)) + c * (3.0 * t * t * (1.0 - t)) + d * t.powi(3));
|
||||
}
|
||||
}
|
||||
if let Some(first) = p.first() {
|
||||
out.push(*first);
|
||||
}
|
||||
out
|
||||
}
|
||||
pub fn spline_end_tangent_mode(p: &[Vec2], control: bool, periodic: bool, at_end: bool) -> Option<Vec2> {
|
||||
if !periodic {
|
||||
return spline_end_tangent(p, control, at_end);
|
||||
}
|
||||
let pieces = crate::periodic_beziers(p).ok()?;
|
||||
if at_end {
|
||||
let c = pieces.last()?;
|
||||
(c[3] - c[2]).normalized()
|
||||
} else {
|
||||
let c = pieces.first()?;
|
||||
(c[1] - c[0]).normalized()
|
||||
}
|
||||
}
|
||||
|
||||
/// The Bézier pieces (each `degree + 1` points) of the clamped uniform B-spline over `ctrl`
|
||||
/// (Boehm knot insertion until every interior knot has multiplicity `degree`).
|
||||
pub fn bspline_beziers(ctrl: &[Vec2], degree: usize) -> Vec<Vec<Vec2>> {
|
||||
|
||||
@@ -59,6 +59,26 @@ pub fn dim_frame(sk: &Sketch, k: &ConstraintKind) -> Option<DimFrame> {
|
||||
let (a, b) = line_ends(sk, l)?;
|
||||
DimFrame::Linear { p0: a, p1: b, dir: unit(b - a, Vec2::X) }
|
||||
}
|
||||
LineAngle { l, value } => {
|
||||
let (a, b) = line_ends(sk, l)?;
|
||||
let d = unit(b - a, Vec2::X);
|
||||
if value < 0.0 {
|
||||
DimFrame::Angular { vertex: a, d0: d, sweep: (-value).rem_euclid(std::f64::consts::TAU) }
|
||||
} else {
|
||||
DimFrame::Angular { vertex: a, d0: Vec2::X, sweep: value.rem_euclid(std::f64::consts::TAU) }
|
||||
}
|
||||
}
|
||||
ArcSweep { c, .. } => match sk.segs(c).first()? {
|
||||
solvecraft_geom::Seg2::Arc { center, start, sweep, .. } => {
|
||||
DimFrame::Angular { vertex: *center, d0: Vec2::from_angle(*start), sweep: *sweep }
|
||||
}
|
||||
_ => return None,
|
||||
},
|
||||
SlotOverallLength { a, b, .. } => {
|
||||
let (ca, cb) = (sk.center(a)?, sk.center(b)?);
|
||||
let dir = unit(cb - ca, Vec2::X);
|
||||
DimFrame::Linear { p0: ca - dir * sk.radius(a)?, p1: cb + dir * sk.radius(b)?, dir }
|
||||
}
|
||||
PointLineDistance { p, l, .. } | LinearDiameter { p, l, .. } => {
|
||||
let (a, b) = line_ends(sk, l)?;
|
||||
let q = sk.point(p)?;
|
||||
|
||||
@@ -0,0 +1,840 @@
|
||||
//! Persistent free-form offsets with a whole-span normal-distance error certificate.
|
||||
//! The certificate bounds the second derivative of the exact normal offset and of
|
||||
//! the actual cubic interpolant (natural for legacy output, periodic for new closed output). The endpoint interpolation theorem then
|
||||
//! bounds their distance everywhere, rather than just at selected samples.
|
||||
use crate::{CurveKind, Sketch, SketchError, fit_beziers_mode};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use solvecraft_geom::{Seg2, Vec2};
|
||||
|
||||
pub const OFFSET_TOLERANCE: f64 = 0.002;
|
||||
const MAX_PIECES: usize = 256;
|
||||
const MAX_ASSOCIATIONS: usize = 128;
|
||||
const MAX_OFFSET_WORK: usize = 1_048_576;
|
||||
struct Fit {
|
||||
tolerance: f64,
|
||||
periodic: bool,
|
||||
}
|
||||
type Result<T> = std::result::Result<T, SketchError>;
|
||||
fn bad(message: &str) -> SketchError {
|
||||
SketchError::Invalid(message.into())
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct FreeformOffset {
|
||||
pub source: String,
|
||||
pub output: String,
|
||||
pub forward: bool,
|
||||
pub distance: f64,
|
||||
/// Uniform dyadic subdivision count per exact source piece; preserves point roles.
|
||||
pub divisions: usize,
|
||||
pub pieces: usize,
|
||||
pub closed: bool,
|
||||
pub tolerance: f64,
|
||||
pub certificate: u8,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct I {
|
||||
lo: f64,
|
||||
hi: f64,
|
||||
}
|
||||
impl I {
|
||||
fn value(v: f64) -> Self {
|
||||
Self { lo: v, hi: v }
|
||||
}
|
||||
fn hull(values: impl Iterator<Item = f64>) -> Self {
|
||||
let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY);
|
||||
for v in values {
|
||||
lo = lo.min(v);
|
||||
hi = hi.max(v);
|
||||
}
|
||||
let padding = 64.0 * f64::EPSILON * (lo.abs().max(hi.abs()) + 1.0);
|
||||
Self { lo: lo - padding, hi: hi + padding }
|
||||
}
|
||||
fn add(self, b: Self) -> Self {
|
||||
Self { lo: self.lo + b.lo, hi: self.hi + b.hi }
|
||||
}
|
||||
fn neg(self) -> Self {
|
||||
Self { lo: -self.hi, hi: -self.lo }
|
||||
}
|
||||
fn sub(self, b: Self) -> Self {
|
||||
self.add(b.neg())
|
||||
}
|
||||
fn mul(self, b: Self) -> Self {
|
||||
Self::hull([self.lo * b.lo, self.lo * b.hi, self.hi * b.lo, self.hi * b.hi].into_iter())
|
||||
}
|
||||
fn scale(self, b: f64) -> Self {
|
||||
self.mul(Self::value(b))
|
||||
}
|
||||
fn div(self, b: Self) -> Result<Self> {
|
||||
if b.lo <= 0.0 || !b.hi.is_finite() {
|
||||
return Err(bad("uncertifiable rational offset denominator"));
|
||||
}
|
||||
Ok(self.mul(Self { lo: 1.0 / b.hi, hi: 1.0 / b.lo }))
|
||||
}
|
||||
fn abs_max(self) -> f64 {
|
||||
self.lo.abs().max(self.hi.abs())
|
||||
}
|
||||
fn abs_min(self) -> f64 {
|
||||
if self.lo <= 0.0 && self.hi >= 0.0 { 0.0 } else { self.lo.abs().min(self.hi.abs()) }
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Copy)]
|
||||
struct V {
|
||||
x: I,
|
||||
y: I,
|
||||
}
|
||||
impl V {
|
||||
fn hull(values: &[Vec2]) -> Self {
|
||||
Self { x: I::hull(values.iter().map(|v| v.x)), y: I::hull(values.iter().map(|v| v.y)) }
|
||||
}
|
||||
fn sub(self, b: Self) -> Self {
|
||||
Self { x: self.x.sub(b.x), y: self.y.sub(b.y) }
|
||||
}
|
||||
fn mul(self, b: I) -> Self {
|
||||
Self { x: self.x.mul(b), y: self.y.mul(b) }
|
||||
}
|
||||
fn div(self, b: I) -> Result<Self> {
|
||||
Ok(Self { x: self.x.div(b)?, y: self.y.div(b)? })
|
||||
}
|
||||
fn upper(self) -> f64 {
|
||||
self.x.abs_max().hypot(self.y.abs_max())
|
||||
}
|
||||
fn lower(self) -> f64 {
|
||||
self.x.abs_min().hypot(self.y.abs_min())
|
||||
}
|
||||
fn cross(self, b: Self) -> I {
|
||||
self.x.mul(b.y).sub(self.y.mul(b.x))
|
||||
}
|
||||
}
|
||||
|
||||
/// Homogeneous controls retain the original parameter during restriction. Re-normalising
|
||||
/// a conic with Seg2::split_at would change that parameter and invalidate the certificate.
|
||||
#[derive(Clone)]
|
||||
struct H {
|
||||
n: Vec<Vec2>,
|
||||
d: Vec<f64>,
|
||||
}
|
||||
impl H {
|
||||
fn normal_end(&self, at_end: bool, distance: f64) -> Result<Vec2> {
|
||||
let last = self.n.len() - 1;
|
||||
let (i, j) = if at_end { (last, last - 1) } else { (0, 1) };
|
||||
let position = self.n[i] / self.d[i];
|
||||
let sign = if at_end { -1.0 } else { 1.0 };
|
||||
let dn = (self.n[j] - self.n[i]) * (last as f64 * sign);
|
||||
let dd = (self.d[j] - self.d[i]) * (last as f64 * sign);
|
||||
let tangent = ((dn - position * dd) / self.d[i]).normalized().ok_or_else(|| bad("offset source has a stationary tangent"))?;
|
||||
Ok(position + tangent.perp() * distance)
|
||||
}
|
||||
fn from_seg(seg: &Seg2) -> Result<Self> {
|
||||
let (points, weights) = match *seg {
|
||||
Seg2::Line { a, b } => (vec![a, b], vec![1.0; 2]),
|
||||
Seg2::Cubic { p0, p1, p2, p3 } => (vec![p0, p1, p2, p3], vec![1.0; 4]),
|
||||
Seg2::Bezier { n, p } if (1..=7).contains(&n) => (p[..=usize::from(n)].to_vec(), vec![1.0; usize::from(n) + 1]),
|
||||
Seg2::Conic { a, apex, b, w } if w.is_finite() && w > 0.0 => (vec![a, apex, b], vec![1.0, w, 1.0]),
|
||||
_ => return Err(bad("unsupported exact free-form offset piece")),
|
||||
};
|
||||
if points.iter().any(|p| !p.is_finite()) {
|
||||
return Err(bad("nonfinite offset source"));
|
||||
}
|
||||
let scale = weights.iter().copied().fold(1.0_f64, f64::max);
|
||||
let d = weights.iter().map(|w| w / scale).collect::<Vec<_>>();
|
||||
Ok(Self { n: points.iter().zip(&d).map(|(p, w)| *p * *w).collect(), d })
|
||||
}
|
||||
fn split(&self, t: f64) -> (Self, Self) {
|
||||
let (mut n, mut d) = (self.n.clone(), self.d.clone());
|
||||
let (mut ln, mut rn, mut ld, mut rd) = (vec![n[0]], vec![n[n.len() - 1]], vec![d[0]], vec![d[d.len() - 1]]);
|
||||
for width in (1..n.len()).rev() {
|
||||
for i in 0..width {
|
||||
n[i] = n[i].lerp(n[i + 1], t);
|
||||
d[i] = d[i] * (1.0 - t) + d[i + 1] * t;
|
||||
}
|
||||
ln.push(n[0]);
|
||||
rn.push(n[width - 1]);
|
||||
ld.push(d[0]);
|
||||
rd.push(d[width - 1]);
|
||||
}
|
||||
rn.reverse();
|
||||
rd.reverse();
|
||||
(Self { n: ln, d: ld }, Self { n: rn, d: rd })
|
||||
}
|
||||
fn range(&self, a: f64, b: f64) -> Self {
|
||||
let left = if b < 1.0 { self.split(b).0 } else { self.clone() };
|
||||
if a > 0.0 { left.split(a / b).1 } else { left }
|
||||
}
|
||||
fn derivatives(&self) -> Result<[V; 4]> {
|
||||
let origin = self.n[0] / self.d[0];
|
||||
let mut n = self.n.iter().zip(&self.d).map(|(n, d)| *n - origin * *d).collect::<Vec<_>>();
|
||||
let mut d = self.d.clone();
|
||||
let mut nh = Vec::new();
|
||||
let mut dh = Vec::new();
|
||||
for _ in 0..4 {
|
||||
nh.push(V::hull(&n));
|
||||
dh.push(I::hull(d.iter().copied()));
|
||||
let degree = n.len().saturating_sub(1) as f64;
|
||||
n = if n.len() > 1 { n.windows(2).map(|p| (p[1] - p[0]) * degree).collect() } else { vec![Vec2::ZERO] };
|
||||
d = if d.len() > 1 { d.windows(2).map(|p| (p[1] - p[0]) * degree).collect() } else { vec![0.0] };
|
||||
}
|
||||
let r = nh[0].div(dh[0])?;
|
||||
let v = nh[1].sub(r.mul(dh[1])).div(dh[0])?;
|
||||
let a = nh[2].sub(v.mul(dh[1].scale(2.0))).sub(r.mul(dh[2])).div(dh[0])?;
|
||||
let j = nh[3].sub(a.mul(dh[1].scale(3.0))).sub(v.mul(dh[2].scale(3.0))).sub(r.mul(dh[3])).div(dh[0])?;
|
||||
Ok([r, v, a, j])
|
||||
}
|
||||
fn offset_second_bound(&self, distance: f64) -> Result<f64> {
|
||||
let [_, v, a, j] = self.derivatives()?;
|
||||
let speed = v.lower();
|
||||
if speed <= 1e-12 {
|
||||
return Err(bad("offset source has an unresolved stationary tangent"));
|
||||
}
|
||||
let curvature = v.cross(a).div(I { lo: speed.powi(3), hi: v.upper().powi(3) })?;
|
||||
if curvature.scale(distance).hi >= 1.0 - 1e-8 {
|
||||
return Err(bad("offset crosses a curvature cusp"));
|
||||
}
|
||||
let bound = a.upper() + distance.abs() * (2.0 * j.upper() / speed + 5.0 * (a.upper() / speed).powi(2));
|
||||
if !bound.is_finite() {
|
||||
return Err(bad("offset derivative bound overflow"));
|
||||
}
|
||||
Ok(bound)
|
||||
}
|
||||
}
|
||||
|
||||
/// Subdivision tightens the proof, not the stored geometry. Endpoint discrepancies
|
||||
/// are measured against the exact rational normal, then the second derivative
|
||||
/// interpolation bound certifies the full intervening interval.
|
||||
fn certify(h: &H, cubic: &[Vec2; 4], distance: f64, tolerance: f64, depth: u8, budget: &mut usize) -> Result<()> {
|
||||
if *budget == 0 {
|
||||
return Err(bad("offset certificate work limit exceeded"));
|
||||
}
|
||||
*budget -= 1;
|
||||
let endpoint_error = cubic[0].dist(h.normal_end(false, distance)?).max(cubic[3].dist(h.normal_end(true, distance)?));
|
||||
if endpoint_error + 1e-10 > tolerance {
|
||||
return Err(bad("offset spline exceeds its endpoint error certificate"));
|
||||
}
|
||||
let cubic_second = ((cubic[2] - cubic[1] * 2.0 + cubic[0]) * 6.0).len().max(((cubic[3] - cubic[2] * 2.0 + cubic[1]) * 6.0).len());
|
||||
if h.offset_second_bound(distance).is_ok_and(|second| endpoint_error + (second + cubic_second) / 8.0 * (1.0 + 1e-10) + 1e-10 <= tolerance) {
|
||||
return Ok(());
|
||||
}
|
||||
if depth >= 8 {
|
||||
return Err(bad("offset spline exceeds its whole-span error or regularity certificate"));
|
||||
}
|
||||
let (left, right) = h.split(0.5);
|
||||
let curve = Seg2::Cubic { p0: cubic[0], p1: cubic[1], p2: cubic[2], p3: cubic[3] };
|
||||
let (a, b) = curve.split_half();
|
||||
let controls = |s: Seg2| match s {
|
||||
Seg2::Cubic { p0, p1, p2, p3 } => Ok([p0, p1, p2, p3]),
|
||||
_ => Err(bad("invalid cubic certificate")),
|
||||
};
|
||||
certify(&left, &controls(a)?, distance, tolerance, depth + 1, budget)?;
|
||||
certify(&right, &controls(b)?, distance, tolerance, depth + 1, budget)
|
||||
}
|
||||
|
||||
fn normal_point(seg: &Seg2, t: f64, d: f64) -> Result<Vec2> {
|
||||
let normal = seg.derivative(t).normalized().ok_or_else(|| bad("offset source has a stationary tangent"))?.perp();
|
||||
let p = seg.point_at(t) + normal * d;
|
||||
if !p.is_finite() {
|
||||
return Err(bad("nonfinite offset point"));
|
||||
}
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
fn verify_simple(points: &[Vec2], cubics: &[[Vec2; 4]], closed: bool) -> Result<()> {
|
||||
// Each cubic's derivative controls must lie in the forward half-plane of its
|
||||
// chord. This proves local injectivity; separated convex hulls prove distant
|
||||
// spans cannot intersect. Near or ambiguous contacts are refused atomically.
|
||||
for c in cubics {
|
||||
let chord = c[3] - c[0];
|
||||
if c.windows(2).any(|p| (p[1] - p[0]).dot(chord) <= 1e-18) {
|
||||
return Err(bad("offset spline cannot be certified locally simple"));
|
||||
}
|
||||
}
|
||||
// Adjacent spans need their own proof: individual monotonicity does not
|
||||
// preclude them crossing each other away from their common endpoint.
|
||||
let separates_joint = |a: &[Vec2; 4], b: &[Vec2; 4]| {
|
||||
let joint = a[3];
|
||||
let direction = (a[3] - a[0]) + (b[3] - b[0]);
|
||||
joint.dist(b[0]) < 1e-7
|
||||
&& a[..3].iter().all(|p| (*p - joint).dot(direction) < -1e-18)
|
||||
&& b[1..].iter().all(|p| (*p - joint).dot(direction) > 1e-18)
|
||||
};
|
||||
for pair in cubics.windows(2) {
|
||||
if !separates_joint(&pair[0], &pair[1]) {
|
||||
return Err(bad("offset junction cannot be certified simple"));
|
||||
}
|
||||
}
|
||||
if closed && cubics.first().zip(cubics.last()).is_some_and(|(first, last)| !separates_joint(last, first)) {
|
||||
return Err(bad("offset seam cannot be certified simple"));
|
||||
}
|
||||
for i in 0..cubics.len() {
|
||||
for j in i + 2..cubics.len() {
|
||||
if closed && i == 0 && j + 1 == cubics.len() {
|
||||
continue;
|
||||
}
|
||||
let a = V::hull(&cubics[i]);
|
||||
let b = V::hull(&cubics[j]);
|
||||
if a.x.hi < b.x.lo || b.x.hi < a.x.lo || a.y.hi < b.y.lo || b.y.hi < a.y.lo {
|
||||
continue;
|
||||
}
|
||||
// A separating axis from either chord also separates both convex hulls.
|
||||
let separated = [points[i + 1] - points[i], points[j + 1] - points[j]].iter().any(|d| {
|
||||
let n = d.perp();
|
||||
let a = I::hull(cubics[i].iter().map(|p| p.dot(n)));
|
||||
let b = I::hull(cubics[j].iter().map(|p| p.dot(n)));
|
||||
a.hi < b.lo || b.hi < a.lo
|
||||
});
|
||||
if !separated {
|
||||
return Err(bad("offset self-intersection or ambiguous close contact"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn geometry(sk: &Sketch, source: usize, forward: bool, d: f64, divisions: usize, fit: Fit, work: &mut usize) -> Result<(Vec<Vec2>, usize, bool)> {
|
||||
if *work == 0 {
|
||||
return Err(bad("offset transaction certificate work limit exceeded"));
|
||||
}
|
||||
let Fit { tolerance, periodic } = fit;
|
||||
let mut pieces = sk.exact_segs(source).ok_or_else(|| bad("offset source changed shape"))?;
|
||||
if pieces.is_empty()
|
||||
|| pieces.len() > MAX_PIECES
|
||||
|| divisions == 0
|
||||
|| !divisions.is_power_of_two()
|
||||
|| divisions > 256
|
||||
|| pieces.len().saturating_mul(divisions) >= crate::MAX_SPLINE_POINTS
|
||||
|| !d.is_finite()
|
||||
|| d.abs() < 1e-9
|
||||
|| !tolerance.is_finite()
|
||||
|| tolerance <= 0.0
|
||||
|| tolerance > OFFSET_TOLERANCE
|
||||
{
|
||||
return Err(bad("invalid or excessive certified offset"));
|
||||
}
|
||||
if !forward {
|
||||
pieces.reverse();
|
||||
pieces = pieces.into_iter().map(|p| p.reversed()).collect();
|
||||
}
|
||||
let mut points = Vec::new();
|
||||
let mut restricted = Vec::new();
|
||||
for piece in &pieces {
|
||||
let homogeneous = H::from_seg(piece)?;
|
||||
let first = normal_point(piece, 0.0, d)?;
|
||||
if points.last().is_some_and(|p: &Vec2| p.dist(first) > 1e-7) {
|
||||
return Err(bad("free-form offset has a nonsmooth source junction"));
|
||||
}
|
||||
if points.is_empty() {
|
||||
points.push(first);
|
||||
}
|
||||
for i in 0..divisions {
|
||||
let (a, b) = (i as f64 / divisions as f64, (i + 1) as f64 / divisions as f64);
|
||||
restricted.push(homogeneous.range(a, b));
|
||||
let end = normal_point(piece, b, d)?;
|
||||
points.push(end);
|
||||
}
|
||||
}
|
||||
let closed = pieces.first().is_some_and(|a| pieces.last().is_some_and(|b| a.point_at(0.0).dist(b.point_at(1.0)) < 1e-7));
|
||||
if closed && points[0].dist(points[points.len() - 1]) > 1e-7 {
|
||||
return Err(bad("free-form closed offset has a nonsmooth seam"));
|
||||
}
|
||||
if closed {
|
||||
let first = points[0];
|
||||
if let Some(last) = points.last_mut() {
|
||||
*last = first;
|
||||
}
|
||||
}
|
||||
let cubics = fit_beziers_mode(&points, periodic && closed)?;
|
||||
let allowance = (*work).min(65_536);
|
||||
let mut budget = allowance;
|
||||
let result = restricted.iter().zip(&cubics).try_for_each(|(h, c)| certify(h, c, d, tolerance, 0, &mut budget));
|
||||
*work -= allowance - budget;
|
||||
result?;
|
||||
verify_simple(&points, &cubics, closed)?;
|
||||
Ok((points, pieces.len(), closed))
|
||||
}
|
||||
|
||||
impl Sketch {
|
||||
/// Validate persisted association roles without solving or certifying geometry.
|
||||
pub fn validate_freeform_offsets(&self) -> Result<()> {
|
||||
if self.freeform_offsets.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
if self.freeform_offsets.len() > MAX_ASSOCIATIONS {
|
||||
return Err(bad("too many associative free-form offsets"));
|
||||
}
|
||||
if self.points.len() > 100_000 || self.curves.len() > 100_000 {
|
||||
return Err(bad("offset sketch exceeds ownership validation limit"));
|
||||
}
|
||||
let mut owners = vec![0usize; self.points.len()];
|
||||
let mut references = 0usize;
|
||||
for curve in &self.curves {
|
||||
if matches!(&curve.kind, CurveKind::Spline {pts,..} if pts.len() > crate::MAX_SPLINE_POINTS) {
|
||||
return Err(bad("offset sketch contains an excessive spline"));
|
||||
}
|
||||
for index in curve.kind.point_ids() {
|
||||
references += 1;
|
||||
if references > 1_000_000 {
|
||||
return Err(bad("offset point ownership work limit exceeded"));
|
||||
}
|
||||
if let Some(count) = owners.get_mut(index) {
|
||||
*count += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut outputs = std::collections::BTreeSet::new();
|
||||
for record in &self.freeform_offsets {
|
||||
if record.source.is_empty()
|
||||
|| record.source.len() > 512
|
||||
|| record.output.is_empty()
|
||||
|| record.output.len() > 512
|
||||
|| record.source == record.output
|
||||
|| !matches!(record.certificate, 1 | 2)
|
||||
|| record.pieces == 0
|
||||
|| record.pieces > MAX_PIECES
|
||||
|| record.divisions == 0
|
||||
|| !record.divisions.is_power_of_two()
|
||||
|| record.divisions > 256
|
||||
|| record.pieces.saturating_mul(record.divisions) >= crate::MAX_SPLINE_POINTS
|
||||
|| !record.distance.is_finite()
|
||||
|| record.distance.abs() < 1e-9
|
||||
|| !record.tolerance.is_finite()
|
||||
|| record.tolerance <= 0.0
|
||||
|| record.tolerance > OFFSET_TOLERANCE
|
||||
|| !outputs.insert(record.output.as_str())
|
||||
|| self.freeform_offsets.iter().any(|other| other.output == record.source && !outputs.contains(other.output.as_str()))
|
||||
{
|
||||
return Err(bad("invalid cyclic or unbounded offset association"));
|
||||
}
|
||||
let source = self.curve_index(&record.source).ok_or_else(|| bad("offset source vanished"))?;
|
||||
if !matches!(self.curves[source].kind, CurveKind::Ellipse { .. } | CurveKind::Conic { .. } | CurveKind::Spline { .. }) {
|
||||
return Err(bad("offset source changed shape"));
|
||||
}
|
||||
let output = self.curve_index(&record.output).ok_or_else(|| bad("offset output vanished"))?;
|
||||
match &self.curves[output].kind {
|
||||
CurveKind::Spline { pts, control: false, degree: 3, periodic }
|
||||
if *periodic == (record.certificate == 2)
|
||||
&& (record.certificate != 2 || record.closed)
|
||||
&& pts.len() == record.pieces * record.divisions + 1
|
||||
&& pts.iter().all(|i| *i < self.points.len())
|
||||
&& pts.iter().copied().collect::<std::collections::BTreeSet<_>>().len() == pts.len()
|
||||
&& pts
|
||||
.iter()
|
||||
.all(|i| self.points.get(*i).is_some_and(|point| point.fixed && point.link.is_none()) && owners.get(*i) == Some(&1)) => {}
|
||||
_ => return Err(bad("invalid offset output point roles")),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn add_freeform_offset(&mut self, source: usize, forward: bool, distance: f64) -> Result<usize> {
|
||||
if self.freeform_offsets.len() >= MAX_ASSOCIATIONS {
|
||||
return Err(bad("too many associative free-form offsets"));
|
||||
}
|
||||
let source_id = self.curves.get(source).ok_or_else(|| bad("missing offset source"))?.id.clone();
|
||||
let source_pieces = self.exact_segs(source).ok_or_else(|| bad("offset source changed shape"))?.len();
|
||||
let mut result = None;
|
||||
let mut failure = None;
|
||||
let mut work = MAX_OFFSET_WORK;
|
||||
for divisions in [1, 2, 4, 8, 16, 32, 64, 128, 256] {
|
||||
if source_pieces.saturating_mul(divisions) >= crate::MAX_SPLINE_POINTS {
|
||||
break;
|
||||
}
|
||||
match geometry(self, source, forward, distance, divisions, Fit { tolerance: OFFSET_TOLERANCE, periodic: true }, &mut work) {
|
||||
Ok(g) => {
|
||||
result = Some((divisions, g));
|
||||
break;
|
||||
}
|
||||
Err(error) => {
|
||||
failure = Some(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
let (divisions, (points, pieces, closed)) = result.ok_or_else(|| failure.unwrap_or_else(|| bad("offset subdivision limit exceeded")))?;
|
||||
let mut candidate = self.clone();
|
||||
let indices = points.iter().map(|p| candidate.add_point(*p, None)).collect::<Result<Vec<_>>>()?;
|
||||
for i in &indices {
|
||||
if let Some(p) = candidate.points.get_mut(*i) {
|
||||
p.fixed = true;
|
||||
}
|
||||
}
|
||||
let output = candidate.add_curve(CurveKind::Spline { pts: indices, control: false, degree: 3, periodic: closed }, None)?;
|
||||
candidate.freeform_offsets.push(FreeformOffset {
|
||||
source: source_id,
|
||||
output: candidate.curves[output].id.clone(),
|
||||
forward,
|
||||
distance,
|
||||
divisions,
|
||||
pieces,
|
||||
closed,
|
||||
tolerance: OFFSET_TOLERANCE,
|
||||
certificate: if closed { 2 } else { 1 },
|
||||
});
|
||||
*self = candidate;
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
pub(crate) fn refresh_freeform_offsets(&mut self) -> Result<()> {
|
||||
self.validate_freeform_offsets()?;
|
||||
let mut candidate = self.clone();
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
let mut work = MAX_OFFSET_WORK;
|
||||
for (record_index, record) in self.freeform_offsets.clone().into_iter().enumerate() {
|
||||
if !matches!(record.certificate, 1 | 2)
|
||||
|| record.source == record.output
|
||||
|| !seen.insert(record.output.clone())
|
||||
|| candidate.freeform_offsets.iter().any(|later| later.output == record.source && !seen.contains(&later.output))
|
||||
{
|
||||
return Err(bad("invalid cyclic offset association"));
|
||||
}
|
||||
let source = candidate.curve_index(&record.source).ok_or_else(|| bad("offset source vanished"))?;
|
||||
let output = candidate.curve_index(&record.output).ok_or_else(|| bad("offset output vanished"))?;
|
||||
let source_pieces = candidate.exact_segs(source).ok_or_else(|| bad("offset source changed shape"))?.len();
|
||||
let mut divisions = record.divisions;
|
||||
if source_pieces != record.pieces {
|
||||
let lineage = candidate.freeform_offsets.iter().any(|parent| parent.output == record.source);
|
||||
if !lineage || source_pieces < record.pieces || source_pieces % record.pieces != 0 {
|
||||
return Err(bad("offset source topology changed outside its refinement lineage"));
|
||||
}
|
||||
let ratio = source_pieces / record.pieces;
|
||||
if !ratio.is_power_of_two() {
|
||||
return Err(bad("offset source refinement has incompatible point roles"));
|
||||
}
|
||||
divisions = (record.divisions / ratio).max(1);
|
||||
}
|
||||
let (points, pieces, closed) = loop {
|
||||
match geometry(
|
||||
&candidate,
|
||||
source,
|
||||
record.forward,
|
||||
record.distance,
|
||||
divisions,
|
||||
Fit { tolerance: record.tolerance, periodic: record.certificate == 2 },
|
||||
&mut work,
|
||||
) {
|
||||
Ok(geometry) => break geometry,
|
||||
Err(error) => {
|
||||
if divisions >= 256 || source_pieces.saturating_mul(divisions.saturating_mul(2)) >= crate::MAX_SPLINE_POINTS {
|
||||
return Err(bad(&format!("offset refinement limit reached while certifying its chain: {error}")));
|
||||
}
|
||||
divisions *= 2;
|
||||
}
|
||||
}
|
||||
};
|
||||
if closed != record.closed {
|
||||
return Err(bad("offset source topology changed"));
|
||||
}
|
||||
let old_indices = match &candidate.curves[output].kind {
|
||||
CurveKind::Spline { pts, control: false, degree: 3, periodic }
|
||||
if *periodic == (record.certificate == 2)
|
||||
&& (record.certificate != 2 || record.closed)
|
||||
&& pts.len() == record.pieces * record.divisions + 1 =>
|
||||
{
|
||||
pts.clone()
|
||||
}
|
||||
_ => return Err(bad("offset output was edited; break its association first")),
|
||||
};
|
||||
// Refinement never reuses or removes an old node ID. Existing dyadic
|
||||
// roles remain at the same normalized source parameters; new nodes
|
||||
// append to the point table, so dimensions keep their point indices.
|
||||
let old_spans = record.pieces * record.divisions;
|
||||
let new_spans = pieces * divisions;
|
||||
if new_spans < old_spans || new_spans % old_spans != 0 || !(new_spans / old_spans).is_power_of_two() {
|
||||
return Err(bad("offset refinement would change existing normalized point roles"));
|
||||
}
|
||||
let factor = new_spans / old_spans;
|
||||
let mut indices = Vec::with_capacity(points.len());
|
||||
for (role, pos) in points.iter().enumerate() {
|
||||
let index = if role % factor == 0 {
|
||||
*old_indices.get(role / factor).ok_or_else(|| bad("offset node role vanished"))?
|
||||
} else {
|
||||
candidate.add_point(*pos, None)?
|
||||
};
|
||||
indices.push(index);
|
||||
}
|
||||
for (i, pos) in indices.iter().zip(points) {
|
||||
let p = candidate.points.get_mut(*i).ok_or_else(|| bad("offset output point vanished"))?;
|
||||
p.pos = pos;
|
||||
p.fixed = true;
|
||||
}
|
||||
candidate.curves[output].kind = CurveKind::Spline { pts: indices, control: false, degree: 3, periodic: record.certificate == 2 };
|
||||
candidate.freeform_offsets[record_index].divisions = divisions;
|
||||
candidate.freeform_offsets[record_index].pieces = pieces;
|
||||
}
|
||||
*self = candidate;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn ellipse() -> (Sketch, usize) {
|
||||
let mut sketch = Sketch::new();
|
||||
let center = sketch.add_point(Vec2::ZERO, None).unwrap();
|
||||
let major = sketch.add_point(Vec2::new(10.0, 0.0), None).unwrap();
|
||||
let source = sketch.add_curve(CurveKind::Ellipse { c: center, m: major, r: 5.0 }, None).unwrap();
|
||||
(sketch, source)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn certified_offset_ellipse_refreshes_exact_normals_and_identity() {
|
||||
let (mut sk, source) = ellipse();
|
||||
let output = sk.add_freeform_offset(source, true, -1.0).unwrap();
|
||||
let record = sk.freeform_offsets[0].clone();
|
||||
let original_ids = sk.curves[output].kind.point_ids().iter().map(|i| sk.points[*i].id.clone()).collect::<Vec<_>>();
|
||||
let verify = |sk: &Sketch| {
|
||||
let record = &sk.freeform_offsets[0];
|
||||
let base = sk.exact_segs(source).unwrap();
|
||||
let curve = sk.exact_segs(output).unwrap();
|
||||
for (piece, source_piece) in base.iter().enumerate() {
|
||||
for span in 0..record.divisions {
|
||||
for t in [0.0, 0.13, 0.41, 0.79, 1.0] {
|
||||
let want = normal_point(source_piece, (span as f64 + t) / record.divisions as f64, -1.0).unwrap();
|
||||
let got = curve[piece * record.divisions + span].point_at(t);
|
||||
assert!(got.dist(want) <= OFFSET_TOLERANCE, "{got:?} vs {want:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
verify(&sk);
|
||||
// Independent Steiner area check for the convex ellipse expanded by 1mm.
|
||||
// Simpson integration evaluates the analytic ellipse speed, not offset samples.
|
||||
let n = 4096usize;
|
||||
let h = std::f64::consts::TAU / n as f64;
|
||||
let speed = |t: f64| (100.0 * t.sin().powi(2) + 25.0 * t.cos().powi(2)).sqrt();
|
||||
let perimeter = (0..=n)
|
||||
.map(|i| {
|
||||
speed(i as f64 * h)
|
||||
* if i == 0 || i == n {
|
||||
1.0
|
||||
} else if i % 2 == 0 {
|
||||
2.0
|
||||
} else {
|
||||
4.0
|
||||
}
|
||||
})
|
||||
.sum::<f64>()
|
||||
* h
|
||||
/ 3.0;
|
||||
let expected_area = 50.0 * std::f64::consts::PI + perimeter + std::f64::consts::PI;
|
||||
let actual_area = sk.exact_segs(output).unwrap().iter().map(Seg2::area_term).sum::<f64>();
|
||||
assert!((actual_area - expected_area).abs() < 0.15, "area {actual_area} vs {expected_area}");
|
||||
if let CurveKind::Ellipse { m, .. } = sk.curves[source].kind {
|
||||
sk.points[m].pos = Vec2::new(12.0, 0.0);
|
||||
}
|
||||
sk.refresh_offsets().unwrap();
|
||||
assert!(sk.freeform_offsets[0].divisions >= record.divisions);
|
||||
let factor = sk.freeform_offsets[0].divisions / record.divisions;
|
||||
assert_eq!(sk.curves[output].kind.point_ids().iter().step_by(factor).map(|i| sk.points[*i].id.clone()).collect::<Vec<_>>(), original_ids);
|
||||
verify(&sk);
|
||||
let first = sk.segs(output)[0].point_at(0.0);
|
||||
assert!(first.dist(Vec2::new(13.0, 0.0)) < 1e-10);
|
||||
let encoded = serde_json::to_string(&sk).unwrap();
|
||||
let mut reopened: Sketch = serde_json::from_str(&encoded).unwrap();
|
||||
reopened.refresh_offsets().unwrap();
|
||||
assert_eq!(reopened, sk);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn certified_offset_refuses_cusp_and_hostile_records_atomically() {
|
||||
let (mut sk, source) = ellipse();
|
||||
let before = sk.clone();
|
||||
// At (10,0), curvature radius is b²/a=2.5. An inward offset of 3
|
||||
// necessarily crosses the evolute and reverses its tangent orientation.
|
||||
assert!(sk.add_freeform_offset(source, true, 3.0).is_err());
|
||||
assert_eq!(sk, before);
|
||||
sk.add_freeform_offset(source, true, -1.0).unwrap();
|
||||
for divisions in [0, 3, usize::MAX] {
|
||||
let mut candidate = sk.clone();
|
||||
candidate.freeform_offsets[0].divisions = divisions;
|
||||
let before = candidate.clone();
|
||||
assert!(candidate.refresh_offsets().is_err());
|
||||
assert_eq!(candidate, before);
|
||||
}
|
||||
let mut cyclic = sk.clone();
|
||||
cyclic.freeform_offsets[0].source = cyclic.freeform_offsets[0].output.clone();
|
||||
let before = cyclic.clone();
|
||||
assert!(cyclic.refresh_offsets().is_err());
|
||||
assert_eq!(cyclic, before);
|
||||
let source_points = sk.curves[source].kind.point_ids();
|
||||
let output = sk.curve_index(&sk.freeform_offsets[0].output).unwrap();
|
||||
let mut aliased = sk.clone();
|
||||
if let CurveKind::Spline { pts, .. } = &mut aliased.curves[output].kind {
|
||||
pts[0] = source_points[0];
|
||||
}
|
||||
let before = aliased.clone();
|
||||
assert!(aliased.validate_freeform_offsets().is_err());
|
||||
assert!(aliased.refresh_offsets().is_err());
|
||||
assert_eq!(aliased, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn certified_offset_chain_preserves_roles_during_upstream_refinement() {
|
||||
let mut sk = Sketch::new();
|
||||
let start = sk.add_point(Vec2::new(10.0, 0.0), None).unwrap();
|
||||
let apex = sk.add_point(Vec2::new(10.0, 5.0), None).unwrap();
|
||||
let end = sk.add_point(Vec2::new(0.0, 5.0), None).unwrap();
|
||||
let w = std::f64::consts::FRAC_1_SQRT_2;
|
||||
let source = sk.add_curve(CurveKind::Conic { a: start, b: end, apex, rho: w / (1.0 + w) }, None).unwrap();
|
||||
let a = sk.add_freeform_offset(source, true, -1.0).unwrap();
|
||||
let b = sk.add_freeform_offset(a, true, -1.0).unwrap();
|
||||
let original = [a, b].map(|i| sk.curves[i].kind.point_ids().iter().map(|point| sk.points[*point].id.clone()).collect::<Vec<_>>());
|
||||
let records = sk.freeform_offsets.clone();
|
||||
for major in [12.0, 16.0, 20.0, 24.0] {
|
||||
sk.points[start].pos.x = major;
|
||||
sk.points[apex].pos.x = major;
|
||||
sk.refresh_offsets().unwrap();
|
||||
if sk.freeform_offsets[0].divisions > records[0].divisions {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(sk.freeform_offsets[0].divisions > records[0].divisions, "test must exercise real upstream refinement");
|
||||
for (record_index, output) in [a, b].into_iter().enumerate() {
|
||||
let old = &records[record_index];
|
||||
let current = &sk.freeform_offsets[record_index];
|
||||
let factor = current.pieces * current.divisions / (old.pieces * old.divisions);
|
||||
assert_eq!(
|
||||
sk.curves[output].kind.point_ids().iter().step_by(factor).map(|i| sk.points[*i].id.clone()).collect::<Vec<_>>(),
|
||||
original[record_index]
|
||||
);
|
||||
let source = sk.curve_index(¤t.source).unwrap();
|
||||
let source_pieces = sk.exact_segs(source).unwrap();
|
||||
let output_pieces = sk.exact_segs(output).unwrap();
|
||||
for (piece, source) in source_pieces.iter().enumerate() {
|
||||
for span in 0..current.divisions {
|
||||
let t = 0.371;
|
||||
let want = normal_point(source, (span as f64 + t) / current.divisions as f64, current.distance).unwrap();
|
||||
assert!(output_pieces[piece * current.divisions + span].point_at(t).dist(want) < OFFSET_TOLERANCE);
|
||||
}
|
||||
}
|
||||
}
|
||||
let saved = serde_json::to_string(&sk).unwrap();
|
||||
let mut reopened: Sketch = serde_json::from_str(&saved).unwrap();
|
||||
reopened.refresh_offsets().unwrap();
|
||||
assert_eq!(reopened, sk);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn certified_offset_closed_chain_refuses_natural_spline_seam_atomically() {
|
||||
let (mut sk, source) = ellipse();
|
||||
let first = sk.add_freeform_offset(source, true, -1.0).unwrap();
|
||||
// Explicitly reconstruct the old saved semantics, not the new periodic output.
|
||||
if let CurveKind::Spline { periodic, .. } = &mut sk.curves[first].kind {
|
||||
*periodic = false;
|
||||
}
|
||||
sk.freeform_offsets[0].certificate = 1;
|
||||
sk.refresh_offsets().unwrap();
|
||||
let before = sk.clone();
|
||||
let error = sk.add_freeform_offset(first, true, -0.5).unwrap_err();
|
||||
assert!(error.to_string().contains("nonsmooth seam"), "{error}");
|
||||
assert_eq!(sk, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn certified_offset_periodic_closed_chain_has_c2_seams_and_stable_roles() {
|
||||
let (mut sk, source) = ellipse();
|
||||
let source_points = sk.curves[source].kind.point_ids();
|
||||
let unchanged = source_points.iter().map(|i| sk.points[*i].clone()).collect::<Vec<_>>();
|
||||
let a = sk.add_freeform_offset(source, true, -1.0).unwrap();
|
||||
let b = sk.add_freeform_offset(a, true, -0.5).unwrap();
|
||||
assert_eq!(source_points.iter().map(|i| sk.points[*i].clone()).collect::<Vec<_>>(), unchanged);
|
||||
let old = sk.freeform_offsets.clone();
|
||||
let ids = [a, b].map(|i| sk.curves[i].kind.point_ids().iter().map(|p| sk.points[*p].id.clone()).collect::<Vec<_>>());
|
||||
let verify = |sk: &Sketch| {
|
||||
for output in [a, b] {
|
||||
let record = sk.freeform_offsets.iter().find(|r| r.output == sk.curves[output].id).unwrap();
|
||||
assert_eq!(record.certificate, 2);
|
||||
let points = sk.curves[output].kind.point_ids().iter().map(|p| sk.point(*p).unwrap()).collect::<Vec<_>>();
|
||||
let cubics = crate::periodic_beziers(&points).unwrap();
|
||||
let first = cubics[0];
|
||||
let last = *cubics.last().unwrap();
|
||||
let (h0, h1) = (points[0].dist(points[1]), points[points.len() - 2].dist(points[points.len() - 1]));
|
||||
assert_eq!(first[0], last[3]);
|
||||
assert!(((first[1] - first[0]) / h0 - (last[3] - last[2]) / h1).len() < 1e-10);
|
||||
assert!(((first[2] - first[1] * 2.0 + first[0]) / (h0 * h0) - (last[3] - last[2] * 2.0 + last[1]) / (h1 * h1)).len() < 1e-9);
|
||||
let source = sk.curve_index(&record.source).unwrap();
|
||||
for (i, piece) in sk.exact_segs(source).unwrap().iter().enumerate() {
|
||||
for j in 0..record.divisions {
|
||||
for t in [0.0, 0.13, 0.41, 0.79, 1.0] {
|
||||
let exact = normal_point(piece, (j as f64 + t) / record.divisions as f64, record.distance).unwrap();
|
||||
let got = sk.exact_segs(output).unwrap()[i * record.divisions + j].point_at(t);
|
||||
assert!(got.dist(exact) <= OFFSET_TOLERANCE);
|
||||
if source == 0 {
|
||||
// Independent ellipse implicit-gradient normal, rather
|
||||
// than using the offset implementation as its own oracle.
|
||||
let base = piece.point_at((j as f64 + t) / record.divisions as f64);
|
||||
let major = sk.point(source_points[1]).unwrap().x;
|
||||
let normal = Vec2::new(base.x / (major * major), base.y / 25.0).normalized().unwrap();
|
||||
assert!(got.dist(base + normal) <= OFFSET_TOLERANCE);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
verify(&sk);
|
||||
// Steiner's formula is independent of fitted output: both offsets expand
|
||||
// the original ellipse by 1.5mm, within the accumulated two certificates.
|
||||
let n = 4096;
|
||||
let h = std::f64::consts::TAU / n as f64;
|
||||
let perimeter = (0..=n)
|
||||
.map(|i| {
|
||||
let t = i as f64 * h;
|
||||
(100.0 * t.sin().powi(2) + 25.0 * t.cos().powi(2)).sqrt()
|
||||
* if i == 0 || i == n {
|
||||
1.0
|
||||
} else if i % 2 == 0 {
|
||||
2.0
|
||||
} else {
|
||||
4.0
|
||||
}
|
||||
})
|
||||
.sum::<f64>()
|
||||
* h
|
||||
/ 3.0;
|
||||
let expected = 50.0 * std::f64::consts::PI + 1.5 * perimeter + 2.25 * std::f64::consts::PI;
|
||||
let area = sk.exact_segs(b).unwrap().iter().map(Seg2::area_term).sum::<f64>();
|
||||
assert!((area - expected).abs() < 0.03, "{area} vs {expected}");
|
||||
let profiles = crate::find_profiles(&sk);
|
||||
assert_eq!(profiles.len(), 3);
|
||||
if let CurveKind::Ellipse { m, .. } = sk.curves[source].kind {
|
||||
sk.points[m].pos.x = 12.0;
|
||||
}
|
||||
sk.refresh_offsets().unwrap();
|
||||
verify(&sk);
|
||||
for (j, i) in [a, b].into_iter().enumerate() {
|
||||
let now = &sk.freeform_offsets[j];
|
||||
let factor = now.pieces * now.divisions / (old[j].pieces * old[j].divisions);
|
||||
assert_eq!(sk.curves[i].kind.point_ids().iter().step_by(factor).map(|p| sk.points[*p].id.clone()).collect::<Vec<_>>(), ids[j]);
|
||||
}
|
||||
let encoded = serde_json::to_string(&sk).unwrap();
|
||||
let mut reopened: Sketch = serde_json::from_str(&encoded).unwrap();
|
||||
reopened.validate_periodic_splines().unwrap();
|
||||
reopened.refresh_offsets().unwrap();
|
||||
assert_eq!(sk, reopened);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn certified_offset_periodic_circle_and_reverse_have_analytic_normals() {
|
||||
for forward in [true, false] {
|
||||
let mut sk = Sketch::new();
|
||||
let center = sk.add_point(Vec2::ZERO, None).unwrap();
|
||||
let major = sk.add_point(Vec2::new(5.0, 0.0), None).unwrap();
|
||||
let source = sk.add_curve(CurveKind::Ellipse { c: center, m: major, r: 5.0 }, None).unwrap();
|
||||
let distance = if forward { -1.0 } else { 1.0 };
|
||||
let a = sk.add_freeform_offset(source, forward, distance).unwrap();
|
||||
let b = sk.add_freeform_offset(a, true, distance * 0.5).unwrap();
|
||||
for (output, radius) in [(a, 6.0), (b, 6.5)] {
|
||||
let pieces = sk.exact_segs(output).unwrap();
|
||||
for curve in &pieces {
|
||||
for t in [0.0, 0.13, 0.41, 0.79, 1.0] {
|
||||
assert!((curve.point_at(t).len() - radius).abs() <= 2.0 * OFFSET_TOLERANCE);
|
||||
}
|
||||
}
|
||||
let area = pieces.iter().map(Seg2::area_term).sum::<f64>().abs();
|
||||
assert!((area - std::f64::consts::PI * radius * radius).abs() < 0.03);
|
||||
}
|
||||
sk.refresh_offsets().unwrap();
|
||||
sk.validate_periodic_splines().unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,10 +10,12 @@
|
||||
|
||||
mod curves;
|
||||
mod dims;
|
||||
mod freeform_offset;
|
||||
mod linalg;
|
||||
mod link;
|
||||
mod model;
|
||||
mod offset;
|
||||
mod periodic;
|
||||
mod profiles;
|
||||
mod shape;
|
||||
mod solver;
|
||||
@@ -21,17 +23,20 @@ mod text;
|
||||
mod wire;
|
||||
|
||||
pub use curves::{
|
||||
MAX_SPLINE_POINTS, bspline_beziers, conic_point, ellipse_point, end_curvature, fit_beziers, spline_end_tangent, spline_point, spline_polyline,
|
||||
MAX_SPLINE_POINTS, bspline_beziers, conic_point, ellipse_point, end_curvature, fit_beziers, fit_beziers_mode, spline_end_tangent,
|
||||
spline_end_tangent_mode, spline_point, spline_point_mode, spline_polyline, spline_polyline_mode,
|
||||
};
|
||||
pub use dims::{DimFrame, DimLayout, chain_centres, default_text, dim_frame, dim_layout, encode_text};
|
||||
pub use freeform_offset::{FreeformOffset, OFFSET_TOLERANCE};
|
||||
pub use link::{Link, LinkGeom, LinkKind, LinkSource, MAX_LINK_ENTITIES};
|
||||
pub use model::{Constraint, ConstraintKind, Curve, CurveKind, SPoint, Sketch, SketchError, SketchView};
|
||||
pub use offset::OffsetChain;
|
||||
pub use periodic::periodic_beziers;
|
||||
pub use profiles::{CurvePick, Profile, distinct_curves, find_drawn_profiles, find_profiles, merge_regions, profile_at_point, profile_by_curves};
|
||||
pub use shape::{Shape, intersections};
|
||||
pub use solver::{Hold, SolveReport, SolveStatus, measure_dimension, solve, solve_holding};
|
||||
pub use text::{MAX_TEXT_CHARS, text_geometry};
|
||||
pub use wire::{MAX_FIT_POINTS, MAX_WIRE_POINTS, Wire, fit_polyline};
|
||||
pub use wire::{MAX_FIT_POINTS, MAX_WIRE_POINTS, Wire, WireSpace, fit_polyline};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
+197
-46
@@ -13,6 +13,9 @@ use crate::model::{Curve, CurveKind, Result, Sketch, SketchError};
|
||||
|
||||
/// Points of one link closer than this are merged into one point.
|
||||
const MERGE_TOL: f64 = 1e-7;
|
||||
|
||||
#[path = "link_loops.rs"]
|
||||
mod loops;
|
||||
/// Most entities a single link may produce.
|
||||
pub const MAX_LINK_ENTITIES: usize = 20_000;
|
||||
|
||||
@@ -107,6 +110,9 @@ pub struct Link {
|
||||
/// Persistent model face identity, resolved by the document before geometry refresh.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub face_name: Option<String>,
|
||||
/// Automatically projected borders owned by a durable sketch face attachment.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub auto_face: bool,
|
||||
/// The reference could not be found on the last recompute; the geometry is the last good one.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub lost: bool,
|
||||
@@ -142,6 +148,7 @@ pub enum LinkGeom {
|
||||
pts: Vec<Vec2>,
|
||||
control: bool,
|
||||
degree: u8,
|
||||
periodic: bool,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -157,8 +164,11 @@ impl LinkGeom {
|
||||
LinkGeom::Ellipse { c, major, minor } => {
|
||||
ok(c) && ok(major) && c.dist(*major) > 1e-9 && minor.is_finite() && *minor > 1e-9 && *minor < 1e9
|
||||
}
|
||||
LinkGeom::Spline { pts, degree, .. } => {
|
||||
(2..=crate::curves::MAX_SPLINE_POINTS).contains(&pts.len()) && pts.iter().all(ok) && (1..=7).contains(degree)
|
||||
LinkGeom::Spline { pts, control, degree, periodic } => {
|
||||
(!*periodic || (!*control && *degree == 3 && crate::periodic_beziers(pts).is_ok()))
|
||||
&& (2..=crate::curves::MAX_SPLINE_POINTS).contains(&pts.len())
|
||||
&& pts.iter().all(ok)
|
||||
&& (1..=7).contains(degree)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -181,7 +191,7 @@ enum LCurve {
|
||||
Ellipse(usize, usize, f64),
|
||||
/// Start, end, first interior point and interior count (interior points are consecutive
|
||||
/// and never shared), control flag, degree.
|
||||
Spline(usize, usize, usize, usize, bool, u8),
|
||||
Spline(usize, usize, usize, usize, bool, u8, bool),
|
||||
}
|
||||
|
||||
fn layout(geom: &[LinkGeom]) -> Result<Layout> {
|
||||
@@ -234,14 +244,14 @@ fn layout(geom: &[LinkGeom]) -> Result<Layout> {
|
||||
l.curves.push(LCurve::Ellipse(c, m, minor));
|
||||
}
|
||||
}
|
||||
LinkGeom::Spline { pts, control, degree } => {
|
||||
LinkGeom::Spline { pts, control, degree, periodic } => {
|
||||
let (Some(first), Some(last)) = (pts.first(), pts.last()) else { continue };
|
||||
let s0 = pt(&mut l.pts, *first);
|
||||
let first_in = l.pts.len();
|
||||
let inner = pts.get(1..pts.len() - 1).unwrap_or_default();
|
||||
l.pts.extend(inner.iter().copied());
|
||||
let s1 = pt(&mut l.pts, *last);
|
||||
l.curves.push(LCurve::Spline(s0, s1, first_in, inner.len(), control, degree));
|
||||
l.curves.push(LCurve::Spline(s0, s1, first_in, inner.len(), control, degree, periodic));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -293,13 +303,20 @@ fn same_geometry(a: &[(LCurve, Vec<Vec2>)], b: &[(LCurve, Vec<Vec2>)]) -> bool {
|
||||
(LCurve::Arc(..), LCurve::Arc(..)) => all(),
|
||||
(LCurve::Conic(.., ra), LCurve::Conic(.., rb)) => all() && close(*ra, *rb),
|
||||
(LCurve::Ellipse(.., ra), LCurve::Ellipse(.., rb)) => all() && close(*ra, *rb),
|
||||
(LCurve::Spline(.., ca, da), LCurve::Spline(.., cb, db)) => ca == cb && da == db && all(),
|
||||
(LCurve::Spline(.., ca, da, pa), LCurve::Spline(.., cb, db, pb)) => ca == cb && da == db && pa == pb && all(),
|
||||
_ => false,
|
||||
}
|
||||
};
|
||||
if a.len() != b.len() {
|
||||
return false;
|
||||
}
|
||||
// Unchanged ordered links are common; avoid a quadratic permutation scan.
|
||||
if a.iter().zip(b).all(|(x, y)| matches(x, y)) {
|
||||
return true;
|
||||
}
|
||||
if a.len() > 512 {
|
||||
return false;
|
||||
}
|
||||
let mut used = vec![false; b.len()];
|
||||
a.iter().all(|x| {
|
||||
let hit = b.iter().enumerate().find(|(j, y)| !used.get(*j).copied().unwrap_or(true) && matches(x, y)).map(|(j, _)| j);
|
||||
@@ -330,6 +347,48 @@ fn curve_points(c: &LCurve) -> Vec<usize> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Incidence roles distinguish nearby arc centres, endpoints and hole centres during a
|
||||
/// resize. Spatial proximity alone can select a different kind of point in a dense rim.
|
||||
fn point_roles(curves: &[LCurve], point_count: usize) -> Vec<[usize; 10]> {
|
||||
let mut roles = vec![[0; 10]; point_count];
|
||||
let mut add = |point: usize, role: usize| {
|
||||
if let Some(count) = roles.get_mut(point).and_then(|r| r.get_mut(role)) {
|
||||
*count += 1;
|
||||
}
|
||||
};
|
||||
for curve in curves {
|
||||
match *curve {
|
||||
LCurve::Line(a, b) => {
|
||||
add(a, 0);
|
||||
add(b, 0);
|
||||
}
|
||||
LCurve::Circle(c, _) => add(c, 1),
|
||||
LCurve::Arc(c, a, b) => {
|
||||
add(c, 2);
|
||||
add(a, 3);
|
||||
add(b, 3);
|
||||
}
|
||||
LCurve::Conic(a, b, x, _) => {
|
||||
add(a, 4);
|
||||
add(b, 4);
|
||||
add(x, 5);
|
||||
}
|
||||
LCurve::Ellipse(c, m, _) => {
|
||||
add(c, 6);
|
||||
add(m, 7);
|
||||
}
|
||||
LCurve::Spline(a, b, first, count, ..) => {
|
||||
add(a, 8);
|
||||
add(b, 8);
|
||||
for i in first..first + count {
|
||||
add(i, 9);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
roles
|
||||
}
|
||||
|
||||
impl Sketch {
|
||||
pub fn link(&self, id: &str) -> Option<&Link> {
|
||||
self.links.iter().find(|l| l.id == id)
|
||||
@@ -371,7 +430,7 @@ impl Sketch {
|
||||
return Err(SketchError::TooLarge);
|
||||
}
|
||||
let id = self.fresh("j");
|
||||
self.links.push(Link { id: id.clone(), kind, source, face_name: None, lost: false });
|
||||
self.links.push(Link { id: id.clone(), kind, source, face_name: None, auto_face: false, lost: false });
|
||||
self.build_link(&id, &lay)?;
|
||||
Ok(id)
|
||||
}
|
||||
@@ -400,13 +459,13 @@ impl Sketch {
|
||||
LCurve::Arc(c, a, b) => (CurveKind::Arc { c: point(self, c)?, a: point(self, a)?, b: point(self, b)? }, "a"),
|
||||
LCurve::Conic(a, b, x, rho) => (CurveKind::Conic { a: point(self, a)?, b: point(self, b)?, apex: point(self, x)?, rho }, "k"),
|
||||
LCurve::Ellipse(c, m, r) => (CurveKind::Ellipse { c: point(self, c)?, m: point(self, m)?, r }, "e"),
|
||||
LCurve::Spline(a, b, f, n, control, degree) => {
|
||||
LCurve::Spline(a, b, f, n, control, degree, periodic) => {
|
||||
let mut pts = vec![point(self, a)?];
|
||||
for i in f..f + n {
|
||||
pts.push(point(self, i)?);
|
||||
}
|
||||
pts.push(point(self, b)?);
|
||||
(CurveKind::Spline { pts, control, degree }, "s")
|
||||
(CurveKind::Spline { pts, control, degree, periodic }, "s")
|
||||
}
|
||||
};
|
||||
let cid = self.fresh(prefix);
|
||||
@@ -435,6 +494,16 @@ impl Sketch {
|
||||
return Err(SketchError::Unknown(id.into()));
|
||||
}
|
||||
let lay = layout(geom)?;
|
||||
if self.link(id).is_some_and(|l| matches!(l.source, LinkSource::Face { .. }))
|
||||
&& lay.lone.is_empty()
|
||||
&& lay.curves.len() <= 512
|
||||
&& lay.pts.len() <= 512
|
||||
&& lay.curves.iter().all(|c| matches!(c, LCurve::Line(..) | LCurve::Arc(..) | LCurve::Circle(..)))
|
||||
&& !loops::valid(&lay.curves, &lay.pts)
|
||||
{
|
||||
self.set_link_lost(id, true);
|
||||
return Err(SketchError::Invalid("projected face boundaries cross, touch or have ambiguous topology; last geometry retained".into()));
|
||||
}
|
||||
let curves = self.link_curves(id);
|
||||
let points = self.link_points(id);
|
||||
// Current layout of the link, in the same terms.
|
||||
@@ -447,7 +516,7 @@ impl Sketch {
|
||||
Some(CurveKind::Arc { c, a, b }) => Some(LCurve::Arc(local(*c)?, local(*a)?, local(*b)?)),
|
||||
Some(CurveKind::Conic { a, b, apex, rho }) => Some(LCurve::Conic(local(*a)?, local(*b)?, local(*apex)?, *rho)),
|
||||
Some(CurveKind::Ellipse { c, m, r }) => Some(LCurve::Ellipse(local(*c)?, local(*m)?, *r)),
|
||||
Some(CurveKind::Spline { pts, control, degree }) => {
|
||||
Some(CurveKind::Spline { pts, control, degree, periodic }) => {
|
||||
let (a, b) = (local(*pts.first()?)?, local(*pts.last()?)?);
|
||||
let inner: Vec<usize> =
|
||||
pts.get(1..pts.len().saturating_sub(1)).unwrap_or_default().iter().map(|q| local(*q)).collect::<Option<_>>()?;
|
||||
@@ -456,7 +525,7 @@ impl Sketch {
|
||||
if inner.iter().enumerate().any(|(k, x)| *x != f + k) {
|
||||
return None;
|
||||
}
|
||||
Some(LCurve::Spline(a, b, f, inner.len(), *control, *degree))
|
||||
Some(LCurve::Spline(a, b, f, inner.len(), *control, *degree, *periodic))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
@@ -512,7 +581,7 @@ impl Sketch {
|
||||
LCurve::Arc(c, a, b) => LCurve::Arc(renum(c), renum(a), renum(b)),
|
||||
LCurve::Conic(a, b, x, r) => LCurve::Conic(renum(a), renum(b), renum(x), r),
|
||||
LCurve::Ellipse(c, m, r) => LCurve::Ellipse(renum(c), renum(m), r),
|
||||
LCurve::Spline(a, b, f, n, ct, d) => LCurve::Spline(renum(a), renum(b), renum(f), n, ct, d),
|
||||
LCurve::Spline(a, b, f, n, ct, d, periodic) => LCurve::Spline(renum(a), renum(b), renum(f), n, ct, d, periodic),
|
||||
})
|
||||
.collect();
|
||||
let same = match &cur {
|
||||
@@ -527,8 +596,8 @@ impl Sketch {
|
||||
(LCurve::Arc(a0, a1, a2), LCurve::Arc(b0, b1, b2)) => a0 == b0 && a1 == b1 && a2 == b2,
|
||||
(LCurve::Conic(a0, a1, a2, _), LCurve::Conic(b0, b1, b2, _)) => a0 == b0 && a1 == b1 && a2 == b2,
|
||||
(LCurve::Ellipse(a0, a1, _), LCurve::Ellipse(b0, b1, _)) => a0 == b0 && a1 == b1,
|
||||
(LCurve::Spline(a0, a1, a2, a3, a4, a5), LCurve::Spline(b0, b1, b2, b3, b4, b5)) => {
|
||||
a0 == b0 && a1 == b1 && (a2 == b2 || *a3 == 0) && a3 == b3 && a4 == b4 && a5 == b5
|
||||
(LCurve::Spline(a0, a1, a2, a3, a4, a5, a6), LCurve::Spline(b0, b1, b2, b3, b4, b5, b6)) => {
|
||||
a0 == b0 && a1 == b1 && (a2 == b2 || *a3 == 0) && a3 == b3 && a4 == b4 && a5 == b5 && a6 == b6
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
@@ -539,26 +608,6 @@ impl Sketch {
|
||||
if let Some(l) = self.links.iter_mut().find(|l| l.id == id) {
|
||||
l.lost = false;
|
||||
}
|
||||
if same {
|
||||
for (k, pi) in points.iter().enumerate() {
|
||||
let p = order.get(k).and_then(|li| lay.pts.get(*li)).copied();
|
||||
if let (Some(p), Some(sp)) = (p, self.points.get_mut(*pi)) {
|
||||
sp.pos = p;
|
||||
}
|
||||
}
|
||||
for (ci, c) in curves.iter().zip(&new) {
|
||||
if let (LCurve::Circle(_, r), Some(Curve { kind: CurveKind::Circle { r: slot, .. }, .. })) = (c, self.curves.get_mut(*ci)) {
|
||||
*slot = *r;
|
||||
}
|
||||
if let (LCurve::Conic(.., r), Some(Curve { kind: CurveKind::Conic { rho, .. }, .. })) = (c, self.curves.get_mut(*ci)) {
|
||||
*rho = *r;
|
||||
}
|
||||
if let (LCurve::Ellipse(.., r), Some(Curve { kind: CurveKind::Ellipse { r: slot, .. }, .. })) = (c, self.curves.get_mut(*ci)) {
|
||||
*slot = *r;
|
||||
}
|
||||
}
|
||||
return Ok(false);
|
||||
}
|
||||
// The same geometry walked in another order or direction (e.g. a face loop re-read after
|
||||
// a rollback) is not a change: keep the entities, and the constraints on them.
|
||||
if let Some(cur) = &cur {
|
||||
@@ -588,6 +637,7 @@ impl Sketch {
|
||||
&& points.len() == lay.pts.len()
|
||||
&& cur.len() == lay.curves.len()
|
||||
&& points.len() <= 512
|
||||
&& cur.len() <= 512
|
||||
{
|
||||
let old: Vec<Vec2> = points.iter().filter_map(|i| self.point(*i)).collect();
|
||||
let normalized = |ps: &[Vec2]| -> Vec<Vec2> {
|
||||
@@ -595,10 +645,33 @@ impl Sketch {
|
||||
let hi = ps.iter().fold(Vec2::new(f64::NEG_INFINITY, f64::NEG_INFINITY), |a, p| Vec2::new(a.x.max(p.x), a.y.max(p.y)));
|
||||
ps.iter().map(|p| Vec2::new((p.x - lo.x) / (hi.x - lo.x).max(1e-9), (p.y - lo.y) / (hi.y - lo.y).max(1e-9))).collect()
|
||||
};
|
||||
let (a, b) = (normalized(&old), normalized(&lay.pts));
|
||||
let loop_roles_required = self.link(id).is_some_and(|l| matches!(l.source, LinkSource::Face { .. }))
|
||||
&& cur.iter().chain(&lay.curves).all(|c| matches!(c, LCurve::Line(..) | LCurve::Arc(..) | LCurve::Circle(..)))
|
||||
&& lay.lone.is_empty();
|
||||
let loop_roles = loop_roles_required.then(|| loops::roles(cur, &old, &lay.curves, &lay.pts)).flatten();
|
||||
if loop_roles_required && loop_roles.is_none() {
|
||||
self.set_link_lost(id, true);
|
||||
return Err(SketchError::Invalid("projected face boundary identity is ambiguous; last geometry retained".into()));
|
||||
}
|
||||
let (a, b) = match &loop_roles {
|
||||
Some(roles) => (roles.old_normal.clone(), roles.fresh_normal.clone()),
|
||||
None => (normalized(&old), normalized(&lay.pts)),
|
||||
};
|
||||
let (old_roles, fresh_roles) = (point_roles(cur, old.len()), point_roles(&lay.curves, lay.pts.len()));
|
||||
let mut mapping = Vec::new();
|
||||
for p in &a {
|
||||
let mut candidates: Vec<(usize, f64)> = b.iter().enumerate().map(|(i, q)| (i, p.dist(*q))).collect();
|
||||
for (old_i, p) in a.iter().enumerate() {
|
||||
let mut candidates: Vec<(usize, f64)> = b
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(i, _)| {
|
||||
old_roles.get(old_i) == fresh_roles.get(*i)
|
||||
&& loop_roles.as_ref().is_none_or(|roles| {
|
||||
roles.old.get(old_i) == roles.fresh.get(*i)
|
||||
&& roles.old_lines.get(old_i).zip(roles.fresh_lines.get(*i)).is_some_and(|(a, b)| loops::same_lines(a, b))
|
||||
})
|
||||
})
|
||||
.map(|(i, q)| (i, p.dist(*q)))
|
||||
.collect();
|
||||
candidates.sort_by(|x, y| x.1.total_cmp(&y.1));
|
||||
if let Some((i, d)) = candidates.first()
|
||||
&& *d < 0.1
|
||||
@@ -613,22 +686,59 @@ impl Sketch {
|
||||
let mut used = Vec::new();
|
||||
let mut curve_map = Vec::new();
|
||||
if mapping.len() == points.len() {
|
||||
for c in cur {
|
||||
for (curve_i, c) in cur.iter().enumerate() {
|
||||
let mapped: Option<Vec<usize>> = curve_points(c).iter().map(|i| mapping.get(*i).copied()).collect();
|
||||
let found = lay
|
||||
let candidates: Vec<usize> = lay
|
||||
.curves
|
||||
.iter()
|
||||
.enumerate()
|
||||
.find(|(i, fresh)| {
|
||||
if used.contains(i) || !same_shape(c, fresh) {
|
||||
return false;
|
||||
.filter_map(|(i, fresh)| {
|
||||
if !same_shape(c, fresh) {
|
||||
return None;
|
||||
}
|
||||
let fresh_pts = curve_points(fresh);
|
||||
mapped.as_ref().is_some_and(|p| {
|
||||
*p == fresh_pts || matches!(c, LCurve::Line(..)) && p.iter().rev().copied().collect::<Vec<_>>() == fresh_pts
|
||||
})
|
||||
mapped
|
||||
.as_ref()
|
||||
.is_some_and(|p| {
|
||||
*p == fresh_pts || matches!(c, LCurve::Line(..)) && p.iter().rev().copied().collect::<Vec<_>>() == fresh_pts
|
||||
})
|
||||
.then_some(i)
|
||||
})
|
||||
.map(|(i, _)| i);
|
||||
.collect();
|
||||
let found = if candidates.len() == 1 {
|
||||
candidates.first().copied()
|
||||
} else if let LCurve::Circle(center, _) = c {
|
||||
// Concentric circular boundaries share a point graph. Their radius
|
||||
// order identifies the inner/outer rings through an upstream resize.
|
||||
let mut previous: Vec<(usize, f64)> = cur
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, x)| match x {
|
||||
LCurve::Circle(p, r) if p == center => Some((i, *r)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let mut incoming: Vec<(usize, f64)> = candidates
|
||||
.iter()
|
||||
.filter_map(|i| match lay.curves.get(*i) {
|
||||
Some(LCurve::Circle(_, r)) => Some((*i, *r)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
previous.sort_by(|a, b| a.1.total_cmp(&b.1));
|
||||
incoming.sort_by(|a, b| a.1.total_cmp(&b.1));
|
||||
let distinct = |xs: &[(usize, f64)]| {
|
||||
xs.windows(2).all(|w| matches!(w, [a, b] if b.1 - a.1 > MERGE_TOL * (1.0 + a.1.abs().max(b.1.abs()))))
|
||||
};
|
||||
if previous.len() == incoming.len() && distinct(&previous) && distinct(&incoming) {
|
||||
previous.iter().position(|(i, _)| *i == curve_i).and_then(|rank| incoming.get(rank).map(|(i, _)| *i))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let found = found.filter(|i| !used.contains(i));
|
||||
if let Some(i) = found {
|
||||
used.push(i);
|
||||
curve_map.push(i);
|
||||
@@ -649,10 +759,47 @@ impl Sketch {
|
||||
{
|
||||
*r = *value;
|
||||
}
|
||||
if let (Some(Curve { kind: CurveKind::Conic { rho, .. }, .. }), Some(LCurve::Conic(.., value))) =
|
||||
(self.curves.get_mut(*ci), lay.curves.get(li))
|
||||
{
|
||||
*rho = *value;
|
||||
}
|
||||
if let (Some(Curve { kind: CurveKind::Ellipse { r, .. }, .. }), Some(LCurve::Ellipse(.., value))) =
|
||||
(self.curves.get_mut(*ci), lay.curves.get(li))
|
||||
{
|
||||
*r = *value;
|
||||
}
|
||||
}
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
// Equal topology alone does not identify a face boundary: an outer rim and a
|
||||
// hole can have identical point graphs. Never move saved curve ids between them
|
||||
// when the geometric match is ambiguous; the document reports a lost link.
|
||||
if same && self.link(id).is_some_and(|l| matches!(l.source, LinkSource::Face { .. })) {
|
||||
self.set_link_lost(id, true);
|
||||
return Err(SketchError::Invalid("projected face boundary identity is ambiguous; last geometry retained".into()));
|
||||
}
|
||||
if same {
|
||||
for (k, pi) in points.iter().enumerate() {
|
||||
let p = order.get(k).and_then(|li| lay.pts.get(*li)).copied();
|
||||
if let (Some(p), Some(sp)) = (p, self.points.get_mut(*pi)) {
|
||||
sp.pos = p;
|
||||
}
|
||||
}
|
||||
for (ci, c) in curves.iter().zip(&new) {
|
||||
if let (LCurve::Circle(_, r), Some(Curve { kind: CurveKind::Circle { r: slot, .. }, .. })) = (c, self.curves.get_mut(*ci)) {
|
||||
*slot = *r;
|
||||
}
|
||||
if let (LCurve::Conic(.., r), Some(Curve { kind: CurveKind::Conic { rho, .. }, .. })) = (c, self.curves.get_mut(*ci)) {
|
||||
*rho = *r;
|
||||
}
|
||||
if let (LCurve::Ellipse(.., r), Some(Curve { kind: CurveKind::Ellipse { r: slot, .. }, .. })) = (c, self.curves.get_mut(*ci)) {
|
||||
*slot = *r;
|
||||
}
|
||||
}
|
||||
return Ok(false);
|
||||
}
|
||||
// Rebuild: drop the old entities (constraints on them go too) and make new ones.
|
||||
self.drop_link_entities(id);
|
||||
self.build_link(id, &lay)?;
|
||||
@@ -724,3 +871,7 @@ impl Sketch {
|
||||
self.links.retain(|_| k.next().copied().unwrap_or(true));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "link_identity_tests.rs"]
|
||||
mod identity_tests;
|
||||
@@ -0,0 +1,333 @@
|
||||
use super::*;
|
||||
use crate::{ConstraintKind, solve};
|
||||
|
||||
fn square(size: f64) -> Vec<LinkGeom> {
|
||||
let pts = [Vec2::new(-size, -size), Vec2::new(size, -size), Vec2::new(size, size), Vec2::new(-size, size)];
|
||||
(0..4).map(|i| LinkGeom::Line(pts[i], pts[(i + 1) % 4])).collect()
|
||||
}
|
||||
|
||||
fn face() -> LinkSource {
|
||||
LinkSource::Face { body: "Case".into(), at: Vec3::ZERO }
|
||||
}
|
||||
|
||||
fn ring(outer_first: bool, outer: f64, inner: f64) -> Vec<LinkGeom> {
|
||||
let (first, second) = if outer_first { (outer, inner) } else { (inner, outer) };
|
||||
square(first).into_iter().chain(square(second)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_face_link_keeps_inner_ids_when_boundary_order_changes() {
|
||||
let mut sk = Sketch::new();
|
||||
// An older saved face may have enumerated its inner boundary first.
|
||||
let link = sk.add_link(LinkKind::Project, face(), &ring(false, 10.0, 8.0)).unwrap();
|
||||
let inner = sk.link_curves(&link)[0];
|
||||
let corner = match sk.curves[inner].kind {
|
||||
CurveKind::Line { a, .. } => a,
|
||||
_ => panic!(),
|
||||
};
|
||||
let free = sk.add_point(Vec2::new(-8.0, -8.0), None).unwrap();
|
||||
sk.add_constraint(ConstraintKind::Coincident { p: free, q: corner }, None).unwrap();
|
||||
let serialized = serde_json::to_string(&sk).unwrap();
|
||||
let mut sk: Sketch = serde_json::from_str(&serialized).unwrap();
|
||||
let before = sk.clone();
|
||||
assert!(!sk.update_link(&link, &ring(true, 10.0, 8.0)).unwrap());
|
||||
assert_eq!(sk, before, "canonical outer-first enumeration must not reinterpret saved ids");
|
||||
assert!(solve(&mut sk).ok());
|
||||
assert_eq!(sk.points[free].pos, Vec2::new(-8.0, -8.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resized_and_reordered_face_keeps_constraints_on_the_same_boundary() {
|
||||
let mut sk = Sketch::new();
|
||||
let link = sk.add_link(LinkKind::Project, face(), &ring(false, 10.0, 8.0)).unwrap();
|
||||
let points = sk.link_points(&link);
|
||||
let original: Vec<Vec2> = points.iter().map(|p| sk.points[*p].pos).collect();
|
||||
let ids: Vec<String> = sk.link_curves(&link).iter().map(|c| sk.curves[*c].id.clone()).collect();
|
||||
let free = sk.add_point(Vec2::new(-8.0, -8.0), None).unwrap();
|
||||
sk.add_constraint(ConstraintKind::Coincident { p: free, q: points[0] }, None).unwrap();
|
||||
let fresh: Vec<LinkGeom> = ring(true, 10.0, 8.0)
|
||||
.into_iter()
|
||||
.map(|g| match g {
|
||||
LinkGeom::Line(a, b) => LinkGeom::Line(Vec2::new(b.x * 2.0, b.y * 3.0), Vec2::new(a.x * 2.0, a.y * 3.0)),
|
||||
_ => panic!(),
|
||||
})
|
||||
.collect();
|
||||
assert!(!sk.update_link(&link, &fresh).unwrap());
|
||||
for (p, old) in points.iter().zip(original) {
|
||||
assert_eq!(sk.points[*p].pos, Vec2::new(old.x * 2.0, old.y * 3.0));
|
||||
}
|
||||
assert_eq!(ids, sk.link_curves(&link).iter().map(|c| sk.curves[*c].id.clone()).collect::<Vec<_>>());
|
||||
assert!(solve(&mut sk).ok());
|
||||
assert!(sk.points[free].pos.dist(Vec2::new(-16.0, -24.0)) < 1e-7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ambiguous_face_refresh_preserves_last_geometry_and_marks_link_lost() {
|
||||
let mut sk = Sketch::new();
|
||||
let link = sk.add_link(LinkKind::Project, face(), &ring(true, 10.0, 9.9)).unwrap();
|
||||
let before = sk.clone();
|
||||
assert!(sk.update_link(&link, &ring(false, 10.0, 2.0)).is_err());
|
||||
assert_eq!(sk.points, before.points);
|
||||
assert_eq!(sk.curves, before.curves);
|
||||
assert!(sk.link(&link).unwrap().lost);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_face_permutation_is_bounded_and_preserves_geometry() {
|
||||
let mut sk = Sketch::new();
|
||||
let geom: Vec<LinkGeom> = (1..=129).flat_map(|i| square(i as f64)).collect();
|
||||
let link = sk.add_link(LinkKind::Project, face(), &geom).unwrap();
|
||||
assert!(!sk.update_link(&link, &geom).unwrap(), "ordered unchanged geometry needs no permutation scan");
|
||||
let before = sk.clone();
|
||||
let reversed: Vec<LinkGeom> = (1..=129).rev().flat_map(|i| square(i as f64)).collect();
|
||||
assert!(sk.update_link(&link, &reversed).is_err());
|
||||
assert_eq!(sk.points, before.points);
|
||||
assert_eq!(sk.curves, before.curves);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn geometric_refresh_updates_conic_and_ellipse_scalar_values() {
|
||||
let mut sk = Sketch::new();
|
||||
let geom = |rho, minor| {
|
||||
vec![
|
||||
LinkGeom::Conic { a: Vec2::new(1.0, 1.0), apex: Vec2::new(2.0, 3.0), b: Vec2::new(4.0, 1.0), rho },
|
||||
LinkGeom::Ellipse { c: Vec2::new(10.0, 10.0), major: Vec2::new(14.0, 10.0), minor },
|
||||
]
|
||||
};
|
||||
let link = sk.add_link(LinkKind::Project, LinkSource::Origin, &geom(0.4, 2.0)).unwrap();
|
||||
assert!(!sk.update_link(&link, &geom(0.6, 3.0)).unwrap());
|
||||
assert!(matches!(sk.curves[0].kind, CurveKind::Conic { rho, .. } if rho == 0.6));
|
||||
assert!(matches!(sk.curves[1].kind, CurveKind::Ellipse { r, .. } if r == 3.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_curves_sharing_few_points_do_not_enter_permutation_matching() {
|
||||
let mut sk = Sketch::new();
|
||||
let geom = vec![LinkGeom::Line(Vec2::new(1.0, 1.0), Vec2::new(2.0, 2.0)); 513];
|
||||
let link = sk.add_link(LinkKind::Project, face(), &geom).unwrap();
|
||||
assert_eq!(sk.link_points(&link).len(), 2);
|
||||
let before = sk.clone();
|
||||
let shifted = vec![LinkGeom::Line(Vec2::new(3.0, 3.0), Vec2::new(4.0, 4.0)); 513];
|
||||
assert!(sk.update_link(&link, &shifted).is_err());
|
||||
assert_eq!(sk.points, before.points);
|
||||
assert_eq!(sk.curves, before.curves);
|
||||
assert!(sk.link(&link).unwrap().lost);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concentric_face_resize_keeps_inner_outer_circle_identity() {
|
||||
let mut sk = Sketch::new();
|
||||
let link = sk.add_link(LinkKind::Project, face(), &[LinkGeom::Circle(Vec2::ZERO, 8.0), LinkGeom::Circle(Vec2::ZERO, 10.0)]).unwrap();
|
||||
let ids: Vec<String> = sk.link_curves(&link).iter().map(|i| sk.curves[*i].id.clone()).collect();
|
||||
assert!(!sk.update_link(&link, &[LinkGeom::Circle(Vec2::ZERO, 20.0), LinkGeom::Circle(Vec2::ZERO, 16.0)]).unwrap());
|
||||
assert!(matches!(sk.curves[0].kind, CurveKind::Circle { r, .. } if r == 16.0));
|
||||
assert!(matches!(sk.curves[1].kind, CurveKind::Circle { r, .. } if r == 20.0));
|
||||
assert_eq!(ids, sk.link_curves(&link).iter().map(|i| sk.curves[*i].id.clone()).collect::<Vec<_>>());
|
||||
// Coincident circles do not have a unique boundary identity.
|
||||
let before = sk.clone();
|
||||
assert!(sk.update_link(&link, &[LinkGeom::Circle(Vec2::ZERO, 18.0), LinkGeom::Circle(Vec2::ZERO, 18.0)]).is_err());
|
||||
assert_eq!(sk.points, before.points);
|
||||
assert_eq!(sk.curves, before.curves);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resized_dense_rim_matches_arc_centres_by_role_before_proximity() {
|
||||
let mut sk = Sketch::new();
|
||||
let geometry = |half_width: f64, x: f64| {
|
||||
let mut out = square(half_width);
|
||||
let c = Vec2::new(x, -16.5);
|
||||
let left = c - Vec2::X * 3.0;
|
||||
let right = c + Vec2::X * 3.0;
|
||||
out.push(LinkGeom::Arc { c, a: right, b: left });
|
||||
out.push(LinkGeom::Arc { c, a: left, b: right });
|
||||
out
|
||||
};
|
||||
let link = sk.add_link(LinkKind::Project, face(), &geometry(38.0, -26.5)).unwrap();
|
||||
let arcs: Vec<usize> = sk.link_curves(&link).into_iter().filter(|i| matches!(sk.curves[*i].kind, CurveKind::Arc { .. })).collect();
|
||||
let ids: Vec<String> = arcs.iter().map(|i| sk.curves[*i].id.clone()).collect();
|
||||
// The old centre is spatially closer in normalized space to a fresh endpoint.
|
||||
// Both semicircles must still keep the same shared centre and logical endpoints.
|
||||
assert!(!sk.update_link(&link, &geometry(43.0, -31.5)).unwrap());
|
||||
for i in &arcs {
|
||||
let CurveKind::Arc { c, a, b } = sk.curves[*i].kind else { panic!() };
|
||||
assert_eq!(sk.points[c].pos, Vec2::new(-31.5, -16.5));
|
||||
assert!((sk.points[a].pos.dist(sk.points[c].pos) - 3.0).abs() < 1e-9);
|
||||
assert!((sk.points[b].pos.dist(sk.points[c].pos) - 3.0).abs() < 1e-9);
|
||||
}
|
||||
assert_eq!(ids, arcs.iter().map(|i| sk.curves[*i].id.clone()).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_face_resize_matches_each_loop_before_nearby_outer_vertices() {
|
||||
let rectangle = |x: f64, y: f64| {
|
||||
let p = [Vec2::new(-x, -y), Vec2::new(x, -y), Vec2::new(x, y), Vec2::new(-x, y)];
|
||||
(0..4).map(|i| LinkGeom::Line(p[i], p[(i + 1) % 4])).collect::<Vec<_>>()
|
||||
};
|
||||
let mut sk = Sketch::new();
|
||||
let old: Vec<_> = rectangle(38.0, 28.0).into_iter().chain(rectangle(40.0, 30.0)).collect();
|
||||
let link = sk.add_link(LinkKind::Project, face(), &old).unwrap();
|
||||
let ids: Vec<_> = sk.link_curves(&link).iter().map(|i| sk.curves[*i].id.clone()).collect();
|
||||
let points = sk.link_points(&link);
|
||||
let before: Vec<_> = points.iter().map(|i| sk.points[*i].pos).collect();
|
||||
let fresh: Vec<_> = rectangle(41.0, 36.0).into_iter().chain(rectangle(38.0, 33.0)).collect();
|
||||
assert!(!sk.update_link(&link, &fresh).unwrap());
|
||||
assert!(!sk.link(&link).unwrap().lost);
|
||||
for (i, p) in points.iter().zip(before) {
|
||||
let expected = if p.x.abs() == 38.0 { Vec2::new(p.x, p.y.signum() * 33.0) } else { Vec2::new(p.x.signum() * 41.0, p.y.signum() * 36.0) };
|
||||
assert_eq!(sk.points[*i].pos, expected);
|
||||
}
|
||||
assert_eq!(ids, sk.link_curves(&link).iter().map(|i| sk.curves[*i].id.clone()).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn growing_face_retains_stationary_hole_arcs_and_shared_centre() {
|
||||
let geometry = |width: f64| {
|
||||
let p = [Vec2::ZERO, Vec2::new(width, 0.0), Vec2::new(width, 30.0), Vec2::new(0.0, 30.0)];
|
||||
let mut out: Vec<_> = (0..4).map(|i| LinkGeom::Line(p[i], p[(i + 1) % 4])).collect();
|
||||
let c = Vec2::new(20.0, 15.0);
|
||||
out.extend([
|
||||
LinkGeom::Arc { c, a: c + Vec2::X * 5.0, b: c - Vec2::X * 5.0 },
|
||||
LinkGeom::Arc { c, a: c - Vec2::X * 5.0, b: c + Vec2::X * 5.0 },
|
||||
]);
|
||||
out
|
||||
};
|
||||
let mut sk = Sketch::new();
|
||||
let link = sk.add_link(LinkKind::Project, face(), &geometry(40.0)).unwrap();
|
||||
let saved = sk.clone();
|
||||
assert!(!sk.update_link(&link, &geometry(50.0)).unwrap());
|
||||
assert!(!sk.link(&link).unwrap().lost);
|
||||
for i in sk.link_curves(&link) {
|
||||
assert_eq!(sk.curves[i].id, saved.curves[i].id);
|
||||
if matches!(sk.curves[i].kind, CurveKind::Arc { .. }) {
|
||||
assert_eq!(sk.curves[i], saved.curves[i]);
|
||||
for p in sk.curves[i].kind.point_ids() {
|
||||
assert_eq!(sk.points[p], saved.points[p]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn touching_or_crossed_face_boundaries_refuse_without_retargeting_ids() {
|
||||
for x in [9.0, 11.0] {
|
||||
let mut sk = Sketch::new();
|
||||
let link = sk.add_link(LinkKind::Project, face(), &[LinkGeom::Circle(Vec2::ZERO, 10.0), LinkGeom::Circle(Vec2::ZERO, 1.0)]).unwrap();
|
||||
let saved = sk.clone();
|
||||
assert!(sk.update_link(&link, &[LinkGeom::Circle(Vec2::ZERO, 10.0), LinkGeom::Circle(Vec2::new(x, 0.0), 1.0)]).is_err());
|
||||
assert_eq!(sk.points, saved.points);
|
||||
assert_eq!(sk.curves, saved.curves);
|
||||
assert!(sk.link(&link).unwrap().lost);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resized_rounded_rim_retains_inner_outer_roles_with_shared_arc_centres() {
|
||||
let rounded = |x: f64, y: f64, r: f64| {
|
||||
let centres = [Vec2::new(x - r, -y + r), Vec2::new(x - r, y - r), Vec2::new(-x + r, y - r), Vec2::new(-x + r, -y + r)];
|
||||
let mut out = Vec::new();
|
||||
for i in 0..4 {
|
||||
let start = -std::f64::consts::FRAC_PI_2 + i as f64 * std::f64::consts::FRAC_PI_2;
|
||||
let previous = centres[(i + 3) % 4] + Vec2::from_angle(start) * r;
|
||||
let a = centres[i] + Vec2::from_angle(start) * r;
|
||||
let b = centres[i] + Vec2::from_angle(start + std::f64::consts::FRAC_PI_2) * r;
|
||||
out.push(LinkGeom::Line(previous, a));
|
||||
out.push(LinkGeom::Arc { c: centres[i], a, b });
|
||||
}
|
||||
out
|
||||
};
|
||||
let mut sk = Sketch::new();
|
||||
let old: Vec<_> = rounded(38.0, 28.0, 2.0).into_iter().chain(rounded(40.0, 30.0, 4.0)).collect();
|
||||
let link = sk.add_link(LinkKind::Project, face(), &old).unwrap();
|
||||
let curves = sk.link_curves(&link);
|
||||
let ids: Vec<_> = curves.iter().map(|i| sk.curves[*i].id.clone()).collect();
|
||||
let fresh: Vec<_> = rounded(41.0, 36.0, 4.0).into_iter().chain(rounded(38.0, 33.0, 1.0)).collect();
|
||||
assert!(!sk.update_link(&link, &fresh).unwrap());
|
||||
assert!(!sk.link(&link).unwrap().lost);
|
||||
assert_eq!(ids, sk.link_curves(&link).iter().map(|i| sk.curves[*i].id.clone()).collect::<Vec<_>>());
|
||||
for (old, fresh) in curves.iter().zip(rounded(38.0, 33.0, 1.0).into_iter().chain(rounded(41.0, 36.0, 4.0))) {
|
||||
match (&sk.curves[*old].kind, fresh) {
|
||||
(CurveKind::Line { a, b }, LinkGeom::Line(p, q)) => {
|
||||
assert!(sk.points[*a].pos.dist(p) < 1e-10);
|
||||
assert!(sk.points[*b].pos.dist(q) < 1e-10);
|
||||
}
|
||||
(CurveKind::Arc { c, a, b }, LinkGeom::Arc { c: p, a: q, b: r }) => {
|
||||
assert!(sk.points[*c].pos.dist(p) < 1e-10);
|
||||
assert!(sk.points[*a].pos.dist(q) < 1e-10);
|
||||
assert!(sk.points[*b].pos.dist(r) < 1e-10);
|
||||
}
|
||||
_ => panic!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn far_translated_small_hole_crossing_long_edge_is_not_certified_separate() {
|
||||
let mut sk = Sketch::new();
|
||||
let p = [Vec2::new(-1e8, 1.0), Vec2::new(1e8, 1.0), Vec2::new(1e8, 10.0), Vec2::new(-1e8, 10.0)];
|
||||
let mut old: Vec<_> = (0..4).map(|i| LinkGeom::Line(p[i], p[(i + 1) % 4])).collect();
|
||||
old.push(LinkGeom::Circle(Vec2::new(1e6, 5.0), 2.0));
|
||||
let link = sk.add_link(LinkKind::Project, face(), &old).unwrap();
|
||||
let saved = sk.clone();
|
||||
let mut fresh: Vec<_> = (0..4).map(|i| LinkGeom::Line(p[i], p[(i + 1) % 4])).collect();
|
||||
fresh.push(LinkGeom::Circle(Vec2::new(1e6, 0.0), 2.0));
|
||||
assert!(sk.update_link(&link, &fresh).is_err());
|
||||
assert_eq!(sk.points, saved.points);
|
||||
assert_eq!(sk.curves, saved.curves);
|
||||
assert!(sk.link(&link).unwrap().lost);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equal_nested_sibling_candidates_remain_ambiguous_after_loop_classification() {
|
||||
let mut sk = Sketch::new();
|
||||
let link = sk
|
||||
.add_link(
|
||||
LinkKind::Project,
|
||||
face(),
|
||||
&[LinkGeom::Circle(Vec2::ZERO, 10.0), LinkGeom::Circle(Vec2::new(-2.0, 0.0), 1.0), LinkGeom::Circle(Vec2::new(2.0, 0.0), 1.0)],
|
||||
)
|
||||
.unwrap();
|
||||
let saved = sk.clone();
|
||||
assert!(
|
||||
sk.update_link(
|
||||
&link,
|
||||
&[LinkGeom::Circle(Vec2::ZERO, 10.0), LinkGeom::Circle(Vec2::new(0.0, -2.0), 1.0), LinkGeom::Circle(Vec2::new(0.0, 2.0), 1.0)]
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(sk.points, saved.points);
|
||||
assert_eq!(sk.curves, saved.curves);
|
||||
assert!(sk.link(&link).unwrap().lost);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tiny_circle_crossing_huge_round_boundary_is_not_certified_separate() {
|
||||
let mut sk = Sketch::new();
|
||||
let direction = Vec2::new(std::f64::consts::FRAC_1_SQRT_2, std::f64::consts::FRAC_1_SQRT_2);
|
||||
let link = sk.add_link(LinkKind::Project, face(), &[LinkGeom::Circle(Vec2::ZERO, 1e8), LinkGeom::Circle(direction * (1e8 + 10.0), 2.0)]).unwrap();
|
||||
let saved = sk.clone();
|
||||
assert!(sk.update_link(&link, &[LinkGeom::Circle(Vec2::ZERO, 1e8), LinkGeom::Circle(direction * (1e8 + 1.0), 2.0)]).is_err());
|
||||
assert_eq!(sk.points, saved.points);
|
||||
assert_eq!(sk.curves, saved.curves);
|
||||
assert!(sk.link(&link).unwrap().lost);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn huge_loop_does_not_make_nearby_bowtie_edges_topologically_adjacent() {
|
||||
let mut sk = Sketch::new();
|
||||
let link = sk.add_link(LinkKind::Project, face(), &square(10.0)).unwrap();
|
||||
let saved = sk.clone();
|
||||
let p = [
|
||||
Vec2::ZERO,
|
||||
Vec2::new(0.04, 0.04),
|
||||
Vec2::new(0.0, 0.04),
|
||||
Vec2::new(0.04, 0.0),
|
||||
Vec2::new(9e8, 0.0),
|
||||
Vec2::new(9e8, 10.0),
|
||||
Vec2::new(0.0, 10.0),
|
||||
];
|
||||
let crossed: Vec<_> = (0..p.len()).map(|i| LinkGeom::Line(p[i], p[(i + 1) % p.len()])).collect();
|
||||
assert!(sk.update_link(&link, &crossed).is_err());
|
||||
assert_eq!(sk.points, saved.points);
|
||||
assert_eq!(sk.curves, saved.curves);
|
||||
assert!(sk.link(&link).unwrap().lost);
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
//! Conservative analytic boundary roles for associative face identity.
|
||||
//! Endpoint walks exclude support centres. Crossings/touches refuse before nesting.
|
||||
use super::{LCurve, curve_points};
|
||||
use crate::{Shape, intersections};
|
||||
use solvecraft_geom::Vec2;
|
||||
use std::f64::consts::TAU;
|
||||
|
||||
struct Boundary {
|
||||
curves: Vec<usize>,
|
||||
shapes: Vec<Shape>,
|
||||
lo: Vec2,
|
||||
hi: Vec2,
|
||||
depth: usize,
|
||||
signature: [usize; 3],
|
||||
}
|
||||
pub(super) struct Roles {
|
||||
pub old: Vec<Vec<usize>>,
|
||||
pub fresh: Vec<Vec<usize>>,
|
||||
pub old_normal: Vec<Vec2>,
|
||||
pub fresh_normal: Vec<Vec2>,
|
||||
pub old_lines: Vec<Vec<Vec2>>,
|
||||
pub fresh_lines: Vec<Vec<Vec2>>,
|
||||
}
|
||||
|
||||
pub(super) fn same_lines(a: &[Vec2], b: &[Vec2]) -> bool {
|
||||
a.len() == b.len() && a.iter().all(|x| b.iter().any(|y| x.dot(*y).abs() > 0.98))
|
||||
}
|
||||
fn on(s: &Shape, p: Vec2, tol: f64) -> bool {
|
||||
match *s {
|
||||
Shape::Line { a, b } => {
|
||||
let d = b - a;
|
||||
let t = (p - a).dot(d) / d.len2().max(1e-30);
|
||||
t >= -tol / d.len().max(tol) && t <= 1.0 + tol / d.len().max(tol) && (a + d * t).dist(p) <= tol
|
||||
}
|
||||
Shape::Round { c, r, start, sweep } => {
|
||||
(p.dist(c) - r).abs() <= tol && (sweep >= TAU - 1e-12 || ((p - c).angle() - start).rem_euclid(TAU) <= sweep + tol / r)
|
||||
}
|
||||
}
|
||||
}
|
||||
fn endpoints(s: &Shape) -> [Vec2; 2] {
|
||||
let (_, end) = s.range();
|
||||
[s.point(0.0), s.point(end)]
|
||||
}
|
||||
fn stable_intersections(a: &Shape, b: &Shape, tol: f64) -> Vec<Vec2> {
|
||||
match (*a, *b) {
|
||||
(Shape::Line { a, b }, Shape::Round { c, r, .. }) | (Shape::Round { c, r, .. }, Shape::Line { a, b }) => {
|
||||
let Some(direction) = (b - a).normalized() else { return Vec::new() };
|
||||
// Work in the circle's local orthonormal frame. The world-coordinate
|
||||
// quadratic discriminant can lose every significant bit on long lines.
|
||||
let foot = a + direction * (c - a).dot(direction);
|
||||
let distance = foot.dist(c);
|
||||
if distance > r + tol {
|
||||
return Vec::new();
|
||||
}
|
||||
let half = ((r - distance).max(0.0) * (r + distance)).sqrt();
|
||||
vec![foot - direction * half, foot + direction * half]
|
||||
}
|
||||
(Shape::Round { c: ac, r: ar, .. }, Shape::Round { c: bc, r: br, .. }) => {
|
||||
let ((small, r), (large, radius)) = if ar <= br { ((ac, ar), (bc, br)) } else { ((bc, br), (ac, ar)) };
|
||||
let delta = large - small;
|
||||
let distance = delta.len();
|
||||
if distance <= tol || distance > radius + r + tol || distance < radius - r - tol {
|
||||
return Vec::new();
|
||||
}
|
||||
let direction = delta / distance;
|
||||
// Compute from the smaller circle; factoring d^2-R^2 avoids the
|
||||
// cancellation of R^2-a^2 for a small hole crossing a huge circle.
|
||||
let along = ((distance - radius) * (distance + radius) + r * r) / (2.0 * distance);
|
||||
let height = ((r - along).max(0.0) * (r + along).max(0.0)).sqrt();
|
||||
let foot = small + direction * along;
|
||||
vec![foot - direction.perp() * height, foot + direction.perp() * height]
|
||||
}
|
||||
_ => intersections(a, b),
|
||||
}
|
||||
}
|
||||
fn clear(a: &Shape, b: &Shape, shared: &[Vec2], tol: f64) -> bool {
|
||||
let allowed = |p: Vec2| {
|
||||
shared.iter().any(|q| {
|
||||
let joint_tol = 1e-7 + 128.0 * f64::EPSILON * (1.0 + p.len().max(q.len()));
|
||||
q.dist(p) <= joint_tol
|
||||
})
|
||||
};
|
||||
// Parallel coincident lines/circles have no isolated intersections.
|
||||
// Interior overlap is nevertheless ambiguous, including duplicate boundaries.
|
||||
for s in [a, b] {
|
||||
let other = if std::ptr::eq(s, a) { b } else { a };
|
||||
let (_, end) = s.range();
|
||||
for t in [0.0, 0.5 * end, end] {
|
||||
let p = s.point(t);
|
||||
if on(other, p, tol) && !allowed(p) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
stable_intersections(a, b, tol).into_iter().all(|p| !on(a, p, tol) || !on(b, p, tol) || allowed(p))
|
||||
}
|
||||
fn contains(boundary: &Boundary, p: Vec2, tol: f64) -> Option<bool> {
|
||||
let mut crossings = 0;
|
||||
for shape in &boundary.shapes {
|
||||
// Avoid ray/vertex coincidences rather than guessing a half-open arc rule.
|
||||
if endpoints(shape).iter().any(|q| (q.y - p.y).abs() <= tol) {
|
||||
return None;
|
||||
}
|
||||
match *shape {
|
||||
Shape::Line { a, b } => {
|
||||
if (a.y > p.y) != (b.y > p.y) {
|
||||
let x = a.x + (p.y - a.y) * (b.x - a.x) / (b.y - a.y);
|
||||
if (x - p.x).abs() <= tol {
|
||||
return None;
|
||||
}
|
||||
crossings += usize::from(x > p.x);
|
||||
}
|
||||
}
|
||||
Shape::Round { c, r, start, sweep } => {
|
||||
let y = (p.y - c.y) / r;
|
||||
if (y.abs() - 1.0).abs() <= tol / r {
|
||||
return None;
|
||||
}
|
||||
if y.abs() < 1.0 {
|
||||
let angle = y.asin();
|
||||
for theta in [angle, std::f64::consts::PI - angle] {
|
||||
let off = (theta - start).rem_euclid(TAU);
|
||||
if off < sweep {
|
||||
let x = c.x + r * theta.cos();
|
||||
if (x - p.x).abs() <= tol {
|
||||
return None;
|
||||
}
|
||||
crossings += usize::from(x > p.x);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(crossings % 2 == 1)
|
||||
}
|
||||
fn boundaries(curves: &[LCurve], pts: &[Vec2]) -> Option<Vec<Boundary>> {
|
||||
let get = |i| pts.get(i).copied();
|
||||
let mut shapes = Vec::new();
|
||||
let mut ends = Vec::new();
|
||||
let mut incidence = vec![Vec::new(); pts.len()];
|
||||
for (i, curve) in curves.iter().enumerate() {
|
||||
let (shape, ep) = match *curve {
|
||||
LCurve::Line(a, b) => (Shape::Line { a: get(a)?, b: get(b)? }, Some((a, b))),
|
||||
LCurve::Arc(c, a, b) => {
|
||||
let (c, a_pos, b_pos) = (get(c)?, get(a)?, get(b)?);
|
||||
let sweep = ((b_pos - c).angle() - (a_pos - c).angle()).rem_euclid(TAU);
|
||||
(Shape::Round { c, r: c.dist(a_pos), start: (a_pos - c).angle(), sweep }, Some((a, b)))
|
||||
}
|
||||
LCurve::Circle(c, r) => (Shape::Round { c: get(c)?, r, start: 0.0, sweep: TAU }, None),
|
||||
// Existing free-form identity matching remains conservative and unchanged.
|
||||
_ => return None,
|
||||
};
|
||||
if let Some((a, b)) = ep {
|
||||
incidence.get_mut(a)?.push(i);
|
||||
incidence.get_mut(b)?.push(i);
|
||||
}
|
||||
shapes.push(shape);
|
||||
ends.push(ep);
|
||||
}
|
||||
if incidence.iter().any(|v| !v.is_empty() && v.len() != 2) {
|
||||
return None;
|
||||
}
|
||||
let mut visited = vec![false; curves.len()];
|
||||
let mut out = Vec::new();
|
||||
for first in 0..curves.len() {
|
||||
if *visited.get(first)? {
|
||||
continue;
|
||||
}
|
||||
let mut members = Vec::new();
|
||||
let mut pending = vec![first];
|
||||
while let Some(i) = pending.pop() {
|
||||
if *visited.get(i)? {
|
||||
continue;
|
||||
}
|
||||
*visited.get_mut(i)? = true;
|
||||
members.push(i);
|
||||
if let Some((a, b)) = *ends.get(i)? {
|
||||
pending.extend(incidence.get(a)?);
|
||||
pending.extend(incidence.get(b)?);
|
||||
}
|
||||
}
|
||||
let mut lo = Vec2::new(f64::INFINITY, f64::INFINITY);
|
||||
let mut hi = Vec2::new(f64::NEG_INFINITY, f64::NEG_INFINITY);
|
||||
let mut signature = [0; 3];
|
||||
let mut bound_shapes = Vec::new();
|
||||
for i in &members {
|
||||
let shape = *shapes.get(*i)?;
|
||||
let mut candidates = endpoints(&shape).to_vec();
|
||||
if let Shape::Round { c, r, .. } = shape {
|
||||
for angle in [0.0, std::f64::consts::FRAC_PI_2, std::f64::consts::PI, 3.0 * std::f64::consts::FRAC_PI_2] {
|
||||
let p = c + Vec2::from_angle(angle) * r;
|
||||
if on(&shape, p, 1e-7) {
|
||||
candidates.push(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
for p in candidates {
|
||||
lo = Vec2::new(lo.x.min(p.x), lo.y.min(p.y));
|
||||
hi = Vec2::new(hi.x.max(p.x), hi.y.max(p.y));
|
||||
}
|
||||
signature[match curves.get(*i)? {
|
||||
LCurve::Line(..) => 0,
|
||||
LCurve::Arc(..) => 1,
|
||||
_ => 2,
|
||||
}] += 1;
|
||||
bound_shapes.push(shape);
|
||||
}
|
||||
out.push(Boundary { curves: members, shapes: bound_shapes, lo, hi, depth: 0, signature });
|
||||
}
|
||||
let scale = out.iter().map(|b| (b.hi - b.lo).len()).fold(1.0, f64::max);
|
||||
let tol = (scale * 1e-10).max(1e-7);
|
||||
let mut work = 0usize;
|
||||
for i in 0..out.len() {
|
||||
for j in i..out.len() {
|
||||
for (a_i, a) in out.get(i)?.shapes.iter().enumerate() {
|
||||
for (b_i, b) in out.get(j)?.shapes.iter().enumerate() {
|
||||
if i == j && a_i >= b_i {
|
||||
continue;
|
||||
}
|
||||
work += 1;
|
||||
if work > 262_144 {
|
||||
return None;
|
||||
}
|
||||
let mut shared = Vec::new();
|
||||
if i == j {
|
||||
let ai = *out.get(i)?.curves.get(a_i)?;
|
||||
let bi = *out.get(j)?.curves.get(b_i)?;
|
||||
if let (Some((a0, a1)), Some((b0, b1))) = (*ends.get(ai)?, *ends.get(bi)?) {
|
||||
for point in [a0, a1] {
|
||||
if point == b0 || point == b1 {
|
||||
shared.push(get(point)?);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !clear(a, b, &shared, tol) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for i in 0..out.len() {
|
||||
let mut depth = 0;
|
||||
for j in 0..out.len() {
|
||||
if i == j {
|
||||
continue;
|
||||
}
|
||||
let shape = out.get(i)?.shapes.first()?;
|
||||
let (_, end) = shape.range();
|
||||
let inside = [0.317, 0.613, 0.823].into_iter().find_map(|t| contains(out.get(j)?, shape.point(end * t), tol))?;
|
||||
depth += usize::from(inside);
|
||||
}
|
||||
out.get_mut(i)?.depth = depth;
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
pub(super) fn valid(curves: &[LCurve], points: &[Vec2]) -> bool {
|
||||
boundaries(curves, points).is_some()
|
||||
}
|
||||
fn normalize(p: Vec2, lo: Vec2, hi: Vec2) -> Vec2 {
|
||||
Vec2::new((p.x - lo.x) / (hi.x - lo.x).max(1e-9), (p.y - lo.y) / (hi.y - lo.y).max(1e-9))
|
||||
}
|
||||
pub(super) fn roles(old_curves: &[LCurve], a: &[Vec2], fresh_curves: &[LCurve], b: &[Vec2]) -> Option<Roles> {
|
||||
let (previous, incoming) = (boundaries(old_curves, a)?, boundaries(fresh_curves, b)?);
|
||||
if previous.len() != incoming.len() {
|
||||
return None;
|
||||
}
|
||||
let bounds = |loops: &[Boundary]| {
|
||||
loops.iter().fold((Vec2::new(f64::INFINITY, f64::INFINITY), Vec2::new(f64::NEG_INFINITY, f64::NEG_INFINITY)), |(lo, hi), x| {
|
||||
(Vec2::new(lo.x.min(x.lo.x), lo.y.min(x.lo.y)), Vec2::new(hi.x.max(x.hi.x), hi.y.max(x.hi.y)))
|
||||
})
|
||||
};
|
||||
let ((alo, ahi), (blo, bhi)) = (bounds(&previous), bounds(&incoming));
|
||||
let mut mapping = Vec::new();
|
||||
for x in &previous {
|
||||
let mut candidates: Vec<_> = incoming
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, y)| x.depth == y.depth && x.signature == y.signature)
|
||||
.map(|(i, y)| (i, normalize((x.lo + x.hi) * 0.5, alo, ahi).dist(normalize((y.lo + y.hi) * 0.5, blo, bhi))))
|
||||
.collect();
|
||||
candidates.sort_by(|x, y| x.1.total_cmp(&y.1));
|
||||
let (i, d) = *candidates.first()?;
|
||||
if mapping.contains(&i) || (candidates.len() > 1 && (d >= 0.1 || candidates.get(1).is_some_and(|(_, second)| d >= second * 0.5))) {
|
||||
return None;
|
||||
}
|
||||
let y = incoming.get(i)?;
|
||||
// Preserve the conservative bound on relative boundary changes. This does
|
||||
// not mistake a stationary hole's coordinates for the outer loop's scaling.
|
||||
let old_size = normalize(x.hi, alo, ahi) - normalize(x.lo, alo, ahi);
|
||||
let new_size = normalize(y.hi, blo, bhi) - normalize(y.lo, blo, bhi);
|
||||
if old_size.dist(new_size) >= 0.1 {
|
||||
return None;
|
||||
}
|
||||
mapping.push(i);
|
||||
}
|
||||
let membership = |loops: &[Boundary], curves: &[LCurve], pts: &[Vec2], remap: Option<&[usize]>| -> Option<(Vec<Vec<usize>>, Vec<Vec2>)> {
|
||||
let mut roles = vec![Vec::new(); pts.len()];
|
||||
let mut coordinates = vec![Vec2::ZERO; pts.len()];
|
||||
for (i, loop_) in loops.iter().enumerate() {
|
||||
let target = remap.and_then(|m| m.get(i)).copied().unwrap_or(i);
|
||||
for curve in &loop_.curves {
|
||||
for p in curve_points(curves.get(*curve)?) {
|
||||
if !roles.get(p)?.contains(&target) {
|
||||
roles.get_mut(p)?.push(target);
|
||||
*coordinates.get_mut(p)? += normalize(*pts.get(p)?, loop_.lo, loop_.hi);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (role, coordinate) in roles.iter_mut().zip(&mut coordinates) {
|
||||
if role.is_empty() {
|
||||
return None;
|
||||
}
|
||||
role.sort_unstable();
|
||||
*coordinate = *coordinate / role.len() as f64;
|
||||
}
|
||||
Some((roles, coordinates))
|
||||
};
|
||||
let ((old, old_normal), (fresh, fresh_normal)) =
|
||||
(membership(&previous, old_curves, a, Some(&mapping))?, membership(&incoming, fresh_curves, b, None)?);
|
||||
let line_roles = |loops: &[Boundary], curves: &[LCurve], pts: &[Vec2]| -> Option<Vec<Vec<Vec2>>> {
|
||||
let mut roles = vec![Vec::new(); pts.len()];
|
||||
for loop_ in loops {
|
||||
let size = loop_.hi - loop_.lo;
|
||||
for i in &loop_.curves {
|
||||
if let LCurve::Line(a, b) = *curves.get(*i)? {
|
||||
let d = *pts.get(b)? - *pts.get(a)?;
|
||||
let direction = Vec2::new(d.x / size.x.max(1e-9), d.y / size.y.max(1e-9)).normalized()?;
|
||||
roles.get_mut(a)?.push(direction);
|
||||
roles.get_mut(b)?.push(direction);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(roles)
|
||||
};
|
||||
let old_lines = line_roles(&previous, old_curves, a)?;
|
||||
let fresh_lines = line_roles(&incoming, fresh_curves, b)?;
|
||||
Some(Roles { old, fresh, old_normal, fresh_normal, old_lines, fresh_lines })
|
||||
}
|
||||
+123
-16
@@ -53,6 +53,9 @@ pub enum CurveKind {
|
||||
control: bool,
|
||||
#[serde(default = "three")]
|
||||
degree: u8,
|
||||
/// Explicit cyclic C2 fit interpolation; absent retains natural endpoints.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
periodic: bool,
|
||||
},
|
||||
/// Conic from `a` to `b` shaped by the `apex` point and `rho` in (0, 1) (0.5 parabola,
|
||||
/// less elliptical, more hyperbolic).
|
||||
@@ -111,6 +114,7 @@ impl CurveKind {
|
||||
pub fn ends(&self) -> Option<(usize, usize)> {
|
||||
match self {
|
||||
CurveKind::Line { a, b } | CurveKind::Arc { a, b, .. } | CurveKind::Conic { a, b, .. } => Some((*a, *b)),
|
||||
CurveKind::Spline { periodic: true, .. } => None,
|
||||
CurveKind::Spline { pts, .. } => Some((*pts.first()?, *pts.last()?)),
|
||||
CurveKind::Circle { .. } | CurveKind::Ellipse { .. } => None,
|
||||
}
|
||||
@@ -233,6 +237,22 @@ pub enum ConstraintKind {
|
||||
l: usize,
|
||||
value: f64,
|
||||
},
|
||||
/// Signed angle of a line's stored start-to-end direction from sketch +X (radians).
|
||||
LineAngle {
|
||||
l: usize,
|
||||
value: f64,
|
||||
},
|
||||
/// Signed logical sweep of an arc (radians), preserving clockwise and major arcs.
|
||||
ArcSweep {
|
||||
c: usize,
|
||||
value: f64,
|
||||
},
|
||||
/// Overall length of a straight slot: cap-centre distance plus both cap radii.
|
||||
SlotOverallLength {
|
||||
a: usize,
|
||||
b: usize,
|
||||
value: f64,
|
||||
},
|
||||
Radius {
|
||||
c: usize,
|
||||
value: f64,
|
||||
@@ -282,6 +302,9 @@ impl ConstraintKind {
|
||||
| DistanceY { value, .. }
|
||||
| PointLineDistance { value, .. }
|
||||
| Length { value, .. }
|
||||
| LineAngle { value, .. }
|
||||
| ArcSweep { value, .. }
|
||||
| SlotOverallLength { value, .. }
|
||||
| Radius { value, .. }
|
||||
| Diameter { value, .. }
|
||||
| ArcLength { value, .. }
|
||||
@@ -298,6 +321,9 @@ impl ConstraintKind {
|
||||
| DistanceY { value, .. }
|
||||
| PointLineDistance { value, .. }
|
||||
| Length { value, .. }
|
||||
| LineAngle { value, .. }
|
||||
| ArcSweep { value, .. }
|
||||
| SlotOverallLength { value, .. }
|
||||
| Radius { value, .. }
|
||||
| Diameter { value, .. }
|
||||
| ArcLength { value, .. }
|
||||
@@ -307,7 +333,7 @@ impl ConstraintKind {
|
||||
}
|
||||
}
|
||||
pub fn is_angle(&self) -> bool {
|
||||
matches!(self, ConstraintKind::Angle { .. })
|
||||
matches!(self, ConstraintKind::Angle { .. } | ConstraintKind::LineAngle { .. } | ConstraintKind::ArcSweep { .. })
|
||||
}
|
||||
/// Short type name (Fusion-like) for listings.
|
||||
pub fn name(&self) -> &'static str {
|
||||
@@ -328,7 +354,8 @@ impl ConstraintKind {
|
||||
Distance { .. } | DistanceX { .. } | DistanceY { .. } | PointLineDistance { .. } | Length { .. } => "LinearDimension",
|
||||
Radius { .. } => "RadialDimension",
|
||||
Diameter { .. } => "DiameterDimension",
|
||||
Angle { .. } => "AngularDimension",
|
||||
Angle { .. } | LineAngle { .. } | ArcSweep { .. } => "AngularDimension",
|
||||
SlotOverallLength { .. } => "LinearDimension",
|
||||
Smooth { .. } => "Smooth",
|
||||
ArcLength { .. } => "ArcLengthDimension",
|
||||
LinearDiameter { .. } => "LinearDiameterDimension",
|
||||
@@ -340,12 +367,12 @@ impl ConstraintKind {
|
||||
Coincident { p, q } | HorizontalPoints { p, q } | VerticalPoints { p, q } => (vec![p, q], vec![]),
|
||||
Distance { p, q, .. } | DistanceX { p, q, .. } | DistanceY { p, q, .. } => (vec![p, q], vec![]),
|
||||
PointOnCurve { p, c } => (vec![p], vec![c]),
|
||||
Horizontal { l } | Vertical { l } | Length { l, .. } => (vec![], vec![l]),
|
||||
Radius { c, .. } | Diameter { c, .. } => (vec![], vec![c]),
|
||||
Horizontal { l } | Vertical { l } | Length { l, .. } | LineAngle { l, .. } => (vec![], vec![l]),
|
||||
Radius { c, .. } | Diameter { c, .. } | ArcSweep { c, .. } => (vec![], vec![c]),
|
||||
Parallel { a, b } | Perpendicular { a, b } | Collinear { a, b } | Tangent { a, b } | Equal { a, b } | Concentric { a, b } => {
|
||||
(vec![], vec![a, b])
|
||||
}
|
||||
Angle { a, b, .. } => (vec![], vec![a, b]),
|
||||
Angle { a, b, .. } | SlotOverallLength { a, b, .. } => (vec![], vec![a, b]),
|
||||
Midpoint { p, l } | PointLineDistance { p, l, .. } => (vec![p], vec![l]),
|
||||
Symmetric { p, q, l } => (vec![p, q], vec![l]),
|
||||
Fix { p } => (vec![p], vec![]),
|
||||
@@ -379,13 +406,13 @@ impl ConstraintKind {
|
||||
fp(p);
|
||||
fc(c);
|
||||
}
|
||||
Horizontal { l } | Vertical { l } | Length { l, .. } => fc(l),
|
||||
Radius { c, .. } | Diameter { c, .. } => fc(c),
|
||||
Horizontal { l } | Vertical { l } | Length { l, .. } | LineAngle { l, .. } => fc(l),
|
||||
Radius { c, .. } | Diameter { c, .. } | ArcSweep { c, .. } => fc(c),
|
||||
Parallel { a, b } | Perpendicular { a, b } | Collinear { a, b } | Tangent { a, b } | Equal { a, b } | Concentric { a, b } => {
|
||||
fc(a);
|
||||
fc(b);
|
||||
}
|
||||
Angle { a, b, .. } => {
|
||||
Angle { a, b, .. } | SlotOverallLength { a, b, .. } => {
|
||||
fc(a);
|
||||
fc(b);
|
||||
}
|
||||
@@ -469,6 +496,9 @@ pub struct Sketch {
|
||||
pub links: Vec<crate::link::Link>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub offsets: Vec<crate::offset::OffsetChain>,
|
||||
/// New certified normal offsets; legacy sampled output splines remain independent.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub freeform_offsets: Vec<crate::freeform_offset::FreeformOffset>,
|
||||
/// 3D curves (world coordinates) carried by the sketch.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub wires: Vec<crate::wire::Wire>,
|
||||
@@ -498,6 +528,7 @@ impl Sketch {
|
||||
constraints: Vec::new(),
|
||||
links: Vec::new(),
|
||||
offsets: Vec::new(),
|
||||
freeform_offsets: Vec::new(),
|
||||
wires: Vec::new(),
|
||||
counters: Default::default(),
|
||||
view: SketchView::default(),
|
||||
@@ -694,11 +725,12 @@ impl Sketch {
|
||||
Horizontal { l }
|
||||
| Vertical { l }
|
||||
| Length { l, .. }
|
||||
| LineAngle { l, .. }
|
||||
| Midpoint { l, .. }
|
||||
| Symmetric { l, .. }
|
||||
| PointLineDistance { l, .. }
|
||||
| LinearDiameter { l, .. } => need_line(l)?,
|
||||
ArcLength { c, .. } if !matches!(self.curves.get(c).map(|c| &c.kind), Some(CurveKind::Arc { .. })) => {
|
||||
ArcLength { c, .. } | ArcSweep { c, .. } if !matches!(self.curves.get(c).map(|c| &c.kind), Some(CurveKind::Arc { .. })) => {
|
||||
return Err(SketchError::WrongKind(name(c), "arc length needs an arc".into()));
|
||||
}
|
||||
Smooth { a, b } => {
|
||||
@@ -722,6 +754,36 @@ impl Sketch {
|
||||
need_round(a)?;
|
||||
need_round(b)?;
|
||||
}
|
||||
SlotOverallLength { a, b, value } => {
|
||||
if a == b || ![a, b].iter().all(|i| matches!(self.curves.get(*i).map(|c| &c.kind), Some(CurveKind::Arc { .. }))) {
|
||||
return Err(SketchError::Invalid("overall slot length needs two different arc caps".into()));
|
||||
}
|
||||
let radius = |cap: usize| {
|
||||
self.constraints
|
||||
.iter()
|
||||
.filter(|c| !c.driven)
|
||||
.find_map(|dimension| match dimension.kind {
|
||||
Radius { c, value } if c == cap => Some(value),
|
||||
Diameter { c, value } if c == cap => Some(value / 2.0),
|
||||
// Slot caps are constrained equal; a diameter on either drives both.
|
||||
Diameter { c, value } | Radius { c, value }
|
||||
if (c == a || c == b)
|
||||
&& self
|
||||
.constraints
|
||||
.iter()
|
||||
.any(|e| matches!(e.kind, Equal { a: x, b: y } if (x == a && y == b) || (x == b && y == a))) =>
|
||||
{
|
||||
Some(if matches!(dimension.kind, Diameter { .. }) { value / 2.0 } else { value })
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.or_else(|| self.radius(cap))
|
||||
.unwrap_or(0.0)
|
||||
};
|
||||
if value <= radius(a) + radius(b) + 1e-9 {
|
||||
return Err(SketchError::Invalid("overall slot length must exceed its width".into()));
|
||||
}
|
||||
}
|
||||
Tangent { a, b } => {
|
||||
let free = |i: usize| self.curves.get(i).is_some_and(|c| c.kind.is_freeform());
|
||||
if !(is_round(a) || is_round(b) || free(a) || free(b)) {
|
||||
@@ -739,6 +801,11 @@ impl Sketch {
|
||||
{
|
||||
return Err(SketchError::Invalid(format!("dimension value {v}")));
|
||||
}
|
||||
if let ArcSweep { value, .. } = *k
|
||||
&& !(value.abs() > 1e-9 && value.abs() < std::f64::consts::TAU - 1e-9)
|
||||
{
|
||||
return Err(SketchError::Invalid("arc sweep must be nonzero and less than a full turn".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -827,7 +894,7 @@ impl Sketch {
|
||||
|
||||
/// Is curve `c` held in place: fixed or projected (linked).
|
||||
pub fn curve_locked(&self, c: usize) -> bool {
|
||||
self.curves.get(c).is_some_and(|c| c.fixed || c.link.is_some())
|
||||
self.curves.get(c).is_some_and(|c| c.fixed || c.link.is_some() || self.freeform_offsets.iter().any(|offset| offset.output == c.id))
|
||||
}
|
||||
|
||||
/// Radius of a circle or arc.
|
||||
@@ -899,11 +966,13 @@ impl Sketch {
|
||||
)
|
||||
}
|
||||
CurveKind::Conic { a, b, apex, rho } => Some(vec![Seg2::Conic { a: pt(a)?, apex: pt(apex)?, b: pt(b)?, w: rho / (1.0 - rho).max(1e-9) }]),
|
||||
CurveKind::Spline { pts, control: false, .. } => {
|
||||
CurveKind::Spline { pts, control: false, periodic, .. } => {
|
||||
let p: Vec<Vec2> = pts.iter().map(pt).collect::<Option<_>>()?;
|
||||
Some(crate::curves::fit_beziers(&p).into_iter().map(|[p0, p1, p2, p3]| Seg2::Cubic { p0, p1, p2, p3 }).collect())
|
||||
Some(
|
||||
crate::curves::fit_beziers_mode(&p, *periodic).ok()?.into_iter().map(|[p0, p1, p2, p3]| Seg2::Cubic { p0, p1, p2, p3 }).collect(),
|
||||
)
|
||||
}
|
||||
CurveKind::Spline { pts, control: true, degree } if (*degree as usize) <= solvecraft_geom::MAX_BEZIER_DEGREE => {
|
||||
CurveKind::Spline { pts, control: true, degree, .. } if (*degree as usize) <= solvecraft_geom::MAX_BEZIER_DEGREE => {
|
||||
let p: Vec<Vec2> = pts.iter().map(pt).collect::<Option<_>>()?;
|
||||
let k = (*degree as usize).min(p.len().saturating_sub(1)).max(1);
|
||||
Some(crate::curves::bspline_beziers(&p, k).iter().filter_map(|c| solvecraft_geom::bezier(c)).collect())
|
||||
@@ -922,9 +991,9 @@ impl Sketch {
|
||||
(Some(c), Some(m)) => crate::curves::ellipse_polyline(c, m, *r),
|
||||
_ => Vec::new(),
|
||||
},
|
||||
CurveKind::Spline { pts, control, degree } => {
|
||||
CurveKind::Spline { pts, control, degree, periodic } => {
|
||||
let p: Option<Vec<Vec2>> = pts.iter().map(pt).collect();
|
||||
p.map(|p| crate::curves::spline_polyline(&p, *control, *degree)).unwrap_or_default()
|
||||
p.map(|p| crate::curves::spline_polyline_mode(&p, *control, *degree, *periodic)).unwrap_or_default()
|
||||
}
|
||||
CurveKind::Conic { a, b, apex, rho } => match (pt(a), pt(apex), pt(b)) {
|
||||
(Some(a), Some(x), Some(b)) => crate::curves::conic_polyline(a, x, b, *rho),
|
||||
@@ -960,10 +1029,20 @@ impl Sketch {
|
||||
}
|
||||
"e"
|
||||
}
|
||||
CurveKind::Spline { pts, degree, .. } => {
|
||||
CurveKind::Spline { pts, control, degree, periodic } => {
|
||||
if pts.len() < 2 || pts.len() > crate::curves::MAX_SPLINE_POINTS || !(1..=7).contains(degree) {
|
||||
return Err(SketchError::Invalid("a spline needs 2 to 500 points and degree 1 to 7".into()));
|
||||
}
|
||||
if *periodic {
|
||||
if *control || *degree != 3 {
|
||||
return Err(SketchError::Invalid("periodic mode requires a cubic fit spline".into()));
|
||||
}
|
||||
let p = pts
|
||||
.iter()
|
||||
.map(|i| self.point(*i).ok_or_else(|| SketchError::Invalid("missing periodic point".into())))
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
crate::periodic_beziers(&p)?;
|
||||
}
|
||||
"s"
|
||||
}
|
||||
CurveKind::Conic { rho, .. } => {
|
||||
@@ -1001,6 +1080,7 @@ impl Sketch {
|
||||
|
||||
/// Remove curves only (points stay), remapping constraints.
|
||||
fn drop_curves(&mut self, which: &[usize]) {
|
||||
self.prune_offsets_for_removed_curves(which);
|
||||
let mut cmap = vec![None; self.curves.len()];
|
||||
let mut n = 0;
|
||||
for (i, slot) in cmap.iter_mut().enumerate() {
|
||||
@@ -1028,7 +1108,34 @@ impl Sketch {
|
||||
let gone = |p: usize| p != 0 && which.contains(&p);
|
||||
let dead_curves: Vec<usize> =
|
||||
self.curves.iter().enumerate().filter(|(_, c)| c.kind.point_ids().into_iter().any(gone)).map(|(i, _)| i).collect();
|
||||
let private = dead_curves
|
||||
.iter()
|
||||
.filter_map(|i| self.curves.get(*i))
|
||||
.filter(|c| self.freeform_offsets.iter().any(|r| r.output == c.id))
|
||||
.flat_map(|c| c.kind.point_ids())
|
||||
.collect::<std::collections::BTreeSet<_>>();
|
||||
self.drop_curves(&dead_curves);
|
||||
let mut removed = which.iter().copied().filter(|i| *i != 0).collect::<std::collections::BTreeSet<_>>();
|
||||
// Keep any node still named by a surviving curve or constraint.
|
||||
let referenced = self.curves.iter().flat_map(|c| c.kind.point_ids()).collect::<std::collections::BTreeSet<_>>();
|
||||
let constraint_points = std::cell::RefCell::new(std::collections::BTreeSet::new());
|
||||
for constraint in &self.constraints {
|
||||
let mut kind = constraint.kind.clone();
|
||||
kind.remap(
|
||||
&|p| {
|
||||
constraint_points.borrow_mut().insert(p);
|
||||
Some(p)
|
||||
},
|
||||
&Some,
|
||||
);
|
||||
}
|
||||
let constraint_points = constraint_points.into_inner();
|
||||
for index in private {
|
||||
if index != 0 && !referenced.contains(&index) && !constraint_points.contains(&index) {
|
||||
removed.insert(index);
|
||||
}
|
||||
}
|
||||
let gone = |p: usize| removed.contains(&p);
|
||||
let mut pmap = vec![None; self.points.len()];
|
||||
let mut n = 0;
|
||||
for (i, slot) in pmap.iter_mut().enumerate() {
|
||||
|
||||
@@ -12,7 +12,51 @@ pub struct OffsetChain {
|
||||
}
|
||||
|
||||
impl Sketch {
|
||||
/// Removing an output removes its relationship. A partial analytic chain
|
||||
/// deletion releases the surviving outputs, while retained dependents keep
|
||||
/// their source references so the command's refresh refuses broken sources.
|
||||
pub(crate) fn prune_offsets_for_removed_curves(&mut self, which: &[usize]) {
|
||||
let removed = which.iter().filter_map(|i| self.curves.get(*i).map(|curve| curve.id.clone())).collect::<std::collections::BTreeSet<_>>();
|
||||
if removed.is_empty() {
|
||||
return;
|
||||
}
|
||||
let released = self
|
||||
.offsets
|
||||
.iter()
|
||||
.filter(|offset| offset.outputs.iter().any(|id| removed.contains(id)))
|
||||
.flat_map(|offset| offset.outputs.iter().cloned())
|
||||
.chain(self.freeform_offsets.iter().filter(|offset| removed.contains(&offset.output)).map(|offset| offset.output.clone()))
|
||||
.collect::<std::collections::BTreeSet<_>>();
|
||||
self.offsets.retain(|offset| !offset.outputs.iter().any(|id| removed.contains(id)));
|
||||
self.freeform_offsets.retain(|offset| !removed.contains(&offset.output));
|
||||
let points = self
|
||||
.curves
|
||||
.iter()
|
||||
.filter(|curve| released.contains(&curve.id))
|
||||
.flat_map(|curve| curve.kind.point_ids())
|
||||
.collect::<std::collections::BTreeSet<_>>();
|
||||
for index in points {
|
||||
if index != 0
|
||||
&& self.curves.iter().all(|curve| !curve.kind.uses(index) || released.contains(&curve.id))
|
||||
&& let Some(point) = self.points.get_mut(index)
|
||||
{
|
||||
point.fixed = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn refresh_offsets(&mut self) -> Result<(), SketchError> {
|
||||
if self.offsets.is_empty() && self.freeform_offsets.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut candidate = self.clone();
|
||||
candidate.refresh_analytic_offsets()?;
|
||||
candidate.refresh_freeform_offsets()?;
|
||||
*self = candidate;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn refresh_analytic_offsets(&mut self) -> Result<(), SketchError> {
|
||||
for offset in self.offsets.clone() {
|
||||
if offset.sources.len() != offset.outputs.len() || offset.sources.len() > 10_000 || !offset.distance.is_finite() {
|
||||
return Err(SketchError::Invalid("damaged offset chain".into()));
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
//! Explicit cyclic C2 fit splines. Missing periodic markers retain natural interpolation.
|
||||
use crate::{MAX_SPLINE_POINTS, Sketch, SketchError};
|
||||
use solvecraft_geom::Vec2;
|
||||
|
||||
type Result<T> = std::result::Result<T, SketchError>;
|
||||
fn bad() -> SketchError {
|
||||
SketchError::Invalid("periodic fit spline needs 3 distinct cyclic samples, an exact closing point, and regular bounded chords".into())
|
||||
}
|
||||
|
||||
pub(crate) fn validate_periodic_points(points: &[Vec2]) -> Result<()> {
|
||||
if points.len() < 4
|
||||
|| points.len() > MAX_SPLINE_POINTS
|
||||
|| points.first() != points.last()
|
||||
|| points.iter().any(|p| !p.is_finite() || p.x.abs() >= 1e9 || p.y.abs() >= 1e9)
|
||||
|| points.windows(2).any(|p| {
|
||||
let h = p[0].dist(p[1]);
|
||||
!h.is_finite() || h <= 1e-9
|
||||
})
|
||||
{
|
||||
return Err(bad());
|
||||
}
|
||||
let mut distinct = Vec::new();
|
||||
for p in points {
|
||||
if !distinct.contains(p) {
|
||||
distinct.push(*p);
|
||||
}
|
||||
if distinct.len() == 3 {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Err(bad())
|
||||
}
|
||||
pub fn periodic_beziers(points: &[Vec2]) -> Result<Vec<[Vec2; 4]>> {
|
||||
validate_periodic_points(points)?;
|
||||
let n = points.len() - 1;
|
||||
let h: Vec<f64> = points.windows(2).map(|p| p[0].dist(p[1])).collect();
|
||||
let mut diagonal = Vec::with_capacity(n);
|
||||
let mut rhs = Vec::with_capacity(n);
|
||||
for i in 0..n {
|
||||
let previous = (i + n - 1) % n;
|
||||
diagonal.push(2.0 * (h[previous] + h[i]));
|
||||
rhs.push(((points[i + 1] - points[i]) / h[i] - (points[i] - points[previous]) / h[previous]) * 6.0);
|
||||
}
|
||||
// Remove the two corner entries with a rank-one correction. The underlying
|
||||
// cyclic matrix is strictly diagonally dominant; all pivots are still checked.
|
||||
let corner = h[n - 1];
|
||||
let gamma = -diagonal[0];
|
||||
diagonal[0] -= gamma;
|
||||
diagonal[n - 1] -= corner * corner / gamma;
|
||||
let solve = |mut rhs: Vec<Vec2>| -> Result<Vec<Vec2>> {
|
||||
let mut diagonal = diagonal.clone();
|
||||
for i in 1..n {
|
||||
if !diagonal[i - 1].is_finite() || diagonal[i - 1].abs() < 1e-12 * (h[i - 1] + h[(i + n - 2) % n]) {
|
||||
return Err(bad());
|
||||
}
|
||||
let factor = h[i - 1] / diagonal[i - 1];
|
||||
diagonal[i] -= factor * h[i - 1];
|
||||
rhs[i] = rhs[i] - rhs[i - 1] * factor;
|
||||
}
|
||||
for i in (0..n).rev() {
|
||||
if !diagonal[i].is_finite() || diagonal[i].abs() < 1e-12 * (h[i] + h[(i + n - 1) % n]) {
|
||||
return Err(bad());
|
||||
}
|
||||
let next = rhs.get(i + 1).copied().unwrap_or_default() * h[i];
|
||||
rhs[i] = (rhs[i] - next) / diagonal[i];
|
||||
if !rhs[i].is_finite() {
|
||||
return Err(bad());
|
||||
}
|
||||
}
|
||||
Ok(rhs)
|
||||
};
|
||||
let mut second = solve(rhs)?;
|
||||
let mut correction_rhs = vec![Vec2::ZERO; n];
|
||||
correction_rhs[0].x = gamma;
|
||||
correction_rhs[n - 1].x = corner;
|
||||
let correction = solve(correction_rhs)?;
|
||||
let denominator = 1.0 + correction[0].x + corner * correction[n - 1].x / gamma;
|
||||
if !denominator.is_finite() || denominator.abs() <= 1e-12 {
|
||||
return Err(bad());
|
||||
}
|
||||
let factor = (second[0] + second[n - 1] * (corner / gamma)) / denominator;
|
||||
for (value, correction) in second.iter_mut().zip(&correction) {
|
||||
*value -= factor * correction.x;
|
||||
}
|
||||
let mut out = Vec::with_capacity(n);
|
||||
for i in 0..n {
|
||||
let next = (i + 1) % n;
|
||||
let chord = points[i + 1] - points[i];
|
||||
let t0 = chord - (second[i] * 2.0 + second[next]) * (h[i] * h[i] / 6.0);
|
||||
let t1 = chord + (second[i] + second[next] * 2.0) * (h[i] * h[i] / 6.0);
|
||||
let cubic = [points[i], points[i] + t0 / 3.0, points[i + 1] - t1 / 3.0, points[i + 1]];
|
||||
if cubic.iter().any(|p| !p.is_finite() || p.x.abs() >= 1e9 || p.y.abs() >= 1e9) {
|
||||
return Err(bad());
|
||||
}
|
||||
out.push(cubic);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
impl Sketch {
|
||||
pub fn validate_periodic_splines(&self) -> Result<()> {
|
||||
let mut work = 0usize;
|
||||
for curve in &self.curves {
|
||||
if let crate::CurveKind::Spline { pts, control, degree, periodic: true } = &curve.kind {
|
||||
work = work.saturating_add(pts.len());
|
||||
if *control || *degree != 3 || work > 1_000_000 || pts.len() > MAX_SPLINE_POINTS {
|
||||
return Err(bad());
|
||||
}
|
||||
let points = pts.iter().map(|i| self.point(*i).ok_or_else(bad)).collect::<Result<Vec<_>>>()?;
|
||||
validate_periodic_points(&points)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn periodic_c2_unequal_chords_and_legacy_natural_are_distinct() {
|
||||
let p = [Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(3.0, 2.0), Vec2::new(-1.0, 1.0), Vec2::new(0.0, 0.0)];
|
||||
let curves = periodic_beziers(&p).unwrap();
|
||||
for i in 0..curves.len() {
|
||||
let j = (i + 1) % curves.len();
|
||||
let (a, b) = (curves[i], curves[j]);
|
||||
let (ha, hb) = (p[i].dist(p[i + 1]), p[j].dist(p[j + 1]));
|
||||
assert_eq!(a[3], b[0]);
|
||||
assert!(((a[3] - a[2]) * (3.0 / ha) - (b[1] - b[0]) * (3.0 / hb)).len() < 1e-12);
|
||||
assert!(((a[3] - a[2] * 2.0 + a[1]) * (6.0 / (ha * ha)) - (b[2] - b[1] * 2.0 + b[0]) * (6.0 / (hb * hb))).len() < 1e-12);
|
||||
}
|
||||
let legacy = crate::fit_beziers(&p);
|
||||
assert!(
|
||||
(legacy[0][1] - legacy[0][0]).normalized().unwrap().dist((legacy.last().unwrap()[3] - legacy.last().unwrap()[2]).normalized().unwrap())
|
||||
> 0.01
|
||||
);
|
||||
let global = |t| crate::spline_point_mode(&p, false, 3, true, t);
|
||||
let h = 1e-5;
|
||||
assert!(((global(h) - global(0.0)) / h - (global(1.0) - global(1.0 - h)) / h).len() < 0.002);
|
||||
}
|
||||
#[test]
|
||||
fn periodic_rejects_two_samples_and_hostile_geometry() {
|
||||
let a = Vec2::ZERO;
|
||||
let b = Vec2::X;
|
||||
assert!(periodic_beziers(&[a, b, a, b, a]).is_err());
|
||||
assert!(periodic_beziers(&[a, b, Vec2::new(0.0, 1.0), b]).is_err());
|
||||
assert!(periodic_beziers(&[a, b, Vec2::new(f64::INFINITY, 1.0), a]).is_err());
|
||||
assert!(periodic_beziers(&vec![a; MAX_SPLINE_POINTS + 1]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn periodic_solver_closes_shared_roles_and_refuses_immutable_or_collapsed_nodes() {
|
||||
let mut sk = Sketch::new();
|
||||
let first = sk.add_point(Vec2::ZERO, None).unwrap();
|
||||
let a = sk.add_point(Vec2::new(4.0, 0.0), None).unwrap();
|
||||
let b = sk.add_point(Vec2::new(3.0, 2.0), None).unwrap();
|
||||
let seam = sk.add_point(Vec2::ZERO, None).unwrap();
|
||||
let c = sk.add_point(Vec2::new(-4.0, 0.0), None).unwrap();
|
||||
let d = sk.add_point(Vec2::new(-3.0, -2.0), None).unwrap();
|
||||
let last = sk.add_point(Vec2::ZERO, None).unwrap();
|
||||
sk.add_curve(crate::CurveKind::Spline { pts: vec![first, a, b, seam], control: false, degree: 3, periodic: true }, None).unwrap();
|
||||
sk.add_curve(crate::CurveKind::Spline { pts: vec![seam, c, d, last], control: false, degree: 3, periodic: true }, None).unwrap();
|
||||
sk.points[first].pos = Vec2::new(0.2, 0.1);
|
||||
assert!(crate::solve_holding(&mut sk, &crate::Hold { points: vec![first], radii: vec![] }).ok());
|
||||
assert_eq!(sk.point(first), sk.point(seam));
|
||||
assert_eq!(sk.point(first), sk.point(last));
|
||||
sk.validate_periodic_splines().unwrap();
|
||||
let mut fixed = sk.clone();
|
||||
fixed.points[first].fixed = true;
|
||||
fixed.points[seam].fixed = true;
|
||||
fixed.points[seam].pos.x += 1e-8;
|
||||
let before = fixed.clone();
|
||||
assert!(!crate::solve(&mut fixed).ok());
|
||||
assert_eq!(fixed, before);
|
||||
let mut collapsed = sk;
|
||||
collapsed.points[a].pos = collapsed.points[first].pos;
|
||||
let before = collapsed.clone();
|
||||
assert!(!crate::solve_holding(&mut collapsed, &crate::Hold { points: vec![first, a], radii: vec![] }).ok());
|
||||
assert_eq!(collapsed, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn periodic_link_projection_keeps_mode_and_break_geometry() {
|
||||
let p = vec![Vec2::ZERO, Vec2::new(4.0, 0.0), Vec2::new(3.0, 2.0), Vec2::new(-1.0, 1.0), Vec2::ZERO];
|
||||
let mut sk = Sketch::new();
|
||||
let source = crate::LinkSource::SketchCurve { sketch: 99, curve: "source".into() };
|
||||
let geometry = crate::LinkGeom::Spline { pts: p.clone(), control: false, degree: 3, periodic: true };
|
||||
let id = sk.add_link(crate::LinkKind::Project, source, &[geometry]).unwrap();
|
||||
let curve = sk.link_curves(&id)[0];
|
||||
assert!(matches!(sk.curves[curve].kind, crate::CurveKind::Spline { periodic: true, .. }));
|
||||
let before = sk.exact_segs(curve).unwrap();
|
||||
sk.break_link(&id).unwrap();
|
||||
assert_eq!(sk.exact_segs(curve).unwrap(), before);
|
||||
sk.validate_periodic_splines().unwrap();
|
||||
let mut singular = Sketch::new();
|
||||
let points =
|
||||
[Vec2::ZERO, Vec2::X, Vec2::ZERO, Vec2::new(0.0, 1.0), Vec2::ZERO].into_iter().map(|p| singular.add_point(p, None).unwrap()).collect();
|
||||
let curve = singular.add_curve(crate::CurveKind::Spline { pts: points, control: false, degree: 3, periodic: true }, None).unwrap();
|
||||
let before = singular.clone();
|
||||
assert!(singular.add_freeform_offset(curve, true, 0.1).is_err());
|
||||
assert_eq!(singular, before);
|
||||
}
|
||||
}
|
||||
+278
-13
@@ -9,7 +9,7 @@
|
||||
//! gives the remaining degrees of freedom and which points are fully determined.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use solvecraft_geom::Vec2;
|
||||
use solvecraft_geom::{Seg2, Vec2};
|
||||
|
||||
use crate::linalg::{Mat, determined_vars, solve as lin_solve};
|
||||
use crate::model::{ConstraintKind, CurveKind, Sketch};
|
||||
@@ -169,14 +169,73 @@ impl State<'_> {
|
||||
};
|
||||
crate::curves::ellipse_polyline(self.p(*ci), self.p(*m), r)
|
||||
}
|
||||
Some(CurveKind::Spline { pts, control, degree }) => {
|
||||
let p: Vec<Vec2> = pts.iter().map(|q| self.p(*q)).collect();
|
||||
crate::curves::spline_polyline(&p, *control, *degree)
|
||||
Some(CurveKind::Spline { pts, control, degree, periodic }) => {
|
||||
let p = self.spline_points(pts, *periodic);
|
||||
crate::curves::spline_polyline_mode(&p, *control, *degree, *periodic)
|
||||
}
|
||||
Some(CurveKind::Conic { a, b, apex, rho }) => crate::curves::conic_polyline(self.p(*a), self.p(*apex), self.p(*b), *rho),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
/// Point-on-curve constraints use the exact shape. A polyline residual would move an
|
||||
/// exact crossing onto its chord, changing geometry merely by splitting it.
|
||||
fn spline_points(&self, pts: &[usize], periodic: bool) -> Vec<Vec2> {
|
||||
let mut points: Vec<Vec2> = pts.iter().map(|i| self.p(*i)).collect();
|
||||
if periodic
|
||||
&& let Some(first) = points.first().copied()
|
||||
&& let Some(last) = points.last_mut()
|
||||
{
|
||||
*last = first;
|
||||
}
|
||||
points
|
||||
}
|
||||
fn freeform_dist(&self, c: usize, q: Vec2) -> f64 {
|
||||
let segs: Vec<Seg2> = match self.sk.curves.get(c).map(|c| &c.kind) {
|
||||
Some(CurveKind::Ellipse { c: ci, m, .. }) => {
|
||||
let center = self.p(*ci);
|
||||
let u = self.p(*m) - center;
|
||||
let a = u.len();
|
||||
let r = self.radius_of(c);
|
||||
if a <= 1e-12 || r <= 1e-12 {
|
||||
return q.dist(center);
|
||||
}
|
||||
let delta = q - center;
|
||||
let x = delta.dot(u) / (a * a);
|
||||
let y = delta.cross(u) / (a * r);
|
||||
return (x.hypot(y) - 1.0) * a.min(r);
|
||||
}
|
||||
Some(CurveKind::Spline { pts, control, degree, periodic }) => {
|
||||
let p = self.spline_points(pts, *periodic);
|
||||
if p.len() < 2 {
|
||||
return q.dist(p.first().copied().unwrap_or_default());
|
||||
}
|
||||
if *control {
|
||||
let k = (*degree as usize).min(solvecraft_geom::MAX_BEZIER_DEGREE).min(p.len().saturating_sub(1)).max(1);
|
||||
crate::curves::bspline_beziers(&p, k).iter().filter_map(|span| solvecraft_geom::bezier(span)).collect()
|
||||
} else {
|
||||
crate::curves::fit_beziers_mode(&p, *periodic)
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|[p0, p1, p2, p3]| Seg2::Cubic { p0, p1, p2, p3 })
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
Some(CurveKind::Conic { a, b, apex, rho }) => {
|
||||
vec![Seg2::Conic { a: self.p(*a), b: self.p(*b), apex: self.p(*apex), w: rho / (1.0 - rho).max(1e-9) }]
|
||||
}
|
||||
_ => Vec::new(),
|
||||
};
|
||||
segs.iter()
|
||||
.map(|seg| {
|
||||
let t = seg.closest_param(q);
|
||||
let delta = q - seg.point_at(t);
|
||||
let d = delta.len();
|
||||
(d, if seg.derivative(t).cross(delta) >= 0.0 { d } else { -d })
|
||||
})
|
||||
.min_by(|a, b| a.0.total_cmp(&b.0))
|
||||
.map(|(_, signed)| signed)
|
||||
.unwrap_or_else(|| crate::curves::polyline_signed_dist(&self.poly(c), q))
|
||||
}
|
||||
/// Radius of a circle or arc; an ellipse's minor radius.
|
||||
fn radius_of(&self, c: usize) -> f64 {
|
||||
match self.sk.curves.get(c).map(|x| &x.kind) {
|
||||
@@ -204,6 +263,17 @@ impl State<'_> {
|
||||
_ => 0.0,
|
||||
}
|
||||
}
|
||||
fn arc_sweep(&self, c: usize) -> f64 {
|
||||
let Some(curve) = self.sk.curves.get(c) else { return 0.0 };
|
||||
let CurveKind::Arc { c: cp, a, b } = curve.kind else { return 0.0 };
|
||||
let sweep = ((self.p(b) - self.p(cp)).angle() - (self.p(a) - self.p(cp)).angle()).rem_euclid(std::f64::consts::TAU);
|
||||
if curve.reversed { -sweep } else { sweep }
|
||||
}
|
||||
fn slot_length(&self, a: usize, b: usize) -> f64 {
|
||||
let (ca, ra) = self.round(a);
|
||||
let (cb, rb) = self.round(b);
|
||||
ca.dist(cb) + ra + rb
|
||||
}
|
||||
/// Curvature vector of a curve at its point `p` (towards the centre of curvature).
|
||||
fn curvature_at(&self, c: usize, p: usize) -> Vec2 {
|
||||
let Some(kind) = self.sk.curves.get(c).map(|c| &c.kind) else { return Vec2::ZERO };
|
||||
@@ -213,10 +283,10 @@ impl State<'_> {
|
||||
let (cc, r) = self.round(c);
|
||||
(cc - self.p(p)) / (r * r).max(1e-24)
|
||||
}
|
||||
CurveKind::Spline { pts, control, degree } => {
|
||||
let q: Vec<Vec2> = pts.iter().map(|i| self.p(*i)).collect();
|
||||
CurveKind::Spline { pts, control, degree, periodic } => {
|
||||
let q = self.spline_points(pts, *periodic);
|
||||
let at_end = pts.last() == Some(&p) && pts.first() != Some(&p);
|
||||
crate::curves::end_curvature(&|t| crate::curves::spline_point(&q, *control, *degree, t), at_end)
|
||||
crate::curves::end_curvature(&|t| crate::curves::spline_point_mode(&q, *control, *degree, *periodic, t), at_end)
|
||||
}
|
||||
CurveKind::Conic { a, b, apex, rho } => {
|
||||
let (pa, pb, px) = (self.p(*a), self.p(*b), self.p(*apex));
|
||||
@@ -229,9 +299,9 @@ impl State<'_> {
|
||||
match self.sk.curves.get(c).map(|c| &c.kind)? {
|
||||
CurveKind::Line { a, b } => (self.p(*b) - self.p(*a)).normalized(),
|
||||
CurveKind::Circle { .. } | CurveKind::Arc { .. } => (self.p(p) - self.round(c).0).perp().normalized(),
|
||||
CurveKind::Spline { pts, control, .. } => {
|
||||
let q: Vec<Vec2> = pts.iter().map(|i| self.p(*i)).collect();
|
||||
crate::curves::spline_end_tangent(&q, *control, pts.last() == Some(&p) && pts.first() != Some(&p))
|
||||
CurveKind::Spline { pts, control, periodic, .. } => {
|
||||
let q = self.spline_points(pts, *periodic);
|
||||
crate::curves::spline_end_tangent_mode(&q, *control, *periodic, pts.last() == Some(&p) && pts.first() != Some(&p))
|
||||
}
|
||||
CurveKind::Conic { a, b, apex, .. } => {
|
||||
if p == *a {
|
||||
@@ -281,7 +351,7 @@ fn residuals(s: &State, k: &ConstraintKind, out: &mut Vec<f64>) {
|
||||
PointOnCurve { p, c } => {
|
||||
let pp = s.p(p);
|
||||
if s.is_freeform(c) {
|
||||
out.push(crate::curves::polyline_signed_dist(&s.poly(c), pp));
|
||||
out.push(s.freeform_dist(c, pp));
|
||||
} else if s.is_line(c) {
|
||||
let (a, b) = s.line(c);
|
||||
out.push(line_dist(pp, a, b));
|
||||
@@ -388,6 +458,18 @@ fn residuals(s: &State, k: &ConstraintKind, out: &mut Vec<f64>) {
|
||||
let (a, b) = s.line(l);
|
||||
out.push(a.dist(b) - value);
|
||||
}
|
||||
LineAngle { l, value } => {
|
||||
let (a, b) = s.line(l);
|
||||
// A dimension with no typed length must not satisfy its angle by collapsing
|
||||
// the line. Scale with the original geometry, independently of the unknowns.
|
||||
let scale = match s.sk.curves.get(l).map(|c| &c.kind) {
|
||||
Some(CurveKind::Line { a, b }) => s.sk.point(*a).zip(s.sk.point(*b)).map(|(a, b)| a.dist(b)).unwrap_or(1.0),
|
||||
_ => 1.0,
|
||||
};
|
||||
out.push(wrap_angle((b - a).angle() - value) * scale.max(1.0));
|
||||
}
|
||||
ArcSweep { c, value } => out.push((s.arc_sweep(c) - value) * s.sk.radius(c).unwrap_or(1.0).max(1.0)),
|
||||
SlotOverallLength { a, b, value } => out.push(s.slot_length(a, b) - value),
|
||||
Radius { c, value } => out.push(s.radius_of(c) - value),
|
||||
Diameter { c, value } => out.push(2.0 * s.round(c).1 - value),
|
||||
Angle { a, b, value, flip } => {
|
||||
@@ -438,6 +520,12 @@ fn measure(s: &State, k: &ConstraintKind) -> Option<f64> {
|
||||
let (a, b) = s.line(l);
|
||||
a.dist(b)
|
||||
}
|
||||
LineAngle { l, value } => {
|
||||
let (a, b) = s.line(l);
|
||||
value + wrap_angle((b - a).angle() - value)
|
||||
}
|
||||
ArcSweep { c, .. } => s.arc_sweep(c),
|
||||
SlotOverallLength { a, b, .. } => s.slot_length(a, b),
|
||||
Radius { c, .. } => s.radius_of(c),
|
||||
Diameter { c, .. } => 2.0 * s.round(c).1,
|
||||
Angle { a, b, flip, .. } => {
|
||||
@@ -466,6 +554,7 @@ pub fn measure_dimension(sk: &Sketch, k: &ConstraintKind) -> Option<f64> {
|
||||
/// One residual block: implicit arc radius equality, a user constraint, or a tangency at a known
|
||||
/// touch point (better conditioned than the distance form when an end point is on the curve).
|
||||
enum Block<'a> {
|
||||
Closure { a: usize, b: usize },
|
||||
Arc { c: usize, a: usize, b: usize },
|
||||
User(usize, &'a ConstraintKind),
|
||||
TangentAt(usize, &'a ConstraintKind, usize),
|
||||
@@ -473,6 +562,7 @@ enum Block<'a> {
|
||||
|
||||
fn copy_block<'a>(b: &Block<'a>) -> Block<'a> {
|
||||
match b {
|
||||
Block::Closure { a, b } => Block::Closure { a: *a, b: *b },
|
||||
Block::Arc { c, a, b } => Block::Arc { c: *c, a: *a, b: *b },
|
||||
Block::User(i, k) => Block::User(*i, k),
|
||||
Block::TangentAt(i, k, p) => Block::TangentAt(*i, k, *p),
|
||||
@@ -481,6 +571,10 @@ fn copy_block<'a>(b: &Block<'a>) -> Block<'a> {
|
||||
|
||||
fn block_residuals(s: &State, b: &Block, out: &mut Vec<f64>) {
|
||||
match b {
|
||||
Block::Closure { a, b } => {
|
||||
let d = s.p(*a) - s.p(*b);
|
||||
out.extend([d.x, d.y]);
|
||||
}
|
||||
Block::Arc { c, a, b } => {
|
||||
let cc = s.p(*c);
|
||||
out.push(cc.dist(s.p(*b)) - cc.dist(s.p(*a)));
|
||||
@@ -551,6 +645,10 @@ fn block_vars(sk: &Sketch, lay: &Layout, b: &Block) -> Vec<usize> {
|
||||
};
|
||||
use ConstraintKind::*;
|
||||
match b {
|
||||
Block::Closure { a, b } => {
|
||||
pt(&mut v, *a);
|
||||
pt(&mut v, *b);
|
||||
}
|
||||
Block::Arc { c, a, b } => {
|
||||
pt(&mut v, *c);
|
||||
pt(&mut v, *a);
|
||||
@@ -569,14 +667,21 @@ fn block_vars(sk: &Sketch, lay: &Layout, b: &Block) -> Vec<usize> {
|
||||
pt(&mut v, p);
|
||||
curve(&mut v, c);
|
||||
}
|
||||
Horizontal { l } | Vertical { l } | Length { l, .. } | Radius { c: l, .. } | Diameter { c: l, .. } => curve(&mut v, l),
|
||||
Horizontal { l }
|
||||
| Vertical { l }
|
||||
| Length { l, .. }
|
||||
| LineAngle { l, .. }
|
||||
| ArcSweep { c: l, .. }
|
||||
| Radius { c: l, .. }
|
||||
| Diameter { c: l, .. } => curve(&mut v, l),
|
||||
Parallel { a, b }
|
||||
| Perpendicular { a, b }
|
||||
| Collinear { a, b }
|
||||
| Tangent { a, b }
|
||||
| Equal { a, b }
|
||||
| Concentric { a, b }
|
||||
| Angle { a, b, .. } => {
|
||||
| Angle { a, b, .. }
|
||||
| SlotOverallLength { a, b, .. } => {
|
||||
curve(&mut v, a);
|
||||
curve(&mut v, b);
|
||||
}
|
||||
@@ -801,6 +906,20 @@ pub fn solve(sk: &mut Sketch) -> SolveReport {
|
||||
/// constraint between two entities holds the first so only the second moves. Everything else
|
||||
/// moves as little as it can. On failure the geometry is restored.
|
||||
pub fn solve_holding(sk: &mut Sketch, hold: &Hold) -> SolveReport {
|
||||
let mut orientation_before = Vec::new();
|
||||
for constraint in &sk.constraints {
|
||||
if !constraint.driven
|
||||
&& let ConstraintKind::ArcSweep { c, value } = constraint.kind
|
||||
&& value.is_finite()
|
||||
&& let Some(curve) = sk.curves.get_mut(c)
|
||||
&& let CurveKind::Arc { a, b, .. } = &mut curve.kind
|
||||
&& curve.reversed != (value < 0.0)
|
||||
{
|
||||
orientation_before.push((c, *a, *b, curve.reversed));
|
||||
std::mem::swap(a, b);
|
||||
curve.reversed = value < 0.0;
|
||||
}
|
||||
}
|
||||
let lay = layout(sk, hold);
|
||||
let mut x = vec![0.0; lay.n];
|
||||
for (i, p) in sk.points.iter().enumerate() {
|
||||
@@ -821,9 +940,45 @@ pub fn solve_holding(sk: &mut Sketch, hold: &Hold) -> SolveReport {
|
||||
}
|
||||
}
|
||||
let x0 = x.clone();
|
||||
// Exactly opposite directions sit on the wrapped angle's derivative discontinuity.
|
||||
// Nudge one free endpoint into a continuous branch before Newton iterations. The
|
||||
// untouched x0 still restores the complete original geometry on a failed solve.
|
||||
for constraint in &sk.constraints {
|
||||
if constraint.driven {
|
||||
continue;
|
||||
}
|
||||
let ConstraintKind::LineAngle { l, value } = constraint.kind else { continue };
|
||||
let Some(CurveKind::Line { a, b }) = sk.curves.get(l).map(|c| &c.kind) else { continue };
|
||||
let (pa, pb) = {
|
||||
let state = State { sk, lay: &lay, x: &x };
|
||||
(state.p(*a), state.p(*b))
|
||||
};
|
||||
let delta = wrap_angle((pb - pa).angle() - value);
|
||||
if delta.abs() < std::f64::consts::PI - 1e-5 || !delta.is_finite() {
|
||||
continue;
|
||||
}
|
||||
let d = Vec2::from_angle((pb - pa).angle() - delta.signum() * 0.01) * pa.dist(pb);
|
||||
let (point, at) = if lay.pvar.get(*b).copied().flatten().is_some() { (*b, pa + d) } else { (*a, pb - d) };
|
||||
if let Some(index) = lay.pvar.get(point).copied().flatten() {
|
||||
if let Some(v) = x.get_mut(index) {
|
||||
*v = at.x;
|
||||
}
|
||||
if let Some(v) = x.get_mut(index + 1) {
|
||||
*v = at.y;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut blocks: Vec<(Block, Vec<usize>)> = Vec::new();
|
||||
for c in &sk.curves {
|
||||
if let CurveKind::Spline { pts, periodic: true, .. } = &c.kind
|
||||
&& let (Some(a), Some(b)) = (pts.first(), pts.last())
|
||||
&& a != b
|
||||
{
|
||||
let bl = Block::Closure { a: *a, b: *b };
|
||||
let vars = block_vars(sk, &lay, &bl);
|
||||
blocks.push((bl, vars));
|
||||
}
|
||||
if let CurveKind::Arc { c, a, b } = c.kind {
|
||||
let bl = Block::Arc { c, a, b };
|
||||
let vars = block_vars(sk, &lay, &bl);
|
||||
@@ -944,6 +1099,63 @@ pub fn solve_holding(sk: &mut Sketch, hold: &Hold) -> SolveReport {
|
||||
let (r, _, owner) = system(sk, &lay, &consts, &mut x, false);
|
||||
check(&r, &owner, &consts, &mut failing);
|
||||
}
|
||||
// Weld the whole connected closure graph, preserving every immutable node.
|
||||
// Validate the actual prospective geometry before accepting a numerical solve.
|
||||
let has_periodic = sk.curves.iter().any(|c| matches!(c.kind, CurveKind::Spline { periodic: true, .. }));
|
||||
let periodic_positions = if has_periodic {
|
||||
let state = State { sk, lay: &lay, x: &x };
|
||||
let mut positions = (0..sk.points.len()).map(|i| state.p(i)).collect::<Vec<_>>();
|
||||
let mut parent = (0..positions.len()).collect::<Vec<_>>();
|
||||
for curve in &sk.curves {
|
||||
if let CurveKind::Spline { pts, periodic: true, .. } = &curve.kind
|
||||
&& let (Some(a), Some(b)) = (pts.first(), pts.last())
|
||||
&& *a < parent.len()
|
||||
&& *b < parent.len()
|
||||
{
|
||||
let (a, b) = (find(&mut parent, *a), find(&mut parent, *b));
|
||||
if let Some(slot) = parent.get_mut(b) {
|
||||
*slot = a;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut representatives = std::collections::BTreeMap::new();
|
||||
let mut valid = true;
|
||||
for i in 0..positions.len() {
|
||||
let root = find(&mut parent, i);
|
||||
if let Some(previous) = representatives.get(&root).copied() {
|
||||
let fixed = |p| lay.pvar.get(p).is_some_and(Option::is_none);
|
||||
if fixed(i) && fixed(previous) && positions[i] != positions[previous] {
|
||||
valid = false;
|
||||
}
|
||||
if fixed(i) && !fixed(previous) {
|
||||
representatives.insert(root, i);
|
||||
}
|
||||
} else {
|
||||
representatives.insert(root, i);
|
||||
}
|
||||
}
|
||||
for (i, position) in positions.iter_mut().enumerate() {
|
||||
if let Some(index) = representatives.get(&find(&mut parent, i)) {
|
||||
*position = state.p(*index);
|
||||
}
|
||||
}
|
||||
for curve in &sk.curves {
|
||||
if let CurveKind::Spline { pts, control, degree, periodic: true } = &curve.kind {
|
||||
let points = pts.iter().map(|i| positions.get(*i).copied()).collect::<Option<Vec<_>>>();
|
||||
if *control || *degree != 3 || points.as_ref().is_none_or(|p| crate::periodic::validate_periodic_points(p).is_err()) {
|
||||
valid = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !valid {
|
||||
max_residual = max_residual.max(1.0);
|
||||
None
|
||||
} else {
|
||||
Some(positions)
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let status = if max_residual < ACCEPT { SolveStatus::Solved } else { SolveStatus::Failed };
|
||||
let use_x = if status == SolveStatus::Solved { &x } else { &x0 };
|
||||
// Write back.
|
||||
@@ -957,6 +1169,24 @@ pub fn solve_holding(sk: &mut Sketch, hold: &Hold) -> SolveReport {
|
||||
*r = use_x.get(v).copied().unwrap_or(*r).abs().max(1e-9);
|
||||
}
|
||||
}
|
||||
if status == SolveStatus::Solved
|
||||
&& let Some(positions) = periodic_positions
|
||||
{
|
||||
for (point, position) in sk.points.iter_mut().zip(positions) {
|
||||
point.pos = position;
|
||||
}
|
||||
}
|
||||
if status == SolveStatus::Failed {
|
||||
for (ci, a_before, b_before, reversed) in orientation_before.into_iter().rev() {
|
||||
if let Some(curve) = sk.curves.get_mut(ci)
|
||||
&& let CurveKind::Arc { a, b, .. } = &mut curve.kind
|
||||
{
|
||||
*a = a_before;
|
||||
*b = b_before;
|
||||
curve.reversed = reversed;
|
||||
}
|
||||
}
|
||||
}
|
||||
let vdet = |v: Option<usize>| v.is_none_or(|v| det.get(v).copied().unwrap_or(false));
|
||||
let pdet = |p: usize| match lay.pvar.get(p).copied().flatten() {
|
||||
Some(v) => vdet(Some(v)) && vdet(Some(v + 1)),
|
||||
@@ -986,3 +1216,38 @@ pub fn solve_holding(sk: &mut Sketch, hold: &Hold) -> SolveReport {
|
||||
curve_determined,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod typed_dimension_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn failed_signed_sweep_restores_arc_orientation_and_coordinates() {
|
||||
let mut sk = Sketch::new();
|
||||
let c = sk.add_arc(Vec2::ZERO, Vec2::new(10.0, 0.0), Vec2::new(0.0, 10.0), [Some(0), None, None], None).unwrap();
|
||||
let id = sk.add_constraint(ConstraintKind::ArcSweep { c, value: std::f64::consts::FRAC_PI_2 }, None).unwrap();
|
||||
sk.curves[c].fixed = true;
|
||||
assert!(solve(&mut sk).ok());
|
||||
let before = sk.curves.clone();
|
||||
let points = sk.points.clone();
|
||||
sk.constraints.iter_mut().find(|constraint| constraint.id == id).unwrap().kind.set_value(-std::f64::consts::FRAC_PI_2);
|
||||
assert!(!solve(&mut sk).ok());
|
||||
assert_eq!(sk.curves, before);
|
||||
assert_eq!(sk.points, points);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signed_dimensions_validate_kinds_values_and_survive_curve_removal() {
|
||||
let mut sk = Sketch::new();
|
||||
let l = sk.add_line(Vec2::ZERO, Vec2::new(10.0, 10.0), Some(0), None, None).unwrap();
|
||||
assert!(sk.add_constraint(ConstraintKind::ArcSweep { c: l, value: 1.0 }, None).is_err());
|
||||
assert!(sk.add_constraint(ConstraintKind::LineAngle { l, value: f64::NAN }, None).is_err());
|
||||
sk.add_constraint(ConstraintKind::LineAngle { l, value: -std::f64::consts::FRAC_PI_4 }, None).unwrap();
|
||||
assert!(solve(&mut sk).ok());
|
||||
let CurveKind::Line { a, b } = sk.curves[l].kind else { panic!("line") };
|
||||
let direction = sk.points[b].pos - sk.points[a].pos;
|
||||
assert!((direction.angle() + std::f64::consts::FRAC_PI_4).abs() < 1e-7);
|
||||
sk.remove_curves(&[l]);
|
||||
assert!(sk.constraints.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -424,7 +424,7 @@ fn exact_profiles_for_high_degree_and_cut_free_form_curves() {
|
||||
.iter()
|
||||
.map(|p| sk.add_point(*p, None).unwrap())
|
||||
.collect();
|
||||
sk.add_curve(CurveKind::Spline { pts: ids.clone(), control: true, degree: 5 }, None).unwrap();
|
||||
sk.add_curve(CurveKind::Spline { pts: ids.clone(), control: true, degree: 5, periodic: false }, None).unwrap();
|
||||
sk.add_line_pts(ids[5], ids[0], None).unwrap();
|
||||
let pr = find_profiles(&sk);
|
||||
assert_eq!(pr.len(), 1);
|
||||
@@ -433,7 +433,7 @@ fn exact_profiles_for_high_degree_and_cut_free_form_curves() {
|
||||
// A fit spline arch over a base line, cut by a vertical line at x = 10.
|
||||
let mut sk = Sketch::default();
|
||||
let ids: Vec<usize> = [v(0.0, 0.0), v(6.0, 9.0), v(14.0, 9.0), v(20.0, 0.0)].iter().map(|p| sk.add_point(*p, None).unwrap()).collect();
|
||||
sk.add_curve(CurveKind::Spline { pts: ids.clone(), control: false, degree: 3 }, None).unwrap();
|
||||
sk.add_curve(CurveKind::Spline { pts: ids.clone(), control: false, degree: 3, periodic: false }, None).unwrap();
|
||||
sk.add_line_pts(ids[3], ids[0], None).unwrap();
|
||||
let (a, b) = (sk.add_point(v(10.0, -5.0), None).unwrap(), sk.add_point(v(10.0, 20.0), None).unwrap());
|
||||
sk.add_line_pts(a, b, None).unwrap();
|
||||
|
||||
+181
-20
@@ -1,4 +1,4 @@
|
||||
//! 3D sketch curves (wires): polylines in world coordinates that a sketch carries besides its
|
||||
//! 3D sketch curves (wires): polylines with explicit coordinates that a sketch carries besides its
|
||||
//! planar geometry — included 3D edges, curves projected onto surfaces, intersection curves.
|
||||
//! They are reference geometry: drawn and usable as paths, not part of profiles or the solver.
|
||||
|
||||
@@ -11,11 +11,35 @@ use crate::model::{Result, Sketch, SketchError};
|
||||
/// Most points one wire may have.
|
||||
pub const MAX_WIRE_POINTS: usize = 100_000;
|
||||
|
||||
/// Coordinate meaning of a stored wire and its editable fit points.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum WireSpace {
|
||||
/// Legacy drawn or detached geometry remains physically fixed in the world.
|
||||
#[default]
|
||||
World,
|
||||
/// Geometry follows the sketch's owning component placement.
|
||||
Component,
|
||||
}
|
||||
|
||||
impl WireSpace {
|
||||
/// Coordinate semantics of a retained legacy producer, including a currently lost link.
|
||||
pub fn from_legacy_link(link: &Link) -> Self {
|
||||
match (&link.kind, &link.source) {
|
||||
(LinkKind::Include, LinkSource::Edge { .. } | LinkSource::SketchCurve { .. })
|
||||
| (_, LinkSource::OnSurface { .. } | LinkSource::Intersection { .. } | LinkSource::Iso { .. }) => Self::Component,
|
||||
_ => Self::World,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Wire {
|
||||
pub id: String,
|
||||
/// World-space polyline.
|
||||
/// Polyline in `space` coordinates.
|
||||
pub pts: Vec<Vec3>,
|
||||
#[serde(default)]
|
||||
pub space: WireSpace,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub link: Option<String>,
|
||||
/// Drawn in a 3D sketch: the points the curve was drawn through (one: a point; two: a
|
||||
@@ -68,8 +92,11 @@ pub fn fit_polyline(fit: &[Vec3]) -> Vec<Vec3> {
|
||||
}
|
||||
|
||||
fn clean(w: &[Vec3]) -> Option<Vec<Vec3>> {
|
||||
if w.len() > MAX_WIRE_POINTS {
|
||||
return None;
|
||||
}
|
||||
let mut out: Vec<Vec3> = Vec::new();
|
||||
for p in w.iter().take(MAX_WIRE_POINTS) {
|
||||
for p in w {
|
||||
if !(p.is_finite() && p.x.abs() < 1e9 && p.y.abs() < 1e9 && p.z.abs() < 1e9) {
|
||||
return None;
|
||||
}
|
||||
@@ -80,7 +107,77 @@ fn clean(w: &[Vec3]) -> Option<Vec<Vec3>> {
|
||||
(out.len() >= 2).then_some(out)
|
||||
}
|
||||
|
||||
fn clean_wires(wires: &[Vec<Vec3>]) -> Result<Vec<Vec<Vec3>>> {
|
||||
if wires.len() > crate::link::MAX_LINK_ENTITIES || wires.iter().fold(0usize, |n, w| n.saturating_add(w.len())) > 1_000_000 {
|
||||
return Err(SketchError::Invalid("3D linked curves exceed the stored geometry budget".into()));
|
||||
}
|
||||
wires.iter().map(|w| clean(w).ok_or_else(|| SketchError::Invalid("3D linked curve points out of range or coincident".into()))).collect()
|
||||
}
|
||||
|
||||
fn drawn_polyline(fit: &[Vec3]) -> Result<Vec<Vec3>> {
|
||||
if fit.is_empty() || fit.len() > MAX_FIT_POINTS {
|
||||
return Err(SketchError::Invalid(format!("a 3D curve needs 1 to {MAX_FIT_POINTS} points")));
|
||||
}
|
||||
if fit.iter().any(|p| !(p.is_finite() && p.x.abs() < 1e9 && p.y.abs() < 1e9 && p.z.abs() < 1e9)) {
|
||||
return Err(SketchError::Invalid("3D point out of range".into()));
|
||||
}
|
||||
if fit.windows(2).any(|w| w[0].dist(w[1]) < 1e-9) {
|
||||
return Err(SketchError::Invalid("the points of a 3D curve must differ".into()));
|
||||
}
|
||||
let pts = fit_polyline(fit);
|
||||
if pts.iter().any(|p| !(p.is_finite() && p.x.abs() < 1e9 && p.y.abs() < 1e9 && p.z.abs() < 1e9)) {
|
||||
return Err(SketchError::Invalid("3D spline samples out of range".into()));
|
||||
}
|
||||
Ok(pts)
|
||||
}
|
||||
|
||||
impl Sketch {
|
||||
fn wire_budget(&self, replacing: Option<&str>, new_count: usize, new_points: usize) -> Result<()> {
|
||||
let mut count = new_count;
|
||||
let mut points = new_points;
|
||||
for w in self.wires.iter().filter(|w| replacing.is_none() || w.link.as_deref() != replacing) {
|
||||
count = count.saturating_add(1);
|
||||
points = points.saturating_add(w.pts.len()).saturating_add(w.fit.len());
|
||||
}
|
||||
if count > crate::link::MAX_LINK_ENTITIES || points > 1_000_000 {
|
||||
return Err(SketchError::Invalid("3D curves exceed the stored geometry budget".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validate saved arrays without regenerating legacy geometry or changing point values.
|
||||
pub fn validate_wires(&self) -> Result<()> {
|
||||
if self.wires.len() > crate::link::MAX_LINK_ENTITIES {
|
||||
return Err(SketchError::Invalid("too many 3D curves".into()));
|
||||
}
|
||||
let mut work = 0usize;
|
||||
let mut ids = std::collections::BTreeSet::new();
|
||||
for w in &self.wires {
|
||||
work = work.saturating_add(w.pts.len()).saturating_add(w.fit.len());
|
||||
if work > 1_000_000
|
||||
|| w.id.is_empty()
|
||||
|| w.id.len() > 512
|
||||
|| !ids.insert(&w.id)
|
||||
|| w.link.as_ref().is_some_and(|id| id.is_empty() || id.len() > 512)
|
||||
|| w.pts.is_empty()
|
||||
|| w.pts.len() > MAX_WIRE_POINTS
|
||||
|| w.fit.len() > MAX_FIT_POINTS
|
||||
|| (w.pts.len() == 1 && w.fit.len() != 1)
|
||||
|| w.pts.iter().chain(&w.fit).any(|p| !(p.is_finite() && p.x.abs() < 1e9 && p.y.abs() < 1e9 && p.z.abs() < 1e9))
|
||||
{
|
||||
return Err(SketchError::Invalid("3D curve arrays, ids or point bounds are invalid".into()));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Producer semantics for legacy wires with retained association provenance. Breaking a
|
||||
/// link removes this evidence, so detached wires conservatively retain world coordinates.
|
||||
pub fn legacy_wire_space(&self, wire: &Wire) -> WireSpace {
|
||||
let Some(link) = wire.link.as_deref().and_then(|id| self.link(id)) else { return WireSpace::World };
|
||||
WireSpace::from_legacy_link(link)
|
||||
}
|
||||
|
||||
pub fn wire_index(&self, id: &str) -> Option<usize> {
|
||||
self.wires.iter().position(|w| w.id == id)
|
||||
}
|
||||
@@ -92,13 +189,14 @@ impl Sketch {
|
||||
|
||||
/// Add a link with planar geometry and/or 3D wires.
|
||||
pub fn add_link_with_wires(&mut self, kind: LinkKind, source: LinkSource, geom: &[LinkGeom], wires: &[Vec<Vec3>]) -> Result<String> {
|
||||
let ws: Vec<Vec<Vec3>> = wires.iter().filter_map(|w| clean(w)).collect();
|
||||
let ws = clean_wires(wires)?;
|
||||
self.wire_budget(None, ws.len(), ws.iter().map(Vec::len).sum())?;
|
||||
if ws.is_empty() {
|
||||
return self.add_link(kind, source, geom);
|
||||
}
|
||||
let id = if geom.is_empty() {
|
||||
let id = self.fresh("j");
|
||||
self.links.push(Link { id: id.clone(), kind, source, face_name: None, lost: false });
|
||||
self.links.push(Link { id: id.clone(), kind, source, face_name: None, auto_face: false, lost: false });
|
||||
id
|
||||
} else {
|
||||
self.add_link(kind, source, geom)?
|
||||
@@ -112,7 +210,8 @@ impl Sketch {
|
||||
if self.link(id).is_none() {
|
||||
return Err(SketchError::Unknown(id.into()));
|
||||
}
|
||||
let ws: Vec<Vec<Vec3>> = wires.iter().filter_map(|w| clean(w)).collect();
|
||||
let ws = clean_wires(wires)?;
|
||||
self.wire_budget(Some(id), ws.len(), ws.iter().map(Vec::len).sum())?;
|
||||
let old: Vec<String> = self.link_wires(id).iter().filter_map(|i| self.wires.get(*i).map(|w| w.id.clone())).collect();
|
||||
self.wires.retain(|w| w.link.as_deref() != Some(id));
|
||||
for (k, pts) in ws.into_iter().enumerate() {
|
||||
@@ -120,24 +219,22 @@ impl Sketch {
|
||||
Some(o) => o.clone(),
|
||||
None => self.fresh("w"),
|
||||
};
|
||||
self.wires.push(Wire { id: wid, pts, link: Some(id.to_string()), fit: Vec::new() });
|
||||
self.wires.push(Wire { id: wid, pts, space: WireSpace::Component, link: Some(id.to_string()), fit: Vec::new() });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Add a curve drawn in a 3D sketch through `fit` (see [`Wire::fit`]).
|
||||
pub fn add_drawn_wire(&mut self, fit: &[Vec3]) -> Result<String> {
|
||||
if fit.is_empty() || fit.len() > MAX_FIT_POINTS {
|
||||
return Err(SketchError::Invalid(format!("a 3D curve needs 1 to {MAX_FIT_POINTS} points")));
|
||||
}
|
||||
if fit.iter().any(|p| !(p.is_finite() && p.x.abs() < 1e9 && p.y.abs() < 1e9 && p.z.abs() < 1e9)) {
|
||||
return Err(SketchError::Invalid("3D point out of range".into()));
|
||||
}
|
||||
if fit.windows(2).any(|w| w[0].dist(w[1]) < 1e-9) {
|
||||
return Err(SketchError::Invalid("the points of a 3D curve must differ".into()));
|
||||
}
|
||||
self.add_drawn_wire_in(fit, WireSpace::World)
|
||||
}
|
||||
|
||||
/// Add a drawn curve without changing the coordinate meaning supplied by its author.
|
||||
pub fn add_drawn_wire_in(&mut self, fit: &[Vec3], space: WireSpace) -> Result<String> {
|
||||
let pts = drawn_polyline(fit)?;
|
||||
self.wire_budget(None, 1, pts.len() + fit.len())?;
|
||||
let id = self.fresh(if fit.len() == 1 { "q" } else { "w" });
|
||||
self.wires.push(Wire { id: id.clone(), pts: fit_polyline(fit), link: None, fit: fit.to_vec() });
|
||||
self.wires.push(Wire { id: id.clone(), pts, space, link: None, fit: fit.to_vec() });
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
@@ -148,17 +245,32 @@ impl Sketch {
|
||||
return Err(SketchError::Invalid("3D point out of range".into()));
|
||||
}
|
||||
let w = self.wire_index(wire).ok_or_else(|| SketchError::Unknown(wire.into()))?;
|
||||
let space = self
|
||||
.wires
|
||||
.get(w)
|
||||
.filter(|w| w.link.is_none())
|
||||
.map(|w| w.space)
|
||||
.ok_or_else(|| SketchError::Invalid("linked 3D geometry cannot be moved".into()))?;
|
||||
let from = self.wires.get(w).and_then(|w| w.fit.get(index)).copied().ok_or_else(|| SketchError::Unknown(format!("{wire} point {index}")))?;
|
||||
let mut n = 0;
|
||||
for w in self.wires.iter_mut().filter(|w| !w.fit.is_empty()) {
|
||||
let mut changes = Vec::new();
|
||||
for (index, w) in self.wires.iter().enumerate().filter(|(_, w)| !w.fit.is_empty() && w.link.is_none() && w.space == space) {
|
||||
let mut fit = w.fit.clone();
|
||||
let mut changed = false;
|
||||
for p in w.fit.iter_mut().filter(|p| p.dist(from) < 1e-9) {
|
||||
for p in fit.iter_mut().filter(|p| p.dist(from) < 1e-9) {
|
||||
*p = to;
|
||||
changed = true;
|
||||
n += 1;
|
||||
}
|
||||
if changed {
|
||||
w.pts = fit_polyline(&w.fit);
|
||||
let pts = drawn_polyline(&fit)?;
|
||||
changes.push((index, fit, pts));
|
||||
}
|
||||
}
|
||||
for (index, fit, pts) in changes {
|
||||
if let Some(w) = self.wires.get_mut(index) {
|
||||
w.fit = fit;
|
||||
w.pts = pts;
|
||||
}
|
||||
}
|
||||
Ok(n)
|
||||
@@ -170,3 +282,52 @@ impl Sketch {
|
||||
self.prune_links();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn wire_space_defaults_and_preserves_detached_provenance() {
|
||||
let mut sk = Sketch::new();
|
||||
let id = sk.add_drawn_wire(&[Vec3::new(1.0, 2.0, 3.0)]).unwrap();
|
||||
assert_eq!(sk.wires[0].space, WireSpace::World);
|
||||
let mut raw = serde_json::to_value(&sk.wires[0]).unwrap();
|
||||
raw.as_object_mut().unwrap().remove("space");
|
||||
assert_eq!(serde_json::from_value::<Wire>(raw).unwrap().space, WireSpace::World);
|
||||
let link = sk
|
||||
.add_link_with_wires(
|
||||
LinkKind::Include,
|
||||
LinkSource::Edge { body: "Missing".into(), at: Vec3::ZERO },
|
||||
&[],
|
||||
&[vec![Vec3::new(1.0, 2.0, 3.0), Vec3::new(1.0, 2.0, 4.0)]],
|
||||
)
|
||||
.unwrap();
|
||||
sk.set_link_lost(&link, true);
|
||||
let wire = sk.wires.iter().find(|w| w.link.as_deref() == Some(&link)).unwrap();
|
||||
assert_eq!(sk.legacy_wire_space(wire), WireSpace::Component);
|
||||
let wid = wire.id.clone();
|
||||
sk.break_link(&link).unwrap();
|
||||
let wire = sk.wires.iter().find(|w| w.id == wid).unwrap();
|
||||
assert_eq!(wire.space, WireSpace::Component);
|
||||
assert_eq!(sk.legacy_wire_space(wire), WireSpace::World);
|
||||
assert_eq!(sk.wires.iter().find(|w| w.id == id).unwrap().space, WireSpace::World);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wire_space_invalid_producers_and_move_are_atomic() {
|
||||
let mut sk = Sketch::new();
|
||||
let wire = sk.add_drawn_wire_in(&[Vec3::ZERO, Vec3::Z], WireSpace::Component).unwrap();
|
||||
sk.add_drawn_wire(&[Vec3::ZERO]).unwrap();
|
||||
assert_eq!(sk.move_drawn_point(&wire, 0, Vec3::X).unwrap(), 1);
|
||||
assert_eq!(sk.wires[1].fit[0], Vec3::ZERO);
|
||||
let before = sk.clone();
|
||||
assert!(sk.move_drawn_point(&wire, 0, Vec3::Z).is_err());
|
||||
assert_eq!(sk, before);
|
||||
assert!(sk.add_link_with_wires(LinkKind::Include, LinkSource::Origin, &[], &[vec![Vec3::ZERO, Vec3::new(f64::NAN, 0.0, 0.0)]]).is_err());
|
||||
assert_eq!(sk, before);
|
||||
assert!(sk.add_link_with_wires(LinkKind::Include, LinkSource::Origin, &[], &[vec![Vec3::ZERO; MAX_WIRE_POINTS + 1]]).is_err());
|
||||
assert_eq!(sk, before);
|
||||
sk.validate_wires().unwrap();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user