diff --git a/crates/geom/src/brep.rs b/crates/geom/src/brep.rs index 6e5ab5513..dbc3cab74 100644 --- a/crates/geom/src/brep.rs +++ b/crates/geom/src/brep.rs @@ -89,10 +89,11 @@ pub struct Face { /// What the face is: its surface as the producer names it (a cylinder, a NURBS…). pub surface: Surface, /// The NURBS form the face is parameterised on, when it differs from `surface`'s own - /// parameters: a cylinder, cone, sphere or torus as SMLib holds it (every SMLib analytic - /// surface is a B-spline surface, its trims in that NURBS's parameters). When given, `domain` - /// and every pcurve are in this surface's (u, v), and `surface` only says what it is; it is a - /// `Spline` or `RationalSpline` and `surface` is a cylinder, cone, sphere or torus + /// parameters: a cylinder, cone, sphere, torus or placed revolution as SMLib holds it (every + /// SMLib analytic surface is a B-spline surface, its trims in that NURBS's parameters). When + /// given, `domain` and every pcurve are in this surface's (u, v), and `surface` only says what + /// it is; it is a `Spline` or `RationalSpline` and `surface` is a cylinder, cone, sphere, torus + /// or placed revolution /// (docs/native-brep.md, "Surfaces"). #[serde(default, skip_serializing_if = "Option::is_none")] pub nurbs: Option, @@ -589,6 +590,8 @@ impl Brep { "NURBS form on a curve that is not a line, circle or ellipse", )?; } + // A circle or ellipse is a label: its geometry is its NURBS form. + require(e.nurbs.is_some() || !matches!(e.curve, Curve::Circle { .. } | Curve::Ellipse { .. }), "a circle or ellipse without its NURBS form")?; interval(&e.interval, curve_natural(e.parameters()))?; require(e.vertices.iter().all(|&v| (v as usize) < self.vertices.len()), "edge vertices")?; tolerance(e.tolerance)?; @@ -600,10 +603,26 @@ impl Brep { surface(n, 0, &mut budget)?; require(matches!(n, Surface::Spline { .. } | Surface::RationalSpline { .. }), "NURBS form is not a NURBS")?; require( - matches!(f.surface, Surface::Cylinder { .. } | Surface::Cone { .. } | Surface::Sphere { .. } | Surface::Torus { .. }), - "NURBS form on a surface that is not a cylinder, cone, sphere or torus", + matches!( + f.surface, + Surface::Cylinder { .. } + | Surface::Cone { .. } + | Surface::Sphere { .. } + | Surface::Torus { .. } + | Surface::PlacedRevolution { .. } + ), + "NURBS form on a surface that is not a cylinder, cone, sphere, torus or revolution", )?; } + // A cylinder, cone, sphere, torus or revolution is a label: its geometry is its form. + require( + f.nurbs.is_some() + || !matches!( + f.surface, + Surface::Cylinder { .. } | Surface::Cone { .. } | Surface::Sphere { .. } | Surface::Torus { .. } | Surface::PlacedRevolution { .. } + ), + "a cylinder, cone, sphere, torus or revolution without its NURBS form", + )?; let [u, v] = surface_natural(f.parameters()); interval(&f.domain[0], u)?; interval(&f.domain[1], v)?; diff --git a/crates/geom/src/brep/form.rs b/crates/geom/src/brep/form.rs index caff2ea7b..55f8a53cf 100644 --- a/crates/geom/src/brep/form.rs +++ b/crates/geom/src/brep/form.rs @@ -61,6 +61,18 @@ fn quarters([a0, a1]: [f64; 2]) -> Option<(f64, usize)> { (n <= 5).then_some((q0, n)) } +/// A face's quarters along an angle direction and its domain there: a whole turn is exactly +/// four quarters from the one it starts in (the form closes on itself, so it is periodic and the +/// face's seam uses lie a period apart), anything less the quarters it needs. +fn face_quarters(a: [f64; 2]) -> Option<((f64, usize), [f64; 2])> { + if a[1] - a[0] >= TAU * (1.0 - 1e-9) { + let q0 = quarter_of(a[0]); + return Some(((q0, 4), [q0, q0 + 4.0])); + } + let grid = quarters(a)?; + Some((grid, params(a, grid))) +} + /// The form parameters of an angle interval on the quarters `quarters` chose for it (its ends kept /// on them: an end within rounding past a quarter's end stays in that quarter). fn params([a0, a1]: [f64; 2], (q0, n): (f64, usize)) -> [f64; 2] { @@ -128,9 +140,8 @@ fn conic(frame: &Frame, [rx, ry]: [f64; 2], t: [f64; 2]) -> Option<(Curve, [f64; /// parameters: angles, and the height along the axis of a cylinder or cone) and the domain in the /// form's parameters; `None` for another kind, or a domain of more than one turn. pub fn surface(s: &Surface, [u, v]: [[f64; 2]; 2]) -> Option<(Surface, [[f64; 2]; 2])> { - let grid = quarters(u)?; + let (grid, fu) = face_quarters(u)?; let (u_knots, ring) = arcs(grid.0, grid.1); - let fu = params(u, grid); // The ring of arcs times a profile `(control, weight)` mapped to (radial, axial) about the // frame: a rational tensor product, its weights the products. let net = |f: &Frame, profile: &[([f64; 2], f64)], at: &dyn Fn([f64; 2]) -> (f64, f64)| -> Option>> { @@ -168,10 +179,45 @@ pub fn surface(s: &Surface, [u, v]: [[f64; 2]; 2]) -> Option<(Surface, [[f64; 2] Some((Surface::RationalSpline { u_knots, v_knots, homogeneous }, [fu, params(v, vgrid)])) } Surface::Torus { frame, major_radius, minor_radius } => { - let vgrid = quarters(v)?; + let (vgrid, fv) = face_quarters(v)?; let (v_knots, tube) = arcs(vgrid.0, vgrid.1); let homogeneous = net(frame, &tube, &|[c, s]| (major_radius + minor_radius * c, minor_radius * s))?; - Some((Surface::RationalSpline { u_knots, v_knots, homogeneous }, [fu, params(v, vgrid)])) + Some((Surface::RationalSpline { u_knots, v_knots, homogeneous }, [fu, fv])) + } + Surface::PlacedRevolution { profile, origin, axis, matrix, forward } => { + // The profile's control points turned about the axis on the quarter grid from angle + // zero (the profile): (a + ib)(c + is) for each point's radial (a, b) in the frame and + // each arc control point (c, s), weights multiplied; then the matrix. + let (angles, along) = if *forward { (v, u) } else { (u, v) }; + let (ring_grid, fa) = face_quarters(angles)?; + let (a_knots, arcs_r) = arcs(ring_grid.0, ring_grid.1); + let (p_knots, h) = profile_nurbs(profile, Some(along))?; + let fp = match profile.as_ref() { + Curve::Circle { .. } | Curve::Ellipse { .. } => curve(profile, along)?.1, + _ => along, + }; + let (o, x, y, k) = revolution_frame(&h, *origin, *axis)?; + let net: Vec> = arcs_r + .iter() + .map(|([c, s], wu)| { + h.iter() + .map(|hp| { + let d = Vec3::new(hp[0] / hp[3], hp[1] / hp[3], hp[2] / hp[3]) - o; + let (a, b, z) = (d.dot(x), d.dot(y), d.dot(k)); + let q = o + k * z + x * (a * c - b * s) + y * (a * s + b * c); + hom(affine(matrix, q), wu * hp[3]) + }) + .collect() + }) + .collect(); + if *forward { + // u the profile, v the angle: the net turned over. + let n = net.first()?.len(); + let t: Vec> = (0..n).map(|j| net.iter().filter_map(|r| r.get(j).copied()).collect()).collect(); + Some((Surface::RationalSpline { u_knots: p_knots, v_knots: a_knots, homogeneous: t }, [fp, fa])) + } else { + Some((Surface::RationalSpline { u_knots: a_knots, v_knots: p_knots, homogeneous: net }, [fa, fp])) + } } _ => None, } @@ -196,14 +242,60 @@ pub fn on_frame(c: &Curve, [t0, t1]: [f64; 2], frame: &Frame, tol: f64) -> Optio Some((Curve::Circle { frame: relabel, radius: *radius }, [t0 + shift, t1 + shift])) } -/// The frame of a cylinder, cone, sphere or torus (`None` for another surface). -pub fn frame_of(s: &Surface) -> Option<&Frame> { +/// The frame of a cylinder, cone, sphere or torus, or of a placed revolution (its axis, angle +/// zero at its profile: [`revolution_frame`]); `None` for another surface. +pub fn frame_of(s: &Surface) -> Option { match s { - Surface::Cylinder { frame, .. } | Surface::Cone { frame, .. } | Surface::Sphere { frame, .. } | Surface::Torus { frame, .. } => Some(frame), + Surface::Cylinder { frame, .. } | Surface::Cone { frame, .. } | Surface::Sphere { frame, .. } | Surface::Torus { frame, .. } => { + Some(frame.clone()) + } + Surface::PlacedRevolution { profile, origin, axis, matrix, .. } => { + let (_, h) = profile_nurbs(profile, None)?; + let (o, x, y, _) = revolution_frame(&h, *origin, *axis)?; + let m = |p: Vec3| affine(matrix, p); + let (mo, mx, my) = (m(o), m(o + x) - m(o), m(o + y) - m(o)); + Some(Frame { origin: [mo.x, mo.y, mo.z], x_axis: [mx.x, mx.y, mx.z], y_axis: [my.x, my.y, my.z] }) + } _ => None, } } +/// `matrix` (column-major, `matrix[column][row]`) applied to `p`. +fn affine(matrix: &[[f64; 4]; 4], p: Vec3) -> Vec3 { + let row = |r: usize| matrix[0][r] * p.x + matrix[1][r] * p.y + matrix[2][r] * p.z + matrix[3][r]; + Vec3::new(row(0), row(1), row(2)) +} + +/// A revolution's profile as a NURBS: its knots and homogeneous control points (a B-spline or +/// NURBS as it is, a line or conic as its form over `range`; `None` without a range). +fn profile_nurbs(profile: &Curve, range: Option<[f64; 2]>) -> Option<(Vec, Vec<[f64; 4]>)> { + let formed; + let c = match profile { + Curve::Spline { .. } | Curve::RationalSpline { .. } => profile, + other => { + formed = curve(other, range?)?.0; + &formed + } + }; + match c { + Curve::Spline { knots, points } => Some((knots.clone(), points.iter().map(|p| [p[0], p[1], p[2], 1.0]).collect())), + Curve::RationalSpline { knots, homogeneous } => Some((knots.clone(), homogeneous.clone())), + _ => None, + } +} + +/// A revolution's frame: the origin and unit axis, x the radial direction of the profile's +/// first control point off the axis (angle zero), y = axis × x. +fn revolution_frame(h: &[[f64; 4]], origin: [f64; 3], axis: [f64; 3]) -> Option<(Vec3, Vec3, Vec3, Vec3)> { + let (o, k) = (v3(origin), v3(axis).normalized()?); + let x = h.iter().find_map(|h| { + let d = Vec3::new(h[0] / h[3], h[1] / h[3], h[2] / h[3]) - o; + let r = d - k * d.dot(k); + if r.len() > 1e-12 * (1.0 + d.len()) { r.normalized() } else { None } + })?; + Some((o, x, k.cross(x), k)) +} + /// An edge's label and NURBS form: a circle about the axis of one of `frames` (the cylinder, /// cone, sphere and torus faces it bounds) is labelled on that frame ([`on_frame`]), so its form /// lies on that face's quarter grid; a circle or ellipse then has its form ([`curve`]). The label @@ -221,3 +313,52 @@ pub fn edge<'a>( }; Some((label, iv, form)) } + +/// Points per edge along a loop taken for a face's extent. +const EXTENT_POINTS: usize = 32; + +/// The parameter box of a face on `label` over its boundary: each loop's points (`loops`, in +/// order along each loop) projected onto the label, a periodic parameter unwrapped from one point +/// to the next. What the face's NURBS form ([`surface`]) is built over; no pcurve is involved. +pub fn extent(label: &Surface, loops: &[Vec<(&Curve, [f64; 2], bool)>]) -> Option<[[f64; 2]; 2]> { + let eval = super::eval::SurfaceEval::new(label).ok()?; + let period = eval.domain().period; + let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]); + for l in loops { + let mut prev: Option<[f64; 2]> = None; + for (c, [t0, t1], forward) in l { + let curve = super::eval::CurveEval::new(c).ok()?; + for k in 0..=EXTENT_POINTS { + let f = k as f64 / EXTENT_POINTS as f64; + let t = if *forward { t0 * (1.0 - f) + t1 * f } else { t1 * (1.0 - f) + t0 * f }; + let mut q = eval.project(curve.point(t)?, prev, f64::INFINITY)?; + if let Some(p) = prev { + for d in 0..2 { + if let Some(Some(per)) = period.get(d) { + q[d] += ((p[d] - q[d]) / per).round() * per; + } + } + } + // At a pole the collapsed parameter is anything: it bounds nothing. + let pole = eval.pole(q); + for d in 0..2 { + if !pole.get(d).copied().unwrap_or(false) { + lo[d] = lo[d].min(q[d]); + hi[d] = hi[d].max(q[d]); + } + } + if !pole.iter().any(|p| *p) { + prev = Some(q); + } + } + } + } + // At most one turn round a periodic direction; a boundary that never goes round it (a face + // bounded by its seam alone) covers the whole turn from there. + for d in 0..2 { + if let Some(Some(per)) = period.get(d) { + hi[d] = if hi[d] - lo[d] <= 1e-9 * per { lo[d] + per } else { hi[d].min(lo[d] + per) }; + } + } + (lo[0] < hi[0] && lo[1] < hi[1]).then_some([[lo[0], hi[0]], [lo[1], hi[1]]]) +} diff --git a/crates/geom/src/brep/pcurve.rs b/crates/geom/src/brep/pcurve.rs index 4cfd38c4d..88b86a6bc 100644 --- a/crates/geom/src/brep/pcurve.rs +++ b/crates/geom/src/brep/pcurve.rs @@ -212,7 +212,7 @@ impl On { } fn pcurve(&self, record: &Curve, curve: &CurveEval, range: [f64; 2], tol: f64) -> Result { - if let Some(pc) = self.exact(record, curve, range)? + if let Some(pc) = self.exact(record, curve, range, tol)? && self.lifts(&pc, curve, range, 0.5 * tol) { return Ok(pc); @@ -221,7 +221,7 @@ impl On { } /// The closed-form pcurve where there is one (unchecked). - fn exact(&self, record: &Curve, curve: &CurveEval, [t0, t1]: [f64; 2]) -> Result> { + fn exact(&self, record: &Curve, curve: &CurveEval, [t0, t1]: [f64; 2], tol: f64) -> Result> { let segment = |a: [f64; 2], b: [f64; 2]| Curve2::Spline { knots: vec![t0, t0, t1, t1], points: vec![a, b] }; let at = |t: f64| curve.point(t).ok_or_else(|| Error::Failed(format!("the curve has no point at {t}"))); Ok(match (&self.surface, record) { @@ -283,7 +283,7 @@ impl On { let c = super::eval::Axes::new(frame); let turn = c.z.dot(axes.z); if (turn.abs() - 1.0).abs() > 1e-9 { - return Ok(None); + return Ok(self.meridian(axes, &c, *radius, curve, [t0, t1])); } let sign = turn.signum(); let u0 = c.x.dot(axes.y).atan2(c.x.dot(axes.x)); @@ -305,28 +305,69 @@ impl On { let u = b.atan2(a); Some(segment([u, height(t0)?], [u, height(t1)?])) } - (SurfaceEval::Eval(..), _) => self.along(curve, [t0, t1]), + (SurfaceEval::Eval(..), _) => self.along(curve, [t0, t1], tol), _ => None, }) } + /// A meridian of a sphere or a tube circle of a torus (a circle in a plane through the axis, + /// centred on the sphere's centre or on the torus's ring): u fixed at the arc's azimuth, v its + /// angle from the outward radial toward the axis, `α + s·t` (`s` ±1 as the circle runs). + /// `None` for any other circle. + fn meridian(&self, axes: &super::eval::Axes, c: &super::eval::Axes, radius: f64, curve: &CurveEval, [t0, t1]: [f64; 2]) -> Option { + let ring = match &self.surface { + SurfaceEval::Sphere { radius: r, .. } => (0.0, *r), + SurfaceEval::Torus { major, minor, .. } => (*major, *minor), + _ => return None, + }; + let size = 1.0 + ring.0 + ring.1; + if c.z.dot(axes.z).abs() > 1e-9 || (radius - ring.1).abs() > 1e-9 * size { + return None; + } + let tm = 0.5 * (t0 + t1); + let m = curve.point(tm)?; + let [mx, my, _] = axes.local(m); + let u0 = my.atan2(mx); + let radial = (axes.x * mx + axes.y * my).normalized()?; + // The circle's centre: the sphere's, or the torus's ring at that azimuth. + let centre = axes.o + radial * ring.0; + if c.o.dist(centre) > 1e-9 * size { + return None; + } + let s = c.z.dot(radial.cross(axes.z)).signum(); + let d = m - centre; + let vm = d.dot(axes.z).atan2(d.dot(radial)); + let alpha = vm - s * tm; + Some(Curve2::Spline { knots: vec![t0, t0, t1, t1], points: vec![[u0, alpha + s * t0], [u0, alpha + s * t1]] }) + } + /// On a spline face (a NURBS form, or another spline), the edge's pcurve where it runs along /// the face's parameters at its own parameter's pace: a straight line in (u, v), between the /// ends' parameters, or with u (or v) the edge's parameter itself (a rim of a revolved form on /// the same quarter grid, whose two ends are one point on the seam). A candidate is taken only - /// where it lifts onto the edge to within rounding, so it is the exact pcurve; none is fitted. - fn along(&self, curve: &CurveEval, [t0, t1]: [f64; 2]) -> Option { + /// where it lifts onto the edge within the record's tolerance, as the closed forms on analytic + /// surfaces must: the closed form the geometry has, never a fit. + fn along(&self, curve: &CurveEval, [t0, t1]: [f64; 2], tol: f64) -> Option { let (p0, p1, pm) = (curve.point(t0)?, curve.point(t1)?, curve.point(0.5 * (t0 + t1))?); let size = [p0, p1, pm].iter().flat_map(|p| [p.x.abs(), p.y.abs(), p.z.abs()]).fold(1.0, f64::max); - let exact = EXACT * size; + // Within the record's tolerance, as the closed forms on analytic surfaces are, and never + // looser than rounding. + let exact = (0.5 * tol).max(EXACT * size); let line = |a: [f64; 2], b: [f64; 2]| Curve2::Spline { knots: vec![t0, t0, t1, t1], points: vec![a, b] }; let mut candidates = Vec::with_capacity(3); - if let (Some(a), Some(b)) = (self.project(p0, None, exact), self.project(p1, None, exact)) { + let ends = (self.project_in(p0, exact), self.project_in(p1, exact)); + if let (Some(a), Some(b)) = ends { candidates.push(line(a, b)); } + // One parameter fixed where the edge's middle is (an end on a seam or at an apex may + // project anywhere along it), the other from the ends. + if let (Some(a), Some(b), Some(m)) = (ends.0, ends.1, self.project_in(pm, exact)) { + candidates.push(line([m[0], a[1]], [m[0], b[1]])); + candidates.push(line([a[0], m[1]], [b[0], m[1]])); + } // u or v the edge's own parameter, either way along and offset (forms on one frame's // quarter grid, or on the same grid turned over), the other fixed. - if let Some([u, v]) = self.project(pm, None, exact) { + if let Some([u, v]) = self.project_in(pm, exact) { let tm = 0.5 * (t0 + t1); for sign in [1.0, -1.0] { let (cu, cv) = (u - sign * tm, v - sign * tm); @@ -351,6 +392,17 @@ impl On { }) } + /// The parameters of `p` within `accept` inside the face's parameter box when it has one: a + /// spline extended past its knots, or a profile turned past where the face lies, has other + /// preimages outside it. The global search first, then from the box's centre. + fn project_in(&self, p: Vec3, accept: f64) -> Option<[f64; 2]> { + let Some(b) = self.face else { return self.project(p, None, accept) }; + let pad = |d: usize| 1e-9 * (1.0 + (b[d][1] - b[d][0]).abs()); + let inside = |q: [f64; 2]| (0..2).all(|d| q[d] >= b[d][0] - pad(d) && q[d] <= b[d][1] + pad(d)); + let centre = [0.5 * (b[0][0] + b[0][1]), 0.5 * (b[1][0] + b[1][1])]; + [None, Some(centre)].into_iter().filter_map(|near| self.project(p, near, accept)).find(|q| inside(*q)) + } + /// The parameters of `p` within `accept`, from `near` (and unwrapped to it) when given. fn project(&self, p: Vec3, near: Option<[f64; 2]>, accept: f64) -> Option<[f64; 2]> { let mut q = self.surface.project_with(&self.starts, p, near, accept)?; diff --git a/crates/geom/src/brep/pcurve_tests.rs b/crates/geom/src/brep/pcurve_tests.rs index 93d314dd7..04d5f096f 100644 --- a/crates/geom/src/brep/pcurve_tests.rs +++ b/crates/geom/src/brep/pcurve_tests.rs @@ -128,10 +128,10 @@ fn rulings_are_v_lines() { } } -/// Curves with no closed form are fitted cubic B-splines within the tolerance: a tilted circle -/// on a sphere, a plane's ellipse on a cylinder, a circle off the axis on a plane. +/// Curves with no closed form on their face are refused, never fitted: a tilted circle on a +/// sphere, a plane's ellipse on a cylinder, a circle off the axis on a plane. #[test] -fn other_curves_are_fitted_within_tolerance() { +fn curves_without_a_closed_form_are_refused() { let (s, c) = 0.5f64.sin_cos(); let sphere = Surface::Sphere { frame: about_z([0.; 3], false), radius: 6. }; let great = Curve::Circle { frame: frame([0.; 3], [1., 0., 0.], [0., c, s]), radius: 6. }; @@ -143,22 +143,10 @@ fn other_curves_are_fitted_within_tolerance() { let plane = Surface::Plane { origin: [0.; 3], u_axis: [1., 0., 0.], v_axis: [0., 1., 0.] }; let circle = Curve::Circle { frame: about_z([3., 1., 0.], false), radius: 2. }; for (surface, curve, interval) in [(&sphere, &great, [0., TAU]), (&cylinder, &ellipse, [0.2, 6.]), (&plane, &circle, [0., 3.])] { - for tol in [1e-3, 1e-6] { - let pc = &pcurves(surface, &one(curve, interval), tol).unwrap()[0][0]; - let Curve2::Spline { knots, .. } = pc else { panic!("a B-spline") }; - assert_eq!(knots.len() - pc_count(pc) - 1, 3, "cubic"); - let e = lift_error(surface, curve, interval, pc); - assert!(e <= tol, "{curve:?} at {tol}: {e}"); - } + let r = pcurves(surface, &one(curve, interval), 1e-6); + assert!(matches!(&r, Err(Error::Failed(m)) if m.contains("not supported yet: no exact pcurve")), "{curve:?}: {r:?}"); } } -fn pc_count(pc: &Curve2) -> usize { - match pc { - Curve2::Spline { points, .. } => points.len(), - Curve2::RationalSpline { homogeneous, .. } => homogeneous.len(), - } -} - /// The ends of each use in loop order and the loop's signed area in (u, v). fn walk(l: &[EdgeUse<'_>], pcs: &[Curve2]) -> (Vec<([f64; 2], [f64; 2])>, f64) { let mut ring = Vec::new(); @@ -288,27 +276,30 @@ fn a_seam_from_pole_to_pole_encloses_the_whole_sphere() { knots: vec![0., 0., 0., 0.5, 0.5, 1., 1., 1.], homogeneous: vec![h(o - z + side, 1.), h(o - z + r, w), h(o + r, 1.), h(o + z + r, w), h(o + z - side, 1.)], }; - for (seam, iv) in [(&circle, [-FRAC_PI_2, FRAC_PI_2]), (&nurbs, [0., 1.])] { + // The circle on the sphere as it is; the NURBS meridian, on a parameter of its own, + // on the sphere's NURBS form (one turn is four quarters there, the latitude two). + let (form, _) = crate::brep::form::surface(&sphere, [[0., TAU], [-FRAC_PI_2, FRAC_PI_2]]).unwrap(); + for (seam, iv, on, period, height) in [(&circle, [-FRAC_PI_2, FRAC_PI_2], &sphere, TAU, PI), (&nurbs, [0., 1.], &form, 4., 2.)] { for order in [[true, false], [false, true]] { let l: Vec = order .iter() .map(|&forward| EdgeUse { edge: 0, curve: seam, interval: iv, forward, tolerance: 0.0, given: None }) .collect(); - let pcs = &pcurves(&sphere, std::slice::from_ref(&l), tol).unwrap()[0]; + let pcs = &pcurves(on, std::slice::from_ref(&l), tol).unwrap()[0]; let what = format!("{sf:?} {turn} {off} {seam:?} {order:?}"); for pc in pcs { - assert!(lift_error(&sphere, seam, iv, pc) <= tol, "{what}"); + assert!(lift_error(on, seam, iv, pc) <= tol, "{what}"); } let mid = 0.5 * (iv[0] + iv[1]); let (a, b) = (pcs[0].eval(mid).unwrap(), pcs[1].eval(mid).unwrap()); - assert!(((a[0] - b[0]).abs() - TAU).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-12, "a period apart: {a:?} {b:?} {what}"); + assert!(((a[0] - b[0]).abs() - period).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-12, "a period apart: {a:?} {b:?} {what}"); let (ends, area) = walk(&l, pcs); for k in 0..2 { assert!((ends[k].1[1] - ends[(k + 1) % 2].0[1]).abs() < 1e-6, "closed in v: {ends:?} {what}"); } // The box less the corners `walk` cuts (it joins each use's 16th // sample to the next use's start): about 15/16 of it. - assert!((area / (TAU * PI * 15. / 16.) - 1.).abs() < 1e-2, "counter-clockwise around the box: {area} {what}"); + assert!((area / (period * height * 15. / 16.) - 1.).abs() < 1e-2, "counter-clockwise around the box: {area} {what}"); } } } @@ -346,28 +337,6 @@ fn a_torus_bounded_by_its_seams_spans_both_periods() { } } -/// A surface of revolution about +z as a rational spline closed in u, as SMLib writes a fillet -/// ring round a hole's rim and STEP a NURBS cylinder: u the nine-point rational quadratic -/// circle on [0, 1] (first and last rows the same), v the profile's `[radius, height, weight]` -/// points on `v_knots`. -pub(crate) fn closed_ring(profile: &[[f64; 3]], v_knots: &[f64]) -> Surface { - let w = std::f64::consts::FRAC_1_SQRT_2; - let around = [[1., 0., 1.], [1., 1., w], [0., 1., 1.], [-1., 1., w], [-1., 0., 1.], [-1., -1., w], [0., -1., 1.], [1., -1., w], [1., 0., 1.]]; - let homogeneous = around - .iter() - .map(|&[cx, cy, wu]| { - profile - .iter() - .map(|&[r, z, wv]| { - let wt = wu * wv; - [r * cx * wt, r * cy * wt, z * wt, wt] - }) - .collect() - }) - .collect(); - Surface::RationalSpline { u_knots: vec![0., 0., 0., 0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 1., 1., 1.], v_knots: v_knots.to_vec(), homogeneous } -} - /// The pcurves of a loop on a spline closed in u (period 1): each lifts within `tol`, the /// seam's two uses (`seam`: their positions) lie one period apart, the loop closes (in v alone /// where it meets a pole) and turns counter-clockwise once around the whole (u, v) box, all in @@ -380,7 +349,9 @@ fn closes_around_the_box(surface: &Surface, l: &[EdgeUse<'_>], seam: [usize; 2], let iv = l[seam[0]].interval; let mid = 0.5 * (iv[0] + iv[1]); let (a, b) = (pcs[seam[0]].eval(mid).unwrap(), pcs[seam[1]].eval(mid).unwrap()); - assert!(((a[0] - b[0]).abs() - 1.).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9, "{what}: seam uses a period apart: {a:?} {b:?}"); + let dom = SurfaceEval::new(surface).unwrap().domain(); + let period = dom.period[0].unwrap(); + assert!(((a[0] - b[0]).abs() - period).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9, "{what}: seam uses a period apart: {a:?} {b:?}"); let (ends, area) = walk(l, pcs); let n = l.len(); for k in 0..n { @@ -390,6 +361,8 @@ fn closes_around_the_box(surface: &Surface, l: &[EdgeUse<'_>], seam: [usize; 2], } // At a pole `walk` cuts the corner (it joins each use's 16th sample to the next use's // start, across the pole's line): a sliver of the box less. + let [u, v] = dom.range.map(|r| r.unwrap()); + let area = area / ((u.1 - u.0) * (v.1 - v.0)); let least = if pole.is_some() { 0.9 } else { 1. - 1e-6 }; assert!(area >= least && area < 1. + 1e-6, "{what}: counter-clockwise around the box: {area}"); for pc in pcs { @@ -397,7 +370,7 @@ fn closes_around_the_box(surface: &Surface, l: &[EdgeUse<'_>], seam: [usize; 2], for k in 0..=32 { let t = knots[0] + (knots[knots.len() - 1] - knots[0]) * k as f64 / 32.; let q = pc.eval(t).unwrap(); - assert!((-1e-9..=1. + 1e-9).contains(&q[0]), "{what}: base period: {q:?}"); + assert!((u.0 - 1e-9..=u.1 + 1e-9).contains(&q[0]), "{what}: base period: {q:?}"); } } } @@ -408,43 +381,45 @@ fn closes_around_the_box(surface: &Surface, l: &[EdgeUse<'_>], seam: [usize; 2], /// into its pole. Each seam's uses come out a period apart, never both on u = 0. #[test] fn a_seam_on_a_spline_closed_in_u_gets_pcurves_a_period_apart() { - let w = std::f64::consts::FRAC_1_SQRT_2; let full = [0., TAU]; let (big, small) = (5., 1.); - // The torus band: the tube's quarter from its outer equator (v = 0) to its top (v = 1). - let band = closed_ring(&[[big + small, 0., 1.], [big + small, small, w], [big, small, 1.]], &[0., 0., 0., 1., 1., 1.]); - let outer = Curve::Circle { frame: about_z([0.; 3], false), radius: big + small }; - let top = Curve::Circle { frame: about_z([0., 0., small], false), radius: big }; - let quarter = Curve::Circle { frame: frame([big, 0., 0.], [1., 0., 0.], [0., 0., 1.]), radius: small }; + // Each surface and circle on its NURBS form (`form`), as SolidCraft's builders give them. + let on = |c: &Curve, iv: [f64; 2]| crate::brep::form::curve(c, iv).unwrap(); + // The torus band: the tube's quarter from its outer equator to its top. + let torus = Surface::Torus { frame: about_z([0.; 3], false), major_radius: big, minor_radius: small }; + let (band, _) = crate::brep::form::surface(&torus, [full, [0., FRAC_PI_2]]).unwrap(); + let outer = on(&Curve::Circle { frame: about_z([0.; 3], false), radius: big + small }, full); + let top = on(&Curve::Circle { frame: about_z([0., 0., small], false), radius: big }, full); + let quarter = on(&Curve::Circle { frame: frame([big, 0., 0.], [1., 0., 0.], [0., 0., 1.]), radius: small }, [0., FRAC_PI_2]); let l = vec![ - EdgeUse { edge: 0, curve: &outer, interval: full, forward: true, tolerance: 0.0, given: None }, - EdgeUse { edge: 1, curve: &quarter, interval: [0., FRAC_PI_2], forward: true, tolerance: 0.0, given: None }, - EdgeUse { edge: 2, curve: &top, interval: full, forward: false, tolerance: 0.0, given: None }, - EdgeUse { edge: 1, curve: &quarter, interval: [0., FRAC_PI_2], forward: false, tolerance: 0.0, given: None }, + EdgeUse { edge: 0, curve: &outer.0, interval: outer.1, forward: true, tolerance: 0.0, given: None }, + EdgeUse { edge: 1, curve: &quarter.0, interval: quarter.1, forward: true, tolerance: 0.0, given: None }, + EdgeUse { edge: 2, curve: &top.0, interval: top.1, forward: false, tolerance: 0.0, given: None }, + EdgeUse { edge: 1, curve: &quarter.0, interval: quarter.1, forward: false, tolerance: 0.0, given: None }, ]; for tol in [1e-4, 1e-7] { closes_around_the_box(&band, &l, [1, 3], None, tol, &format!("torus band, tol {tol}")); } - // The cylinder: radius 3 from z = 0 (v = 0) to z = 4 (v = 1), its seam a line. - let cylinder = closed_ring(&[[3., 0., 1.], [3., 4., 1.]], &[0., 0., 1., 1.]); - let (low, high) = - (Curve::Circle { frame: about_z([0.; 3], false), radius: 3. }, Curve::Circle { frame: about_z([0., 0., 4.], false), radius: 3. }); + // The cylinder: radius 3 from z = 0 to z = 4, its seam a line. + let (cylinder, _) = crate::brep::form::surface(&Surface::Cylinder { frame: about_z([0.; 3], false), radius: 3. }, [full, [0., 4.]]).unwrap(); + let low = on(&Curve::Circle { frame: about_z([0.; 3], false), radius: 3. }, full); + let high = on(&Curve::Circle { frame: about_z([0., 0., 4.], false), radius: 3. }, full); let line = Curve::Line { start: [3., 0., 0.], end: [3., 0., 4.] }; let l = vec![ - EdgeUse { edge: 0, curve: &low, interval: full, forward: true, tolerance: 0.0, given: None }, + EdgeUse { edge: 0, curve: &low.0, interval: low.1, forward: true, tolerance: 0.0, given: None }, EdgeUse { edge: 1, curve: &line, interval: [0., 1.], forward: true, tolerance: 0.0, given: None }, - EdgeUse { edge: 2, curve: &high, interval: full, forward: false, tolerance: 0.0, given: None }, + EdgeUse { edge: 2, curve: &high.0, interval: high.1, forward: false, tolerance: 0.0, given: None }, EdgeUse { edge: 1, curve: &line, interval: [0., 1.], forward: false, tolerance: 0.0, given: None }, ]; closes_around_the_box(&cylinder, &l, [1, 3], None, 1e-7, "cylinder"); - // The dome: radius 6 from its equator (v = 0) to its pole (v = 1), the seam a meridian. - let dome = closed_ring(&[[6., 0., 1.], [6., 6., w], [0., 6., 1.]], &[0., 0., 0., 1., 1., 1.]); - let equator = Curve::Circle { frame: about_z([0.; 3], false), radius: 6. }; - let meridian = Curve::Circle { frame: frame([0.; 3], [1., 0., 0.], [0., 0., 1.]), radius: 6. }; + // The dome: radius 6 from its equator to its pole, the seam a meridian. + let (dome, _) = crate::brep::form::surface(&Surface::Sphere { frame: about_z([0.; 3], false), radius: 6. }, [full, [0., FRAC_PI_2]]).unwrap(); + let equator = on(&Curve::Circle { frame: about_z([0.; 3], false), radius: 6. }, full); + let meridian = on(&Curve::Circle { frame: frame([0.; 3], [1., 0., 0.], [0., 0., 1.]), radius: 6. }, [0., FRAC_PI_2]); let l = vec![ - EdgeUse { edge: 0, curve: &equator, interval: full, forward: true, tolerance: 0.0, given: None }, - EdgeUse { edge: 1, curve: &meridian, interval: [0., FRAC_PI_2], forward: true, tolerance: 0.0, given: None }, - EdgeUse { edge: 1, curve: &meridian, interval: [0., FRAC_PI_2], forward: false, tolerance: 0.0, given: None }, + EdgeUse { edge: 0, curve: &equator.0, interval: equator.1, forward: true, tolerance: 0.0, given: None }, + EdgeUse { edge: 1, curve: &meridian.0, interval: meridian.1, forward: true, tolerance: 0.0, given: None }, + EdgeUse { edge: 1, curve: &meridian.0, interval: meridian.1, forward: false, tolerance: 0.0, given: None }, ]; closes_around_the_box(&dome, &l, [1, 2], Some(2), 1e-7, "dome"); // A spline whose ends merely come near each other stays open: no period, so the seam's @@ -454,11 +429,11 @@ fn a_seam_on_a_spline_closed_in_u_gets_pcurves_a_period_apart() { open[8][0][1] += 1e-3; let open = Surface::RationalSpline { u_knots: u_knots.clone(), v_knots: v_knots.clone(), homogeneous: open }; assert_eq!(SurfaceEval::new(&open).unwrap().domain().period, [None, None]); - assert_eq!(SurfaceEval::new(&cylinder).unwrap().domain().period, [Some(1.), None]); + assert_eq!(SurfaceEval::new(&cylinder).unwrap().domain().period, [Some(4.), None]); } /// An intersection record evaluates to the point of both surfaces in the leader's normal -/// plane, and its pcurves on either surface fit. +/// plane; it has no exact pcurve on either. #[test] fn intersection_curves_lie_on_both_surfaces() { // The cylinder x² + y² = 25 cut by the plane z = 20 + x tan 0.4: an ellipse. @@ -482,9 +457,10 @@ fn intersection_curves_lie_on_both_surfaces() { let p = eval.point(12. * i as f64 / 48.).unwrap(); assert!((p.x.hypot(p.y) - 5.).abs() < 1e-11 && (p.z - 20. - p.x * k).abs() < 1e-11, "{i}: {p:?}"); } + // It has no closed-form pcurve on either surface (an intersection record is a construction, + // not a NURBS): refused, never fitted. for surface in [&cylinder, &plane] { - let pc = &pcurves(surface, &one(&curve, [0., 12.]), 1e-6).unwrap()[0][0]; - assert!(lift_error(surface, &curve, [0., 12.], pc) <= 1e-6); + assert!(matches!(pcurves(surface, &one(&curve, [0., 12.]), 1e-6), Err(Error::Failed(m)) if m.contains("no exact pcurve"))); } } @@ -555,13 +531,11 @@ fn an_edge_along_the_rim_of_a_band_winding_close_to_itself_stays_on_its_turn() { } } -/// A curve that is smooth through a knot of full multiplicity (one smooth curve with the knot -/// inserted three times, as SMLib's intersection curves come) gets a pcurve with one tangent -/// there. Two pieces fitted apart meet at an angle in (u, v) (a tenth of a degree here, over the -/// degree SMLib's check allows on a real thread), sharp where u runs hundreds of times as fast as -/// v. +/// A curve weaving across a thread flank, smooth through a knot of full multiplicity (one smooth +/// curve with the knot inserted three times, as SMLib's intersection curves come), has no +/// closed-form pcurve on the flank: it is refused, never fitted (SMLib gives its own trims). #[test] -fn a_smooth_curve_through_a_full_knot_gets_a_pcurve_with_a_tangent_there() { +fn a_curve_weaving_across_a_thread_flank_is_refused() { let (surface, _) = thread_flank(); let s = SurfaceEval::new(&surface).unwrap(); // Along the flank as it winds, a third of a turn (u = t), weaving a little across it. @@ -576,13 +550,8 @@ fn a_smooth_curve_through_a_full_knot_gets_a_pcurve_with_a_tangent_there() { (knots, ctrl) = crate::bspline::insert_knot(3, &knots, &ctrl, k).unwrap(); } let weave = Curve::Spline { knots, points: ctrl.iter().map(|h| h.project().unwrap()).map(|p| [p.x, p.y, p.z]).collect() }; - let pc = &pcurves(&surface, &one(&weave, [a, b]), 1e-3).unwrap()[0][0]; - assert!(lift_error(&surface, &weave, [a, b], pc) <= 1e-3); - let h = 1e-7; - let (l, m, r) = (pc.eval(k - h).unwrap(), pc.eval(k).unwrap(), pc.eval(k + h).unwrap()); - let (dl, dr) = ([m[0] - l[0], m[1] - l[1]], [r[0] - m[0], r[1] - m[1]]); - let cos = (dl[0] * dr[0] + dl[1] * dr[1]) / (dl[0].hypot(dl[1]) * dr[0].hypot(dr[1])); - assert!(cos > 1. - 1e-6, "the pcurve turns by {} degrees at the knot", cos.min(1.).acos().to_degrees()); + // A curve weaving across the flank has no closed-form pcurve there: refused, never fitted. + assert!(matches!(pcurves(&surface, &one(&weave, [a, b]), 1e-3), Err(Error::Failed(m)) if m.contains("no exact pcurve"))); } /// Hostile records give errors, never a panic. @@ -607,11 +576,12 @@ fn hostile_records_give_errors() { // Too many uses, refused before any work. let many = vec![vec![EdgeUse { edge: 0, curve: &line, interval: [0., 1.], forward: true, tolerance: 0.0, given: None }; MAX_USES + 1]]; assert!(matches!(pcurves(&plane, &many, 1e-6), Err(Error::TooLarge(_)))); - // A polyline of many points on a curved surface: too many spans for one pcurve. + // A polyline of many points across a curved surface: it has no exact pcurve there, and is + // refused as such (nothing is fitted). let cylinder = Surface::Cylinder { frame: about_z([0.; 3], false), radius: 1. }; let n = 5000; let zigzag = Curve::Polyline { points: (0..n).map(|i| [(i as f64 * 0.01).cos(), (i as f64 * 0.01).sin(), (i % 2) as f64]).collect() }; - assert!(matches!(pcurves(&cylinder, &one(&zigzag, [0., (n - 1) as f64]), 1e-6), Err(Error::TooLarge(_)))); + assert!(matches!(pcurves(&cylinder, &one(&zigzag, [0., (n - 1) as f64]), 1e-6), Err(Error::Failed(m)) if m.contains("no exact pcurve"))); // A degree the evaluators do not take. let high = Curve::Spline { knots: [vec![0.; 10], vec![1.; 10]].concat(), points: (0..10).map(|i| [i as f64, 0., 0.]).collect() }; assert!(matches!(pcurves(&cylinder, &one(&high, [0., 1.]), 1e-6), Err(Error::Failed(_)))); diff --git a/crates/geom/src/brep/tests.rs b/crates/geom/src/brep/tests.rs index 0fdd82bc8..62bdc35cb 100644 --- a/crates/geom/src/brep/tests.rs +++ b/crates/geom/src/brep/tests.rs @@ -25,6 +25,26 @@ fn list_uses(b: &mut Brep) { } } +/// Every analytic face and conic edge on its NURBS form, as producers make them: a face's form +/// over its stated domain, a circle about a face's axis labelled on its frame (`form::edge`). +fn on_forms(b: &mut Brep) { + let frames: Vec = b.faces.iter().filter(|f| f.nurbs.is_none()).filter_map(|f| form::frame_of(&f.surface)).collect(); + for f in &mut b.faces { + if f.nurbs.is_none() + && let Some((n, d)) = form::surface(&f.surface, f.domain) + { + (f.nurbs, f.domain) = (Some(n), d); + } + } + for e in &mut b.edges { + if e.nurbs.is_none() + && let Some((label, _, Some((n, iv)))) = form::edge(&e.curve, e.interval, &frames, b.tolerance) + { + (e.curve, e.nurbs, e.interval) = (label, Some(n), iv); + } + } +} + /// Every oriented edge's pcurve from its face's surface and its edge (`pcurve::pcurves`). fn fit_pcurves(b: &mut Brep) { for f in &mut b.faces { @@ -38,7 +58,7 @@ fn fit_pcurves(b: &mut Brep) { let e = &b.edges[u.edge as usize]; pcurve::EdgeUse { edge: u.edge, - curve: &e.curve, + curve: e.parameters(), interval: e.interval, forward: u.forward, tolerance: e.tolerance, @@ -49,7 +69,7 @@ fn fit_pcurves(b: &mut Brep) { Loop::Vertex { .. } => vec![], }) .collect(); - let fitted = pcurve::pcurves(&f.surface, &loops, 1e-7).unwrap(); + let fitted = pcurve::pcurves_within(f.parameters(), &loops, 1e-7, Some(f.domain)).unwrap(); for (l, pcs) in f.loops.iter_mut().zip(fitted) { if let Loop::Edges { edges } = l { for (u, pc) in edges.iter_mut().zip(pcs) { @@ -166,6 +186,7 @@ fn tube() -> Brep { vertices: vec![Vertex { point: [3., 2., 3.], tolerance: 1e-7 }, Vertex { point: [3., 2., 8.], tolerance: 1e-7 }], }; list_uses(&mut b); + on_forms(&mut b); fit_pcurves(&mut b); b } @@ -190,21 +211,22 @@ fn one_face(surface: Surface, domain: [[f64; 2]; 2], edges: Vec<(Curve, [f64; 2] vertices: vertices.iter().map(|&point| Vertex { point, tolerance: 1e-7 }).collect(), }; list_uses(&mut b); + on_forms(&mut b); fit_pcurves(&mut b); b } -/// A ring of a torus as a rational spline closed in u (first and last control rows the same), -/// as SMLib writes the fillet round a hole's rim: bounded by its two circles and the tube's -/// quarter at u = 0, a seam used twice. +/// A ring of a torus on its NURBS form, closed in u (first and last control rows the same), as +/// SMLib holds the fillet round a hole's rim: bounded by its two circles and the tube's quarter +/// at u = 0, a seam used twice, each on its form. fn closed_band() -> Brep { - let w = std::f64::consts::FRAC_1_SQRT_2; let (big, small) = (5., 1.); - let surface = pcurve::tests::closed_ring(&[[big + small, 0., 1.], [big + small, small, w], [big, small, 1.]], &[0., 0., 0., 1., 1., 1.]); + let torus = + Surface::Torus { frame: Frame { origin: [0., 0., 0.], x_axis: [1., 0., 0.], y_axis: [0., 1., 0.] }, major_radius: big, minor_radius: small }; let about = |z: f64| Frame { origin: [0., 0., z], x_axis: [1., 0., 0.], y_axis: [0., 1., 0.] }; let quarter = Curve::Circle { frame: Frame { origin: [big, 0., 0.], x_axis: [1., 0., 0.], y_axis: [0., 0., 1.] }, radius: small }; one_face( - surface, - [[0., 1.], [0., 1.]], + torus, + [[0., TAU], [0., FRAC_PI_2]], vec![ (Curve::Circle { frame: about(0.), radius: big + small }, [0., TAU], [0, 0]), (quarter, [0., FRAC_PI_2], [0, 1]), @@ -359,9 +381,9 @@ fn one_defect_fixtures_are_refused() { } b }), - ("edge interval past one turn", "parameter interval exceeds one turn", { + ("edge interval past its form", "parameter interval outside the natural domain", { let mut b = tube(); - b.edges[0].interval = [0., TAU + 0.1]; + b.edges[0].interval = [0., 4.1]; b }), ("edge interval outside a spline", "parameter interval outside the natural domain", { @@ -377,13 +399,13 @@ fn one_defect_fixtures_are_refused() { }), ("face domain outside the sphere", "parameter interval outside the natural domain", { let mut b = sheet(); - b.faces[0].surface = Surface::Sphere { frame: a_frame(), radius: 2. }; - b.faces[0].domain = [[0., TAU], [-FRAC_PI_2 - 0.1, FRAC_PI_2]]; + formed(&mut b, Surface::Sphere { frame: a_frame(), radius: 2. }, [[0., TAU], [-FRAC_PI_2, FRAC_PI_2]]); + b.faces[0].domain[1][0] -= 0.1; b }), - ("face domain past one turn", "parameter interval exceeds one turn", { + ("face domain past its form", "parameter interval outside the natural domain", { let mut b = tube(); - b.faces[0].domain[0] = [0., TAU + 0.1]; + b.faces[0].domain[0] = [0., 4.1]; b }), ("face domain outside a spline surface", "parameter interval outside the natural domain", { @@ -480,8 +502,8 @@ fn one_defect_fixtures_are_refused() { }), ("cone domain past its apex", "parameter interval outside the natural domain", { let mut b = sheet(); - b.faces[0].surface = Surface::Cone { frame: a_frame(), radius_at_origin: 1., half_angle: 0.25 * std::f64::consts::PI }; - b.faces[0].domain = [[0., 1.], [-2., 1.]]; + formed(&mut b, Surface::Cone { frame: a_frame(), radius_at_origin: 1., half_angle: 0.25 * std::f64::consts::PI }, [[0., 1.], [-1., 1.]]); + b.faces[0].domain[1][0] = -2.; b }), ]; @@ -491,6 +513,12 @@ fn one_defect_fixtures_are_refused() { } } +/// Face 0 relabelled `surface` on its NURBS form over `domain` (its loops left as they were). +fn formed(b: &mut Brep, surface: Surface, domain: [[f64; 2]; 2]) { + let (nurbs, domain) = form::surface(&surface, domain).expect("a form"); + let f = &mut b.faces[0]; + (f.surface, f.nurbs, f.domain) = (surface, Some(nurbs), domain); +} fn pcurve_of(b: &mut Brep, face: usize, position: usize) -> &mut Curve2 { let Loop::Edges { edges } = &mut b.faces[face].loops[0] else { panic!("an edge loop") }; &mut edges[position].pcurve @@ -536,8 +564,9 @@ fn geometric_defects_are_refused_by_record() { Record::Use { face: 0, r#loop: 0, position: 1 }, Box::new(|p: &Problem| matches!(p, Problem::Period { .. })), { + // One turn of the tube's NURBS form is four quarters. let mut b = tube(); - shift(pcurve_of(&mut b, 0, 1), [TAU, 0.]); + shift(pcurve_of(&mut b, 0, 1), [4., 0.]); b }, ), @@ -549,10 +578,11 @@ fn geometric_defects_are_refused_by_record() { ( "seam uses of a closed spline on one line", Record::Use { face: 0, r#loop: 0, position: 1 }, - Box::new(|p: &Problem| *p == Problem::Period { gap: 1., period: 1. }), + // On the ring's NURBS form one turn is four quarters. + Box::new(|p: &Problem| *p == Problem::Period { gap: 4., period: 4. }), { let mut b = closed_band(); - shift(pcurve_of(&mut b, 0, 1), [-1., 0.]); + shift(pcurve_of(&mut b, 0, 1), [-4., 0.]); b }, ), @@ -566,7 +596,8 @@ fn geometric_defects_are_refused_by_record() { let mut b = ball(); let mid = |b: &mut Brep, k: usize| pcurve_of(b, 0, k).eval(0.).unwrap()[0]; let by = mid(&mut b, 0) - mid(&mut b, 1); - assert!((by.abs() - TAU).abs() < 1e-9, "a period apart: {by}"); + // On the sphere's NURBS form one turn is four quarters. + assert!((by.abs() - 4.).abs() < 1e-9, "a period apart: {by}"); shift(pcurve_of(&mut b, 0, 1), [by, 0.]); b }, @@ -626,7 +657,9 @@ fn hostile_records_never_panic_the_geometry_check() { b.faces[0].loops[1] = Loop::Vertex { vertex: u32::MAX }; cases.push(b); let mut b = tube(); - b.faces[0].surface = Surface::Cylinder { frame: a_frame(), radius: f64::NAN }; + if let Some(Surface::RationalSpline { homogeneous, .. }) = &mut b.faces[0].nurbs { + homogeneous[0][0][0] = f64::NAN; + } cases.push(b); let mut b = tube(); b.edges[0].tolerance = f64::NAN; diff --git a/crates/kernel/src/assemble.rs b/crates/kernel/src/assemble.rs index 829f38135..65d245897 100644 --- a/crates/kernel/src/assemble.rs +++ b/crates/kernel/src/assemble.rs @@ -12,7 +12,9 @@ use solidcraft_geom::Vec3; use solidcraft_geom::brep::pcurve::{EdgeUse, pcurves_within}; -use solidcraft_geom::brep::{Brep, Curve, Curve2, Edge, Face, Loop, Natural, OrientedEdge, OrientedFace, Region, Shell, Surface, VERSION, Vertex}; +use solidcraft_geom::brep::{ + Brep, Curve, Curve2, Edge, Face, Frame, Loop, Natural, OrientedEdge, OrientedFace, Region, Shell, Surface, VERSION, Vertex, form, +}; use crate::body::Body; use crate::history::{EdgeOrigin, FaceProv}; @@ -62,13 +64,6 @@ pub(crate) struct AFace { pub domain: Option<[[f64; 2]; 2]>, } -impl AFace { - /// The surface the face's (u, v) are on, as `Face::parameters`. - pub fn parameters(&self) -> &Surface { - self.nurbs.as_ref().unwrap_or(&self.surface) - } -} - /// A body taken apart: vertices, edges and faces that [`Assembly::finish`] builds into a record. #[derive(Clone, Debug)] pub(crate) struct Assembly { @@ -215,10 +210,11 @@ impl Assembly { let mut by_shell: Vec> = vec![Vec::new(); self.shells]; let mut faces: Vec = Vec::with_capacity(kept.len()); let mut sides: Vec = Vec::with_capacity(kept.len()); + let formed = self.formed()?; for (k, &i) in kept.iter().enumerate() { let f = self.faces.get(i).and_then(Option::as_ref).ok_or_else(|| invalid("face reference"))?; by_shell.get_mut(f.shell).ok_or_else(|| invalid("shell reference"))?.push(index(k)?); - faces.push(self.stored(i, f)?); + faces.push(self.stored(i, f, &formed)?); sides.push(f.natural_out); } let shells = by_shell @@ -237,10 +233,10 @@ impl Assembly { regions.push(Region { shells: region.shells.iter().copied().filter(|s| used(*s)).collect(), void: region.void }); } } - let edges = self.edges.iter().map(|a| Edge { - nurbs: a.nurbs.clone(), - curve: a.curve.clone(), - interval: a.interval, + let edges = self.edges.iter().zip(&formed.edges).map(|(a, f)| Edge { + nurbs: f.nurbs.clone(), + curve: f.label.clone(), + interval: f.interval, vertices: a.vertices, tolerance: a.tolerance, uses: Vec::new(), @@ -258,9 +254,64 @@ impl Assembly { Ok(Finished { record: part.brep, faces: face_map, edges: part.edges.iter().map(|e| *e as usize).collect() }) } + /// Which faces and edges go on a NURBS form, and theirs. A cylinder, cone, sphere, torus or + /// revolution face without one takes one where none of its uses brings its own pcurve (those + /// are on its label's parameters); an edge without one takes one (a circle about such a + /// face's axis labelled on its frame, `form::edge`) where none of its uses brings a pcurve + /// and every face it bounds is a plane, a spline or on a form. + fn formed(&self) -> Result { + let takes: Vec = self + .faces + .iter() + .map(|f| { + f.as_ref() + .is_some_and(|f| f.nurbs.is_none() && form::frame_of(&f.surface).is_some() && f.loops.iter().flatten().all(|u| u.given.is_none())) + }) + .collect(); + let n = self.edges.len(); + let (mut frames, mut open, mut given): (Vec>, Vec, Vec) = (vec![Vec::new(); n], vec![true; n], vec![false; n]); + for (f, takes) in self.faces.iter().zip(&takes) { + let Some(f) = f else { continue }; + let on_form = f.nurbs.is_some() + || *takes + || matches!( + f.surface, + Surface::Plane { .. } | Surface::PlaneThrough { .. } | Surface::Spline { .. } | Surface::RationalSpline { .. } + ); + let frame = if *takes { form::frame_of(&f.surface) } else { None }; + for u in f.loops.iter().flatten() { + let e = u.edge as usize; + if u.given.is_some() { + if let Some(g) = given.get_mut(e) { + *g = true; + } + } + if !on_form && let Some(o) = open.get_mut(e) { + *o = false; + } + if let (Some(fr), Some(slot)) = (&frame, frames.get_mut(e)) { + slot.push(fr.clone()); + } + } + } + let mut edges = Vec::with_capacity(n); + for (i, a) in self.edges.iter().enumerate() { + let free = a.nurbs.is_none() && !given.get(i).copied().unwrap_or(true) && open.get(i).copied().unwrap_or(false); + let fr = frames.get(i).map(Vec::as_slice).unwrap_or(&[]); + edges.push(match (free, form::edge(&a.curve, a.interval, fr, self.tolerance)) { + (true, Some((label, iv, Some((nurbs, interval))))) => { + FormedEdge { label: label.clone(), label_interval: iv, nurbs: Some(nurbs), interval } + } + _ => FormedEdge { label: a.curve.clone(), label_interval: a.interval, nurbs: a.nurbs.clone(), interval: a.interval }, + }); + } + Ok(Formed { faces: takes, edges }) + } + /// Face `i` as the record stores it: its loops relative to its surface's natural normal, each - /// use with its pcurve (the record's own where the use kept one), and its parameter box. - fn stored(&self, i: usize, f: &AFace) -> Result { + /// use with its pcurve (the record's own where the use kept one), on its NURBS form (its own, + /// or the one [`Assembly::formed`] gives it, over its boundary's extent), and its parameter box. + fn stored(&self, i: usize, f: &AFace, formed: &Formed) -> Result { let loops: Vec> = f .loops .iter() @@ -278,10 +329,11 @@ impl Assembly { l.iter() .map(|u| { let e = self.edges.get(u.edge as usize).ok_or_else(|| invalid("edge reference"))?; + let fe = formed.edges.get(u.edge as usize).ok_or_else(|| invalid("edge reference"))?; Ok(EdgeUse { edge: u.edge, - curve: e.nurbs.as_ref().unwrap_or(&e.curve), - interval: e.interval, + curve: fe.nurbs.as_ref().unwrap_or(&fe.label), + interval: fe.interval, forward: u.forward, tolerance: e.tolerance, given: u.given.as_ref(), @@ -290,8 +342,21 @@ impl Assembly { .collect::>>() }) .collect::>()?; - let pcurves = pcurves_within(f.parameters(), &uses, self.tolerance, f.domain).map_err(|e| invalid(format!("face {i}: {e}")))?; - let domain = domain_of(f.parameters(), &pcurves, f.domain).ok_or_else(|| invalid(format!("face {i}: no parameter box")))?; + // A face taking a form: its form over its boundary's extent on its label. + let (nurbs, kept) = if formed.faces.get(i).copied().unwrap_or(false) { + let boundary: Vec> = loops + .iter() + .map(|l| l.iter().filter_map(|u| formed.edges.get(u.edge as usize).map(|e| (&e.label, e.label_interval, u.forward))).collect()) + .collect(); + let extent = form::extent(&f.surface, &boundary).ok_or_else(|| invalid(format!("face {i}: its boundary is not on its surface")))?; + let (n, d) = form::surface(&f.surface, extent).ok_or_else(|| invalid(format!("face {i}: more than one turn")))?; + (Some(n), Some(d)) + } else { + (f.nurbs.clone(), f.domain) + }; + let on = nurbs.as_ref().unwrap_or(&f.surface); + let pcurves = pcurves_within(on, &uses, self.tolerance, kept).map_err(|e| invalid(format!("face {i}: {e}")))?; + let domain = domain_of(on, &pcurves, kept).ok_or_else(|| invalid(format!("face {i}: no parameter box")))?; let stored = loops .iter() .zip(&pcurves) @@ -299,10 +364,24 @@ impl Assembly { edges: l.iter().zip(pc).map(|(u, pcurve)| OrientedEdge { edge: u.edge, forward: u.forward, pcurve: pcurve.clone() }).collect(), }) .collect(); - Ok(Face { nurbs: f.nurbs.clone(), surface: f.surface.clone(), domain, loops: stored }) + Ok(Face { nurbs, surface: f.surface.clone(), domain, loops: stored }) } } +/// What [`Assembly::formed`] decides: which faces take a NURBS form, and each edge's label (a +/// circle relabelled on a face's frame), its interval there, and its form with its interval. +struct Formed { + faces: Vec, + edges: Vec, +} + +struct FormedEdge { + label: Curve, + label_interval: [f64; 2], + nurbs: Option, + interval: [f64; 2], +} + /// Reverse a loop: the same edges, the other way round. fn reverse(l: &mut [AUse]) { l.reverse(); diff --git a/crates/kernel/src/sew.rs b/crates/kernel/src/sew.rs index f4e62e469..f83b314cf 100644 --- a/crates/kernel/src/sew.rs +++ b/crates/kernel/src/sew.rs @@ -1365,12 +1365,12 @@ pub(crate) fn assemble(parts: Parts, solid: bool) -> Result { // 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. - let mut frames_of: Vec> = vec![Vec::new(); edges.len()]; + let mut frames_of: Vec> = vec![Vec::new(); edges.len()]; for f in &faces { let Some(frame) = b::form::frame_of(&f.surface) else { continue }; for u in f.loops.iter().flatten() { if let Some(slot) = frames_of.get_mut(u.edge as usize) { - slot.push(frame); + slot.push(frame.clone()); } } } @@ -1383,7 +1383,7 @@ pub(crate) fn assemble(parts: Parts, solid: bool) -> Result { continue; } let (label, interval, form) = - b::form::edge(&e.curve, e.interval, frames.iter().copied(), tol).ok_or_else(|| fail("an arc of more than one turn".into()))?; + b::form::edge(&e.curve, e.interval, frames.iter(), tol).ok_or_else(|| fail("an arc of more than one turn".into()))?; labels.push((label, interval)); forms.push(form); } @@ -1405,18 +1405,26 @@ pub(crate) fn assemble(parts: Parts, solid: bool) -> Result { }) .collect() }; - let folded_label = folded_on(None); + // A cylinder, cone, sphere or torus on its NURBS form, over the extent of its boundary on + // its label. let form = match f.surface { b::Surface::Cylinder { .. } | b::Surface::Cone { .. } | b::Surface::Sphere { .. } | b::Surface::Torus { .. } => { - let label = pcurve::pcurves(&f.surface, &uses_of(&edges, &forms, ls, false, &folded_label, tol)?, tol).map_err(failed)?; - let extent = domain_of(&f.surface, &label).ok_or_else(|| fail(format!("face {fi} has no area in its parameters")))?; - Some(b::form::surface(&f.surface, extent).ok_or_else(|| fail(format!("face {fi}: more than one turn")))?.0) + let boundary: Vec> = ls + .iter() + .map(|l| l.iter().filter_map(|&(e, forward, _)| labels.get(e as usize).map(|(c, i)| (c, *i, forward))).collect()) + .collect(); + let extent = b::form::extent(&f.surface, &boundary).ok_or_else(|| fail(format!("face {fi}: its boundary is not on its surface")))?; + Some(b::form::surface(&f.surface, extent).ok_or_else(|| fail(format!("face {fi}: more than one turn")))?) } _ => None, }; + let (form, form_box) = match form { + Some((s, d)) => (Some(s), Some(d)), + None => (None, None), + }; let on = form.as_ref().unwrap_or(&f.surface); let folded_form = if form.is_some() { folded_on(form.as_ref()) } else { Vec::new() }; - let pc = pcurve::pcurves(on, &uses_of(&edges, &forms, ls, true, &folded_form, tol)?, tol).map_err(failed)?; + let pc = pcurve::pcurves_within(on, &uses_of(&edges, &forms, ls, &folded_form, tol)?, tol, form_box).map_err(failed)?; domains.push(domain_of(on, &pc).ok_or_else(|| fail(format!("face {fi} has no area in its parameters")))?); pcs.push(pc); face_forms.push(form); @@ -1568,14 +1576,13 @@ pub(crate) fn assemble(parts: Parts, solid: bool) -> Result { /// A face's parameter box: around its pcurves' control points (a B-spline lies in their hull), /// held inside the surface's natural domain (one turn where periodic). None when it has no /// width in either direction. -/// A face's edge uses for `pcurve::pcurves`: on each edge's NURBS form where it has one and -/// `formed`, else on its curve as given; `folded` gives the pcurves of edges folded across the -/// face (see [`folded_pcurve`]). +/// A face's edge uses for `pcurve::pcurves`: on each edge's NURBS form where it has one, else on +/// its curve as given; `folded` gives the pcurves of edges folded across the face (see +/// [`folded_pcurve`]). fn uses_of<'a>( edges: &'a [PartEdge], forms: &'a [Option<(b::Curve, [f64; 2])>], ls: &[Vec<(u32, bool, Option<&'a Curve2>)>], - formed: bool, folded: &'a [(u32, Curve2)], tol: f64, ) -> Result>>> { @@ -1585,7 +1592,7 @@ fn uses_of<'a>( .map(|&(e, forward, given)| { let edge = edges.get(e as usize).ok_or_else(|| KernelError::Invalid("sew: edge reference".into()))?; let (curve, interval) = match forms.get(e as usize).and_then(Option::as_ref) { - Some((c, i)) if formed => (c, *i), + Some((c, i)) => (c, *i), _ => (&edge.curve, edge.interval), }; let given = given.or_else(|| folded.iter().find(|(f, _)| *f == e).map(|(_, c)| c)); diff --git a/crates/step/src/topology.rs b/crates/step/src/topology.rs index 0683b24b3..a238544cb 100644 --- a/crates/step/src/topology.rs +++ b/crates/step/src/topology.rs @@ -965,34 +965,47 @@ impl<'b, 'a> Builder<'b, 'a> { // Which loop index in `face.loops` each edge loop is. let positions: Vec = face.loops.iter().enumerate().filter(|(_, l)| matches!(l, LoopB::Edges(_))).map(|(i, _)| i).collect(); let tol = self.tol; - // The face's pcurves on `on`, each edge on its NURBS form when `formed`. - let pcurves_on = |on: &BSurface, formed: bool| -> R>> { + // The face's pcurves on `on`, each edge on its NURBS form. + let pcurves_on = |on: &BSurface, domain: Option<[[f64; 2]; 2]>| -> R>> { let mut uses = Vec::with_capacity(edge_loops.len()); for l in &edge_loops { let mut u = Vec::with_capacity(l.len()); for &(e, forward) in l { let edge = self.edges.get(e as usize).ok_or("edge reference")?; let (curve, interval) = match &edge.form { - Some((c, i)) if formed => (c, *i), + Some((c, i)) => (c, *i), _ => (&edge.curve, edge.interval), }; u.push(EdgeUse { edge: e, curve, interval, forward, tolerance: 0.0, given: None }); } uses.push(u); } - pcurve::pcurves(on, &uses, tol).map_err(|e| e.to_string()) + pcurve::pcurves_within(on, &uses, tol, domain).map_err(|e| e.to_string()) }; - // A cylinder, cone, sphere or torus on its NURBS form, over the extent its label's pcurves - // give; then every pcurve on the forms. + // A cylinder, cone, sphere, torus or revolution on its NURBS form, over the extent of its + // boundary on its label; then every pcurve on the forms. let form = match brep::form::frame_of(&label) { Some(_) => { - let extent = face_domain(&label, &pcurves_on(&label, false)?)?; - Some(brep::form::surface(&label, extent).ok_or_else(|| unsupported("a face of more than one turn"))?.0) + let mut boundary = Vec::with_capacity(edge_loops.len()); + for l in &edge_loops { + let mut b = Vec::with_capacity(l.len()); + for &(e, forward) in l { + let edge = self.edges.get(e as usize).ok_or("edge reference")?; + b.push((&edge.curve, edge.interval, forward)); + } + boundary.push(b); + } + let extent = brep::form::extent(&label, &boundary).ok_or_else(|| unsupported("a face whose boundary does not lie on its surface"))?; + Some(brep::form::surface(&label, extent).ok_or_else(|| unsupported("a face of more than one turn"))?) } None => None, }; + let (form, box_on_form) = match form { + Some((f, d)) => (Some(f), Some(d)), + None => (None, None), + }; let surface = form.clone().unwrap_or(label); - let pcs = pcurves_on(&surface, true)?; + let pcs = pcurves_on(&surface, box_on_form)?; // Signed areas of the loops that close in (u, v). let periods = natural_periods(&surface); // Each use starts near where the one before it ends, along a bounded direction that diff --git a/crates/step/src/topology/swept.rs b/crates/step/src/topology/swept.rs index 3ff7441b3..227902659 100644 --- a/crates/step/src/topology/swept.rs +++ b/crates/step/src/topology/swept.rs @@ -237,6 +237,14 @@ fn whole(c: &Curve) -> R> { /// The middle parameter of a TRIMMED_CURVE trimmed by parameters (on a closed conic, the /// middle of the arc its sense runs over). fn trimmed_middle(c: &Curve) -> Option { + let (a, b) = trimmed_range(c)?; + let m = 0.5 * (a + b); + m.is_finite().then_some(m) +} + +/// A trimmed profile's range on its basis, low end first, where both trims are parameters: on +/// a closed basis (a circle, an ellipse) the way round `sense` gives. +fn trimmed_range(c: &Curve) -> Option<(f64, f64)> { let Curve::Trimmed { basis, trim_1, trim_2, sense, .. } = c else { return None }; let param = |t: &[crate::geom::Trim]| { t.iter().find_map(|x| match x { @@ -248,8 +256,8 @@ fn trimmed_middle(c: &Curve) -> Option { if is_closed(basis) { b = if *sense { a + (b - a).rem_euclid(TAU) } else { a - (a - b).rem_euclid(TAU) }; } - let m = 0.5 * (a + b); - m.is_finite().then_some(m) + let (lo, hi) = (a.min(b), a.max(b)); + (lo.is_finite() && hi.is_finite() && lo < hi).then_some((lo, hi)) } fn is_closed(c: &Curve) -> bool { @@ -309,7 +317,12 @@ fn revolution(profile: &Curve, axis: &Axis1, ext: &Extent) -> R { // The profile's side of the axis where the face is. let mid = ts.get(ts.len() / 2).copied().ok_or("a face without boundary points")?; let e = probe(mid).map(radial).and_then(|r| r.normalized()).unwrap_or(e); - let s = span(&ts, &seam, is_closed(c))?; + // A trimmed profile is the file's range of its basis exactly; otherwise the face's + // reach along it. + let s = match trimmed_range(profile) { + Some(r) => Span::Open { inner: r, outer: r }, + None => span(&ts, &seam, is_closed(c))?, + }; // Stop where the profile crosses the axis outside the face. let side = |t: f64| probe(t).map(|q| (q - o).dot(e)); let s = match s { @@ -394,7 +407,11 @@ fn extrusion(profile: &Curve, direction: P3, magnitude: f64, ext: &Extent) -> R< return Err(unsupported("an extrusion along its profile's plane")); } let seam: Vec = ext.seam.iter().filter_map(|q| onto(*q)).collect(); - bounded(c, span(&ts, &seam, is_closed(c))?)? + let s = match trimmed_range(profile) { + Some(r) => Span::Open { inner: r, outer: r }, + None => span(&ts, &seam, is_closed(c))?, + }; + bounded(c, s)? } }; let (knots, homogeneous, rational) = match curve { diff --git a/crates/step/src/topology_tests.rs b/crates/step/src/topology_tests.rs index e5ba31def..37bebece5 100644 --- a/crates/step/src/topology_tests.rs +++ b/crates/step/src/topology_tests.rs @@ -373,14 +373,20 @@ fn a_cylinder_has_a_seam_used_twice_by_its_side() { assert_eq!(seam.uses[0].face, seam.uses[1].face); for e in &s.brep.edges { if matches!(e.curve, BCurve::Circle { .. }) { - assert!((e.interval[1] - e.interval[0] - TAU).abs() < 1e-12); + // On its NURBS form: a whole turn in angle, its interval in the form's parameter. + let [a0, a1] = e.curve_interval().unwrap(); + assert!(e.nurbs.is_some() && (a1 - a0 - TAU).abs() < 1e-12); assert_eq!(e.vertices[0], e.vertices[1]); } } faces_away(&s.brep, 0, |p| [1.0, 2.0, p[2].clamp(1.0, 9.0)]); - // The side face spans one turn of the cylinder and its height. + // The side face spans one turn of the cylinder (four quarters of its NURBS form) and its height. let f = s.brep.faces.iter().find(|f| matches!(f.surface, BSurface::Cylinder { .. })).unwrap(); - assert!((f.domain[0][1] - f.domain[0][0] - TAU).abs() < 1e-9 && f.domain[1][0] < 1e-6 && f.domain[1][1] > 10.0 - 1e-6, "{:?}", f.domain); + assert!( + f.nurbs.is_some() && (f.domain[0][1] - f.domain[0][0] - 4.0).abs() < 1e-9 && f.domain[1][0] < 1e-6 && f.domain[1][1] > 10.0 - 1e-6, + "{:?}", + f.domain + ); } #[test] @@ -402,7 +408,8 @@ fn a_ball_bounded_by_its_seam_alone() { let s = one_solid(&w.file(&[solid])); assert_eq!(counts(&s.brep), [2, 1, 1, 1, 2]); let e = &s.brep.edges[0]; - assert!((e.interval[1] - e.interval[0] - PI).abs() < 1e-12, "{:?}", e.interval); + let [a0, a1] = e.curve_interval().unwrap(); + assert!((a1 - a0 - PI).abs() < 1e-12, "{:?}", e.interval); faces_away(&s.brep, 0, |_| [0.0; 3]); } }