SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Wave 219/509: brep: forms on their frame's quarter grid, across the seam (and 3 more)
jyvikoc2a1e7524e6d
diff --git a/crates/geom/src/brep.rs b/crates/geom/src/brep.rsindex 2c62760bc7..6e5ab55137 100644--- a/crates/geom/src/brep.rs+++ b/crates/geom/src/brep.rs@@ -12,6 +12,7 @@ use serde::{Deserialize, Serialize};mod curve2;pub mod envelope;pub mod eval;+pub mod form;pub mod geometry;pub mod history;pub mod part;@@ -75,8 +76,9 @@ pub enum Shell {#[serde(deny_unknown_fields)]pub struct OrientedFace {pub face: u32,- /// The face's normal in this shell is its surface's natural normal (∂S/∂u × ∂S/∂v). In a- /// closed shell the normals point out of the material.+ /// The face's normal in this shell is the natural normal (∂S/∂u × ∂S/∂v) of the surface its+ /// (u, v) are on, [`Face::parameters`]: its NURBS form when it has one. In a closed shell the+ /// normals point out of the material.pub forward: bool,}@@ -529,6 +531,35 @@ impl Face {pub fn parameters(&self) -> &Surface {self.nurbs.as_ref().unwrap_or(&self.surface)}++ /// Whether the face's NURBS form turns its natural normal against `surface`'s (away from+ /// the axis of a cylinder or cone, the centre of a sphere, the tube's centre circle of a+ /// torus), at the middle of `domain`. A shell's `forward` is about [`Face::parameters`], so+ /// the side `surface` is used on is `forward != form_turns()`. `Some(false)` without a form;+ /// `None` where the form does not evaluate there.+ pub fn form_turns(&self) -> Option<bool> {+ let Some(form) = &self.nurbs else { return Some(false) };+ let eval = eval::SurfaceEval::new(form).ok()?;+ let [[u0, u1], [v0, v1]] = self.domain;+ let (p, su, sv) = eval.derivs(0.5 * (u0 + u1), 0.5 * (v0 + v1))?;+ let v3 = |a: [f64; 3]| crate::Vec3::new(a[0], a[1], a[2]);+ let radial = |f: &Frame| {+ let (o, z) = (v3(f.origin), v3(f.x_axis).cross(v3(f.y_axis)));+ let d = p - o;+ (o, d - z * (d.dot(z) / z.dot(z)))+ };+ let outward = match &self.surface {+ Surface::Cylinder { frame, .. } | Surface::Cone { frame, .. } => radial(frame).1,+ Surface::Sphere { frame, .. } => p - v3(frame.origin),+ Surface::Torus { frame, major_radius, .. } => {+ let (o, r) = radial(frame);+ p - (o + r.normalized()? * *major_radius)+ }+ _ => return None,+ };+ let along = su.cross(sv).dot(outward);+ (along.abs() > 0.0).then_some(along < 0.0)+ }}impl Brep {diff --git a/crates/geom/src/brep/form.rs b/crates/geom/src/brep/form.rsnew file mode 100644index 0000000000..d1ca7a96a4--- /dev/null+++ b/crates/geom/src/brep/form.rs@@ -0,0 +1,171 @@+//! The NURBS forms of the record's analytic curves and surfaces: the exact B-spline each one is+//! (docs/native-brep.md, "Surfaces"), built the way SMLib holds its own, so that a circle and every+//! face it bounds share one parameterisation and their pcurves are exact by construction.+//!+//! Angles are on rational quadratic quarter arcs laid on their frame's quarter grid: quarter `q`+//! runs from `q·π/2` to `(q+1)·π/2` from the frame's x axis, and the form parameter of an angle+//! `θ` in it is `q + u`, `u` the arc's own parameter (closed form, [`quarter_u`]). Every form on one+//! frame therefore has the same parameter at the same angle, whatever quarters it spans: a circle+//! edge's form and its cylinder's form agree along it, so its pcurve is a straight line in (u, v).+//! A form spans the quarters its interval needs (at most five for one turn), so an arc across the+//! frame's x axis has a form like any other.+//!+//! A circle or ellipse is the arcs (an ellipse scaled by its radii, which keeps it exact: its+//! parameter is the eccentric angle). A cylinder or cone is the arcs times a degree-1 line along the+//! axis; a sphere the arcs times arcs of latitude (from `−π/2` to `π/2`); a torus the arcs times+//! the arcs of its tube. A line is the degree-1 B-spline on its own parameter.++use super::{Curve, Frame, Surface};+use crate::Vec3;+use std::f64::consts::{FRAC_1_SQRT_2, FRAC_PI_2, FRAC_PI_8, TAU};++/// Rounding room on an angle at a quarter's end.+const SLACK: f64 = 1e-12;++/// The quarter arc's parameter `u` in `[0, 1]` at angle `ψ` in `[0, π/2]` from its start: the+/// arc with ends `±π/4` from its bisector and middle weight `cos π/4` has+/// `tan((ψ − π/4)/2) = tan(π/8)(2u − 1)`.+fn quarter_u(psi: f64) -> f64 {+ 0.5 * (1.0 + (0.5 * psi - FRAC_PI_8).tan() / FRAC_PI_8.tan())+}++fn quarter_psi(u: f64) -> f64 {+ 2.0 * (((2.0 * u - 1.0) * FRAC_PI_8.tan()).atan() + FRAC_PI_8)+}++/// The quarter an angle lies in (an angle on a quarter's end lies in the one after it).+fn quarter_of(theta: f64) -> f64 {+ (theta / FRAC_PI_2 + SLACK).floor()+}++/// The form parameter of angle `theta`: its quarter plus the arc's parameter there.+pub fn param(theta: f64) -> f64 {+ let q = quarter_of(theta);+ q + quarter_u((theta - q * FRAC_PI_2).clamp(0.0, FRAC_PI_2))+}++/// The angle at form parameter `s`.+pub fn angle(s: f64) -> f64 {+ let q = s.floor();+ q * FRAC_PI_2 + quarter_psi(s - q)+}++/// The quarters an angle interval needs: the first one and how many.+fn quarters([a0, a1]: [f64; 2]) -> Option<(f64, usize)> {+ if !(a0.is_finite() && a1.is_finite() && a1 > a0 && a1 - a0 <= TAU * (1.0 + 1e-9)) {+ return None;+ }+ let q0 = quarter_of(a0);+ let q1 = (a1 / FRAC_PI_2 - SLACK).ceil();+ let n = (q1 - q0).max(1.0) as usize;+ (n <= 5).then_some((q0, n))+}++/// 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)>) {+ let at = |a: f64| [a.cos(), a.sin()];+ let mut pts = Vec::with_capacity(2 * n + 1);+ let mut knots = vec![q0; 3];+ for k in 0..n {+ let q = q0 + k as f64;+ let (p, r) = (at(q * FRAC_PI_2), at((q + 1.0) * FRAC_PI_2));+ if k == 0 {+ pts.push((p, 1.0));+ }+ pts.push(([p[0] + r[0], p[1] + r[1]], FRAC_1_SQRT_2));+ pts.push((r, 1.0));+ knots.extend(if k + 1 < n { vec![q + 1.0; 2] } else { vec![q + 1.0; 3] });+ }+ (knots, pts)+}++fn v3(a: [f64; 3]) -> Vec3 {+ Vec3::new(a[0], a[1], a[2])+}++fn hom(p: Vec3, w: f64) -> [f64; 4] {+ [p.x * w, p.y * w, p.z * w, w]+}++/// The frame's origin and unit axes (z = x × y).+fn axes(f: &Frame) -> Option<(Vec3, Vec3, Vec3, Vec3)> {+ let (x, y) = (v3(f.x_axis).normalized()?, v3(f.y_axis).normalized()?);+ Some((v3(f.origin), x, y, x.cross(y).normalized()?))+}++/// The NURBS form of a line, circle or ellipse edge and its interval in the form's parameter;+/// `None` for another kind, or an arc of more than one turn.+pub fn curve(c: &Curve, [t0, t1]: [f64; 2]) -> Option<(Curve, [f64; 2])> {+ match c {+ Curve::Line { start, end } => {+ let (a, d) = (v3(*start), v3(*end) - v3(*start));+ let (p0, p1) = (a + d * t0, a + d * t1);+ Some((Curve::Spline { knots: vec![t0, t0, t1, t1], points: vec![[p0.x, p0.y, p0.z], [p1.x, p1.y, p1.z]] }, [t0, t1]))+ }+ Curve::Circle { frame, radius } => conic(frame, [*radius; 2], [t0, t1]),+ Curve::Ellipse { frame, radii } => conic(frame, *radii, [t0, t1]),+ _ => None,+ }+}++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 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])]))+}++/// 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])];+ // 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]>>> {+ let (o, x, y, z) = axes(f)?;+ Some(+ ring.iter()+ .map(|([c, s], wu)| {+ let r = x * *c + y * *s;+ profile+ .iter()+ .map(|(q, wv)| {+ let (radial, axial) = at(*q);+ hom(o + r * radial + z * axial, wu * wv)+ })+ .collect()+ })+ .collect(),+ )+ };+ let line = [([v[0], 0.0], 1.0), ([v[1], 0.0], 1.0)];+ match s {+ Surface::Cylinder { frame, radius } => {+ let homogeneous = net(frame, &line, &|[h, _]| (*radius, h))?;+ Some((Surface::RationalSpline { u_knots, v_knots: vec![v[0], v[0], v[1], v[1]], homogeneous }, [fu, v]))+ }+ Surface::Cone { frame, radius_at_origin, half_angle } => {+ let slope = half_angle.tan();+ let homogeneous = net(frame, &line, &|[h, _]| (radius_at_origin + h * slope, h))?;+ 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 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])]]))+ }+ Surface::Torus { frame, major_radius, minor_radius } => {+ let (p0, m) = quarters(v)?;+ let (v_knots, tube) = arcs(p0, m);+ 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])]]))+ }+ _ => None,+ }+}diff --git a/crates/kernel/src/assemble.rs b/crates/kernel/src/assemble.rsindex d5ccb3e8c8..829f381358 100644--- a/crates/kernel/src/assemble.rs+++ b/crates/kernel/src/assemble.rs@@ -52,6 +52,9 @@ pub(crate) struct AUse {#[derive(Clone, Debug)]pub(crate) struct AFace {pub surface: Surface,+ /// The NURBS form the face's parameters are on, as the record's `Face::nurbs`: its domain,+ /// pcurves and `natural_out` are about this surface when it is given.+ pub nurbs: Option<Surface>,pub natural_out: bool,pub loops: Vec<Vec<AUse>>,pub shell: usize,@@ -59,6 +62,13 @@ 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 {@@ -108,7 +118,14 @@ impl Assembly {if slot.is_some() {return Err(invalid("a face used by two shells"));}- *slot = Some(AFace { surface: f.surface.clone(), natural_out: of.forward, loops, shell: s, domain: Some(f.domain) });+ *slot = Some(AFace {+ surface: f.surface.clone(),+ nurbs: f.nurbs.clone(),+ natural_out: of.forward,+ loops,+ shell: s,+ domain: Some(f.domain),+ });}}if faces.iter().any(Option::is_none) {@@ -273,8 +290,8 @@ impl Assembly {.collect::<Result<Vec<_>>>()}).collect::<Result<_>>()?;- let pcurves = pcurves_within(&f.surface, &uses, self.tolerance, f.domain).map_err(|e| invalid(format!("face {i}: {e}")))?;- let domain = domain_of(&f.surface, &pcurves, f.domain).ok_or_else(|| invalid(format!("face {i}: no parameter box")))?;+ 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")))?;let stored = loops.iter().zip(&pcurves)@@ -282,7 +299,7 @@ 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: None, surface: f.surface.clone(), domain, loops: stored })+ Ok(Face { nurbs: f.nurbs.clone(), surface: f.surface.clone(), domain, loops: stored })}}diff --git a/crates/kernel/src/emboss.rs b/crates/kernel/src/emboss.rsindex ce5ce65068..e4b200f360 100644--- a/crates/kernel/src/emboss.rs+++ b/crates/kernel/src/emboss.rs@@ -357,7 +357,7 @@ fn emboss_impl(body: &Body, anchor: Option<Vec3>, plane: &Plane, regions: &[Regicap.push(top);added.extend(walls);}- added.push(AFace { surface: wall.cylinder(rr), natural_out: true, loops: cap, shell: selected.shell, domain: None });+ added.push(AFace { surface: wall.cylinder(rr), nurbs: None, natural_out: true, loops: cap, shell: selected.shell, domain: None });added_history.push(crate::record::cap(true));}// An island inside a profile hole cuts that hole's original-radius patch,@@ -382,7 +382,14 @@ fn emboss_impl(body: &Body, anchor: Option<Vec3>, plane: &Plane, regions: &[Regifor (k, loops) in base_patches.into_iter().enumerate() {// The face's own parameter box only where it keeps its outer loop.let domain = if k == 0 { selected.domain } else { None };- asm.face(AFace { surface: selected.surface.clone(), natural_out: selected.natural_out, loops, shell: selected.shell, domain });+ asm.face(AFace {+ surface: selected.surface.clone(),+ nurbs: selected.nurbs.clone(),+ natural_out: selected.natural_out,+ loops,+ shell: selected.shell,+ domain,+ });}for f in added {asm.face(f);@@ -470,7 +477,7 @@ impl Wrap {AUse { edge: et.edge, forward: !et.forward, given: None },AUse { edge: ra, forward: false, given: None },];- walls.push(AFace { surface, natural_out: true, loops: vec![lp], shell, domain: None });+ walls.push(AFace { surface, nurbs: None, natural_out: true, loops: vec![lp], shell, domain: None });be.push(eb);te.push(et);}diff --git a/crates/kernel/src/lip.rs b/crates/kernel/src/lip.rsindex a7e456730b..f3df8e7b66 100644--- a/crates/kernel/src/lip.rs+++ b/crates/kernel/src/lip.rs@@ -270,7 +270,7 @@ fn wall(p: &Piece, n: Vec3, bottom: &AUse, top: &AUse, up_a: u32, up_b: u32, rigu.forward = !u.forward;}}- Ok(AFace { surface, natural_out, loops: vec![lp], shell, domain: None })+ Ok(AFace { surface, nurbs: None, natural_out, loops: vec![lp], shell, domain: None })}/// Raise the band of the planar face at `at` that runs `width` wide along its outer loop@@ -321,7 +321,14 @@ pub fn raise_band(body: &Body, at: Vec3, width: f64, height: f64, outside: bool)// (The band's edge runs the face's way round: a hole when the band follows the inner// loop, the outer loop when it follows the outer.)let rest_loops = if outside { vec![cedges.clone(), other] } else { vec![other, cedges.clone()] };- let rest = AFace { surface: face.surface.clone(), natural_out: face.natural_out, loops: rest_loops, shell: face.shell, domain: face.domain };+ let rest = AFace {+ surface: face.surface.clone(),+ nurbs: face.nurbs.clone(),+ natural_out: face.natural_out,+ loops: rest_loops,+ shell: face.shell,+ domain: face.domain,+ };// Walls: along the face's loop (the band's outside continues the walls below, on the// loop's right) and along the band's edge (its outside on that edge's left).let mut walls = Vec::with_capacity(2 * k);@@ -343,6 +350,7 @@ pub fn raise_band(body: &Body, at: Vec3, width: f64, height: f64, outside: bool)let u = n.any_perp();let top = AFace {surface: Surface::Plane { origin: arr(origin), u_axis: arr(u), v_axis: arr(n.cross(u)) },+ nurbs: None,natural_out: true,loops: top_loops,shell: face.shell,diff --git a/crates/kernel/src/offset.rs b/crates/kernel/src/offset.rsindex b2dea0ced7..911c869bcf 100644--- a/crates/kernel/src/offset.rs+++ b/crates/kernel/src/offset.rs@@ -37,7 +37,8 @@ fn axes(f: &Frame) -> Option<(Vec3, Vec3)> {/// uses its natural side.pub(crate) fn surf_of(b: &Brep, face: usize) -> Option<Surf> {let f = b.faces.get(face)?;- let out = crate::assemble::natural_out(b, face)?;+ // `forward` is about the face's NURBS form, which may run against its surface.+ let out = crate::assemble::natural_out(b, face)? != f.form_turns()?;let sign = if out { 1.0 } else { -1.0 };Some(match &f.surface {Surface::Plane { origin, u_axis, v_axis } => {