diff --git a/crates/doc/src/construct.rs b/crates/doc/src/construct.rs index dc41296c3..6b21b8465 100644 --- a/crates/doc/src/construct.rs +++ b/crates/doc/src/construct.rs @@ -428,31 +428,66 @@ fn centre(ctx: &Ctx, g: &GeoRef) -> Result { } } -/// Point and unit tangent at fraction `t` along a polyline. -fn along(pts: &[Vec3], t: f64) -> Option<(Vec3, Vec3)> { - let total: f64 = pts.windows(2).map(|w| (w[1] - w[0]).len()).sum(); - if !(total > 0.0) { - return None; - } - let mut left = t.clamp(0.0, 1.0) * total; - for w in pts.windows(2) { - let l = (w[1] - w[0]).len(); - if l <= 0.0 { - continue; - } - if left <= l { - return Some((w[0] + (w[1] - w[0]) * (left / l), (w[1] - w[0]) * (1.0 / l))); - } - left -= l; - } - let (a, b) = (pts.get(pts.len() - 2)?, pts.last()?); - Some((*b, (*b - *a).normalized()?)) +/// The point a fraction `t` (0…1) of the way along a picked edge or sketch curve by arc length, +/// and the unit direction of travel there ([`kernel::along_path`]): exact on the curve itself. +fn along(ctx: &Ctx, g: &GeoRef, t: f64) -> Result<(Vec3, Vec3)> { + Ok(kernel::along_path(&path_segs(ctx, g)?, t)?) } -fn path_points(ctx: &Ctx, g: &GeoRef) -> Result> { +/// A picked edge or sketch curve as the path segments that are its curve exactly, from the end +/// the drawn curve starts at: a body edge's record curve ([`kernel::edge_path`]), a planar sketch +/// curve's exact pieces, a 3D sketch curve's arc, spline, line or linked exact curves. Only a +/// curve that exists as points alone runs along them: an intersection edge (its record holds no +/// exact curve, only the surfaces and a leader near it), a 3D curve known only as its points +/// (projected onto a face, iso curves), a spline above the exact pieces' degree. +fn path_segs(ctx: &Ctx, g: &GeoRef) -> Result> { + let lines = |pts: &[Vec3]| -> Vec { + pts.windows(2).filter(|w| w[0].dist(w[1]) > 0.0).map(|w| kernel::PathSeg::Line { a: w[0], b: w[1] }).collect() + }; match g { - GeoRef::Edge { at, name } => edge_points(ctx.st, *at, name), - GeoRef::SketchCurve { sketch, curve } => sketch_curve_points(ctx, *sketch, curve), + GeoRef::Edge { at, name } => { + let (b, i, pts) = edge_pick(ctx.st, *at, name)?; + let procedural = + b.body.record().edges.get(i).is_some_and(|e| matches!(e.parameters(), solidcraft_geom::brep::Curve::SurfaceIntersection { .. })); + if procedural { + return Ok(lines(&pts)); + } + let segs = kernel::edge_path(&b.body, i)?; + // The drawn edge sets which way t runs, as the picked edge's polyline has it. + let (Some(first), Some(start)) = (pts.first(), segs.first().map(kernel::PathSeg::start)) else { return Ok(segs) }; + let end = segs.last().map(kernel::PathSeg::end).unwrap_or(start); + Ok(if end.dist(*first) < start.dist(*first) { segs.iter().rev().map(kernel::PathSeg::reversed).collect() } else { segs }) + } + GeoRef::SketchCurve { sketch, curve } => { + let ss = ctx.st.sketch(*sketch).ok_or_else(|| DocError::Unknown(format!("sketch {sketch}")))?; + // Evaluation has already mapped wires into this component's frame: their coordinates + // are independent of the sketch plane. + if let Some(wire) = ss.sketch.wires.iter().find(|wire| wire.id == *curve) { + if let Some(arc) = &wire.arc { + let angle = solidcraft_sketch::arc_sweep(arc); + return Ok(vec![kernel::PathSeg::Arc { a: arc.start, center: arc.center, axis: arc.normal, angle }]); + } + if wire.fit.len() >= 3 { + let spline = kernel::PathPiece::Spline { fit: wire.fit.clone(), reversed: false }; + if let Some(spans) = spline.spans()? { + return Ok(spans); + } + } + if let [a, b] = wire.fit.as_slice() { + return Ok(vec![kernel::PathSeg::Line { a: *a, b: *b }]); + } + if !wire.exact.is_empty() { + let mut segs = Vec::new(); + for c in &wire.exact { + segs.extend(kernel::curve_path(&c.curve, c.interval)?); + } + return Ok(segs); + } + return Ok(lines(&wire.pts)); + } + let ci = ss.sketch.curve_index(curve).ok_or_else(|| DocError::Unknown(format!("curve `{curve}`")))?; + Ok(ss.sketch.exact_pieces(ci).iter().map(|s| kernel::PathSeg::of_sketch(&ss.plane, s)).collect()) + } _ => Err(bad("pick an edge or sketch curve as the path")), } } @@ -571,7 +606,7 @@ pub(crate) fn resolve_point(ctx: &Ctx, d: &PointDef) -> Result { } PointDef::AlongPath { path, t } => { let t = Document::eval_in(ctx.vals, t, Kind::Unitless)?; - along(&path_points(ctx, path)?, t).map(|(p, _)| p).ok_or_else(|| bad("the path has no length")) + along(ctx, path, t).map(|(p, _)| p) } } } @@ -634,7 +669,7 @@ pub(crate) fn resolve_geo_plane(ctx: &Ctx, p: &PlaneRef) -> Result { } PlaneRef::AlongPath { path, t } => { let t = Document::eval_in(ctx.vals, t, Kind::Unitless)?; - let (p, tan) = along(&path_points(ctx, path)?, t).ok_or_else(|| bad("the path has no length"))?; + let (p, tan) = along(ctx, path, t)?; Plane::from_normal(p, tan).ok_or_else(degenerate) } PlaneRef::ThroughPoint { base, point: at } => { diff --git a/crates/engine/src/construct_tests.rs b/crates/engine/src/construct_tests.rs index a124cd4b6..9afbb31ba 100644 --- a/crates/engine/src/construct_tests.rs +++ b/crates/engine/src/construct_tests.rs @@ -213,6 +213,24 @@ fn point_along_a_path() { run(&mut s, "construct.point.along_path", json!({"path": {"edge": [20, 0, 0]}, "t": 0.25, "name": "P"})); let p = point(&s, "P"); assert!(near(p, Vec3::new(10.0, 0.0, 0.0)) || near(p, Vec3::new(30.0, 0.0, 0.0)), "{p:?}"); + // On an arc it is the arc's own point by arc length, to rounding: a third of a quarter turn + // of radius 10 is 30° round. A t past either end is refused, not moved onto it. + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Round"})); + let arc = run(&mut s, "sketch.arc.center_point", json!({"center": [0, 0], "start": [10, 0], "end": [0, 10]}))["created"]["curves"][0] + .as_str() + .unwrap() + .to_string(); + run(&mut s, "sketch.finish", json!({})); + let path = json!({"sketch": "Round", "curve": arc}); + run(&mut s, "construct.point.along_path", json!({"path": path, "t": "1/3", "name": "Third"})); + let third = point(&s, "Third"); + let want = Vec3::new(10.0 * (std::f64::consts::PI / 6.0).cos(), 5.0, 0.0); + assert!(third.dist(want) < 1e-12, "{third:?} is {:e} off", third.dist(want)); + for t in [json!(1.5), json!(-0.25), json!("2")] { + let e = s.execute("construct.point.along_path", &json!({"path": path, "t": t})).unwrap_err(); + assert!(e.to_string().contains("0 (its start) to 1 (its end)"), "t {t}: {e}"); + assert!(s.execute("construct.plane.along_path", &json!({"path": path, "t": t})).is_err(), "plane at t {t}"); + } } #[test] diff --git a/crates/geom/src/brep.rs b/crates/geom/src/brep.rs index 6c31ae6ec..bc59ea2a7 100644 --- a/crates/geom/src/brep.rs +++ b/crates/geom/src/brep.rs @@ -24,6 +24,9 @@ mod topology; pub use curve2::Curve2; pub const VERSION: u32 = 4; +/// The most items (records, points, knots, uses) [`Brep::validate`] takes in a record that comes +/// from outside the kernel: a file, the control channel, pasted data. A record the kernel built +/// ([`Brep::validate_built`]) has no such cap. pub const MAX_ITEMS: usize = 4_000_000; pub const MAX_SHELLS: usize = 1024; const MAX_DEPTH: usize = 16; @@ -266,11 +269,19 @@ fn require(condition: bool, message: &'static str) -> Result<()> { if condition { Ok(()) } else { Err(Invalid(message)) } } -struct Budget(usize); +/// The items counted so far and the most allowed. +struct Budget { + used: usize, + limit: usize, +} impl Budget { + /// The budget of a record from outside the kernel. + fn input() -> Budget { + Budget { used: 0, limit: MAX_ITEMS } + } fn add(&mut self, n: usize) -> Result<()> { - self.0 = self.0.checked_add(n).ok_or(Invalid("item budget"))?; - require(self.0 <= MAX_ITEMS, "item budget") + self.used = self.used.checked_add(n).ok_or(Invalid("item budget"))?; + require(self.used <= self.limit, "item budget") } } fn numbers(values: impl IntoIterator) -> Result<()> { @@ -584,12 +595,26 @@ impl Brep { /// list of uses and the canonical order. Does not certify watertightness, that edges lie on /// their surfaces or that pcurves lift onto their edges ([`Brep::check_geometry`] spot-checks /// those). + /// + /// For a record from outside the kernel (a file, the control channel, pasted data): it is + /// refused past [`MAX_ITEMS`] items, so hostile input is bounded before anything walks it. pub fn validate(&self) -> Result<()> { + self.validate_within(Budget::input()) + } + + /// [`Brep::validate`] for a record the kernel built in memory (an operation's result, a + /// body's own record, a part of a validated record): every check but the item budget. The + /// record already sits in memory, its size set by inputs that were bounded where they came + /// in, and the checks are linear in it; a cap here would only refuse a real result. + pub fn validate_built(&self) -> Result<()> { + self.validate_within(Budget { used: 0, limit: usize::MAX }) + } + + fn validate_within(&self, mut budget: Budget) -> Result<()> { require(self.version == VERSION, "unsupported version")?; tolerance(self.tolerance)?; require(!self.shells.is_empty() && self.shells.len() <= MAX_SHELLS, "shell count")?; require(!self.regions.is_empty() && self.regions.len() <= 2 * MAX_SHELLS + 1, "region count")?; - let mut budget = Budget(0); budget.add(self.regions.len() + self.faces.len() + self.edges.len())?; for v in &self.vertices { points(&[v.point], &mut budget)?; diff --git a/crates/geom/src/brep/curve2.rs b/crates/geom/src/brep/curve2.rs index 8d99a181f..9d286d9e1 100644 --- a/crates/geom/src/brep/curve2.rs +++ b/crates/geom/src/brep/curve2.rs @@ -100,12 +100,12 @@ mod tests { #[test] fn pcurves_validate_and_round_trip() { let line = Curve2::Spline { knots: vec![0., 0., 1., 1.], points: vec![[0., 0.], [1., 2.]] }; - curve2(&line, &mut Budget(0)).unwrap(); + curve2(&line, &mut Budget::input()).unwrap(); assert_eq!(line.interval(), Some([0., 1.])); assert_eq!(serde_json::from_str::(&serde_json::to_string(&line).unwrap()).unwrap(), line); let bad = Curve2::RationalSpline { knots: vec![0., 0., 1., 1.], homogeneous: vec![[0., 0., 1.], [1., 2., 0.]] }; - assert!(curve2(&bad, &mut Budget(0)).is_err()); + assert!(curve2(&bad, &mut Budget::input()).is_err()); let nan = Curve2::Spline { knots: vec![0., 0., 1., 1.], points: vec![[0., f64::NAN], [1., 2.]] }; - assert!(curve2(&nan, &mut Budget(0)).is_err()); + assert!(curve2(&nan, &mut Budget::input()).is_err()); } } diff --git a/crates/geom/src/brep/geometry.rs b/crates/geom/src/brep/geometry.rs index 3d6f4e007..ef398420d 100644 --- a/crates/geom/src/brep/geometry.rs +++ b/crates/geom/src/brep/geometry.rs @@ -8,7 +8,7 @@ //! //! A spot check, not a certificate: a fixed number of evaluations per record (three points of //! each edge, [`AREA_SAMPLES`] of each use, one projection per vertex loop), so the work is -//! linear in the item budget [`Brep::validate`] caps. Every distance is held to the record's own tolerance: +//! linear in the record. Every distance is held to the record's own tolerance: //! an edge's for its pcurves, an edge's and its vertex's together where they meet, a vertex's on //! its surface. A point that cannot be evaluated is an error, never a panic. use super::eval::{CurveEval, SurfaceEval}; diff --git a/crates/geom/src/brep/part.rs b/crates/geom/src/brep/part.rs index 5c6502c99..89e3f4462 100644 --- a/crates/geom/src/brep/part.rs +++ b/crates/geom/src/brep/part.rs @@ -370,7 +370,7 @@ impl Brep { edges: new_edges, vertices: new_vertices, }; - brep.validate()?; + brep.validate_built()?; Ok(Part { brep, faces: faces.old, edges: edges.old, vertices: vertices.old }) } } diff --git a/crates/geom/src/brep/pcurve.rs b/crates/geom/src/brep/pcurve.rs index 6517a3b98..1fa54b7ac 100644 --- a/crates/geom/src/brep/pcurve.rs +++ b/crates/geom/src/brep/pcurve.rs @@ -131,7 +131,7 @@ fn check_size(loops: &[Vec>], tolerance: f64) -> Result<()> { /// Each use's pcurve: the given one, or its closed form; a use with neither is its `Failed` /// error, any other error fails the face. fn each_pcurve(surface_record: &Surface, on: &On, loops: &[Vec>], tolerance: f64) -> Result>>> { - let mut budget = Budget(0); + let mut budget = Budget::input(); surface(surface_record, 0, &mut budget).map_err(|e| Error::Invalid(e.to_string()))?; // A seam edge used twice is worked out once. let mut done: Vec<(u32, Result)> = Vec::new(); diff --git a/crates/geom/src/brep/tests.rs b/crates/geom/src/brep/tests.rs index 208d0b441..05a01e6b5 100644 --- a/crates/geom/src/brep/tests.rs +++ b/crates/geom/src/brep/tests.rs @@ -741,19 +741,42 @@ fn a_reversed_face_is_walked_backwards() { b.validate().unwrap(); } +/// A valid record of more than [`MAX_ITEMS`] items: the sheet with its first edge a polyline of +/// that many points (#3992). +fn over_the_item_budget() -> Brep { + let mut b = sheet(); + b.edges[0].curve = Curve::Polyline { points: (0..MAX_ITEMS).map(|i| [i as f64 * 1e-6, 0., 0.]).collect() }; + b +} + +#[test] +fn the_item_budget_bounds_input_records_and_not_the_kernels_own() { + // A record from a file or the control channel is refused past the budget; the same record + // built by the kernel in memory (a boolean's result) is its own size and is taken (#3992). + let big = over_the_item_budget(); + assert_eq!(big.validate().map_err(|e| e.0), Err("item budget")); + big.validate_built().unwrap(); + // Every other check still holds for a built record. + let mut collapsed = big; + if let Curve::Polyline { points } = &mut collapsed.edges[0].curve { + points[1] = points[0]; + } + assert_eq!(collapsed.validate_built().map_err(|e| e.0), Err("collapsed polyline segment")); +} + #[test] fn spline_domains_weights_and_nesting_are_bounded() { - let mut budget = Budget(0); + let mut budget = Budget::input(); assert!(knots(&[0., 0., 1., 1.], 2, &mut budget).is_ok()); for bad in [vec![0., 0., 0., 0.], vec![0., 1., 0., 1.], vec![0., 0., f64::INFINITY, 1.]] { - assert!(knots(&bad, 2, &mut Budget(0)).is_err()); + assert!(knots(&bad, 2, &mut Budget::input()).is_err()); } let c = Curve::RationalSpline { knots: vec![0., 0., 1., 1.], homogeneous: vec![[0., 0., 0., 0.], [1., 0., 0., 1.]] }; - assert!(curve(&c, 0, &mut Budget(0)).is_err()); + assert!(curve(&c, 0, &mut Budget::input()).is_err()); let p = Surface::Plane { origin: [0.; 3], u_axis: [1., 0., 0.], v_axis: [2., 0., 0.] }; - assert!(surface(&p, 0, &mut Budget(0)).is_err()); - assert!(curve(&Curve::Line { start: [0.; 3], end: [1.; 3] }, MAX_DEPTH + 1, &mut Budget(0)).is_err()); - assert!(Budget(MAX_ITEMS).add(1).is_err()); + assert!(surface(&p, 0, &mut Budget::input()).is_err()); + assert!(curve(&Curve::Line { start: [0.; 3], end: [1.; 3] }, MAX_DEPTH + 1, &mut Budget::input()).is_err()); + assert!(Budget { used: MAX_ITEMS, limit: MAX_ITEMS }.add(1).is_err()); assert_eq!(curve_natural(&Curve::Spline { knots: vec![0., 0., 0., 1., 2., 2., 2.], points: vec![[0.; 3]; 4] }), Natural::Range(0., 2.)); } @@ -762,7 +785,7 @@ fn exact_procedural_records_are_validated_and_round_trip() { let plane = |z: f64| Box::new(Surface::Plane { origin: [0., 0., z], u_axis: [1., 0., 0.], v_axis: [0., 1., 0.] }); let leader = Box::new(Curve::Polyline { points: vec![[0.; 3], [0.; 3], [1., 0., 0.]] }); let c = Curve::SurfaceIntersection { surfaces: [plane(0.), plane(1.)], leader: leader.clone(), tolerance: 1e-6 }; - curve(&c, 0, &mut Budget(0)).unwrap(); + curve(&c, 0, &mut Budget::input()).unwrap(); assert_eq!(curve_natural(&c), Natural::Range(0., 2.)); assert_eq!(serde_json::from_str::(&serde_json::to_string(&c).unwrap()).unwrap(), c); let line = Box::new(Curve::Line { start: [0.; 3], end: [1.; 3] }); @@ -771,17 +794,17 @@ fn exact_procedural_records_are_validated_and_round_trip() { Curve::SurfaceIntersection { surfaces: [plane(0.), plane(1.)], leader: leader.clone(), tolerance: f64::NAN }, Curve::SurfaceIntersection { surfaces: [plane(f64::INFINITY), plane(1.)], leader, tolerance: 1e-6 }, ] { - assert!(curve(&bad, 0, &mut Budget(0)).is_err()); + assert!(curve(&bad, 0, &mut Budget::input()).is_err()); } let identity = [[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]; let s = Surface::PlacedRevolution { profile: line.clone(), origin: [0.; 3], axis: [0., 0., 1.], matrix: identity, forward: false }; - surface(&s, 0, &mut Budget(0)).unwrap(); + surface(&s, 0, &mut Budget::input()).unwrap(); assert_eq!(surface_natural(&s), [Natural::Periodic, UNBOUNDED]); assert_eq!(serde_json::from_str::(&serde_json::to_string(&s).unwrap()).unwrap(), s); let mut flat = identity; flat[2] = [0.; 4]; let bad = Surface::PlacedRevolution { profile: line, origin: [0.; 3], axis: [0., 0., 1.], matrix: flat, forward: true }; - assert!(surface(&bad, 0, &mut Budget(0)).is_err()); + assert!(surface(&bad, 0, &mut Budget::input()).is_err()); } #[test] @@ -799,16 +822,16 @@ fn analytic_records_are_unbounded_with_independent_frames() { let narrowing = Surface::Cone { frame: f.clone(), radius_at_origin: 2., half_angle: -0.2 }; assert_eq!(surface_natural(&narrowing)[1], Natural::Range(f64::NEG_INFINITY, apex)); for flat in [0., 1e-13, -1e-13, std::f64::consts::FRAC_PI_2, -std::f64::consts::FRAC_PI_2] { - assert!(surface(&Surface::Cone { frame: f.clone(), radius_at_origin: 2., half_angle: flat }, 0, &mut Budget(0)).is_err()); + assert!(surface(&Surface::Cone { frame: f.clone(), radius_at_origin: 2., half_angle: flat }, 0, &mut Budget::input()).is_err()); } for s in surfaces { - surface(&s, 0, &mut Budget(0)).unwrap(); + surface(&s, 0, &mut Budget::input()).unwrap(); let encoded = serde_json::to_string(&s).unwrap(); assert_eq!(serde_json::from_str::(&encoded).unwrap(), s); assert!(!encoded.contains("\"angle\"") && !encoded.contains("height") && !encoded.contains("longitude")); } for c in [Curve::Circle { frame: f.clone(), radius: 2. }, Curve::Ellipse { frame: f.clone(), radii: [2., 3.] }] { - curve(&c, 0, &mut Budget(0)).unwrap(); + curve(&c, 0, &mut Budget::input()).unwrap(); assert_eq!(serde_json::from_str::(&serde_json::to_string(&c).unwrap()).unwrap(), c); assert_eq!(curve_natural(&c), Natural::Periodic); // A periodic edge may start anywhere and run up to one turn. @@ -816,10 +839,10 @@ fn analytic_records_are_unbounded_with_independent_frames() { } let mut bad = f; bad.y_axis = bad.x_axis; - assert!(frame(&bad, &mut Budget(0)).is_err()); + assert!(frame(&bad, &mut Budget::input()).is_err()); assert!(interval(&[2., 1.], UNBOUNDED).is_err()); assert!(radius(f64::NAN).is_err()); - assert!(surface(&Surface::Torus { frame: a_frame(), major_radius: 1., minor_radius: 2., tube_start: 0.0 }, 0, &mut Budget(0)).is_err()); + assert!(surface(&Surface::Torus { frame: a_frame(), major_radius: 1., minor_radius: 2., tube_start: 0.0 }, 0, &mut Budget::input()).is_err()); } /// A cylinder face round its axis with a hole beside its seam: the seam at 350 degrees (so its diff --git a/crates/kernel/src/body.rs b/crates/kernel/src/body.rs index 2c233bfe0..fbe6f8d50 100644 --- a/crates/kernel/src/body.rs +++ b/crates/kernel/src/body.rs @@ -376,11 +376,11 @@ fn same_shared(a: &Option>, b: &Option Result { - record.validate().map_err(|e| KernelError::Invalid(e.to_string()))?; + record.validate_built().map_err(|e| KernelError::Invalid(e.to_string()))?; if record.faces.is_empty() { return Err(KernelError::Failed("empty result".into())); } @@ -477,7 +477,8 @@ impl Body { } /// The body of a schema 4 record (a solid, or a surface body of open shells): checked for - /// structure (budgets, references, loops, regions, canonical order). Its faces face as the + /// structure (references, loops, regions, canonical order; a record from a file is checked + /// against the file budgets where it is read). Its faces face as the /// record says. pub(crate) fn from_record(record: Brep) -> Result { Ok(Body::bare(solid_record(record)?, None)) diff --git a/crates/kernel/src/build.rs b/crates/kernel/src/build.rs index 7b65f1d86..8dfbb96c4 100644 --- a/crates/kernel/src/build.rs +++ b/crates/kernel/src/build.rs @@ -1234,6 +1234,62 @@ impl PathSeg { } } + /// The segment as the rational Bézier span in space that is the same curve on the same + /// parameter: a sketch cubic, Bézier or conic carried onto its plane (an affine image keeps + /// the weights). `None` for a line or an arc, which have closed forms of their own, and for a + /// span that does not evaluate. + fn space_bezier(&self) -> Option { + use solidcraft_geom::bspline::HPoint; + let PathSeg::Curve { plane, seg } = *self else { + return match *self { + PathSeg::Bezier(b) => Some(b), + _ => None, + }; + }; + let w = |p: Vec2, weight: f64| HPoint::weighted(plane.to_world(p), weight); + match seg { + Seg2::Cubic { p0, p1, p2, p3 } => crate::point_path::SpaceBezier::new(&[w(p0, 1.0), w(p1, 1.0), w(p2, 1.0), w(p3, 1.0)]), + Seg2::Bezier { n, p } => { + let ctrl: Vec = p.get(..=usize::from(n))?.iter().map(|q| w(*q, 1.0)).collect(); + crate::point_path::SpaceBezier::new(&ctrl) + } + Seg2::Conic { a, apex, b, w: weight } => crate::point_path::SpaceBezier::new(&[w(a, 1.0), w(apex, weight), w(b, 1.0)]), + Seg2::Line { .. } | Seg2::Arc { .. } => None, + } + } + + /// The segment's length: a line's and an arc's in closed form, a free-form span's by its + /// arc-length integral ([`crate::SpaceBezier::length`]). `None` for a segment that does not + /// evaluate. + pub fn length(&self) -> Option { + let l = match *self { + PathSeg::Line { a, b } => a.dist(b), + PathSeg::Arc { a, center, angle, .. } => a.dist(center) * angle.abs(), + PathSeg::Curve { plane, seg: seg @ (Seg2::Line { .. } | Seg2::Arc { .. }) } => return PathSeg::of_sketch(&plane, &seg).length(), + PathSeg::Curve { .. } | PathSeg::Bezier(_) => self.space_bezier()?.length()?, + }; + l.is_finite().then_some(l) + } + + /// The point a fraction `f` (0…1) of the way along the segment by arc length, and the unit + /// direction of travel there: a line's and an arc's in closed form (an arc's length grows + /// with its angle), a free-form span's at the parameter where its arc-length integral reaches + /// that fraction ([`crate::SpaceBezier::along`]). `None` for a segment that does not + /// evaluate or has no direction. + pub fn along(&self, f: f64) -> Option<(Vec3, Vec3)> { + let f = f.clamp(0.0, 1.0); + match *self { + PathSeg::Line { a, b } => Some((a.lerp(b, f), (b - a).normalized()?)), + PathSeg::Arc { a, center, axis, angle } => { + let k = axis.normalized()?; + let p = rotate_about(a, center, k, angle * f); + Some((p, (k.cross(p - center) * angle.signum()).normalized()?)) + } + PathSeg::Curve { plane, seg: seg @ (Seg2::Line { .. } | Seg2::Arc { .. }) } => PathSeg::of_sketch(&plane, &seg).along(f), + PathSeg::Curve { .. } | PathSeg::Bezier(_) => self.space_bezier()?.along(f), + } + } + /// The segment the other way round. pub fn reversed(&self) -> PathSeg { match *self { diff --git a/crates/kernel/src/fair.rs b/crates/kernel/src/fair.rs index 592693acb..f59862e0f 100644 --- a/crates/kernel/src/fair.rs +++ b/crates/kernel/src/fair.rs @@ -278,13 +278,20 @@ struct Net<'a, const N: usize> { /// The control points as the design has them; the run moves copies. ctrl: &'a Grid<[f64; N]>, gram: [Gram; 2], - terms: &'static [(usize, usize, f64)], + /// The energy's terms that the net's degrees can carry (see [`Net::new`]). + terms: Vec<(usize, usize, f64)>, } impl<'a, const N: usize> Net<'a, N> { /// Check the degrees, knots and counts and build the Gram matrices: an error, never a panic, /// for a degree above [`MAX_SPLINE_DEGREE`], too few control points for the degree, a knot /// vector of the wrong length, unusable knots or an empty parameter range. + /// + /// A term that differentiates a direction more often than its degree is dropped: on every + /// span the basis functions are polynomials of that degree, so the derivative is zero and so + /// is the term, exactly. A face of degree 1 one way (an extruded curve) has no `S_vv` that + /// way: its energy is the bending along the curve and the twist, and the straight direction + /// pays nothing. fn new(degree: [usize; 2], knots: [Vec; 2], ctrl: &'a Grid<[f64; N]>, terms: &'static [(usize, usize, f64)]) -> Result> { let count = ctrl.count(); if ctrl.cells().len() > MAX_FAIR_POINTS { @@ -311,8 +318,12 @@ impl<'a, const N: usize> Net<'a, N> { return Err(KernelError::Invalid("the fairing's parameter range is empty".into())); } } - if terms.iter().any(|&(ru, rv, w)| ru > degree[0] || rv > degree[1] || !(w.is_finite() && w >= 0.0)) { - return Err(KernelError::Invalid("a fairness term does not fit the net's degrees".into())); + if terms.iter().any(|&(_, _, w)| !(w.is_finite() && w >= 0.0)) { + return Err(KernelError::Invalid("a fairness term's weight is not a non-negative number".into())); + } + let terms: Vec<(usize, usize, f64)> = terms.iter().copied().filter(|&(ru, rv, _)| ru <= degree[0] && rv <= degree[1]).collect(); + if terms.is_empty() { + return Err(KernelError::Invalid(format!("a net of degree {} × {} does not bend: there is nothing to fair", degree[0], degree[1]))); } let gram = [Gram::new(degree[0], &knots[0], count[0])?, Gram::new(degree[1], &knots[1], count[1])?]; Ok(Net { degree, ctrl, gram, terms }) @@ -342,7 +353,7 @@ impl<'a, const N: usize> Net<'a, N> { for j in 0..cv { for i in 0..cu { let mut acc = [0.0f64; N]; - for &(ru, rv, w) in self.terms { + for &(ru, rv, w) in &self.terms { for l in j.saturating_sub(pv)..=(j + pv).min(cv - 1) { for k in i.saturating_sub(pu)..=(i + pu).min(cu - 1) { let a = w * self.gram[0].at(ru, i, k) * self.gram[1].at(rv, j, l); @@ -380,7 +391,7 @@ impl<'a, const N: usize> Net<'a, N> { let mut band = Band::new(interior.points.len(), pu + rows * interior.cols)?; for (r, &at) in interior.points.iter().enumerate() { let (i, j) = (at % cu, at / cu); - for &(ru, rv, w) in self.terms { + for &(ru, rv, w) in &self.terms { for l in j.saturating_sub(pv)..=(j + pv).min(cv - 1) { for k in i.saturating_sub(pu)..=(i + pu).min(cu - 1) { let Some(s) = interior.slot.get(self.index(k, l)).copied().flatten() else { continue }; @@ -392,6 +403,23 @@ impl<'a, const N: usize> Net<'a, N> { band.factorised() } + /// Whether holding `keep` layers at each end of each direction holds every control point: a + /// direction of more than one control point and no more than `2 · keep` of them. + fn all_held(&self, keep: usize) -> bool { + self.count().iter().any(|&c| c > 1 && c <= 2 * keep) + } + + /// The report of a run that moved nothing: the net's energy before and after, no steps. + fn unmoved(&self) -> Result { + let mut grad = vec![[0.0; N]; self.total()]; + let energy = self.energy_gradient(self.ctrl.cells(), &mut grad); + if !energy.is_finite() { + return Err(KernelError::Invalid("the fairness energy of this net is not a finite number".into())); + } + let energy = energy.max(0.0); + Ok(FairReport { energy_before: energy, energy_after: energy, steps: 0, movement: 0.0, energy_trace: Vec::new() }) + } + /// Fair the net with checked `opts`: see the module docs. The result is the input with the /// interior control points moved; the held ones are bit-identical. fn fair(&self, opts: &FairOptions) -> Result<(Grid<[f64; N]>, FairReport)> { @@ -823,7 +851,9 @@ pub fn fair_surface(surface: &NurbsSurface, opts: &FairOptions) -> Result<(Nurbs /// its surface changes in the body's record, so the body is as closed (or as open) as it was, /// holes and all, and SMLib builds it from that record. A face that is not a B-spline (a plane, /// cylinder, cone, sphere, torus or revolution) has no control points to fair and is refused by -/// name; a mesh body has no faces to fair at all. +/// name; a mesh body has no faces to fair at all. A face whose held layers are its whole net (see +/// [`held_face`]) has no interior control vertex to move and is left exactly as it is, its energy +/// reported unchanged. /// /// The report is over the picked faces together: the energies summed, the largest movement of any /// control point, and the energy trace as the sum at each step (a face that stops early keeps its @@ -849,8 +879,13 @@ pub fn fair_faces(body: &Body, faces: &[usize], opts: &FairOptions) -> Result<(B return Err(KernelError::Invalid("pick the faces to fair".into())); } let mut reports: Vec = Vec::with_capacity(picked.len()); + let mut changed: Vec = Vec::with_capacity(picked.len()); for &i in &picked { let Some(face) = record.faces.get_mut(i) else { continue }; + if let Some(report) = held_face(&face.surface, &opts)? { + reports.push(report); + continue; + } let (surface, report) = match &face.surface { b::Surface::Spline { .. } => fair_bspline_surface(&face.surface, &opts)?, b::Surface::RationalSpline { .. } => fair_nurbs_surface(&face.surface, &opts)?, @@ -862,6 +897,7 @@ pub fn fair_faces(body: &Body, faces: &[usize], opts: &FairOptions) -> Result<(B }; face.surface = surface; reports.push(report); + changed.push(i); } let report = FairReport { energy_before: reports.iter().map(|r| r.energy_before).sum(), @@ -873,6 +909,9 @@ pub fn fair_faces(body: &Body, faces: &[usize], opts: &FairOptions) -> Result<(B (0..longest).map(|k| reports.iter().map(|r| r.energy_trace.get(k).copied().unwrap_or(r.energy_after)).sum()).collect() }, }; + if changed.is_empty() { + return Ok((body.clone(), report)); + } let smlib = solidcraft_smlib::Brep::from_record(&record, true).map_err(|e| KernelError::Failed(format!("fair: SMLib: {e}")))?; let (result, order) = crate::native::body_from_smlib_ordered(&smlib)?; // The topology is the body's own, so SMLib's order is the body's: each face kept or @@ -882,7 +921,7 @@ pub fn fair_faces(body: &Body, faces: &[usize], opts: &FairOptions) -> Result<(B return Ok((result, report)); } let mut history = ::identity(body); - for &i in &picked { + for &i in &changed { if let Some(f) = history.faces.get_mut(i) { f.change = Change::Modified; } @@ -890,6 +929,28 @@ pub fn fair_faces(body: &Body, faces: &[usize], opts: &FairOptions) -> Result<(B Ok((result.with_history(history, &[body])?, report)) } +/// The report for a B-spline face whose every control point `opts` holds, which the run leaves +/// exactly as it is: a direction of no more control points than the held layers (a single-span +/// cubic with its edges kept, an extruded curve's two rows) holds the whole net, since every row +/// is a boundary row or one next to it. `None` when some control point is free to move, and for a +/// face that is not a B-spline. +fn held_face(surface: &b::Surface, opts: &FairOptions) -> Result> { + let (u_knots, v_knots, ctrl) = match surface { + b::Surface::Spline { u_knots, v_knots, points } => (u_knots, v_knots, record_net(points)?), + b::Surface::RationalSpline { u_knots, v_knots, homogeneous } => { + (u_knots, v_knots, positions(&record_net(homogeneous)?.map(|h| HPoint { x: h[0], y: h[1], z: h[2], w: h[3] }))?) + } + _ => return Ok(None), + }; + let [cu, cv] = ctrl.count(); + let degree = [degree_of(u_knots, cu)?, degree_of(v_knots, cv)?]; + let net = Net::new(degree, [u_knots.clone(), v_knots.clone()], &ctrl, &SURFACE_ENERGY)?; + if !net.all_held(if opts.keep_edges { 2 } else { 1 }) { + return Ok(None); + } + net.unmoved().map(Some) +} + #[cfg(test)] mod tests { use super::*; @@ -1364,6 +1425,53 @@ mod tests { assert_eq!(faired.ctrl[rough.len() - 1], rough[rough.len() - 1]); } + #[test] + fn a_net_of_degree_one_across_fairs_along_its_curved_direction_only() { + // Cubic along u, linear across v over two spans (three rows): `S_vv` is zero on every + // span, so only the bending along u and the twist count. A plane's net bumped at its + // middle row fairs back to the plane, the boundary rows bit-identical. + let (ku, kv) = (clamped(3, 3), vec![0.0, 0.0, 1.0, 2.0, 2.0]); + let degree = [3, 1]; + let (cu, cv) = (ku.len() - 4, kv.len() - 2); + assert_eq!((cu, cv), (6, 3)); + let smooth = planar_net(&ku, &kv, degree, [0.0, 0.0, 0.0], [30.0, 0.0, 0.0], [0.0, 20.0, 4.0]); + let mut rough = smooth.clone(); + rough[cu + 2][2] += 2.0; + rough[cu + 3][2] -= 1.0; + let faired = fair_net( + degree, + [&ku, &kv], + &Grid::from_fn([cu, cv], |i, j| rough[j * cu + i]).unwrap(), + &FairOptions::new(1.0, 8, false, 100.0).unwrap(), + ) + .unwrap(); + let near = faired.ctrl.cells().iter().zip(&smooth).map(|(a, b)| dist(a, b)).fold(0.0, f64::max); + eprintln!("degree 3 × 1 net: faired to {near:e} mm, energy {:e} → {:e}", faired.report.energy_before, faired.report.energy_after); + assert!(near < 1e-6 && faired.report.energy_after < 1e-9 * faired.report.energy_before); + for i in 0..cu { + for j in [0, cv - 1] { + assert_eq!(faired.ctrl.get(i, j), Some(&rough[j * cu + i]), "({i}, {j}) is on the boundary and moved"); + } + } + } + + #[test] + fn a_face_whose_edges_hold_its_whole_net_is_left_as_it_is() { + // A single-span bicubic with its edges kept: every row is a boundary row or the one next + // to it, so there is nothing to move. The run succeeds, the body is the one it was and + // the report says no step was taken. + let (ku, kv) = (clamped(1, 3), clamped(1, 3)); + let mut net = planar_net(&ku, &kv, [3, 3], [0.0, 0.0, 0.0], [20.0, 0.0, 0.0], [0.0, 15.0, 0.0]); + net[5][2] += 2.0; + let body = sheet(&ku, &kv, &net); + let (faired, report) = fair_faces(&body, &[0], &FairOptions::new(1.0, 10, true, 1.0).unwrap()).unwrap(); + eprintln!("held face: energy {:e} → {:e}, {} steps", report.energy_before, report.energy_after, report.steps); + assert_eq!(face_surface(&faired, 0), face_surface(&body, 0)); + assert_eq!(edge_records(&faired), edge_records(&body)); + assert_eq!((report.steps, report.movement), (0, 0.0)); + assert!(report.energy_before > 0.0 && report.energy_after == report.energy_before); + } + /// A one-face sheet body of the bicubic surface `net` (u fastest) over the clamped knots `ku` /// and `kv`, its sides the straight lines between the surface's corners — true while the /// net's boundary rows describe lines, which is how a plane's control net is built here. diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs index 350f646a7..a0cce026b 100644 --- a/crates/kernel/src/lib.rs +++ b/crates/kernel/src/lib.rs @@ -201,7 +201,8 @@ pub use native::{brep_record, decode_native_body, encode_native_body, native_pre pub use offset::with_same_surface; pub use ops::{BoolOp, boolean, half_space, join_apart, place_matrix, split_by_plane, transform, transform_matrix, union_all, union_apart}; pub use point_path::{ - PathPiece, PointPath, SpaceBezier, curve_path, edge_path, face_section_along, project_onto_face, sketch_record_curve, sweep_point_path_with, + PathPiece, PointPath, SpaceBezier, along_path, curve_path, edge_path, face_section_along, project_onto_face, sketch_record_curve, + sweep_point_path_with, }; pub use polybool::faceted_boolean; pub use polyhedron::{HalfSpace, convex_polyhedron, draft, offset_faces, shell}; diff --git a/crates/kernel/src/native.rs b/crates/kernel/src/native.rs index 4a4d67fe4..9f166d2db 100644 --- a/crates/kernel/src/native.rs +++ b/crates/kernel/src/native.rs @@ -416,6 +416,23 @@ mod tests { assert!(decode_native_body(&huge).is_err()); } + #[test] + fn a_kernel_body_past_the_file_item_budget_is_taken_and_a_file_of_it_refused() { + // The box with its first edge a polyline of the file item budget's worth of points: a + // record the kernel's own operations may make (#3992), and more than a file may carry. + let body = crate::box_solid(Vec3::ZERO, Vec3::new(10., 20., 30.)).unwrap(); + let mut record = body.record().clone(); + let [t0, t1] = record.edges[0].interval; + let n = solidcraft_geom::brep::MAX_ITEMS; + let points = (0..n).map(|i| [i as f64 * 1e-6, 0., 0.]).collect(); + record.edges[0].curve = solidcraft_geom::brep::Curve::Polyline { points }; + assert!(t0 >= 0.0 && t1 <= (n - 1) as f64); + Body::from_record(record.clone()).unwrap(); + let saved = SavedBody { solid: record, metadata: metadata::encode(&body).unwrap(), runtime: Runtime { size: 0.0, coarse_missing: None } }; + let refused = validate_topology(&saved).err().map(|e| e.to_string()).unwrap_or_default(); + assert!(refused.contains("item budget"), "{refused}"); + } + #[test] fn native_preserves_face_appearance_and_authored_boundaries() { let mut body = crate::box_solid(Vec3::new(1., 2., 3.), Vec3::new(10., 20., 30.)) diff --git a/crates/kernel/src/point_path.rs b/crates/kernel/src/point_path.rs index 14174d2a0..94bb0384e 100644 --- a/crates/kernel/src/point_path.rs +++ b/crates/kernel/src/point_path.rs @@ -65,7 +65,7 @@ impl PathPiece { /// The piece's exact segments in the direction of travel: a spline of three or more fit /// points as its spans ([`PathSeg::Bezier`]), a curve held exactly as its segments; `None` /// for a polyline (and a spline of one or two points, a point or a line). - pub(crate) fn spans(&self) -> Result>> { + pub fn spans(&self) -> Result>> { let (fit, reversed) = match self { PathPiece::Spline { fit, reversed } => (fit, reversed), PathPiece::Segs(segs) => return Ok(Some(segs.clone())), @@ -141,6 +141,33 @@ pub fn sweep_point_path_with(plane: &Plane, region: &Region2, path: &PointPath, crate::sweep_path::smlib_sweep_points(plane, region, path, ctl) } +/// The point a fraction `t` of the way along `path` (its segments end to end) by arc length, and +/// the unit direction of travel there: 0 is where the path starts, 1 where it ends. Each +/// segment's length and its point at a length are exact ([`PathSeg::length`], +/// [`PathSeg::along`]): closed forms for lines and arcs, the arc-length parameter of a free-form +/// span. A `t` outside 0…1 is refused: the path does not go on past its ends. +pub fn along_path(path: &[PathSeg], t: f64) -> Result<(Vec3, Vec3)> { + if !(0.0..=1.0).contains(&t) { + return Err(KernelError::Invalid(format!("t is {t}: a point along a path is 0 (its start) to 1 (its end) of the way along it"))); + } + let bad = || KernelError::Invalid("a segment of the path does not evaluate".into()); + let lengths: Vec = path.iter().map(|s| s.length().ok_or_else(bad)).collect::>()?; + let total: f64 = lengths.iter().sum(); + if !(total > 0.0 && total.is_finite()) { + return Err(KernelError::Invalid("the path has no length".into())); + } + let mut left = t * total; + let live = || path.iter().zip(&lengths).filter(|(_, l)| **l > 0.0); + let last = live().next_back().ok_or_else(bad)?; + for (seg, &l) in live() { + if left <= l || std::ptr::eq(seg, last.0) { + return seg.along((left / l).min(1.0)).ok_or_else(bad); + } + left -= l; + } + Err(bad()) +} + /// Most segments one edge's curve may give a path. const MAX_EDGE_SEGS: usize = 1000; diff --git a/crates/kernel/src/validity.rs b/crates/kernel/src/validity.rs index e5dd336ee..578331e16 100644 --- a/crates/kernel/src/validity.rs +++ b/crates/kernel/src/validity.rs @@ -33,7 +33,7 @@ impl Validity { pub fn validity(body: &Body) -> Validity { let record = brep_record(body).map_err(|e| e.to_string()); let checked = record.as_ref().map_err(Clone::clone).and_then(|r| { - r.validate().map_err(|e| format!("structure: {e}"))?; + r.validate_built().map_err(|e| format!("structure: {e}"))?; r.check_geometry().map_err(|e| format!("geometry: {e}")) }); Validity { record: checked, smlib: smlib_validity(body) } diff --git a/crates/smlib/src/export.rs b/crates/smlib/src/export.rs index e81fefe01..70df616f9 100644 --- a/crates/smlib/src/export.rs +++ b/crates/smlib/src/export.rs @@ -265,8 +265,10 @@ fn at(a: &[T], k: usize, what: &str) -> Res { fn idx(x: i64, n: usize, what: &str) -> Res { usize::try_from(x).ok().filter(|i| *i < n).ok_or_else(|| invalid(format!("{what}: {x} out of range"))) } +/// A count in the arrays: at most SMLib's longest array ([`flat::MAX_LEN`], checked on entry), as +/// no block is longer than the array it lies in, so offsets worked out from counts cannot overflow. fn count(x: i64, what: &str) -> Res { - usize::try_from(x).ok().filter(|n| *n <= b::MAX_ITEMS).ok_or_else(|| invalid(format!("{what}: count {x}"))) + usize::try_from(x).ok().filter(|n| *n <= flat::MAX_LEN).ok_or_else(|| invalid(format!("{what}: count {x}"))) } fn index(i: usize) -> Res { u32::try_from(i).map_err(|_| invalid("index")) @@ -320,7 +322,7 @@ fn surfaces(flat: View, n_faces: usize) -> Res::to_vec).ok_or_else(|| invalid("NURBS face arrays")); let pts = slice(flat.f(FACE_NURBS_CVS), 3 * at_.cv, 3 * n)?; let u_knots = slice(flat.f(FACE_NURBS_U_KNOTS), at_.uk, nu + ou)?; @@ -739,7 +741,6 @@ fn native_ordered(arrays: &Arrays) -> Res<(b::Brep, Report, Order)> { || flat.i(EDGEUSE_ORIENTATION).len() != n_edgeuses || flat.i(LOOP_VERTEX).len() != n_loops || flat.i(EDGE_VERTICES).len() != 2 * n_edges - || [n_faceuses, n_faces, n_loops, n_edgeuses, n_edges, n_vertices].iter().any(|n| *n > b::MAX_ITEMS) { return Err(invalid("array lengths")); } @@ -1309,7 +1310,7 @@ fn canonical(parts: Parts, n_vertices: usize, flat: View, tolerances: &Tolerance }) .collect::>>()?; let brep = b::Brep { version: b::VERSION, tolerance, regions, shells, faces: face_records, edges: edge_records, vertices }; - brep.validate().map_err(|e| invalid(format!("the mapped B-rep does not validate: {e}")))?; + brep.validate_built().map_err(|e| invalid(format!("the mapped B-rep does not validate: {e}")))?; let placed = |new: &[Option]| { new.iter().map(|i| i.map(|i| i as usize).ok_or_else(|| invalid("an entity outside the canonical walk"))).collect::>>() }; diff --git a/crates/smlib/src/import.rs b/crates/smlib/src/import.rs index 6417b6746..d715f4e30 100644 --- a/crates/smlib/src/import.rs +++ b/crates/smlib/src/import.rs @@ -83,7 +83,7 @@ fn z_axis(f: &b::Frame) -> [f64; 3] { /// The record as flat arrays. `trusted`: the record comes from a modeller that keeps SMLib's /// rules (SMLib then skips its healer); otherwise SMLib heals it on import. pub fn arrays(brep: &b::Brep, trusted: bool) -> R { - brep.validate().map_err(|e| Unsupported::Invalid(e.0))?; + brep.validate_built().map_err(|e| Unsupported::Invalid(e.0))?; let brep = analytic::analytic(brep)?; laid_out(brep.as_ref(), trusted, true, &HashSet::new()) } @@ -93,7 +93,7 @@ pub fn arrays(brep: &b::Brep, trusted: bool) -> R { /// bilinear patch, to compare what SMLib makes of splines with what it makes of its own analytic /// surfaces. A revolution is still refused (SMLib has no such surface). pub fn arrays_keeping_splines(brep: &b::Brep, trusted: bool) -> R { - brep.validate().map_err(|e| Unsupported::Invalid(e.0))?; + brep.validate_built().map_err(|e| Unsupported::Invalid(e.0))?; laid_out(brep, trusted, false, &HashSet::new()) } diff --git a/docs/native-brep.md b/docs/native-brep.md index 0c6591b52..c6ee109d9 100644 --- a/docs/native-brep.md +++ b/docs/native-brep.md @@ -214,6 +214,12 @@ closed chains through shared vertices; every edge's `uses` lists exactly its use once each, primary first, with `upper` as stated; pcurve intervals; parameter ranges; and the canonical order. +The item cap is for records from outside the kernel: a native file, a STEP file, +the control channel. `Brep::validate_built` runs every other check on a record the +kernel built in memory (an operation's result, a body's own record, a part of one): +that record already sits in memory, its size set by inputs bounded where they came +in, and the checks are linear in it, so a cap there would only refuse a real result. + These are structural and resource guards, not a geometric validity certificate. The validator does not check that edges lie on their surfaces, that pcurves lift onto their edges, that a closed shell is watertight or that shells nest as the @@ -231,8 +237,8 @@ edge loop's pcurves enclose (u, v) area (more than 10⁻⁹ of the square of the loop's extent), and exactly one loop of each face, the outer, runs counter-clockwise about the natural normal, the rest clockwise (told apart by their areas, not their order); every vertex loop's vertex lies on its face's -surface (within the vertex's). It makes a fixed number of evaluations per record, so its work is linear in the item -budget, and a point it cannot evaluate is an error naming the record. It is not +surface (within the vertex's). It makes a fixed number of evaluations per record, so its work is linear in the +record, and a point it cannot evaluate is an error naming the record. It is not a certificate either: between the points it checks, an edge may still leave its surface. The truck adapter runs it before building topology, which truck does without checks of its own. diff --git a/tests/kernel-cases/construction/PATHS b/tests/kernel-cases/construction/PATHS index e90299883..153661e56 100644 --- a/tests/kernel-cases/construction/PATHS +++ b/tests/kernel-cases/construction/PATHS @@ -4,6 +4,8 @@ crates/engine/src/cmd/construct.rs # How a construction reference resolves, and the planes the document resolves. crates/doc/src/construct.rs crates/doc/src/document.rs +# A point along a path: the path's exact curves by arc length. +crates/kernel/src/point_path.rs # The constructions as evaluated, which the grader reads. crates/engine/src/view.rs tests/kernel-cases/construction/** diff --git a/tests/kernel-cases/construction/cov-point-along-path-a-third-of-an-arc/expected.json b/tests/kernel-cases/construction/cov-point-along-path-a-third-of-an-arc/expected.json index 22389d2aa..a51e07b65 100644 --- a/tests/kernel-cases/construction/cov-point-along-path-a-third-of-an-arc/expected.json +++ b/tests/kernel-cases/construction/cov-point-along-path-a-third-of-an-arc/expected.json @@ -2,7 +2,7 @@ "sources": [], "what": "a point a third along a quarter-circle arc", "source": "analytic", - "method": "the arc r 10 about the origin from (10,0) to (0,10) counter-clockwise: a third of its length is 30 deg round: (10 cos 30, 10 sin 30, 0) = (8.6603, 5, 0)", + "method": "the arc r 10 about the origin from (10,0) to (0,10) counter-clockwise: a third of its length is 30 deg round: (10 cos 30, 10 sin 30, 0) = (8.6603, 5, 0); the point is on the arc itself, so it is graded to 1e-9 mm (a chord polyline is 0.87 um off)", "construction": { "P": { "point": [ @@ -11,5 +11,8 @@ 0 ] } + }, + "tolerance": { + "abs_mm": 1e-09 } -} +} \ No newline at end of file diff --git a/tests/kernel-cases/construction/cov-point-along-path-middle-of-a-symmetric-spline/expected.json b/tests/kernel-cases/construction/cov-point-along-path-middle-of-a-symmetric-spline/expected.json new file mode 100644 index 000000000..dcb4a3af8 --- /dev/null +++ b/tests/kernel-cases/construction/cov-point-along-path-middle-of-a-symmetric-spline/expected.json @@ -0,0 +1,18 @@ +{ + "sources": [], + "what": "a point half way along a cubic spline symmetric about x = 20", + "source": "analytic", + "method": "the Bezier (0,0), (10,10), (30,10), (40,0) is its own mirror image in x = 20 (the parameter running backwards), so half its length is reached at its middle, u = 1/2: B(1/2) = (P0 + 3 P1 + 3 P2 + P3) / 8 = (20, 7.5, 0). Graded to 1e-9 mm: the point by the spline's own arc length, not a polyline's", + "tolerance": { + "abs_mm": 1e-09 + }, + "construction": { + "P": { + "point": [ + 20.0, + 7.5, + 0.0 + ] + } + } +} \ No newline at end of file diff --git a/tests/kernel-cases/construction/cov-point-along-path-middle-of-a-symmetric-spline/recipe.json b/tests/kernel-cases/construction/cov-point-along-path-middle-of-a-symmetric-spline/recipe.json new file mode 100644 index 000000000..999c2023d --- /dev/null +++ b/tests/kernel-cases/construction/cov-point-along-path-middle-of-a-symmetric-spline/recipe.json @@ -0,0 +1,49 @@ +{ + "commands": [ + { + "command": "sketch.create", + "params": { + "plane": "XY", + "name": "Path" + } + }, + { + "command": "sketch.spline.control_point", + "params": { + "points": [ + [ + 0, + 0 + ], + [ + 10, + 10 + ], + [ + 30, + 10 + ], + [ + 40, + 0 + ] + ] + } + }, + { + "command": "sketch.finish", + "params": {} + }, + { + "command": "construct.point.along_path", + "params": { + "path": { + "sketch": "Path", + "curve": "s1" + }, + "t": 0.5, + "name": "P" + } + } + ] +} \ No newline at end of file diff --git a/tests/kernel-cases/construction/cov-point-along-path-past-the-end/expected.json b/tests/kernel-cases/construction/cov-point-along-path-past-the-end/expected.json index bc40d5224..13bdaf691 100644 --- a/tests/kernel-cases/construction/cov-point-along-path-past-the-end/expected.json +++ b/tests/kernel-cases/construction/cov-point-along-path-past-the-end/expected.json @@ -1,15 +1,8 @@ { "sources": [], - "what": "a point at t 1.5, past the end of a sketch line", + "what": "a point at t 1.5, past the end of a sketch line, is refused", "source": "analytic", - "method": "t runs 0..1 along the path; a point along it can go no further than its end: (40,0,0)", - "construction": { - "P": { - "point": [ - 40, - 0, - 0 - ] - } - } -} + "method": "t runs 0..1 along the path (the command's contract: `t: expr, 0\u20261 along it`); 1.5 is past its end, and a point along the path can go no further, so it is refused rather than moved back to the end", + "outcome": "refused", + "refusal": "0 (its start) to 1 (its end)" +} \ No newline at end of file diff --git a/tests/kernel-cases/construction/cov-point-along-path-quarter-of-a-line/expected.json b/tests/kernel-cases/construction/cov-point-along-path-quarter-of-a-line/expected.json index 6d5d35143..801a5a368 100644 --- a/tests/kernel-cases/construction/cov-point-along-path-quarter-of-a-line/expected.json +++ b/tests/kernel-cases/construction/cov-point-along-path-quarter-of-a-line/expected.json @@ -2,7 +2,7 @@ "sources": [], "what": "a point a quarter along a sketch line", "source": "analytic", - "method": "the line l1 from (0,0,0) to (40,0,0): t 0.25 is (10,0,0)", + "method": "the line l1 from (0,0,0) to (40,0,0): t 0.25 is (10,0,0); exact, graded to 1e-9 mm", "construction": { "P": { "point": [ @@ -11,5 +11,8 @@ 0 ] } + }, + "tolerance": { + "abs_mm": 1e-09 } -} +} \ No newline at end of file diff --git a/tests/kernel-cases/surfaces/KNOWN_FAILING b/tests/kernel-cases/surfaces/KNOWN_FAILING index a514c68f3..fe07e824c 100644 --- a/tests/kernel-cases/surfaces/KNOWN_FAILING +++ b/tests/kernel-cases/surfaces/KNOWN_FAILING @@ -3,4 +3,3 @@ # that fails and is not listed fails it, and so does a listed case that passes: a fix removes its # line in the same pull request. # Baseline: rig-cases-surfaces 45f69c0e5 with SMLib 60b1c6a, aarch64 Linux. -cov-fair-single-span-face-has-nothing-free-to-move surface.fair refuses a face of degree 1 one way ("a fairness term does not fit the net's degrees"): kernel/src/fair.rs checks its second-derivative terms against the net's degrees instead of fairing only the direction that has them