Skip to content

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

Wave 183/509: kernel: face sections along a direction as SMLib's exact curves (and 3 more)

jyviko00659d4d12f7
diff --git a/crates/doc/src/project.rs b/crates/doc/src/project.rs
index 00b563c975..ba0fa6d8e5 100644
--- a/crates/doc/src/project.rs
+++ b/crates/doc/src/project.rs
@@ -243,20 +243,25 @@ fn resolve_uncached(
}
let name = st.bodies.get(bi).map(|b| b.name.clone()).unwrap_or_else(|| body.clone());
source = LinkSource::Iso { body: name, at: q, dir: dir.clone() };
- let along = match dir.trim().to_ascii_lowercase().as_str() {
- "u" => Some(true),
- "v" => Some(false),
- _ => None,
- };
- match (st.bodies.get(bi).filter(|b| !b.body.is_mesh()), along) {
- // A solid's face along its own parameter: the surface's isoparametric curve.
- (Some(target), Some(along_u)) => {
+ match st.bodies.get(bi).filter(|b| !b.body.is_mesh()) {
+ Some(target) => {
let face = usize::try_from(f).map_err(|_| DocError::Invalid("face index exceeds platform limit".into()))?;
- (wires, exact) = exact_wires(crate::kernel::iso_curves(&target.body, face, q, along_u)?)?;
+ let curves = match dir.trim().to_ascii_lowercase().as_str() {
+ // Along the face's own parameter: the surface's isoparametric curve.
+ "u" => crate::kernel::iso_curves(&target.body, face, q, true)?,
+ "v" => crate::kernel::iso_curves(&target.body, face, q, false)?,
+ // Along a direction: the face cut by the plane through the point that
+ // holds the face's normal there and the direction.
+ other => {
+ let v: Vec<f64> = other.split([',', ' ']).filter_map(|x| x.trim().parse().ok()).collect();
+ let [x, y, z] = v[..] else { return Err(DocError::Invalid(format!("iso direction `{dir}`"))) };
+ crate::kernel::face_section_along(&target.body, face, q, Vec3::new(x, y, z))?
+ }
+ };
+ (wires, exact) = joined_wires(curves, size * 1e-6)?;
}
- // Along an explicit direction (the face cut by a plane), or on a mesh body: its
- // triangles' section.
- _ => {
+ // A mesh body has only its triangles: their section.
+ None => {
wires = crate::project3d::iso_curve(&mesh, f, q, dir);
exact = vec![Vec::new(); wires.len()];
}
@@ -373,12 +378,16 @@ fn projected_wires(
) -> Result<(Vec<Vec<Vec3>>, Vec<Vec<WireCurve>>)> {
let from = segs.first().map(|s| ss.plane.to_world(s.start())).unwrap_or(at);
let toward = if (at - from).dot(normal) < 0.0 { normal * -1.0 } else { normal };
- let curves = crate::kernel::project_onto_face(&target.body, at, &ss.plane, segs, toward)?;
- let tol = size * 1e-6;
+ joined_wires(crate::kernel::project_onto_face(&target.body, at, &ss.plane, segs, toward)?, size * 1e-6)
+}
+
+/// Record curves as wires: curves that meet end to end (within `tol`) one wire, each wire its
+/// points (for display) and its exact curves.
+fn joined_wires(curves: Vec<(solidcraft_geom::brep::Curve, [f64; 2])>, tol: f64) -> Result<(Vec<Vec<Vec3>>, Vec<Vec<WireCurve>>)> {
let (mut wires, mut exact): (Vec<Vec<Vec3>>, Vec<Vec<WireCurve>>) = (Vec::new(), Vec::new());
for (curve, interval) in curves {
let pts = crate::kernel::PathPiece::Segs(crate::kernel::curve_path(&curve, interval)?).points();
- let (Some(start), Some(_)) = (pts.first().copied(), pts.last()) else { continue };
+ let Some(start) = pts.first().copied() else { continue };
match (wires.last_mut(), exact.last_mut()) {
(Some(w), Some(e)) if w.last().is_some_and(|end| end.dist(start) <= tol) => {
w.extend(pts.into_iter().skip(1));
@@ -393,17 +402,6 @@ fn projected_wires(
Ok((wires, exact))
}
-/// Record curves as wires, one each: its points (for display) and the curve itself.
-fn exact_wires(curves: Vec<(solidcraft_geom::brep::Curve, [f64; 2])>) -> Result<(Vec<Vec<Vec3>>, Vec<Vec<WireCurve>>)> {
- let mut wires = Vec::with_capacity(curves.len());
- let mut exact = Vec::with_capacity(curves.len());
- for (curve, interval) in curves {
- wires.push(crate::kernel::PathPiece::Segs(crate::kernel::curve_path(&curve, interval)?).points());
- exact.push(vec![WireCurve { curve, interval }]);
- }
- Ok((wires, exact))
-}
-
/// Curve `ci` of the solved sketch `ss` as its exact pieces in space, in the order its polyline
/// runs; none where a piece has no record curve.
fn sketch_curves(ss: &crate::eval::SolvedSketch, ci: usize) -> Vec<WireCurve> {
diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs
index cac61b90cc..41a3b00320 100644
--- a/crates/kernel/src/lib.rs
+++ b/crates/kernel/src/lib.rs
@@ -188,7 +188,9 @@ pub use native::{body_from_smlib, smlib_body};
pub use native::{brep_record, decode_native_body, encode_native_body, native_preview_mesh};
pub use offset::with_same_surface;
pub use ops::{BoolOp, boolean, half_space, join_apart, place_matrix, split_by_plane, transform, transform_matrix, union_apart};
-pub use point_path::{PathPiece, PointPath, SpaceBezier, curve_path, edge_path, sketch_record_curve, sweep_point_path_with};
+pub use point_path::{
+ PathPiece, PointPath, SpaceBezier, curve_path, edge_path, face_section_along, iso_curves, project_onto_face, sketch_record_curve, sweep_point_path_with,
+};
pub use polybool::faceted_boolean;
pub use polyhedron::{HalfSpace, convex_polyhedron, draft, offset_faces, shell};
pub use prism::{PLANAR_FIT_TOL, extrude_planar_regions, planar_regions_boolean};
diff --git a/crates/kernel/src/point_path.rs b/crates/kernel/src/point_path.rs
index a70577b6e1..a79f9c215b 100644
--- a/crates/kernel/src/point_path.rs
+++ b/crates/kernel/src/point_path.rs
@@ -171,6 +171,27 @@ pub fn project_onto_face(
crate::smlib_sweeps::project_onto_face(body, face_at, plane, segs, direction)
}
+/// The face `face` of `body` through `at` cut along `along` by the plane through `at` that holds
+/// the face's normal there (its exact normal from the record) and `along`: SMLib's section curves
+/// on that face, as record curves on their intervals.
+pub fn face_section_along(body: &Body, face: usize, at: Vec3, along: Vec3) -> Result<Vec<(brep::Curve, [f64; 2])>> {
+ use solidcraft_geom::brep::eval::SurfaceEval;
+ let f = body.record().faces.get(face).ok_or_else(|| KernelError::Invalid(format!("the body has no face {face}")))?;
+ let eval = SurfaceEval::new(&f.surface).map_err(|e| KernelError::Failed(format!("face section: {e}")))?;
+ let [[u0, u1], [v0, v1]] = f.domain;
+ let size = body.size().max(1e-9);
+ let uv = eval
+ .project(at, Some([0.5 * (u0 + u1), 0.5 * (v0 + v1)]), size * 1e-3 + 1e-6)
+ .ok_or_else(|| KernelError::Invalid("face section: the point is not on the face".into()))?;
+ let (_, du, dv) = eval.derivs(uv[0], uv[1]).ok_or_else(|| KernelError::Failed("face section: the surface does not evaluate there".into()))?;
+ let normal = du
+ .cross(dv)
+ .cross(along)
+ .normalized()
+ .ok_or_else(|| KernelError::Invalid("face section: the direction runs along the face's normal".into()))?;
+ crate::smlib_sweeps::face_section(body, at, at, normal)
+}
+
/// Samples per knot span (and at least this many per pcurve) where the iso curves look for the
/// crossings of a face's loops and classify the face's inside.
const ISO_SAMPLES: usize = 64;
diff --git a/crates/kernel/src/smlib_sweeps.rs b/crates/kernel/src/smlib_sweeps.rs
index 8a8c163f16..ed4055527d 100644
--- a/crates/kernel/src/smlib_sweeps.rs
+++ b/crates/kernel/src/smlib_sweeps.rs
@@ -72,7 +72,7 @@ pub(crate) struct Draft {
#[cfg(feature = "smlib")]
pub(crate) use imp::{
- body_from_record, curve, extrude, loft, loft_rails, loft_to_point, path_curve, project_onto_face, revolve, screw, sphere, sweep,
+ body_from_record, curve, extrude, face_section, loft, loft_rails, loft_to_point, path_curve, project_onto_face, revolve, screw, sphere, sweep,
sweep_controlled,
};
@@ -95,6 +95,9 @@ mod stubs {
pub(crate) fn project_onto_face(_: &Body, _: Vec3, _: &Plane, _: &[Seg2], _: Vec3) -> Result<Vec<(solidcraft_geom::brep::Curve, [f64; 2])>> {
Err(not_built())
}
+ pub(crate) fn face_section(_: &Body, _: Vec3, _: Vec3, _: Vec3) -> Result<Vec<(solidcraft_geom::brep::Curve, [f64; 2])>> {
+ Err(not_built())
+ }
pub(crate) fn extrude(_: &Plane, _: &[Piece], _: Option<&Region2>, _: f64, _: f64, _: f64, _: Option<Draft>) -> Result<Body> {
Err(not_built())
}
@@ -122,7 +125,7 @@ mod stubs {
}
#[cfg(not(feature = "smlib"))]
pub(crate) use stubs::{
- body_from_record, extrude, loft, loft_rails, loft_to_point, project_onto_face, revolve, screw, sphere, sweep, sweep_controlled,
+ body_from_record, extrude, face_section, loft, loft_rails, loft_to_point, project_onto_face, revolve, screw, sphere, sweep, sweep_controlled,
};
/// Refuses what no SMLib sweep does, before any work.
@@ -226,19 +229,51 @@ mod imp {
direction: Vec3,
) -> Result<Vec<(solidcraft_geom::brep::Curve, [f64; 2])>> {
let c = segs.iter().map(|s| curve(plane, s)).collect::<Result<Vec<_>>>()?;
- let size = body.size().max(1e-9);
- let out = body.smlib()?.project_curves(p(face_at), size * 1e-3 + 1e-6, &c, p(direction), (size * 1e-6).max(1e-6)).map_err(|e| match e {
- solidcraft_smlib::Error::Empty => KernelError::Invalid("the curve projects to nothing on the face".into()),
- solidcraft_smlib::Error::NoMatch { .. } => KernelError::Invalid("no face of the body at the projection's point".into()),
- e => failed("curve projection", e),
- })?;
+ let out = body
+ .smlib()?
+ .project_curves(p(face_at), pick_reach(body), &c, p(direction), curve_tolerance(body))
+ .map_err(|e| curves_error("curve projection", e))?;
+ record_curves(out, "curve projection")
+ }
+
+ /// The face of `body` at `face_at` cut by the plane through `plane_point` square to `normal`,
+ /// SMLib's section curves on that face, as record curves on their intervals.
+ pub(crate) fn face_section(body: &Body, face_at: Vec3, plane_point: Vec3, normal: Vec3) -> Result<Vec<(solidcraft_geom::brep::Curve, [f64; 2])>> {
+ let out = body
+ .smlib()?
+ .face_section(p(face_at), pick_reach(body), p(plane_point), p(normal), curve_tolerance(body))
+ .map_err(|e| curves_error("face section", e))?;
+ record_curves(out, "face section")
+ }
+
+ /// How far a point may be from the face it picks: the kernel's picking reach.
+ fn pick_reach(body: &Body) -> f64 {
+ body.size().max(1e-9) * 1e-3 + 1e-6
+ }
+
+ /// How close a curve SMLib makes on a body's faces keeps to the true one: a millionth of the
+ /// body's size.
+ fn curve_tolerance(body: &Body) -> f64 {
+ (body.size() * 1e-6).max(1e-6)
+ }
+
+ fn curves_error(what: &str, e: solidcraft_smlib::Error) -> KernelError {
+ match e {
+ solidcraft_smlib::Error::Empty => KernelError::Invalid(format!("{what}: no curve on the face")),
+ solidcraft_smlib::Error::NoMatch { .. } => KernelError::Invalid(format!("{what}: no face of the body at the point")),
+ e => failed(what, e),
+ }
+ }
+
+ /// SMLib's NURBS curves as record curves (rational splines) on their intervals.
+ fn record_curves(out: Vec<(Curve, [f64; 2])>, what: &str) -> Result<Vec<(solidcraft_geom::brep::Curve, [f64; 2])>> {
out.into_iter()
.map(|(c, interval)| match c {
Curve::Nurbs { points, knots, .. } => {
let homogeneous = points.iter().map(|q| [q[0] * q[3], q[1] * q[3], q[2] * q[3], q[3]]).collect();
Ok((solidcraft_geom::brep::Curve::RationalSpline { knots, homogeneous }, interval))
}
- _ => Err(failed("curve projection", "a projected curve is not a B-spline")),
+ _ => Err(failed(what, "a curve SMLib made is not a B-spline")),
})
.collect()
}
diff --git a/crates/kernel/src/sweep_path.rs b/crates/kernel/src/sweep_path.rs
index a137fbf211..b30e9f5ae7 100644
--- a/crates/kernel/src/sweep_path.rs
+++ b/crates/kernel/src/sweep_path.rs
@@ -470,7 +470,8 @@ mod tests {
#[test]
fn sweeps_along_3d_paths() {
- // A quarter of a helix-like 3D curve: a smooth wall, volume ≈ area × length.
+ // A polyline through 41 points of a quarter of a helix-like 3D curve: the profile swept
+ // along its 40 lines, mitred at each point, so volume = area × length.
let path: Vec<Vec3> = (0..=40)
.map(|i| {
let t = i as f64 / 40.0 * std::f64::consts::FRAC_PI_2;
@@ -484,8 +485,9 @@ mod tests {
let v = b.mesh(&crate::MeshTolerance::chord(0.01)).unwrap().measure().volume;
let want = std::f64::consts::PI * 4.0 * len;
assert!((v - want).abs() < 0.02 * want, "{v} vs {want}");
- // One wall per profile segment and two caps (ruled walls would give dozens).
- assert!(b.faces(0.01).unwrap().len() <= 8, "smooth walls: {}", b.faces(0.01).unwrap().len());
+ // The path is its lines (no wall is fitted through the points): a wall per profile
+ // segment (the circle's two arcs) along each of the 40 lines, and two caps.
+ assert_eq!(b.faces(0.01).unwrap().len(), 2 * 40 + 2, "walls along each line");
// An L-shaped path (a sharp corner) with a holed square: mitred ruled walls.
let path = [Vec3::ZERO, Vec3::new(0.0, 0.0, 20.0), Vec3::new(20.0, 0.0, 20.0)];
let plane = Plane::from_normal(Vec3::ZERO, Vec3::Z).unwrap();
diff --git a/crates/smlib/SMLIB_REV b/crates/smlib/SMLIB_REV
index 06c26b671e..2b46cc540d 100644
--- a/crates/smlib/SMLIB_REV
+++ b/crates/smlib/SMLIB_REV
@@ -1 +1 @@
-eedfa514371f80697c66472b40bda7d0e30146f5
+964474aef3baeaca3a1291182eb912297265b3e9