SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Wave 282/509: SMLib pcurves: an end SMLib sets within the edge's tolerance is mapped onto our interval (and 3 more)
jyvikoffb0e6650bb3
diff --git a/crates/geom/src/brep/pcurve.rs b/crates/geom/src/brep/pcurve.rsindex 5c31d60ae3..3a86d24669 100644--- a/crates/geom/src/brep/pcurve.rs+++ b/crates/geom/src/brep/pcurve.rs@@ -495,7 +495,8 @@ impl On {let knots = match pc {Curve2::Spline { knots, .. } | Curve2::RationalSpline { knots, .. } => knots,};- let even = (0..=CHECKS).map(|k| t0 + (t1 - t0) * k as f64 / CHECKS as f64);+ // The ends exactly: `t0 + (t1 − t0)·1` may round past `t1`, where the pcurve has no point.+ let even = (0..=CHECKS).map(|k| if k == CHECKS { t1 } else { t0 + (t1 - t0) * k as f64 / CHECKS as f64 });let spans = knots.windows(2).filter_map(|k| Some((*k.first()?, *k.get(1)?))).filter(|(a, b)| a < b).take(1 << 12).map(|(a, b)| 0.5 * (a + b));even.chain(spans).all(|t| {let lifted = pc.eval(t).and_then(|q| self.surface.point(q));diff --git a/crates/geom/src/brep/pcurve_tests.rs b/crates/geom/src/brep/pcurve_tests.rsindex 04d5f096f8..31ffd01f8c 100644--- a/crates/geom/src/brep/pcurve_tests.rs+++ b/crates/geom/src/brep/pcurve_tests.rs@@ -22,7 +22,7 @@ fn lift_error(surface: &Surface, curve: &Curve, interval: [f64; 2], pc: &Curve2)let knots = match pc {Curve2::Spline { knots, .. } | Curve2::RationalSpline { knots, .. } => knots,};- let mut ts: Vec<f64> = (0..=64).map(|k| t0 + (t1 - t0) * k as f64 / 64.).collect();+ let mut ts: Vec<f64> = (0..=64).map(|k| if k == 64 { t1 } else { t0 + (t1 - t0) * k as f64 / 64. }).collect();ts.extend(knots.windows(2).filter(|k| k[0] < k[1]).map(|k| 0.5 * (k[0] + k[1])));ts.iter().map(|&t| s.point(pc.eval(t).unwrap()).unwrap().dist(c.point(t).unwrap())).fold(0., f64::max)}@@ -33,6 +33,18 @@ fn segment_points(pc: &Curve2) -> [[f64; 2]; 2] {}}+#[test]+fn a_spline_on_a_plane_over_an_interval_whose_even_steps_round_past_its_end_is_mapped() {+ // Poppy Humanoid's edge: t0 + (t1 − t0)·1 is 1.2985843833752289, one rounding past t1, where+ // a pcurve on [t0, t1] has no point; the closed form was refused for it.+ let (t0, t1) = (0.013209624271103393f64, 1.2985843833752286f64);+ assert!(t0 + (t1 - t0) * 1.0 > t1, "the interval's even step rounds past its end");+ let plane = Surface::Plane { origin: [0.; 3], u_axis: [1., 0., 0.], v_axis: [0., 1., 0.] };+ let curve = Curve::Spline { knots: vec![t0, t0, t0, t1, t1, t1], points: vec![[0., 0., 0.], [1., 2., 0.], [3., 1., 0.]] };+ let pc = &pcurves_within(&plane, &one(&curve, [t0, t1]), 1e-9, None).unwrap()[0][0];+ assert!(lift_error(&plane, &curve, [t0, t1], pc) < 1e-12);+}+#[test]fn lines_polylines_and_splines_on_planes_are_their_points_mapped() {let plane = Surface::PlaneThrough { origin: [1., 2., 3.], u_point: [3., 2., 3.], v_point: [1., 2., 7.] };diff --git a/crates/geom/src/bspline.rs b/crates/geom/src/bspline.rsindex 7836fc4917..c68957b973 100644--- a/crates/geom/src/bspline.rs+++ b/crates/geom/src/bspline.rs@@ -303,16 +303,24 @@ pub fn basis_bezier(knots: &[f64], a: f64, b: f64) -> SplineResult<Vec<f64>> {Ok(out)}+/// Ulps of the domain's magnitude a parameter may lie past a spline's domain end and still be+/// that end ([`find_span`]): the rounding of an affine step, `a + (b − a)·s`, a few ulps at most.+pub const DOMAIN_ROUNDING: f64 = 8.0;+/// The span index `k` with `knots[k] ≤ u < knots[k+1]` among the valid spans `p ≤ k < n`-/// (`n` control points), the last span closed at the domain end (NURBS Book A2.1).+/// (`n` control points), the last span closed at the domain end (NURBS Book A2.1). A parameter+/// past an end of the domain by floating-point rounding only ([`DOMAIN_ROUNDING`]) is at that+/// end: `a + (b − a)·1`, the last of a range's even steps, may round one step past `b`.pub fn find_span(knots: &[f64], p: usize, n: usize, u: f64) -> Option<usize> {if n <= p || knots.len() != n + p + 1 || !u.is_finite() {return None;}let (lo, hi) = (*knots.get(p)?, *knots.get(n)?);- if u < lo || u > hi {+ let slack = DOMAIN_ROUNDING * f64::EPSILON * lo.abs().max(hi.abs()).max(1.0);+ if u < lo - slack || u > hi + slack {return None;}+ let u = u.clamp(lo, hi);// The last non-empty span in [p, n−1] that starts at or before u: by bisection (the knots// are sorted), and at the domain end the last non-empty span.let mut k = if u >= hi {@@ -770,6 +778,19 @@ pub(crate) mod tests {assert_eq!(find_span(&knots, p, n, f64::NAN), None);}+ #[test]+ fn a_parameter_a_rounding_past_the_domain_end_is_the_end() {+ // Poppy Humanoid's interval: the last even step, t0 + (t1 − t0)·1, rounds one ulp past t1.+ let (t0, t1) = (0.013209624271103393f64, 1.2985843833752286f64);+ let past = t0 + (t1 - t0) * 1.0;+ assert!(past > t1);+ let knots = [t0, t0, t0, t1, t1, t1];+ assert_eq!(find_span(&knots, 2, 3, past), find_span(&knots, 2, 3, t1));+ assert_eq!(find_span(&knots, 2, 3, t0 - f64::EPSILON), find_span(&knots, 2, 3, t0));+ // A parameter outside the domain by more than rounding is still none.+ assert_eq!(find_span(&knots, 2, 3, t1 + 1e-9), None);+ }+#[test]fn a_segment_is_the_same_curve_on_its_interval() {use crate::brep::{Curve, eval::CurveEval};diff --git a/crates/smlib/src/pcurves.rs b/crates/smlib/src/pcurves.rsindex daf8b80cad..ca37050ffc 100644--- a/crates/smlib/src/pcurves.rs+++ b/crates/smlib/src/pcurves.rs@@ -49,18 +49,51 @@ fn trims(face: &TrimFace<'_>) -> Result<Vec<Vec<Curve2>>, String> {let e = edge_of(u.edge)?;let edge = out.edges.get(e).ok_or("an edge SMLib lost")?;let ours = face.edges.get(u.edge as usize).ok_or("edge reference")?;- let slack = 1e-9 * ours.interval.iter().fold(1.0f64, |m, t| m.max(t.abs()));- if (0..2).any(|k| (edge.interval[k] - ours.interval[k]).abs() > slack) {- return Err(format!("SMLib moved an edge's interval from {:?} to {:?}", ours.interval, edge.interval));- }let found = made_uses.iter().find(|m| m.edge as usize == e && m.forward == (u.forward != reversed));- pcs.push(found.ok_or("a use SMLib did not keep")?.pcurve.clone());+ let pc = found.ok_or("a use SMLib did not keep")?.pcurve.clone();+ pcs.push(on_our_interval(pc, ours, edge.interval)?);}result.push(pcs);}Ok(result)}+/// A pcurve SMLib made on its edge's interval `theirs`, on ours. SMLib may set an edge's end to+/// a parameter of its own (a knot its vertex lies at, the end of the part on the face): where+/// each end it chose is within the edge's tolerance of ours on the edge's curve, the pcurve is+/// mapped onto our interval by the affine change of parameter (exact for a B-spline: its knots+/// move), and the record's check measures it against the edge as any pcurve. Farther is SMLib+/// trimming the edge, refused with how far.+pub(crate) fn on_our_interval(pc: Curve2, ours: &solidcraft_geom::brep::pcurve::TrimEdge<'_>, theirs: [f64; 2]) -> Result<Curve2, String> {+ let [a, b] = ours.interval;+ let [c, d] = theirs;+ if a == c && b == d {+ return Ok(pc);+ }+ let curve = solidcraft_geom::brep::eval::CurveEval::new(ours.nurbs.unwrap_or(ours.curve)).map_err(|e| e.to_string())?;+ let at = |t: f64| curve.point(t).ok_or_else(|| format!("the edge's curve has no point at {t}"));+ let shift = at(a)?.dist(at(c)?).max(at(b)?.dist(at(d)?));+ if !(shift <= ours.tolerance) || !(d > c) {+ return Err(format!(+ "SMLib moved an edge's interval from {:?} to {:?}, its ends {shift} mm along its curve (tolerance {} mm)",+ ours.interval, theirs, ours.tolerance+ ));+ }+ let map = |k: f64| {+ if k == c {+ a+ } else if k == d {+ b+ } else {+ a + (k - c) * ((b - a) / (d - c))+ }+ };+ Ok(match pc {+ Curve2::Spline { knots, points } => Curve2::Spline { knots: knots.into_iter().map(map).collect(), points },+ Curve2::RationalSpline { knots, homogeneous } => Curve2::RationalSpline { knots: knots.into_iter().map(map).collect(), homogeneous },+ })+}+/// The face as a one-face open sheet, and its uses that go without trims.fn sheet(face: &TrimFace<'_>) -> Result<(b::Brep, HashSet<(u32, u32, u32)>), String> {let mut edges: Vec<b::Edge> = facediff --git a/crates/smlib/src/tests.rs b/crates/smlib/src/tests.rsindex 84f4064619..7054be25bd 100644--- a/crates/smlib/src/tests.rs+++ b/crates/smlib/src/tests.rs@@ -90,3 +90,22 @@ fn every_call_is_a_profiler_span_timed_by_the_c_api() {let names: Vec<&str> = r.rows.iter().filter(|r| r.category == "smlib").map(|r| r.name).collect();assert!(names.contains(&"smlib_make_box") && names.contains(&"smlib_brep_volume"), "{r:?}");}++/// SMLib may end an edge at a parameter of its own (a knot its vertex lies at): within the+/// edge's tolerance on its curve the pcurve is mapped onto our interval exactly; farther is SMLib+/// trimming the edge, refused with how far.+#[test]+fn a_pcurve_smlib_ends_within_the_edges_tolerance_is_mapped_onto_our_interval() {+ use solidcraft_geom::brep::pcurve::TrimEdge;+ use solidcraft_geom::brep::{Curve, Curve2};+ let line = Curve::Line { start: [0.0, 0.0, 0.0], end: [2.0, 0.0, 0.0] };+ let edge = TrimEdge { curve: &line, nurbs: None, interval: [0.0, 1.0], vertices: [0, 1], tolerance: 1e-5 };+ let theirs = [0.0, 1.0 - 2e-8];+ let pc = Curve2::Spline { knots: vec![0.0, 0.0, theirs[1], theirs[1]], points: vec![[0.0, 0.0], [1.0, 0.0]] };+ let mapped = crate::pcurves::on_our_interval(pc.clone(), &edge, theirs).unwrap();+ assert_eq!(mapped.interval(), Some([0.0, 1.0]));+ assert_eq!(mapped.eval(1.0), Some([1.0, 0.0]));+ // 0.02 mm along the edge is past its 1e-5 mm.+ let err = crate::pcurves::on_our_interval(pc, &edge, [0.0, 0.99]).unwrap_err();+ assert!(err.contains("SMLib moved an edge's interval") && err.contains("tolerance"), "{err}");+}diff --git a/crates/step/src/topology.rs b/crates/step/src/topology.rsindex 07453e91cd..4d1b9f1a36 100644--- a/crates/step/src/topology.rs+++ b/crates/step/src/topology.rs@@ -458,18 +458,11 @@ impl<'b, 'a> Builder<'b, 'a> {/// and the edge's tolerance covers it. A spline face's gaps are measured on the pcurves its/// kernel makes (`raise_edges`): an iterative nearest point may settle elsewhere on it.fn measure_edges(&mut self, surface: &BSurface, edge_loops: &[Vec<(u32, bool)>]) -> R<()> {- if !matches!(- surface,- BSurface::Plane { .. }- | BSurface::PlaneThrough { .. }- | BSurface::Cylinder { .. }- | BSurface::Cone { .. }- | BSurface::Sphere { .. }- | BSurface::Torus { .. }- ) {- return Ok(());- }let on = SurfaceEval::new(surface).map_err(|m| m.to_string())?;+ // One search grid for all of the face's points, each searched from the whole grid: a+ // nearest point carried on as the next one's start can settle on another part of a+ // closed spline.+ let starts = solidcraft_geom::tess::uv::Starts::default();for l in edge_loops {for &(e, _) in l {let edge = self.edges.get(e as usize).ok_or("edge reference")?;@@ -480,10 +473,10 @@ impl<'b, 'a> Builder<'b, 'a> {let eval = CurveEval::new(curve).map_err(|m| m.to_string())?;let mut gap = 0.0f64;for k in 0..=EDGE_GAP_SAMPLES {- let t = t0 + (t1 - t0) * (k as f64 / EDGE_GAP_SAMPLES as f64);+ let t = if k == EDGE_GAP_SAMPLES { t1 } else { t0 + (t1 - t0) * (k as f64 / EDGE_GAP_SAMPLES as f64) };let Some(p) = eval.point(t) else { continue };// A point with no nearest point is the pcurves' to refuse, with why.- let Some(s) = on.project(p, None, f64::INFINITY).and_then(|q| on.point(q)) else { continue };+ let Some(s) = on.project_with(&starts, p, None, f64::INFINITY).and_then(|q| on.point(q)) else { continue };gap = gap.max(s.dist(p));}self.cover_edge(e, gap, EDGE_SURFACE_MARGIN)?;@@ -502,7 +495,14 @@ impl<'b, 'a> Builder<'b, 'a> {return Err(format!("an edge lies {gap} mm off the face's surface"));}x.tolerance = margin * gap;+ let (tolerance, ends) = (x.tolerance, x.vertices);self.raised_edges.insert(e);+ // A vertex's tolerance covers every edge that meets it, as in any tolerant record.+ for v in ends {+ if let Some(vx) = self.vertices.get_mut(v as usize) {+ vx.tolerance = vx.tolerance.max(tolerance);+ }+ }Ok(())}@@ -523,7 +523,7 @@ impl<'b, 'a> Builder<'b, 'a> {let eval = CurveEval::new(curve).map_err(|m| m.to_string())?;let mut gap = 0.0f64;for k in 0..=EDGE_GAP_SAMPLES {- let t = t0 + (t1 - t0) * (k as f64 / EDGE_GAP_SAMPLES as f64);+ let t = if k == EDGE_GAP_SAMPLES { t1 } else { t0 + (t1 - t0) * (k as f64 / EDGE_GAP_SAMPLES as f64) };// A point a pcurve or surface lacks is the record check's to name.let (Some(q), Some(p)) = (c.eval(t), eval.point(t)) else { continue };if let Some(s) = on.point(q) {