SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Wave 438/509: SMLib import: an extruded circle's circle comes from its widest span, not the face's range (and 3 more)
jyviko4ffc6a901790
diff --git a/crates/engine/src/boolean_regression_tests.rs b/crates/engine/src/boolean_regression_tests.rsindex 69cb1f5c3a..8731e71cbb 100644--- a/crates/engine/src/boolean_regression_tests.rs+++ b/crates/engine/src/boolean_regression_tests.rs@@ -682,7 +682,7 @@ fn ring_notch() -> f64 {}/// The wedge of #1617: a side profile in (y, z) extruded 138 mm along x, its back face leaning-/// by `lean` (the tangent of its angle), with the issue's rounds. The last one runs along the+/// by `lean` (the tangent of its angle), with the issue's rounds, each on the edges it picked. The last one runs along the/// outline of both ends. The issue asked for R1 with `fit: reduce`, which reduces it to 0.854 mm;/// that radius is asked for here directly, which builds the same body without the fit's search/// (about a minute).@@ -700,7 +700,14 @@ fn raked_wedge(lean: f64) -> Session {("solid.fillet", json!({"body": "Wedge", "radius": 1.2, "edges": [[0, -60, 22]]})),("solid.fillet", json!({"body": "Wedge", "radius": 1.5, "edges": [[0, -22, 22]]})),("solid.fillet", json!({"body": "Wedge", "radius": 1.5, "edges": [[0, 38, 60]]})),- ("solid.fillet", json!({"body": "Wedge", "radius": 4, "edges": [[-69, -60, 12], [69, -60, 12], [-69, back, 30], [69, back, 30]]})),+ // The issue's R4 rounds these four end edges alone: carried on round the end outline+ // (tangent propagation, the feature's default since 84bd2daad, after this test), it would+ // run onto the R1.2 round's end arc, where its rail on the end face would be an arc of+ // radius 1.2 - 4 < 0.+ (+ "solid.fillet",+ json!({"body": "Wedge", "radius": 4, "tangent_chain": false, "edges": [[-69, -60, 12], [69, -60, 12], [-69, back, 30], [69, back, 30]]}),+ ),("solid.fillet", json!({"body": "Wedge", "radius": 0.854, "edges": ends})),];for (command, params) in steps {diff --git a/crates/engine/src/cmd/sheet_tests.rs b/crates/engine/src/cmd/sheet_tests.rsindex bb6e3a3624..1f6553bec0 100644--- a/crates/engine/src/cmd/sheet_tests.rs+++ b/crates/engine/src/cmd/sheet_tests.rs@@ -2334,19 +2334,23 @@ fn tiny_cut_inside_exact_circle_survives_unfold_refold_and_dxf() {run(&mut s, "sheet.flange", json!({"sketch": "Disc"}));let circle = s.model.state().sheets[0].base.outer.clone();let displayed = circle.polyline(1e-3);- let at = (displayed[0] + displayed[1]).normalized().unwrap() * 9.9998;+ // A square 0.2 µm across, centred 0.4 µm inside the circle on the bisector of the+ // display polyline's first chord (its middle 0.98 µm inside): outside the polyline, inside+ // the exact circle, each of its walls and its gap to the rim wider than SMLib's 0.1 µm+ // modelling tolerance.+ let (half, at) = (0.0001, (displayed[0] + displayed[1]).normalized().unwrap() * 9.9996);assert!(!circle.contains(at));if initially_flat {run(&mut s, "sheet.unfold", json!({}));}run(&mut s, "sketch.create", json!({"plane": "XY", "name": "TinyCut"}));- run(&mut s, "sketch.rectangle.two_point", json!({"p0": [at.x-0.000025,at.y-0.000025], "p1": [at.x+0.000025,at.y+0.000025]}));+ run(&mut s, "sketch.rectangle.two_point", json!({"p0": [at.x-half,at.y-half], "p1": [at.x+half,at.y+half]}));run(&mut s, "sketch.finish", json!({}));run(&mut s, "solid.extrude", json!({"sketch": "TinyCut", "through_all": true, "operation": "cut", "direction": "symmetric"}));for stage in ["sheet.unfold", "sheet.refold"] {let regions = s.model.state().sheets[0].flat_regions().unwrap();assert_eq!(regions[0].holes.len(), 1);- assert!((regions[0].holes[0].signed_area().abs() - 2.5e-9).abs() < 1e-13);+ assert!((regions[0].holes[0].signed_area().abs() - 4e-8).abs() < 1e-13);assert_eq!(s.model.state().bodies.len(), 1);let dxf = run(&mut s, "sheet.export_dxf", json!({}))["dxf"].as_str().unwrap().to_string();assert_eq!(solidcraft_io::read_dxf(&dxf).unwrap().len(), 5);diff --git a/crates/kernel/src/surface_ruled.rs b/crates/kernel/src/surface_ruled.rsindex e6b59fe44a..5604e814f3 100644--- a/crates/kernel/src/surface_ruled.rs+++ b/crates/kernel/src/surface_ruled.rs@@ -274,18 +274,27 @@ fn planned(body: &Body, at: &[Vec3], r: &Ruled, handles: &[Option<Vec<Vec3>>]) -}}let field = Field { mode, flip: r.flip, distance: d };- let mut rulings = Vec::with_capacity(n);+ // Each edge's face beside it (its surface, whether it is used along its natural normal,+ // whether it lies left of the edge: the strip's tangent direction points away from it).+ let mut sides = Vec::with_capacity(n);for (j, k) in chosen.iter().enumerate() {let (face, along) =k.and_then(|k| around.get(j)?.get(k).copied()).ok_or_else(|| KernelError::Invalid("a picked edge has no face beside it".into()))?;let surface = surfaces.get(face).and_then(Option::as_ref).ok_or_else(|| KernelError::Failed("ruled surface: a face's surface".into()))?;- // The face lies left of its own boundary seen along its (oriented) normal; the strip's- // tangent direction points away from it.let forward = body.face_forward(face);- let base = bases.get(j).ok_or_else(|| KernelError::Failed("ruled surface: an edge".into()))?;- rulings.push(Rulings { base, face: surface, forward, face_left: along == forward, field: &field });+ sides.push((surface, forward, along == forward));}- let sampled: Vec<Sampled> = rulings.iter().map(|r| Sampled::of(r, eps)).collect::<Result<_>>()?;+ fn rulings_on<'a>(bases: &'a [CurveN<4>], sides: &[(&'a SurfaceEval, bool, bool)], field: &'a Field) -> Vec<Rulings<'a>> {+ bases.iter().zip(sides).map(|(base, &(face, forward, face_left))| Rulings { base, face, forward, face_left, field }).collect()+ }+ let sampled: Vec<Sampled> = rulings_on(&bases, &sides, &field).iter().map(|r| Sampled::of(r, eps)).collect::<Result<_>>()?;+ // A free strip's far curve lies in its edge's spline space: a straight edge's (one linear+ // span) holds only the chord between the strip's corners, so its rulings' ends would not count.+ // Such an edge is taken as the cubic it is too (exact degree elevation, the same points at the+ // same parameters), the lowest degree whose interior control points set each end's tangent+ // and let the curve pass near the rulings' ends.+ let bases: Vec<CurveN<4>> = bases.into_iter().zip(&sampled).map(|(c, s)| if s.affine.is_none() { cubic_if_straight(c) } else { c }).collect();+ let rulings = rulings_on(&bases, &sides, &field);// Exact strips' far edges are their edges' images; the rest are solved together.let exact: Vec<Option<CurveN<4>>> = sampled.iter().zip(&bases).map(|(s, base)| s.affine.as_ref().map(|m| mapped(base, |p| m.apply(p)))).collect();let corner = |r: &Reading| r.0 + r.3 * d;@@ -381,6 +390,18 @@ fn base_curve(r: &Brep, e: usize, forward: bool) -> Result<CurveN<4>> {Ok(if forward { c } else { reversed(&c) })}+/// A straight edge's NURBS (degree 1, one span: its two ends) as the cubic Bézier it also is,+/// by exact degree elevation (control points at thirds of the way, weights kept equal); any other+/// curve as it is.+fn cubic_if_straight(c: CurveN<4>) -> CurveN<4> {+ let ([p0, p1], [t0, t1]) = match (c.degree, c.ctrl.as_slice(), c.knots.as_slice()) {+ (1, [p0, p1], [a, _, _, z]) => ([*p0, *p1], [*a, *z]),+ _ => return c,+ };+ let mix = |s: f64| std::array::from_fn::<f64, 4, _>(|i| p0[i] * (1.0 - s) + p1[i] * s);+ CurveN { degree: 3, knots: vec![t0, t0, t0, t0, t1, t1, t1, t1], ctrl: vec![p0, mix(1.0 / 3.0), mix(2.0 / 3.0), p1] }+}+fn degree(knots: &[f64], n: usize) -> Result<usize> {knots.len().checked_sub(n + 1).filter(|d| *d >= 1).ok_or_else(|| KernelError::Invalid("a spline's knots".into()))}@@ -519,7 +540,7 @@ impl Sampled {// Rulings that turn along a free-form edge end on an offset curve, which has no exact NURBS form.// Such a strip's far edge is a curve this module defines instead, and the strip is exactly the// ruled surface between the edge and it: a B-spline on the edge's own degree, knots and weights-// (only its control points are free), from the strip's start corner to its end corner (where the+// (a straight edge's taken as its cubic, `cubic_if_straight`; only its control points are free), from the strip's start corner to its end corner (where the// rulings at the edge's ends reach). Its interior control points are given (the doc's handles)// or, by default, the least-squares solution of these weighted terms, the construction's// parameters:diff --git a/crates/smlib/src/import/analytic.rs b/crates/smlib/src/import/analytic.rsindex ce7a61af27..205d61e49a 100644--- a/crates/smlib/src/import/analytic.rs+++ b/crates/smlib/src/import/analytic.rs@@ -105,7 +105,10 @@ fn extruded_circle(u_knots: &[f64], v_knots: &[f64], net: &[Vec<[f64; 4]>], trimreturn None;}let arc = CurveEval::new(&b::Curve::RationalSpline { knots: arc_knots.to_vec(), homogeneous: first.clone() }).ok()?;- let (center, radius, normal) = circle(&arc, arc_range)?;+ // The circle from the arc's widest span, not from the face's range: three points on a+ // face a small part of a turn round (6 mm of a 3000 mm radius) put the centre off the+ // circle's plane and the radius off by 1e-8 mm, which SMLib does not take back as a cylinder.+ let (center, radius, normal) = circle(&arc, widest_span(arc_knots, first.len())?, arc_range)?;let z = d.normalized()?;if normal.cross(z).len() > 1e-9 {return None;@@ -397,7 +400,7 @@ impl Revolution {return Ok((cone, [angle, v]));}// A circular profile.- let (center, radius, normal) = circle(&self.profile, t).ok_or(NOT_ANALYTIC)?;+ let (center, radius, normal) = circle(&self.profile, t, t).ok_or(NOT_ANALYTIC)?;let slack = 1e-9 * radius.max(1.0);if normal.dot(self.z).abs() > 1e-9 || normal.dot(x).abs() > 1e-9 || (center - self.o).dot(y).abs() > slack {return Err(NOT_ANALYTIC);@@ -506,11 +509,20 @@ fn agree((record, domain): (&b::Surface, [[f64; 2]; 2]), (analytic, range): (&b:Ok(d < 0.0)}-/// The circle a curve runs along over `t`: centre, radius and unit normal (its turning sense),-/// checked at 65 points within 10⁻⁹ of the radius (at least 1 mm).-fn circle(c: &CurveEval, t: [f64; 2]) -> Option<(Vec3, f64, Vec3)> {+/// The widest knot span of a B-spline with `points` control points on `knots`.+fn widest_span(knots: &[f64], points: usize) -> Option<[f64; 2]> {+ let degree = knots.len().checked_sub(points + 1)?;+ knots.get(degree..=points)?.windows(2).map(|w| [w[0], w[1]]).max_by(|a, b| (a[1] - a[0]).total_cmp(&(b[1] - b[0])))+}++/// The circle a curve runs along over `t`, through its points at `fit` (a range of it on that+/// circle a good part of a turn round, where three points fix the circle to rounding): centre,+/// radius and unit normal (its turning sense over `fit`), checked at 65 points over `t` within+/// 10⁻⁹ of the radius (at least 1 mm).+fn circle(c: &CurveEval, fit: [f64; 2], t: [f64; 2]) -> Option<(Vec3, f64, Vec3)> {+ let on = |s: f64| c.point(fit[0] + (fit[1] - fit[0]) * s);let at = |s: f64| c.point(t[0] + (t[1] - t[0]) * s);- let (p, q, r) = (at(0.0)?, at(1.0 / 3.0)?, at(2.0 / 3.0)?);+ let (p, q, r) = (on(0.0)?, on(1.0 / 3.0)?, on(2.0 / 3.0)?);let (u, w) = (q - p, r - p);let normal = u.cross(w);let nn = normal.dot(normal);diff --git a/crates/smlib/src/import/tests.rs b/crates/smlib/src/import/tests.rsindex 553a18d1e0..cf96de0d29 100644--- a/crates/smlib/src/import/tests.rs+++ b/crates/smlib/src/import/tests.rs@@ -267,3 +267,54 @@ fn only_a_tube_clear_of_its_axis_is_a_ring_torus() {assert!(matches!(ring(major), Surface::PlacedRevolution { .. }), "major {major}");}}++/// A 6 mm wide patch of an extruded circle of radius 3000 whose trims straddle the knot where+/// the profile's seam lies (u = 4 of a half circle in two quarter spans): the cylinder takes the+/// patch's own range, 0.002 rad round and 7 high, on the circle exactly. Fitted on the patch's+/// range (three points 2 mm apart) the centre came off the circle's plane by 2.5e-10 mm and the+/// radius off by 8e-9 mm, a cylinder SMLib did not take back from its own NURBS of it.+#[test]+fn a_patch_across_an_extruded_circles_seam_is_its_exact_cylinder() {+ let (r, h, half) = (3000.0, 7.0, 0.001);+ let c = [10.0 - r, 0.0, 0.0];+ let w = std::f64::consts::FRAC_1_SQRT_2;+ let profile = [([c[0], -r], 1.0), ([c[0] + r, -r], w), ([c[0] + r, 0.0], 1.0), ([c[0] + r, r], w), ([c[0], r], 1.0)];+ let homogeneous = profile.iter().map(|&([x, y], wt)| vec![[x * wt, y * wt, 0.0, wt], [x * wt, y * wt, h * wt, wt]]).collect();+ let surface = Surface::RationalSpline { u_knots: vec![3.0, 3.0, 3.0, 4.0, 4.0, 5.0, 5.0, 5.0], v_knots: vec![0.0, 0.0, h, h], homogeneous };+ // The quarter span after the seam reaches `half` at quarter_param(half); the one before it+ // ends there, so the trims run symmetrically round the knot.+ let (u0, u1) = (4.0 - quarter_param(half), 4.0 + quarter_param(half));+ let corners = [[u0, 0.0], [u1, 0.0], [u1, h], [u0, h]];+ let edges: Vec<OrientedEdge> = (0..4)+ .map(|k| OrientedEdge {+ edge: k as u32,+ forward: true,+ pcurve: Curve2::Spline { knots: vec![0.0, 0.0, 1.0, 1.0], points: vec![corners[k], corners[(k + 1) % 4]] },+ })+ .collect();+ let line = Curve::Line { start: [0.0; 3], end: [1.0, 0.0, 0.0] };+ let record = Record {+ version: b::VERSION,+ tolerance: 1e-6,+ regions: Vec::new(),+ shells: Vec::new(),+ faces: vec![Face { surface, nurbs: None, domain: [[3.0, 5.0], [0.0, h]], loops: vec![Loop::Edges { edges }] }],+ edges: (0..4)+ .map(|_| Edge { nurbs: None, curve: line.clone(), interval: [0.0, 1.0], vertices: [0, 0], tolerance: 1e-6, uses: Vec::new() })+ .collect(),+ vertices: Vec::new(),+ };+ let made = analytic::analytic(&record).unwrap();+ let f = &made.faces[0];+ let Surface::Cylinder { frame, radius } = &f.surface else { panic!("{:?}", f.surface) };+ assert!((radius - r).abs() <= 1e-10, "radius {radius}");+ let z = cross(frame.x_axis, frame.y_axis);+ assert!(z[0].abs() <= 1e-15 && z[1].abs() <= 1e-15 && frame.x_axis[2].abs() <= 1e-15, "axis {z:?}, x {:?}", frame.x_axis);+ assert!(frame.origin[2].abs() <= 1e-12 && (frame.origin[0] - c[0]).abs() <= 1e-9 && frame.origin[1].abs() <= 1e-9, "centre {:?}", frame.origin);+ // u from the patch's first edge, 2 * half round; v its height.+ let [[a0, a1], [v0, v1]] = f.domain;+ assert!(a0 == 0.0 && (a1 - 2.0 * half).abs() <= 1e-12, "{:?}", f.domain);+ assert!(v0.abs() <= 1e-12 && (v1 - h).abs() <= 1e-12, "{:?}", f.domain);+ let start = (-half).sin_cos();+ assert!((frame.x_axis[0] - start.1).abs() <= 1e-12 && (frame.x_axis[1] - start.0).abs() <= 1e-12, "x {:?}", frame.x_axis);+}