SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Wave 324/509: Fill: a patch's edges are the body's own edges again, circles and ellipses included (and 3 more)
jyviko48498d477ac3
diff --git a/crates/kernel/src/chamfer_sides_curved_tests.rs b/crates/kernel/src/chamfer_sides_curved_tests.rsindex 915901a13b..07b834010a 100644--- a/crates/kernel/src/chamfer_sides_curved_tests.rs+++ b/crates/kernel/src/chamfer_sides_curved_tests.rs@@ -214,7 +214,7 @@ fn too_large_or_unsupported_is_refused() {.record().edges.iter()- .filter_map(|e| solidcraft_geom::brep::eval::CurveEval::new(&e.curve).ok()?.point(0.5 * (e.interval[0] + e.interval[1])))+ .filter_map(|e| solidcraft_geom::brep::eval::CurveEval::new(e.parameters()).ok()?.point(0.5 * (e.interval[0] + e.interval[1]))).find(|m| (m.z - 10.0).abs() < 1e-6).unwrap();match chamfer_sides(&t, &[rim], 1.0, ChamferSide::Distance(2.0), false) {diff --git a/crates/kernel/src/fair.rs b/crates/kernel/src/fair.rsindex e009123e5b..592693acb4 100644--- a/crates/kernel/src/fair.rs+++ b/crates/kernel/src/fair.rs@@ -1379,6 +1379,7 @@ mod tests {let vertices: Vec<[f64; 3]> = corners.iter().map(|&(i, j)| net[j * cu + i]).collect();let edges = (0..4).map(|k| PartEdge {+ nurbs: None,curve: b::Curve::Line { start: vertices[k], end: vertices[(k + 1) % 4] },interval: [0.0, 1.0],vertices: [k as u32, ((k + 1) % 4) as u32],diff --git a/crates/kernel/src/fill.rs b/crates/kernel/src/fill.rsindex 999ef263ba..57cebd6f50 100644--- a/crates/kernel/src/fill.rs+++ b/crates/kernel/src/fill.rs@@ -709,7 +709,7 @@ fn patch_body(body: &Body, record: &b::Brep, chain: &[(usize, bool)], surface: b})?),Pcurves::Computed => None,};- edges.push(PartEdge { curve: edge.parameters().clone(), interval: edge.interval, vertices: ends });+ edges.push(PartEdge { curve: edge.curve.clone(), nurbs: edge.nurbs.clone(), interval: edge.interval, vertices: ends });uses.push(PartUse { edge: k as u32, forward, given });}if !ccw {@@ -797,9 +797,9 @@ fn quilt_body(body: &Body, record: &b::Brep, chain: &[(usize, bool)], fill: &Iso};}let id = index(edges.len())?;- // The curve the interval and the pcurve's parameter are on: a conic's- // NURBS form.- edges.push(PartEdge { curve: edge.parameters().clone(), interval: [lo, hi], vertices: ends });+ // The edge itself: the interval and the pcurve's parameter are on its+ // NURBS form (a conic's), which it keeps.+ edges.push(PartEdge { curve: edge.curve.clone(), nurbs: edge.nurbs.clone(), interval: [lo, hi], vertices: ends });origin.push(Some(e));piece_of.insert(key, id);id@@ -827,7 +827,7 @@ fn quilt_body(body: &Body, record: &b::Brep, chain: &[(usize, bool)], fill: &Isob::Curve::Spline { knots: curve.knots.clone(), points: curve.points.iter().map(|p| [p.x, p.y, p.z]).collect() }}};- edges.push(PartEdge { curve: spline, interval: [0.0, 1.0], vertices: [start, end] });+ edges.push(PartEdge { curve: spline, nurbs: None, interval: [0.0, 1.0], vertices: [start, end] });origin.push(None);spoke_of.insert(spoke, id);id@@ -976,11 +976,14 @@ mod tests {worst}- /// Whether every edge of `made` is one of `of`'s own (the same curve record on the same- /// interval).+ /// Whether every edge of `made` is one of `of`'s own: the same kind of curve, on the same+ /// curve record it is parameterised on (its NURBS form where it has one), on the same+ /// interval. (A circle's or ellipse's frame is SMLib's again after a round trip, its axes+ /// renormalised to the last bit.)fn own_edges(made: &Body, of: &Body) -> bool {let own = record(of).edges;- record(made).edges.iter().all(|e| own.iter().any(|o| o.curve == e.curve && o.interval == e.interval))+ let kind = |e: &b::Edge| std::mem::discriminant(&e.curve);+ record(made).edges.iter().all(|e| own.iter().any(|o| kind(o) == kind(e) && o.parameters() == e.parameters() && o.interval == e.interval))}/// The fill's mesh: every normal finite, and no triangle folded over (all face the same way@@ -1109,9 +1112,10 @@ mod tests {let mut edges = Vec::new();for k in 0..n {let c = &top[k];- edges.push(PartEdge { curve: c.clone(), interval: interval(c), vertices: [k as u32, ((k + 1) % n) as u32] });- edges.push(PartEdge { curve: moved(c), interval: interval(c), vertices: [(n + k) as u32, (n + (k + 1) % n) as u32] });+ edges.push(PartEdge { nurbs: None, curve: c.clone(), interval: interval(c), vertices: [k as u32, ((k + 1) % n) as u32] });+ edges.push(PartEdge { nurbs: None, curve: moved(c), interval: interval(c), vertices: [(n + k) as u32, (n + (k + 1) % n) as u32] });edges.push(PartEdge {+ nurbs: None,curve: b::Curve::Line { start: arr(corners[k]), end: arr(corners[k] + drop) },interval: [0.0, 1.0],vertices: [k as u32, (n + k) as u32],diff --git a/crates/kernel/src/fill_general_tests.rs b/crates/kernel/src/fill_general_tests.rsindex 4ca551e15f..b0fa414f15 100644--- a/crates/kernel/src/fill_general_tests.rs+++ b/crates/kernel/src/fill_general_tests.rs@@ -108,7 +108,7 @@ fn rim_points(body: &Body, per: usize) -> Vec<Vec3> {let r = body.record();let mut out = Vec::new();for e in r.edges.iter().filter(|e| e.uses.len() == 1) {- let c = CurveEval::new(&e.curve).unwrap();+ let c = CurveEval::new(e.parameters()).unwrap();let [t0, t1] = e.interval;for k in 0..per {out.push(c.point(t0 + (t1 - t0) * (k as f64 + 0.5) / per as f64).unwrap());@@ -238,7 +238,7 @@ fn free_edge_points(body: &Body) -> Vec<Vec3> {.edges.iter().filter(|e| e.uses.len() == 1)- .map(|e| CurveEval::new(&e.curve).unwrap().point(0.5 * (e.interval[0] + e.interval[1])).unwrap())+ .map(|e| CurveEval::new(e.parameters()).unwrap().point(0.5 * (e.interval[0] + e.interval[1])).unwrap()).collect::<Vec<_>>();// In a fixed order.points.sort_by(|a, b| (a.z, a.y, a.x).partial_cmp(&(b.z, b.y, b.x)).unwrap());diff --git a/crates/kernel/src/sew.rs b/crates/kernel/src/sew.rsindex 7a7a0199cb..81a449426b 100644--- a/crates/kernel/src/sew.rs+++ b/crates/kernel/src/sew.rs@@ -286,7 +286,7 @@ impl Builder {}};let id = u32::try_from(self.edges.len()).map_err(|_| KernelError::Invalid("sew: edge budget exceeded".into()))?;- self.edges.push(PartEdge { curve, interval, vertices: [va, vb] });+ self.edges.push(PartEdge { nurbs: None, curve, interval, vertices: [va, vb] });self.by_key.insert((ka, fa, kb, fb, mid, sheet), id);Ok((id, true))}@@ -1303,6 +1303,10 @@ pub(crate) struct PartUse {pub(crate) struct PartEdge {pub curve: b::Curve,+ /// The NURBS form the edge is parameterised on, as a record edge keeps it+ /// ([`b::Edge::nurbs`]): given, `interval` is on it and `curve` only says what the edge is,+ /// so an edge taken from a record goes back as that same edge.+ pub nurbs: Option<b::Curve>,pub interval: [f64; 2],pub vertices: [u32; 2],}@@ -1366,8 +1370,8 @@ pub(crate) fn assemble(parts: Parts, solid: bool) -> Result<Assembled> {g};// Each edge's label and NURBS form (`form::edge`): a circle about a revolved face's axis on- // that face's frame, so its form lies on the face's quarter grid; an edge the caller gave a- // pcurve for keeps the parameter that pcurve is on.+ // that face's frame, so its form lies on the face's quarter grid; an edge given with its form+ // keeps it, and an edge the caller gave a pcurve for keeps the parameter that pcurve is on.let mut frames_of: Vec<Vec<b::Frame>> = vec![Vec::new(); edges.len()];for f in &faces {let Some(frame) = b::form::frame_of(&f.surface) else { continue };@@ -1380,6 +1384,13 @@ pub(crate) fn assemble(parts: Parts, solid: bool) -> Result<Assembled> {let mut labels: Vec<(b::Curve, [f64; 2])> = Vec::with_capacity(edges.len());let mut forms: Vec<Option<(b::Curve, [f64; 2])>> = Vec::with_capacity(edges.len());for ((e, frames), given) in edges.iter().zip(&frames_of).zip(&given_on) {+ if let Some(form) = &e.nurbs {+ let on_label =+ b::curve_interval(&e.curve, Some(form), e.interval).ok_or_else(|| fail("an edge's NURBS form does not evaluate".into()))?;+ labels.push((e.curve.clone(), on_label));+ forms.push(Some((form.clone(), e.interval)));+ continue;+ }if *given {labels.push((e.curve.clone(), e.interval));forms.push(None);diff --git a/crates/kernel/src/smlib_sweeps.rs b/crates/kernel/src/smlib_sweeps.rsindex bc26f505ba..c9bbd3214e 100644--- a/crates/kernel/src/smlib_sweeps.rs+++ b/crates/kernel/src/smlib_sweeps.rs@@ -531,6 +531,16 @@ mod imp {/// it when `translate`. SMLib's sweep follows a smooth path; at a corner (the direction/// jumping) the path is swept piece by piece ([`cornered`]).pub(crate) fn sweep(plane: &Plane, pieces: &[Piece], path: &[crate::PathSeg], translate: bool) -> Result<Body> {+ if translate {+ // Every segment's direction of travel, at its ends and between them.+ let bad = || KernelError::Invalid("a path segment has no direction".into());+ let tangents = path+ .iter()+ .flat_map(|s| (0..=CROSSING_SAMPLES).map(move |i| seg_at(s, i as f64 / CROSSING_SAMPLES as f64).map(|(_, t)| t)))+ .collect::<Option<Vec<Vec3>>>()+ .ok_or_else(bad)?;+ crate::sweep_path::crossing_check(plane, &tangents)?;+ }let runs = smooth_runs(path)?;if runs.len() > 1 {return cornered(plane, pieces, path, &runs, translate);@@ -823,6 +833,8 @@ mod imp {/// Fewest and most stations of a sweep that twists, scales or follows rails.const MIN_STATIONS: usize = 16;+ /// Directions of travel read along each path segment for the parallel sweep's crossing check.+ const CROSSING_SAMPLES: usize = 32;const MAX_STATIONS: usize = 2048;/// The profile `region` on `plane` swept along the smooth `path` the way `ctl` asks: twisted,diff --git a/crates/kernel/src/surfaces.rs b/crates/kernel/src/surfaces.rsindex 89569711ab..b8411cbc1a 100644--- a/crates/kernel/src/surfaces.rs+++ b/crates/kernel/src/surfaces.rs@@ -765,7 +765,12 @@ pub(crate) fn stitch_no_worse(bodies: &[&Body], tol: f64, exempt: &[u32]) -> Res/// ([`crate::offset_backend::thicken`]).pub fn thicken(body: &Body, thickness: f64, symmetric: bool) -> Result<Body> {body.require_brep("thicken")?;- imp::thicken(body, thickness, symmetric)+ // SMLib holds a sheet's faces with both sides and thickens along their surfaces' natural+ // normals; a sheet turned to its back (every face used against its natural normal) grows the+ // other way.+ let sides = face_sides(body.record());+ let turned = !sides.is_empty() && sides.iter().all(|forward| !forward);+ imp::thicken(body, if turned { -thickness } else { thickness }, symmetric)}/// The faces `picked` of `body` (indices in its face order) offset one by one by SMLib, each ontodiff --git a/crates/kernel/src/sweep_path.rs b/crates/kernel/src/sweep_path.rsindex 49d1ef8e3d..6729f6d6ad 100644--- a/crates/kernel/src/sweep_path.rs+++ b/crates/kernel/src/sweep_path.rs@@ -221,6 +221,21 @@ fn frames_toward(tangents: &[Vec3], d: Vec3) -> Result<Vec<[Vec3; 3]>> {.collect()}+/// Kept as drawn (parallel), the profile flattens to nothing where the path runs along its+/// plane: the path, by its directions of travel `tangents` (the first leaving the profile), has to+/// cross the plane at 5 degrees or more all the way.+pub(crate) fn crossing_check(plane: &Plane, tangents: &[Vec3]) -> Result<()> {+ let n = plane.normal().normalized().ok_or_else(|| KernelError::Invalid("sweep frame".into()))?;+ let t0 = *tangents.first().ok_or_else(|| KernelError::Invalid("sweep path".into()))?;+ let axis = if n.dot(t0) < 0.0 { n * -1.0 } else { n };+ if tangents.iter().any(|t| t.dot(axis) < 5f64.to_radians().sin()) {+ return Err(KernelError::Invalid(+ "kept parallel, the profile would lie along the sweep path: the path must keep crossing the profile's plane (by 5 deg or more)".into(),+ ));+ }+ Ok(())+}+/// Stations shaped by sweep options: each maps a world vector at the first station to its image/// at its own (twisted and scaled about the profile's normal through the first station, then/// turned by the orientation's frames), optionally stretched across a corner (mitre). Twist and@@ -246,12 +261,8 @@ pub(crate) fn controlled_stations(// Twist and scale act about the profile's normal, pointing the way the path leaves it.let n = plane.normal().normalized().ok_or_else(|| KernelError::Invalid("sweep frame".into()))?;let axis = if n.dot(t0) < 0.0 { n * -1.0 } else { n };- // Kept as drawn, the profile flattens to nothing where the path runs along its plane: the- // path has to cross it at 5 degrees or more all the way.- if ctl.orientation == SweepOrientation::Parallel && tangents.iter().any(|t| t.dot(axis) < 5f64.to_radians().sin()) {- return Err(KernelError::Invalid(- "kept parallel, the profile would lie along the sweep path: the path must keep crossing the profile's plane (by 5 deg or more)".into(),- ));+ if ctl.orientation == SweepOrientation::Parallel {+ crossing_check(plane, tangents)?;}let mut run = Vec::with_capacity(pts.len());let mut total = 0.0;@@ -457,8 +468,9 @@ mod tests {let want = std::f64::consts::PI * 4.0 * len;assert!((v - want).abs() < 0.02 * want, "{v} vs {want}");// The path is its lines (no wall is fitted through the points): a wall per profile- // segment (the circle's two arcs) along each of the 40 lines, and two caps.- assert_eq!(b.faces(0.01).unwrap().len(), 2 * 40 + 2, "walls along each line");+ // segment (the circle is one closed arc, one edge in SMLib) along each of the 40 lines,+ // and two caps.+ assert_eq!(b.faces(0.01).unwrap().len(), 40 + 2, "walls along each line");// An L-shaped path (a sharp corner) with a holed square: mitred ruled walls.let path = [Vec3::ZERO, Vec3::new(0.0, 0.0, 20.0), Vec3::new(20.0, 0.0, 20.0)];let plane = Plane::from_normal(Vec3::ZERO, Vec3::Z).unwrap();diff --git a/crates/kernel/src/tess/tests.rs b/crates/kernel/src/tess/tests.rsindex 45f5163c2f..07f35669e5 100644--- a/crates/kernel/src/tess/tests.rs+++ b/crates/kernel/src/tess/tests.rs@@ -784,11 +784,16 @@ fn a_face_bounded_by_two_short_arcs_keeps_an_area_to_mesh() {let sq = [[3000.0, 0.0, 0.0], [5000.0, 0.0, 0.0], [5000.0, 2000.0, 0.0], [3000.0, 2000.0, 0.0]];let plane = Surface::Plane { origin: [0.0; 3], u_axis: [1.0, 0.0, 0.0], v_axis: [0.0, 1.0, 0.0] };let mut edges = vec![- PartEdge { curve: circle(-c), interval: [top, PI - top], vertices: [0, 1] },- PartEdge { curve: circle(c), interval: [PI + top, TAU - top], vertices: [1, 0] },+ PartEdge { nurbs: None, curve: circle(-c), interval: [top, PI - top], vertices: [0, 1] },+ PartEdge { nurbs: None, curve: circle(c), interval: [PI + top, TAU - top], vertices: [1, 0] },];for k in 0..4 {- edges.push(PartEdge { curve: line(sq[k], sq[(k + 1) % 4]), interval: [0.0, 1.0], vertices: [2 + k as u32, 2 + ((k + 1) % 4) as u32] });+ edges.push(PartEdge {+ nurbs: None,+ curve: line(sq[k], sq[(k + 1) % 4]),+ interval: [0.0, 1.0],+ vertices: [2 + k as u32, 2 + ((k + 1) % 4) as u32],+ });}let uses = |es: &[u32]| es.iter().map(|&edge| PartUse { edge, forward: true, given: None }).collect::<Vec<_>>();let mut vertices = vec![[half, 0.0, 0.0], [-half, 0.0, 0.0]];diff --git a/crates/kernel/src/thin_face_tests.rs b/crates/kernel/src/thin_face_tests.rsindex a365f25a2f..cdbcb2269e 100644--- a/crates/kernel/src/thin_face_tests.rs+++ b/crates/kernel/src/thin_face_tests.rs@@ -61,11 +61,13 @@ fn a_face_touching_its_own_edge_meshes() {let (h, dip) = (0.3175, 2.8e-7);let vertices = vec![[0.0, 0.0, 0.0], [5.0, 0.0, 0.0], [5.0, h, 0.0], [0.0, h, 0.0]];let line = |a: usize, b: usize| PartEdge {+ nurbs: None,curve: Curve::Line { start: vertices[a], end: vertices[b] },interval: [0.0, 1.0],vertices: [a as u32, b as u32],};let arch = PartEdge {+ nurbs: None,curve: Curve::Spline { knots: vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0], points: vec![[5.0, h, 0.0], [2.5, -h - 2.0 * dip, 0.0], [0.0, h, 0.0]] },interval: [0.0, 1.0],vertices: [2, 3],diff --git a/crates/smlib/src/export.rs b/crates/smlib/src/export.rsindex bded300ce9..e81fefe014 100644--- a/crates/smlib/src/export.rs+++ b/crates/smlib/src/export.rs@@ -531,11 +531,14 @@ fn curves(flat: View, n_edges: usize) -> Res<(Vec<(b::Curve, Option<b::Curve>, [}}CURVE_NURBS => {- let c = next_nurbs()?;+ let c = next_nurbs()?.record();// A NURBS edge stays the NURBS SMLib holds, its trims on its own parameter: SMLib// gives lines, circles and ellipses as their own kinds, and nothing is recognised here.+ // SMLib's interval may start or end a rounding past its knots (a variable round's+ // end trimmed by a cylinder, ladder 07-fillets/012: 7e-15 before the first knot).kept += 1;- (c.record(), None, r, Some([1.0, 0.0]))+ let r = onto(r, c.natural());+ (c, None, r, Some([1.0, 0.0]))}other => return Err(unsupported(format!("SMLib curve kind {other}"))),});@@ -626,8 +629,8 @@ fn mapped(trim: &b::Curve2, same: bool, [scale, offset]: [f64; 2], [t0, t1]: [f6})}-/// A domain side moved onto the natural range where it overshoots it by rounding (a sphere's-/// latitudes, a cone's apex).+/// A domain side or an edge's interval moved onto the natural range where it overshoots it by+/// rounding (a sphere's latitudes, a cone's apex, a NURBS edge's end knots).fn onto(r: [f64; 2], natural: b::Natural) -> [f64; 2] {match natural {b::Natural::Range(lo, hi) => {diff --git a/crates/smlib/src/export/tests.rs b/crates/smlib/src/export/tests.rsindex 867543589e..523d3a255f 100644--- a/crates/smlib/src/export/tests.rs+++ b/crates/smlib/src/export/tests.rs@@ -227,6 +227,49 @@ mod native_tests {assert!((got - want).abs() < 1e-6 * want, "volume {got} vs {want}");}+ /// The variable round r1 -> r5 along a box's top back edge run on into the R5 round of its+ /// corner (ladder 07-fillets/012): its end trimmed by the R5 cylinder is a NURBS edge, whose+ /// interval SMLib gave 7e-15 before the first knot. The record's interval is the NURBS's own+ /// where it overshoots it by rounding, and the record validates; farther past it stays an error.+ #[test]+ fn a_nurbs_edge_interval_a_rounding_past_its_knots_is_moved_onto_them() {+ let block = Brep::make_box([0.0; 3], [60.0, 40.0, 20.0]).unwrap();+ let rounded = block.fillet(&[[60.0, 40.0, 10.0]], 0.1, 5.0).unwrap();+ let r = rounded.fillet_variable([27.5, 40.0, 20.0], 0.1, [0.0, 40.0, 20.0], 1, &[0.0, 0.0, 1.0, 1.0], &[1.0, 5.0]).unwrap();+ let arrays = r.arrays().unwrap();+ let kinds = arrays.ints.get(&EDGE_CURVE_TYPE).cloned().unwrap_or_default();+ let counts = arrays.ints.get(&EDGE_NURBS_VERTEX_COUNT).cloned().unwrap_or_default();+ let orders = arrays.ints.get(&EDGE_NURBS_ORDER).cloned().unwrap_or_default();+ let forms = arrays.ints.get(&EDGE_NURBS_FORM).cloned().unwrap_or_default();+ let knots = arrays.reals.get(&EDGE_NURBS_KNOTS).cloned().unwrap_or_default();+ // Each NURBS block's first and last knots of its domain, in edge order.+ let (mut at, mut block_of) = (0usize, Vec::new());+ for (n, o) in counts.iter().zip(&orders) {+ let (n, o) = (*n as usize, *o as usize);+ block_of.push((knots[at + o - 1], knots[at + n]));+ at += n + o;+ }+ let mut nurbs = 0usize;+ let mut edge = None;+ for (e, kind) in kinds.iter().enumerate() {+ let has_block = *kind == CURVE_NURBS || forms.get(e) == Some(&1);+ if *kind == CURVE_NURBS && edge.is_none() {+ edge = Some((e, block_of[nurbs]));+ }+ nurbs += usize::from(has_block);+ }+ let (e, (first, last)) = edge.expect("the round's end on the cylinder is a NURBS edge");+ let shifted = |by: f64| {+ let mut a = arrays.clone();+ a.reals.get_mut(&EDGE_RANGE).unwrap()[2 * e] = first - by;+ a+ };+ let (record, _) = native(&shifted(7e-15)).unwrap();+ record.validate().unwrap();+ assert!(record.edges.iter().any(|x| x.interval[0] == first && x.interval[1] <= last), "an interval on the NURBS's first knot");+ assert!(native(&shifted(1e-3)).map(|(r, _)| r.validate()).map_or(true, |v| v.is_err()), "a real overshoot is not moved");+ }+#[test]fn hostile_arrays_are_errors_never_panics() {let good = Brep::make_box([0.0; 3], [1.0, 2.0, 3.0]).unwrap().arrays().unwrap();