SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Wave 220/509: sew: faces and edges on their NURBS forms, their pcurves exact (and 3 more)
jyvikob11e66e6065e
diff --git a/crates/geom/src/brep/form.rs b/crates/geom/src/brep/form.rsindex d1ca7a96a4..2995e6267a 100644--- a/crates/geom/src/brep/form.rs+++ b/crates/geom/src/brep/form.rs@@ -61,6 +61,13 @@ fn quarters([a0, a1]: [f64; 2]) -> Option<(f64, usize)> {(n <= 5).then_some((q0, n))}+/// 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] {+ let end = q0 + n as f64;+ [param(a0).clamp(q0, end), param(a1).clamp(q0, end)]+}+/// Quarter arcs from quarter `q0`, `n` of them: their knot vector (in form parameter) and their/// control points (as `(cos, sin)` factors on the unit circle's plane) with weights.fn arcs(q0: f64, n: usize) -> (Vec<f64>, Vec<([f64; 2], f64)>) {@@ -111,19 +118,19 @@ pub fn curve(c: &Curve, [t0, t1]: [f64; 2]) -> Option<(Curve, [f64; 2])> {fn conic(frame: &Frame, [rx, ry]: [f64; 2], t: [f64; 2]) -> Option<(Curve, [f64; 2])> {let (o, x, y, _) = axes(frame)?;- let (q0, n) = quarters(t)?;- let (knots, pts) = arcs(q0, n);+ let grid = quarters(t)?;+ let (knots, pts) = arcs(grid.0, grid.1);let homogeneous = pts.iter().map(|([c, s], w)| hom(o + x * (rx * c) + y * (ry * s), *w)).collect();- Some((Curve::RationalSpline { knots, homogeneous }, [param(t[0]), param(t[1])]))+ Some((Curve::RationalSpline { knots, homogeneous }, params(t, grid)))}/// The NURBS form of a cylinder, cone, sphere or torus face over `domain` (in the label's/// 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 (q0, n) = quarters(u)?;- let (u_knots, ring) = arcs(q0, n);- let fu = [param(u[0]), param(u[1])];+ let grid = 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<Vec<Vec<[f64; 4]>>> {@@ -155,17 +162,36 @@ pub fn surface(s: &Surface, [u, v]: [[f64; 2]; 2]) -> Option<(Surface, [[f64; 2]Some((Surface::RationalSpline { u_knots, v_knots: vec![v[0], v[0], v[1], v[1]], homogeneous }, [fu, v]))}Surface::Sphere { frame, radius } => {- let (p0, m) = quarters(v)?;- let (v_knots, meridian) = arcs(p0, m);+ let vgrid = quarters(v)?;+ let (v_knots, meridian) = arcs(vgrid.0, vgrid.1);let homogeneous = net(frame, &meridian, &|[c, s]| (radius * c, radius * s))?;- Some((Surface::RationalSpline { u_knots, v_knots, homogeneous }, [fu, [param(v[0]), param(v[1])]]))+ Some((Surface::RationalSpline { u_knots, v_knots, homogeneous }, [fu, params(v, vgrid)]))}Surface::Torus { frame, major_radius, minor_radius } => {- let (p0, m) = quarters(v)?;- let (v_knots, tube) = arcs(p0, m);+ let vgrid = 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, [param(v[0]), param(v[1])]]))+ Some((Surface::RationalSpline { u_knots, v_knots, homogeneous }, [fu, params(v, vgrid)]))}_ => None,}}++/// A circle edge labelled on another frame about the same axis: the same circle, its angle+/// measured from `frame`'s x axis (its y axis taken so the circle keeps its own direction), and+/// its interval shifted to match, so its form lies on `frame`'s quarter grid. `None` when the+/// circle is not about `frame`'s axis (centre on it, normal along it, within `tol`).+pub fn on_frame(c: &Curve, [t0, t1]: [f64; 2], frame: &Frame, tol: f64) -> Option<(Curve, [f64; 2])> {+ let Curve::Circle { frame: own, radius } = c else { return None };+ let (o, x, _, z) = axes(own)?;+ let (fo, fx, _, fz) = axes(frame)?;+ let d = o - fo;+ if !((d - fz * d.dot(fz)).len() <= tol && (z.dot(fz).abs() - 1.0).abs() <= 1e-9) {+ return None;+ }+ let nx = (fx - z * fx.dot(z)).normalized()?;+ let ny = z.cross(nx);+ let shift = x.dot(ny).atan2(x.dot(nx));+ let relabel = Frame { origin: [o.x, o.y, o.z], x_axis: [nx.x, nx.y, nx.z], y_axis: [ny.x, ny.y, ny.z] };+ Some((Curve::Circle { frame: relabel, radius: *radius }, [t0 + shift, t1 + shift]))+}diff --git a/crates/geom/src/brep/pcurve.rs b/crates/geom/src/brep/pcurve.rsindex 5bfc774385..1bcfd88dbc 100644--- a/crates/geom/src/brep/pcurve.rs+++ b/crates/geom/src/brep/pcurve.rs@@ -20,6 +20,7 @@use super::eval::{CurveEval, SurfaceEval};use super::{Budget, Curve, Curve2, Surface, curve, curve_natural, interval, surface};use crate::Vec3;+use crate::bspline::{HPoint, segment};use crate::tess::uv::{self, Domain};/// Why no pcurves: the records are malformed or out of bounds (`Invalid`), no pcurve within@@ -66,6 +67,9 @@ const START_SPANS: usize = 4;const MAX_USES: usize = 100_000;/// Lift checks of an exact pcurve: evenly spaced, plus one inside each of its spans up to this.const CHECKS: usize = 16;+/// How close, against the geometry's size, a closed-form pcurve must lift onto its edge to be+/// taken as exact (rounding, well inside any tolerance).+const EXACT: f64 = 1e-9;/// For each loop of a face on `surface`, the pcurve of each of its edge uses, in order, within/// `tolerance` mm (or the use's own edge tolerance where larger) of the edge when lifted onto@@ -148,6 +152,24 @@ fn own_pcurve(c: &Curve2, [t0, t1]: [f64; 2], budget: &mut Budget) -> Result<CurOk(c.clone())}+/// `c` cut exactly to `[t0, t1]` where that is less than its knot interval.+fn cut(c: Curve2, [t0, t1]: [f64; 2]) -> Result<Curve2> {+ let Some([a, b]) = c.interval() else { return Err(Error::Invalid("pcurve: no interval".into())) };+ if a == t0 && b == t1 {+ return Ok(c);+ }+ let (knots, h): (&[f64], Vec<HPoint>) = match &c {+ Curve2::Spline { knots, points } => (knots, points.iter().map(|p| HPoint { x: p[0], y: p[1], z: 0.0, w: 1.0 }).collect()),+ Curve2::RationalSpline { knots, homogeneous } => (knots, homogeneous.iter().map(|p| HPoint { x: p[0], y: p[1], z: 0.0, w: p[2] }).collect()),+ };+ let degree = knots.len().checked_sub(h.len() + 1).ok_or_else(|| Error::Invalid("pcurve degree".into()))?;+ let (knots, h) = segment(degree, knots, &h, t0, t1).map_err(|e| Error::Invalid(format!("pcurve cut to [{t0}, {t1}]: {e:?}")))?;+ Ok(match c {+ Curve2::Spline { .. } => Curve2::Spline { knots, points: h.iter().map(|p| [p.x, p.y]).collect() },+ Curve2::RationalSpline { .. } => Curve2::RationalSpline { knots, homogeneous: h.iter().map(|p| [p.x, p.y, p.w]).collect() },+ })+}+/// A face's surface: its evaluator and parameter box, and the grid a point's parameters on it/// are searched from, made once for all the face's points.struct On {@@ -224,20 +246,21 @@ impl On {knots.push(t1);Some(Curve2::Spline { knots, points: ts.iter().map(|t| map(at(*t)?)).collect::<Result<_>>()? })}- Curve::Spline { knots, points } if curve_natural(record) == super::Natural::Range(t0, t1) => {- Some(Curve2::Spline { knots: knots.clone(), points: points.iter().map(|p| map(Vec3::from(*p))).collect::<Result<_>>()? })+ // The control points through the plane's affine parameters (exact), cut to the+ // edge's interval where it covers part of its curve (a form).+ Curve::Spline { knots, points } => {+ let points = points.iter().map(|p| map(Vec3::from(*p))).collect::<Result<_>>()?;+ Some(cut(Curve2::Spline { knots: knots.clone(), points }, [t0, t1])?)}- Curve::RationalSpline { knots, homogeneous } if curve_natural(record) == super::Natural::Range(t0, t1) => {- Some(Curve2::RationalSpline {- knots: knots.clone(),- homogeneous: homogeneous- .iter()- .map(|h| {- let [u, v] = map(Vec3::new(h[0] / h[3], h[1] / h[3], h[2] / h[3]))?;- Ok([u * h[3], v * h[3], h[3]])- })- .collect::<Result<_>>()?,- })+ Curve::RationalSpline { knots, homogeneous } => {+ let homogeneous = homogeneous+ .iter()+ .map(|h| {+ let [u, v] = map(Vec3::new(h[0] / h[3], h[1] / h[3], h[2] / h[3]))?;+ Ok([u * h[3], v * h[3], h[3]])+ })+ .collect::<Result<_>>()?;+ Some(cut(Curve2::RationalSpline { knots: knots.clone(), homogeneous }, [t0, t1])?)}_ => None,}@@ -275,10 +298,38 @@ impl On {let u = b.atan2(a);Some(segment([u, height(t0)?], [u, height(t1)?]))}+ (SurfaceEval::Eval(..), _) => self.along(curve, [t0, t1]),_ => None,})}+ /// 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<Curve2> {+ 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;+ 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)) {+ candidates.push(line(a, b));+ }+ // 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) {+ let tm = 0.5 * (t0 + t1);+ for sign in [1.0, -1.0] {+ let (cu, cv) = (u - sign * tm, v - sign * tm);+ candidates.push(line([cu + sign * t0, v], [cu + sign * t1, v]));+ candidates.push(line([u, cv + sign * t0], [u, cv + sign * t1]));+ }+ }+ candidates.into_iter().find(|pc| self.lifts(pc, curve, [t0, t1], exact))+ }+/// Whether `pc` lifts onto `curve` within `target` along `range` (evenly, and inside its/// spans).fn lifts(&self, pc: &Curve2, curve: &CurveEval, [t0, t1]: [f64; 2], target: f64) -> bool {diff --git a/crates/kernel/src/sew.rs b/crates/kernel/src/sew.rsindex 80521221c8..ec6903a5ce 100644--- a/crates/kernel/src/sew.rs+++ b/crates/kernel/src/sew.rs@@ -1141,21 +1141,69 @@ pub(crate) fn assemble(parts: Parts, solid: bool) -> Result<Assembled> {.collect()}).collect();+ // Every circle and ellipse edge on its NURBS form (an edge the caller gave a pcurve for keeps+ // the parameter that pcurve is on).+ let given_on: Vec<bool> = {+ let mut g = vec![false; edges.len()];+ for u in faces.iter().flat_map(|f| f.loops.iter().flatten()).filter(|u| u.given.is_some()) {+ if let Some(slot) = g.get_mut(u.edge as usize) {+ *slot = true;+ }+ }+ g+ };+ // A circle on a cylinder, cone, sphere or torus about its axis is labelled on that face's+ // frame, so its form lies on the face's quarter grid and its pcurve there is a straight line.+ let mut frame_of: Vec<Option<&b::Frame>> = vec![None; edges.len()];+ for f in &faces {+ let (b::Surface::Cylinder { frame, .. }+ | b::Surface::Cone { frame, .. }+ | b::Surface::Sphere { frame, .. }+ | b::Surface::Torus { frame, .. }) = &f.surface+ else {+ continue;+ };+ for u in f.loops.iter().flatten() {+ if let Some(slot) = frame_of.get_mut(u.edge as usize).filter(|s| s.is_none()) {+ *slot = Some(frame);+ }+ }+ }+ let labels: Vec<(b::Curve, [f64; 2])> = edges+ .iter()+ .zip(&frame_of)+ .map(|(e, frame)| frame.and_then(|f| b::form::on_frame(&e.curve, e.interval, f, tol)).unwrap_or_else(|| (e.curve.clone(), e.interval)))+ .collect();+ let forms: Vec<Option<(b::Curve, [f64; 2])>> = labels+ .iter()+ .zip(&given_on)+ .map(|((curve, interval), given)| match curve {+ b::Curve::Circle { .. } | b::Curve::Ellipse { .. } if !given => {+ b::form::curve(curve, *interval).ok_or_else(|| fail("an arc of more than one turn".into())).map(Some)+ }+ _ => Ok(None),+ })+ .collect::<Result<_>>()?;+ // Each face on its NURBS form: a cylinder, cone, sphere or torus over the extent its label's+ // pcurves give, then every pcurve again on the forms, exactly.let mut pcs: Vec<Vec<Vec<Curve2>>> = Vec::with_capacity(nf);let mut domains = Vec::with_capacity(nf);+ let mut face_forms: Vec<Option<b::Surface>> = Vec::with_capacity(nf);for (fi, (f, ls)) in faces.iter().zip(&loops).enumerate() {- let mut uses = Vec::with_capacity(ls.len());- for l in ls {- let mut u = Vec::with_capacity(l.len());- for &(e, forward, given) in l {- let edge = edges.get(e as usize).ok_or_else(|| fail("edge reference".into()))?;- u.push(pcurve::EdgeUse { edge: e, curve: &edge.curve, interval: edge.interval, forward, tolerance: tol, given });+ let failed = |e: pcurve::Error| KernelError::Failed(format!("sew: face {fi}: {e}"));+ 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, 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)}- uses.push(u);- }- let pc = pcurve::pcurves(&f.surface, &uses, tol).map_err(|e| KernelError::Failed(format!("sew: face {fi}: {e}")))?;- domains.push(domain_of(&f.surface, &pc).ok_or_else(|| fail(format!("face {fi} has no area in its parameters")))?);+ _ => None,+ };+ let on = form.as_ref().unwrap_or(&f.surface);+ let pc = pcurve::pcurves(on, &uses_of(&edges, &forms, ls, true, tol)?, tol).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);}let users = edge_users(edges.len(), &faces)?;let (groups, _) = components(nf, &users);@@ -1178,7 +1226,8 @@ pub(crate) fn assemble(parts: Parts, solid: bool) -> Result<Assembled> {let mut sum = 0.0;for &f in g {let (Some(face), Some(pc), Some(ls), Some(dom)) = (faces.get(f), pcs.get(f), loops.get(f), domains.get(f)) else { continue };- let s = SurfaceEval::new(&face.surface).map_err(|e| KernelError::Failed(format!("sew: face {f}: {e}")))?;+ let on = face_forms.get(f).and_then(Option::as_ref).unwrap_or(&face.surface);+ let s = SurfaceEval::new(on).map_err(|e| KernelError::Failed(format!("sew: face {f}: {e}")))?;let uses: Vec<Vec<(&Curve2, bool)>> = pc.iter().zip(ls).map(|(c, l)| c.iter().zip(l).map(|(c, u)| (c, u.1)).collect()).collect();let flux = face_flux(&s, dom[1][0], &uses, field).ok_or_else(|| KernelError::Failed(format!("sew: face {f} cannot be evaluated")))?;sum += if face.forward { flux } else { -flux };@@ -1268,11 +1317,19 @@ pub(crate) fn assemble(parts: Parts, solid: bool) -> Result<Assembled> {if record_loops.is_empty() {return Err(fail(format!("face {f} has no loop")));}- record_faces.push(b::Face { nurbs: None, surface: face.surface.clone(), domain: *domain, loops: record_loops });+ let nurbs = face_forms.get(f).cloned().flatten();+ record_faces.push(b::Face { nurbs, surface: face.surface.clone(), domain: *domain, loops: record_loops });}let record_edges = edges.iter()- .map(|e| b::Edge { nurbs: None, curve: e.curve.clone(), interval: e.interval, vertices: e.vertices, tolerance: tol, uses: Vec::new() })+ .zip(forms.iter().zip(&labels))+ .map(|(e, (form, (label, label_interval)))| {+ let (nurbs, interval) = match form {+ Some((c, i)) => (Some(c.clone()), *i),+ None => (None, *label_interval),+ };+ b::Edge { nurbs, curve: label.clone(), interval, vertices: e.vertices, tolerance: tol, uses: Vec::new() }+ }).collect();let record_vertices = vertices.iter().map(|point| b::Vertex { point: *point, tolerance: tol }).collect();let loose = b::Brep { version: b::VERSION, tolerance: tol, regions, shells, faces: record_faces, edges: record_edges, vertices: record_vertices };@@ -1295,6 +1352,31 @@ pub(crate) fn assemble(parts: Parts, solid: bool) -> Result<Assembled> {/// 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.+fn uses_of<'a>(+ edges: &'a [PartEdge],+ forms: &'a [Option<(b::Curve, [f64; 2])>],+ ls: &[Vec<(u32, bool, Option<&'a Curve2>)>],+ formed: bool,+ tol: f64,+) -> Result<Vec<Vec<pcurve::EdgeUse<'a>>>> {+ ls.iter()+ .map(|l| {+ l.iter()+ .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),+ _ => (&edge.curve, edge.interval),+ };+ Ok(pcurve::EdgeUse { edge: e, curve, interval, forward, tolerance: tol, given })+ })+ .collect()+ })+ .collect()+}+fn domain_of(surface: &b::Surface, pcs: &[Vec<Curve2>]) -> Option<[[f64; 2]; 2]> {let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]);for c in pcs.iter().flatten() {@@ -1364,7 +1446,8 @@ fn face_flux(s: &SurfaceEval, v0: f64, loops: &[Vec<(&Curve2, bool)>], field: &dlet [t0, t1] = c.interval()?;let at = |k: f64| {let f = k / FLUX_PIECES as f64;- c.eval(if *forward { t0 + (t1 - t0) * f } else { t1 - (t1 - t0) * f })+ // Exactly the ends at f = 0 and 1, whatever the interval's rounding.+ c.eval(if *forward { t0 * (1.0 - f) + t1 * f } else { t1 * (1.0 - f) + t0 * f })};for k in 0..FLUX_PIECES {let (a, m, z) = (at(k as f64)?, at(k as f64 + 0.5)?, at(k as f64 + 1.0)?);