SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Wave 181/509: kernel: iso_curves, a face's isoparametric curve exactly, trimmed by its loops (and 3 more)
jyvikoe45d7a3873d0
diff --git a/crates/doc/src/project.rs b/crates/doc/src/project.rsindex 14357bbae1..00b563c975 100644--- a/crates/doc/src/project.rs+++ b/crates/doc/src/project.rs@@ -208,8 +208,18 @@ fn resolve_uncached(}let name = st.bodies.get(bi).map(|b| b.name.clone()).unwrap_or_else(|| body.clone());source = LinkSource::OnSurface { sketch: *sketch, curve: curve.clone(), body: name, at: q };- wires = crate::project3d::onto_face(&mesh, f, &pts, plane.normal());- exact = vec![Vec::new(); wires.len()];+ match st.bodies.get(bi).filter(|b| !b.body.is_mesh()) {+ // A solid's face: SMLib's projection of the sketch curve itself.+ Some(target) => {+ let segs = ss.sketch.exact_segs(ci).unwrap_or_else(|| ss.sketch.segs(ci));+ (wires, exact) = projected_wires(target, q, ss, &segs, plane.normal(), size)?;+ }+ // A mesh body has only its triangles: the curve projected onto them.+ None => {+ wires = crate::project3d::onto_face(&mesh, f, &pts, plane.normal());+ exact = vec![Vec::new(); wires.len()];+ }+ }Vec::new()}LinkSource::Intersection { a, b } => {@@ -233,8 +243,24 @@ 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() };- wires = crate::project3d::iso_curve(&mesh, f, q, dir);- exact = vec![Vec::new(); wires.len()];+ 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)) => {+ 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)?)?;+ }+ // Along an explicit direction (the face cut by a plane), or on a mesh body: its+ // triangles' section.+ _ => {+ wires = crate::project3d::iso_curve(&mesh, f, q, dir);+ exact = vec![Vec::new(); wires.len()];+ }+ }Vec::new()}LinkSource::Spun { body, origin, dir } => {@@ -334,6 +360,50 @@ fn edge_curves(body: Option<&crate::ModelBody>, e: usize) -> Vec<WireCurve> {.unwrap_or_default()}+/// The sketch segments `segs` of `ss` projected along the sketch normal `normal` (turned toward+/// the face) onto the face of `target` at `at`: SMLib's projection, the pieces that meet end to+/// end joined into one wire each, every wire its points (for display) and its exact curves.+fn projected_wires(+ target: &crate::ModelBody,+ at: Vec3,+ ss: &crate::eval::SolvedSketch,+ segs: &[Seg2],+ normal: Vec3,+ size: f64,+) -> 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;+ 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 };+ 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));+ e.push(WireCurve { curve, interval });+ }+ _ => {+ wires.push(pts);+ exact.push(vec![WireCurve { curve, interval }]);+ }+ }+ }+ 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/point_path.rs b/crates/kernel/src/point_path.rsindex 5953b3de0b..a70577b6e1 100644--- a/crates/kernel/src/point_path.rs+++ b/crates/kernel/src/point_path.rs@@ -155,6 +155,233 @@ pub fn edge_path(body: &Body, edge: usize) -> Result<Vec<PathSeg>> {curve_path(&e.curve, e.interval)}+/// The sketch segments `segs` on `plane` projected along `direction` (pointing from them toward+/// the face) onto the face of `body` at `face_at`, as the record curves SMLib's projection makes+/// (one per piece of the projection that stays on the face), each on its interval.+pub fn project_onto_face(+ body: &Body,+ face_at: Vec3,+ plane: &Plane,+ segs: &[solidcraft_geom::Seg2],+ direction: Vec3,+) -> Result<Vec<(brep::Curve, [f64; 2])>> {+ if !(face_at.is_finite() && direction.is_finite() && direction.len() > 1e-12) || segs.is_empty() || segs.len() > 4096 {+ return Err(KernelError::Invalid("curve projection: a point, a direction and 1…4096 curves".into()));+ }+ crate::smlib_sweeps::project_onto_face(body, face_at, plane, segs, direction)+}++/// 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;++/// The isoparametric curve of face `face` of `body` through the point `at` on it, the pieces of+/// it inside the face, each as its exact record curve on its interval: along the surface's first+/// parameter (`along_u`; around a cylinder, cone, sphere or torus) or its second (along them).+/// On a B-spline surface the curve is the surface's row at the point's other parameter (each+/// control point the column through it evaluated there, exactly); on an analytic surface its+/// line or circle. The pieces are where the curve crosses the face's loops (their pcurves).+pub fn iso_curves(body: &Body, face: usize, at: Vec3, along_u: bool) -> Result<Vec<(brep::Curve, [f64; 2])>> {+ use solidcraft_geom::brep::eval::SurfaceEval;+ let record = body.record();+ let f = 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!("iso curve: {e}")))?;+ let [[u0, u1], [v0, v1]] = f.domain;+ let size = body.size().max(1e-9);+ let mid = [0.5 * (u0 + u1), 0.5 * (v0 + v1)];+ let [mut pu, mut pv] =+ eval.project(at, Some(mid), size * 1e-3 + 1e-6).ok_or_else(|| KernelError::Invalid("iso curve: the point is not on the face".into()))?;+ // Into the face's box, by whole periods.+ let period = eval.domain().period;+ for (x, (lo, hi), p) in [(&mut pu, (u0, u1), period[0]), (&mut pv, (v0, v1), period[1])] {+ if let Some(p) = p.filter(|p| *p > 0.0) {+ *x = lo + (*x - lo).rem_euclid(p);+ if *x > hi + 1e-12 {+ *x -= p;+ }+ }+ }+ // The iso line in (u, v): `fixed` held, the other running over the box.+ let (fixed, (lo, hi)) = if along_u { (pv, (u0, u1)) } else { (pu, (v0, v1)) };+ let at_t = |t: f64| if along_u { [t, fixed] } else { [fixed, t] };+ let pcurves: Vec<Vec<&brep::Curve2>> = f+ .loops+ .iter()+ .filter_map(|l| match l {+ brep::Loop::Edges { edges } => Some(edges.iter().map(|e| &e.pcurve).collect()),+ brep::Loop::Vertex { .. } => None,+ })+ .collect();+ // Where the line crosses the loops' pcurves (along it), each crossing solved on the pcurve+ // itself, with the box's ends.+ let across = |q: [f64; 2]| if along_u { q[1] - fixed } else { q[0] - fixed };+ let along = |q: [f64; 2]| if along_u { q[0] } else { q[1] };+ let mut cuts = vec![lo, hi];+ for c in pcurves.iter().flatten() {+ let samples = pcurve_samples(c);+ for w in samples.windows(2) {+ let ((ta, qa), (tb, qb)) = (w[0], w[1]);+ let (ka, kb) = (across(qa), across(qb));+ if (ka < 0.0) == (kb < 0.0) || ka == kb {+ continue;+ }+ let (mut x, mut y) = (ta, tb);+ for _ in 0..80 {+ let m = 0.5 * (x + y);+ match c.eval(m).map(across) {+ Some(k) if (k < 0.0) == (ka < 0.0) => x = m,+ Some(_) => y = m,+ None => break,+ }+ }+ if let Some(t) = c.eval(0.5 * (x + y)).map(along).filter(|t| *t > lo && *t < hi) {+ cuts.push(t);+ }+ }+ }+ let loops: Vec<Vec<[f64; 2]>> = pcurves.iter().map(|l| l.iter().flat_map(|c| pcurve_samples(c)).map(|(_, q)| q).collect()).collect();+ cuts.sort_by(f64::total_cmp);+ cuts.dedup_by(|a, b| (*a - *b).abs() <= 1e-9 * (1.0 + b.abs()));+ let inside = |q: [f64; 2]| loops.iter().filter(|l| crosses_right(q, l)).count() % 2 == 1;+ let mut out = Vec::new();+ // Neighbouring inside pieces are one piece.+ let mut run: Option<(f64, f64)> = None;+ for w in cuts.windows(2) {+ let (a, b) = (w[0], w[1]);+ if !(b - a > 1e-12) {+ continue;+ }+ if inside(at_t(0.5 * (a + b))) {+ run = Some(run.map_or((a, b), |(s, _)| (s, b)));+ } else if let Some(r) = run.take() {+ out.push(iso_record(&f.surface, along_u, fixed, r)?);+ }+ }+ if let Some(r) = run {+ out.push(iso_record(&f.surface, along_u, fixed, r)?);+ }+ if out.is_empty() {+ return Err(KernelError::Invalid("the iso curve runs outside the face".into()));+ }+ Ok(out)+}++/// A pcurve's parameters and points at [`ISO_SAMPLES`] per knot span, in its direction.+fn pcurve_samples(c: &brep::Curve2) -> Vec<(f64, [f64; 2])> {+ let Some([a, b]) = c.interval() else { return Vec::new() };+ let spans = match c {+ brep::Curve2::Spline { knots, .. } | brep::Curve2::RationalSpline { knots, .. } => knots.windows(2).filter(|w| w[1] > w[0]).count().max(1),+ };+ let n = (spans * ISO_SAMPLES).min(1 << 16);+ (0..=n)+ .filter_map(|i| {+ let t = a + (b - a) * i as f64 / n as f64;+ c.eval(t).map(|q| (t, q))+ })+ .collect()+}++/// Whether the ray from `q` along +u crosses the closed polyline `l` an odd number of times.+fn crosses_right(q: [f64; 2], l: &[[f64; 2]]) -> bool {+ let mut odd = false;+ for w in l.windows(2) {+ let (a, b) = (w[0], w[1]);+ if (a[1] > q[1]) != (b[1] > q[1]) && q[0] < a[0] + (b[0] - a[0]) * (q[1] - a[1]) / (b[1] - a[1]) {+ odd = !odd;+ }+ }+ odd+}++/// The iso curve of `surface` at `fixed` (the other parameter) as a record curve on `[a, b]` of+/// its own parameter: the surface's own line or circle, or its B-spline row.+fn iso_record(surface: &brep::Surface, along_u: bool, fixed: f64, (a, b): (f64, f64)) -> Result<(brep::Curve, [f64; 2])> {+ use solidcraft_geom::brep::{Curve, Frame, Surface};+ let v = |q: [f64; 3]| Vec3::new(q[0], q[1], q[2]);+ let d = |q: Vec3| [q.x, q.y, q.z];+ let line = |p: Vec3, q: Vec3| (Curve::Line { start: d(p), end: d(q) }, [0.0, 1.0]);+ let circle = |o: Vec3, x: Vec3, y: Vec3, r: f64| (Curve::Circle { frame: Frame { origin: d(o), x_axis: d(x), y_axis: d(y) }, radius: r }, [a, b]);+ let frame = |f: &Frame| (v(f.origin), v(f.x_axis), v(f.y_axis), v(f.x_axis).cross(v(f.y_axis)));+ Ok(match surface {+ Surface::Plane { origin, u_axis, v_axis } => {+ let (o, x, y) = (v(*origin), v(*u_axis), v(*v_axis));+ let at = |t: f64| if along_u { o + x * t + y * fixed } else { o + x * fixed + y * t };+ line(at(a), at(b))+ }+ Surface::PlaneThrough { origin, u_point, v_point } => {+ let (o, x, y) = (v(*origin), v(*u_point) - v(*origin), v(*v_point) - v(*origin));+ let at = |t: f64| if along_u { o + x * t + y * fixed } else { o + x * fixed + y * t };+ line(at(a), at(b))+ }+ Surface::Cylinder { frame: f, radius } => {+ let (o, x, y, z) = frame(f);+ if along_u {+ circle(o + z * fixed, x, y, *radius)+ } else {+ let r = (x * fixed.cos() + y * fixed.sin()) * *radius;+ line(o + r + z * a, o + r + z * b)+ }+ }+ Surface::Cone { frame: f, radius_at_origin, half_angle } => {+ let (o, x, y, z) = frame(f);+ let r = |h: f64| radius_at_origin + h * half_angle.tan();+ if along_u {+ circle(o + z * fixed, x, y, r(fixed))+ } else {+ let dir = x * fixed.cos() + y * fixed.sin();+ line(o + dir * r(a) + z * a, o + dir * r(b) + z * b)+ }+ }+ Surface::Sphere { frame: f, radius } => {+ let (o, x, y, z) = frame(f);+ if along_u {+ circle(o + z * (radius * fixed.sin()), x, y, radius * fixed.cos())+ } else {+ circle(o, x * fixed.cos() + y * fixed.sin(), z, *radius)+ }+ }+ Surface::Torus { frame: f, major_radius, minor_radius } => {+ let (o, x, y, z) = frame(f);+ if along_u {+ circle(o + z * (minor_radius * fixed.sin()), x, y, major_radius + minor_radius * fixed.cos())+ } else {+ let dir = x * fixed.cos() + y * fixed.sin();+ circle(o + dir * *major_radius, dir, z, *minor_radius)+ }+ }+ Surface::Spline { u_knots, v_knots, points } => {+ let rows: Vec<Vec<[f64; 4]>> = points.iter().map(|r| r.iter().map(|q| [q[0], q[1], q[2], 1.0]).collect()).collect();+ spline_iso(u_knots, v_knots, &rows, along_u, fixed, a, b)?+ }+ Surface::RationalSpline { u_knots, v_knots, homogeneous } => spline_iso(u_knots, v_knots, homogeneous, along_u, fixed, a, b)?,+ Surface::PlacedRevolution { .. } => {+ return Err(KernelError::Failed("not supported yet: an iso curve of a revolved surface record".into()));+ }+ })+}++/// The row of a B-spline surface (homogeneous `net[i][j]`, i along u) at `fixed`: along u, each+/// control point the v-column through it evaluated at `fixed` (along v, the u-row), on `[a, b]`.+fn spline_iso(u_knots: &[f64], v_knots: &[f64], net: &[Vec<[f64; 4]>], along_u: bool, fixed: f64, a: f64, b: f64) -> Result<(brep::Curve, [f64; 2])> {+ use solidcraft_geom::bspline::CurveN;+ let bad = || KernelError::Invalid("iso curve: the surface's B-spline does not evaluate".into());+ let (nu, nv) = (net.len(), net.first().map_or(0, Vec::len));+ if nu * nv > MAX_CURVE_POINTS || net.iter().any(|r| r.len() != nv) {+ return Err(bad());+ }+ let (pu, pv) = (u_knots.len().checked_sub(nu + 1).ok_or_else(bad)?, v_knots.len().checked_sub(nv + 1).ok_or_else(bad)?);+ let at = |degree: usize, knots: &[f64], ctrl: Vec<[f64; 4]>| CurveN::<4> { degree, knots: knots.to_vec(), ctrl }.eval(fixed).map(|(p, _)| p);+ let (knots, homogeneous): (Vec<f64>, Vec<[f64; 4]>) = if along_u {+ (u_knots.to_vec(), net.iter().map(|row| at(pv, v_knots, row.clone())).collect::<Option<_>>().ok_or_else(bad)?)+ } else {+ (+ v_knots.to_vec(),+ (0..nv).map(|j| at(pu, u_knots, net.iter().filter_map(|r| r.get(j).copied()).collect())).collect::<Option<_>>().ok_or_else(bad)?,+ )+ };+ Ok((brep::Curve::RationalSpline { knots, homogeneous }, [a, b]))+}+/// Most control points a record curve given to [`curve_path`] may have.const MAX_CURVE_POINTS: usize = 100_000;diff --git a/crates/kernel/src/smlib_sweeps.rs b/crates/kernel/src/smlib_sweeps.rsindex f9d5bf9931..8a8c163f16 100644--- a/crates/kernel/src/smlib_sweeps.rs+++ b/crates/kernel/src/smlib_sweeps.rs@@ -72,7 +72,8 @@ pub(crate) struct Draft {#[cfg(feature = "smlib")]pub(crate) use imp::{- body_from_record, curve, extrude, loft, loft_rails, loft_to_point, path_curve, revolve, screw, sphere, sweep, sweep_controlled,+ body_from_record, curve, extrude, loft, loft_rails, loft_to_point, path_curve, project_onto_face, revolve, screw, sphere, sweep,+ sweep_controlled,};/// The error of an SMLib operation in a build without SMLib.@@ -91,6 +92,9 @@ mod stubs {pub(crate) fn sphere(_: Vec3, _: f64) -> Result<Body> {Err(not_built())}+ 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 extrude(_: &Plane, _: &[Piece], _: Option<&Region2>, _: f64, _: f64, _: f64, _: Option<Draft>) -> Result<Body> {Err(not_built())}@@ -117,7 +121,9 @@ mod stubs {}}#[cfg(not(feature = "smlib"))]-pub(crate) use stubs::{body_from_record, extrude, loft, loft_rails, loft_to_point, revolve, screw, sphere, sweep, sweep_controlled};+pub(crate) use stubs::{+ body_from_record, extrude, loft, loft_rails, loft_to_point, project_onto_face, revolve, screw, sphere, sweep, sweep_controlled,+};/// Refuses what no SMLib sweep does, before any work.pub(crate) fn refuse(what: &str) -> KernelError {@@ -208,6 +214,35 @@ mod imp {body_of(&brep, what)}+ /// The sketch segments `segs` on `plane` projected along `direction` onto the face of+ /// `body` at `face_at`: SMLib's projection (smlib_project_curves), each projected curve the+ /// B-spline SMLib made, as a record curve on its interval, within a millionth of the body's+ /// size of the true projection.+ pub(crate) fn project_onto_face(+ body: &Body,+ face_at: Vec3,+ plane: &Plane,+ segs: &[Seg2],+ 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),+ })?;+ 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")),+ })+ .collect()+ }+/// SMLib's sphere about `center`, each face swept from the arc (segment 0) of the half disc/// a sphere revolves.pub(crate) fn sphere(center: Vec3, radius: f64) -> Result<Body> {