Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Wave 162/509: kernel: profile segments as exact schema 4 edge curves and pcurves (and 1 more)

jyviko11be845827ef
diff --git a/crates/kernel/src/freeform.rs b/crates/kernel/src/freeform.rs
index c860332d10..89114d1a6a 100644
--- a/crates/kernel/src/freeform.rs
+++ b/crates/kernel/src/freeform.rs
@@ -1,29 +1,100 @@
-//! Free-form profile edges: Béziers (cubic and higher) as B-spline curves and conics as rational quadratic
-//! NURBS curves (exact ellipses, parabolas and hyperbolas from sketches).
+//! Profile segments as exact schema 4 curves: each sketch segment on its plane becomes a 3D edge
+//! curve and, on the plane's own surface (`origin + u x + v y`, (u, v) the sketch coordinates), its
+//! pcurve, both on t in [0, 1] with the same knots and weights, so the pcurve lifts onto the edge
+//! exactly. Lines are lines; arcs rational quadratic B-splines (one span per quarter turn or less);
+//! cubic and higher Béziers B-splines on their own control points; conics rational quadratic
+//! Béziers (exact ellipses, parabolas and hyperbolas).
-use solidcraft_geom::{Plane, Seg2};
-use truck_modeling as mt;
+use solidcraft_geom::brep::{Curve, Curve2, Surface};
+use solidcraft_geom::{Plane, Seg2, Vec2, Vec3};
-use crate::body::p3;
+use crate::{KernelError, Result};
-/// The edge for a free-form segment between two existing vertices (None for lines and arcs).
-pub(crate) fn edge(plane: &Plane, s: &Seg2, a: &mt::Vertex, b: &mt::Vertex) -> Option<mt::Edge> {
- match *s {
- Seg2::Cubic { p1, p2, .. } => Some(mt::builder::bezier(a, b, vec![p3(plane.to_world(p1)), p3(plane.to_world(p2))])),
- Seg2::Conic { apex, w, .. } => {
- let (pa, pb, px) = (a.point(), b.point(), p3(plane.to_world(apex)));
- let ctrl = vec![
- mt::Vector4::new(pa.x, pa.y, pa.z, 1.0),
- mt::Vector4::new(px.x * w, px.y * w, px.z * w, w),
- mt::Vector4::new(pb.x, pb.y, pb.z, 1.0),
- ];
- let curve = mt::NurbsCurve::new(mt::BSplineCurve::new(mt::KnotVec::bezier_knot(2), ctrl));
- Some(mt::Edge::new(a, b, mt::Curve::NurbsCurve(curve)))
+/// The interval every curve [`segment`] makes runs on.
+pub(crate) const INTERVAL: [f64; 2] = [0.0, 1.0];
+
+/// The plane of a sketch as a record surface whose (u, v) are the sketch's coordinates.
+pub(crate) fn plane_surface(plane: &Plane) -> Surface {
+ let a = |v: Vec3| [v.x, v.y, v.z];
+ Surface::Plane { origin: a(plane.origin), u_axis: a(plane.x), v_axis: a(plane.y) }
+}
+
+/// A clamped Bézier knot vector of `degree`.
+fn bezier_knots(degree: usize) -> Vec<f64> {
+ std::iter::repeat_n(0.0, degree + 1).chain(std::iter::repeat_n(1.0, degree + 1)).collect()
+}
+
+/// The 2D rational control net of `s` (points, weights, knots), on t in [0, 1].
+fn net(s: &Seg2) -> Result<(Vec<Vec2>, Vec<f64>, Vec<f64>)> {
+ Ok(match *s {
+ Seg2::Line { a, b } => (vec![a, b], vec![1.0; 2], bezier_knots(1)),
+ Seg2::Arc { center, radius, start, sweep } => {
+ if !(radius.is_finite() && radius > 0.0 && sweep.is_finite() && sweep != 0.0 && sweep.abs() <= std::f64::consts::TAU * (1.0 + 1e-9)) {
+ return Err(KernelError::Invalid("an arc with no radius or turn, or turning more than once".into()));
+ }
+ let sweep = sweep.clamp(-std::f64::consts::TAU, std::f64::consts::TAU);
+ let m = (sweep.abs() / std::f64::consts::FRAC_PI_2 - 1e-9).ceil().max(1.0) as usize;
+ let d = sweep / m as f64;
+ let at = |a: f64, r: f64| center + Vec2::new(a.cos(), a.sin()) * r;
+ let w = (d / 2.0).cos();
+ let (mut pts, mut weights, mut knots) = (vec![at(start, radius)], vec![1.0], vec![0.0; 3]);
+ for j in 0..m {
+ let a0 = start + d * j as f64;
+ pts.push(at(a0 + d / 2.0, radius / w));
+ weights.push(w);
+ pts.push(at(a0 + d, radius));
+ weights.push(1.0);
+ let u = (j + 1) as f64 / m as f64;
+ knots.extend(if j + 1 < m { [u, u].as_slice() } else { [1.0, 1.0, 1.0].as_slice() });
+ }
+ (pts, weights, knots)
+ }
+ Seg2::Cubic { p0, p1, p2, p3 } => (vec![p0, p1, p2, p3], vec![1.0; 4], bezier_knots(3)),
+ Seg2::Conic { a, apex, b, w } => {
+ if !(w.is_finite() && w > 0.0) {
+ return Err(KernelError::Invalid("a conic's weight must be positive".into()));
+ }
+ (vec![a, apex, b], vec![1.0, w, 1.0], bezier_knots(2))
}
Seg2::Bezier { n, ref p } => {
- let inner = p.get(1..(n as usize).clamp(1, solidcraft_geom::MAX_BEZIER_DEGREE))?;
- Some(mt::builder::bezier(a, b, inner.iter().map(|q| p3(plane.to_world(*q))).collect()))
+ let n = usize::from(n);
+ let pts = p.get(..=n).filter(|_| (1..=solidcraft_geom::MAX_BEZIER_DEGREE).contains(&n));
+ let pts = pts.ok_or_else(|| KernelError::Invalid("Bézier degree".into()))?;
+ (pts.to_vec(), vec![1.0; n + 1], bezier_knots(n))
}
- Seg2::Line { .. } | Seg2::Arc { .. } => None,
+ })
+}
+
+/// The segment `s` on `plane` as an edge curve and its pcurve on [`plane_surface`], both on
+/// [`INTERVAL`].
+pub(crate) fn segment(plane: &Plane, s: &Seg2) -> Result<(Curve, Curve2)> {
+ let (pts, weights, knots) = net(s)?;
+ if pts.iter().any(|q| !q.is_finite()) {
+ return Err(KernelError::Invalid("a profile curve is not finite".into()));
+ }
+ let w = |q: Vec2| {
+ let p = plane.to_world(q);
+ [p.x, p.y, p.z]
+ };
+ if let Seg2::Line { a, b } = *s {
+ if a.dist(b) <= 0.0 {
+ return Err(KernelError::Invalid("a profile line has no length".into()));
+ }
+ let pc = Curve2::Spline { knots, points: vec![[a.x, a.y], [b.x, b.y]] };
+ return Ok((Curve::Line { start: w(a), end: w(b) }, pc));
+ }
+ if weights.iter().all(|x| *x == 1.0) {
+ let curve = Curve::Spline { knots: knots.clone(), points: pts.iter().map(|q| w(*q)).collect() };
+ return Ok((curve, Curve2::Spline { knots, points: pts.iter().map(|q| [q.x, q.y]).collect() }));
}
+ let homogeneous = pts
+ .iter()
+ .zip(&weights)
+ .map(|(q, h)| {
+ let [x, y, z] = w(*q);
+ [x * h, y * h, z * h, *h]
+ })
+ .collect();
+ let pcurve = Curve2::RationalSpline { knots: knots.clone(), homogeneous: pts.iter().zip(&weights).map(|(q, h)| [q.x * h, q.y * h, *h]).collect() };
+ Ok((Curve::RationalSpline { knots, homogeneous }, pcurve))
}
diff --git a/crates/smlib/SMLIB_REV b/crates/smlib/SMLIB_REV
index a57d774f9b..d5a51ab3aa 100644
--- a/crates/smlib/SMLIB_REV
+++ b/crates/smlib/SMLIB_REV
@@ -1 +1 @@
-2152a2cbbb12ee2c0990caf3e85621f7552d5198
+4a81dd9ca9a7bbd41c5125e4cc7b026f6abae5e5
diff --git a/crates/smlib/src/ffi.rs b/crates/smlib/src/ffi.rs
index 1254d7c04c..2d69a594aa 100644
--- a/crates/smlib/src/ffi.rs
+++ b/crates/smlib/src/ffi.rs
@@ -192,6 +192,7 @@ pub mod history;
pub mod measure;
pub mod ops;
pub mod split;
+pub mod sheets;
pub mod ssi;
pub mod sweeps;
pub mod trim;
diff --git a/crates/smlib/src/ffi/sheets.rs b/crates/smlib/src/ffi/sheets.rs
new file mode 100644
index 0000000000..61f23eda8e
--- /dev/null
+++ b/crates/smlib/src/ffi/sheets.rs
@@ -0,0 +1,40 @@
+//! The sheets block of `capi/include/smlib.h` (`smlib_stitch`, `smlib_offset_sheet`; the fork's
+//! `capi/src/smlib_sheets.cpp`), declared by hand. Part of the FFI boundary, like its parent:
+//! called only through [`crate::sheets`].
+
+#![allow(unsafe_code)]
+
+use super::Handle;
+#[cfg(not(feature = "native"))]
+use super::NOT_BUILT;
+#[cfg(feature = "native")]
+use super::{RawBrep, new_brep};
+
+#[cfg(feature = "native")]
+unsafe extern "C" {
+ fn smlib_stitch(brep: *const RawBrep, tolerance: f64, out_closed: *mut i32, out: *mut *mut RawBrep) -> i32;
+ fn smlib_offset_sheet(sheet: *const RawBrep, distance: f64, out: *mut *mut RawBrep) -> i32;
+}
+
+/// The stitched body and whether it closed into a solid.
+#[cfg(feature = "native")]
+pub fn stitch(b: &Handle, tolerance: f64) -> Result<(Handle, bool), i32> {
+ let mut closed = 0i32;
+ let h = new_brep(|out| unsafe { smlib_stitch(b.raw(), tolerance, &mut closed, out) })?;
+ Ok((h, closed != 0))
+}
+
+#[cfg(feature = "native")]
+pub fn offset_sheet(b: &Handle, distance: f64) -> Result<Handle, i32> {
+ new_brep(|out| unsafe { smlib_offset_sheet(b.raw(), distance, out) })
+}
+
+#[cfg(not(feature = "native"))]
+pub fn stitch(_: &Handle, _: f64) -> Result<(Handle, bool), i32> {
+ Err(NOT_BUILT)
+}
+
+#[cfg(not(feature = "native"))]
+pub fn offset_sheet(_: &Handle, _: f64) -> Result<Handle, i32> {
+ Err(NOT_BUILT)
+}
diff --git a/crates/smlib/src/lib.rs b/crates/smlib/src/lib.rs
index 91f2b98c13..eac6831359 100644
--- a/crates/smlib/src/lib.rs
+++ b/crates/smlib/src/lib.rs
@@ -24,6 +24,7 @@ pub mod import;
mod measure;
mod ops;
mod split;
+mod sheets;
pub mod ssi;
pub mod sweeps;
pub mod trim;
diff --git a/crates/smlib/src/sheets.rs b/crates/smlib/src/sheets.rs
new file mode 100644
index 0000000000..f05306f440
--- /dev/null
+++ b/crates/smlib/src/sheets.rs
@@ -0,0 +1,23 @@
+//! SMLib's sheet operations: sewing a body's faces along the edges that coincide, and a sheet's
+//! offset along its faces' normals. Each returns a new body and leaves its input unchanged;
+//! tagged inputs ([`Brep::tagged`]) give results whose [`Brep::history`] says where each face and
+//! edge came from.
+
+use crate::{Brep, Result, error, ffi, init};
+
+impl Brep {
+ /// The faces sewn along the vertices and edges that coincide within `tolerance` mm, oriented
+ /// outward where they close into a solid, else only made to agree across their shared edges;
+ /// with whether the result is a closed solid.
+ pub fn stitch(&self, tolerance: f64) -> Result<(Brep, bool)> {
+ init()?;
+ ffi::sheets::stitch(&self.0, tolerance).map(|(h, closed)| (Brep(h), closed)).map_err(error)
+ }
+
+ /// This sheet with every face moved onto its surface's offset by `distance` along its normal
+ /// (negative: against it). A closed solid is [`crate::Error::Argument`].
+ pub fn offset_sheet(&self, distance: f64) -> Result<Brep> {
+ init()?;
+ ffi::sheets::offset_sheet(&self.0, distance).map(Brep).map_err(error)
+ }
+}