Skip to content

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

Wave 156/509: kernel: face_params deleted; a face's boundary in its parameters is the record's pcurves (and 3 more)

jyviko0d502d263438
diff --git a/crates/kernel/src/assemble.rs b/crates/kernel/src/assemble.rs
index d0581fd058..14f7b6afdf 100644
--- a/crates/kernel/src/assemble.rs
+++ b/crates/kernel/src/assemble.rs
@@ -131,6 +131,18 @@ impl Assembly {
Ok(Assembly { tolerance: b.tolerance, vertices: b.vertices.clone(), edges, faces, regions: b.regions.clone(), shells: b.shells.len() })
}
+ /// An empty sheet to build faces into: one open shell (shell 0) in the infinite region.
+ pub(crate) fn sheet(tolerance: f64) -> Assembly {
+ Assembly {
+ tolerance,
+ vertices: Vec::new(),
+ edges: Vec::new(),
+ faces: Vec::new(),
+ regions: vec![Region { shells: vec![0], void: false }],
+ shells: 1,
+ }
+ }
+
/// A new vertex at `p`.
pub(crate) fn vertex(&mut self, p: Vec3) -> Result<u32> {
if !p.is_finite() {
diff --git a/crates/kernel/src/clearance.rs b/crates/kernel/src/clearance.rs
index aa33cf60fa..3c9a0e083b 100644
--- a/crates/kernel/src/clearance.rs
+++ b/crates/kernel/src/clearance.rs
@@ -12,8 +12,8 @@
use std::collections::HashMap;
+use solidcraft_geom::brep::Surface;
use solidcraft_geom::{Aabb3, Mesh, Vec3};
-use truck_modeling as mt;
use crate::body::Body;
use crate::offset::{Surf, surf_of};
@@ -232,8 +232,7 @@ impl<'a> Clearance<'a> {
/// The round surface (sphere, cylinder, cone, torus) a face lies on, if it is one.
fn round_of(&self, face: u32) -> Option<Surf> {
- let f = self.body.solid.face_iter().nth(face as usize)?;
- surf_of(f, self.tol * 100.0)
+ surf_of(self.body.record(), face as usize)
}
/// How far the surface may stand off a triangle with its centroid at `p`, towards larger and towards smaller heights along `n`: a
@@ -255,40 +254,47 @@ impl<'a> Clearance<'a> {
if self.body.is_mesh() {
return Reach::Exact;
}
- crate::guard("face reach", || {
- let Some(f) = self.body.solid.face_iter().nth(face as usize) else { return Ok(Reach::Around) };
- let surface = f.oriented_surface();
- if matches!(surface, mt::Surface::Plane(_)) {
- return Ok(Reach::Exact);
- }
- if self.exact
- && let Some((least, greatest)) = crate::planar_faces::control_net_span(&surface, along)
- && (greatest <= lo || least >= hi)
- {
- return Ok(Reach::Never);
- }
- let round = surf_of(f, self.tol * 100.0);
- // A flat face stored otherwise (a revolve's end: a line swept round its axis) is
- // a plane all the same: its triangles lie in it.
- if matches!(round, Some(Surf::Plane { .. })) {
- return Ok(Reach::Exact);
- }
- let straight = matches!(round, Some(Surf::Cylinder { a, .. }) if a.dot(along).abs() > 1.0 - 1e-12)
- || crate::prism::wall_along(&surface, along, self.tol * 10.0, &mut 262_144);
- Ok(if straight {
- Reach::Sideways
- } else if round.and_then(|s| span(&s, along)).is_some_and(|(s0, s1)| s1 <= lo || s0 >= hi) {
- Reach::Never
- } else if let Some(Surf::Cylinder { convex, .. } | Surf::Cone { convex, .. } | Surf::Sphere { convex, .. }) = round {
- Reach::Beyond { convex }
- } else {
- Reach::Around
- })
- })
- .unwrap_or(Reach::Around)
+ let Some(face_record) = self.body.record().faces.get(face as usize) else { return Reach::Around };
+ let surface = &face_record.surface;
+ let round = self.round_of(face);
+ if matches!(round, Some(Surf::Plane { .. })) {
+ return Reach::Exact;
+ }
+ if self.exact
+ && let Some((least, greatest)) = control_net_span(surface, along)
+ && (greatest <= lo || least >= hi)
+ {
+ return Reach::Never;
+ }
+ let straight = matches!(round, Some(Surf::Cylinder { a, .. }) if a.dot(along).abs() > 1.0 - 1e-12)
+ || crate::prism::wall_along(surface, along, self.tol * 10.0, &mut 262_144);
+ if straight {
+ Reach::Sideways
+ } else if round.and_then(|s| span(&s, along)).is_some_and(|(s0, s1)| s1 <= lo || s0 >= hi) {
+ Reach::Never
+ } else if let Some(Surf::Cylinder { convex, .. } | Surf::Cone { convex, .. } | Surf::Sphere { convex, .. }) = round {
+ Reach::Beyond { convex }
+ } else {
+ Reach::Around
+ }
}
}
+/// The least and the greatest `along · p` over the control points of a B-spline or NURBS surface
+/// record; the surface lies between them (it is in the convex hull of its control net). `None`
+/// for any other surface.
+fn control_net_span(s: &Surface, along: Vec3) -> Option<(f64, f64)> {
+ let points: Vec<Vec3> = match s {
+ Surface::Spline { points, .. } => points.iter().flatten().map(|p| Vec3::from(*p)).collect(),
+ Surface::RationalSpline { homogeneous, .. } => {
+ // The hull holds the surface only where every weight is positive.
+ homogeneous.iter().flatten().map(|h| (h[3] > 0.0).then(|| Vec3::new(h[0] / h[3], h[1] / h[3], h[2] / h[3]))).collect::<Option<_>>()?
+ }
+ _ => return None,
+ };
+ points.iter().map(|p| along.dot(*p)).fold(None, |acc, h| Some(acc.map_or((h, h), |(lo, hi): (f64, f64)| (lo.min(h), hi.max(h)))))
+}
+
/// The whole extent of a round surface along `along`, where it has one.
fn span(s: &Surf, along: Vec3) -> Option<(f64, f64)> {
let about = |c: Vec3, r: f64| Some((along.dot(c) - r.abs(), along.dot(c) + r.abs()));
diff --git a/crates/kernel/src/face_params.rs b/crates/kernel/src/face_params.rs
deleted file mode 100644
index 5011a1bdf6..0000000000
--- a/crates/kernel/src/face_params.rs
+++ /dev/null
@@ -1,265 +0,0 @@
-//! A face's boundary in its surface's parameters, and exact parameter lines on a surface:
-//! shared by the operations that rework a face on the surface it lies on (Untrim, Extend).
-//!
-//! A face's loops are sampled into parameters with periodic directions unwrapped along each
-//! loop; which loop is the outer one is worked out from those parameters (the loop enclosing
-//! the most area), never from the order the loops are stored in: an imported face can list
-//! its holes first.
-
-use mt::{BoundedCurve, Cut, InnerSpace, Invertible, MetricSpace, ParametricCurve, ParametricSurface, SearchNearestParameter, Transformed};
-use solidcraft_geom::tess::EvalSurface;
-use solidcraft_geom::{Ring, Vec3};
-use truck_modeling as mt;
-
-use crate::body::from_p3;
-use crate::tess::uv::{self, Domain};
-use crate::{KernelError, Result};
-
-/// Samples along each boundary edge when working out the face's parameter loops.
-pub(crate) const EDGE_SAMPLES: usize = 32;
-/// Golden-section steps that place an extreme of the face's span on an edge.
-const EXTREME_STEPS: usize = 60;
-
-/// A boundary loop of a face sampled in 3D and in the surface's parameters: for each of its
-/// edges (as the loop runs) the curve parameters, points and parameters of its samples, ends
-/// included. Periodic parameters are unwrapped along the loop.
-pub(crate) struct LoopSamples {
- pub(crate) edges: Vec<(mt::Curve, Vec<(f64, Vec3, [f64; 2])>)>,
-}
-
-impl LoopSamples {
- /// The loop as a polygon in parameters (each edge's samples but its last, which the next
- /// edge starts on).
- pub(crate) fn polygon(&self) -> Ring<[f64; 2]> {
- self.edges.iter().flat_map(|(_, s)| s.iter().take(s.len().saturating_sub(1)).map(|x| x.2)).collect()
- }
-
- /// Signed area of the loop in parameters (positive: counter-clockwise).
- pub(crate) fn area(&self) -> f64 {
- self.polygon().signed_area()
- }
-
- /// How far `p` is from the loop (from its samples).
- pub(crate) fn dist(&self, p: Vec3) -> f64 {
- self.edges.iter().flat_map(|(_, s)| s.iter().map(|x| x.1.dist(p))).fold(f64::INFINITY, f64::min)
- }
-}
-
-/// A face's boundary loops (absolute: as they run on its surface) in the surface's parameters,
-/// and which of them is the outer one.
-pub(crate) struct FaceLoops {
- pub(crate) eval: EvalSurface,
- pub(crate) dom: Domain,
- pub(crate) wires: Vec<mt::Wire>,
- pub(crate) loops: Vec<LoopSamples>,
- pub(crate) outer: usize,
-}
-
-impl FaceLoops {
- /// The loops of `face`, its boundary found on its surface within `accept`; `what` names the
- /// operation for a surface no evaluator takes.
- pub(crate) fn of(face: &mt::Face, accept: f64, what: &str) -> Result<FaceLoops> {
- let eval = crate::tess::surface::eval_surface(&face.surface())
- .ok_or_else(|| KernelError::TooLarge(format!("{what} a face on this kind of surface")))?;
- let dom = uv::domain(&eval);
- let wires: Vec<mt::Wire> = face.absolute_boundaries().clone();
- let loops: Vec<LoopSamples> = wires.iter().map(|w| sample_loop(&eval, &dom, w, accept)).collect::<Result<_>>()?;
- // The outer loop encloses the others: the most area in parameters.
- let outer = loops
- .iter()
- .map(LoopSamples::area)
- .enumerate()
- .max_by(|a, b| a.1.abs().total_cmp(&b.1.abs()))
- .map(|(i, _)| i)
- .ok_or_else(|| KernelError::Invalid("the face has no boundary".into()))?;
- Ok(FaceLoops { eval, dom, wires, loops, outer })
- }
-}
-
-/// Sample a boundary loop (absolute: as it runs on the surface) in the surface's parameters.
-pub(crate) fn sample_loop(s: &EvalSurface, dom: &Domain, wire: &mt::Wire, accept: f64) -> Result<LoopSamples> {
- let mut edges = Vec::new();
- let mut prev: Option<[f64; 2]> = None;
- for e in wire.edge_iter() {
- let c = e.oriented_curve();
- let (t0, t1) = c.range_tuple();
- let mut samples = Vec::with_capacity(EDGE_SAMPLES + 1);
- for k in 0..=EDGE_SAMPLES {
- let t = t0 + (t1 - t0) * k as f64 / EDGE_SAMPLES as f64;
- let p = from_p3(c.subs(t));
- let q = parameters(s, dom, p, prev, accept)?;
- samples.push((t, p, q));
- prev = Some(q);
- }
- edges.push((c, samples));
- }
- Ok(LoopSamples { edges })
-}
-
-/// The parameters of `p` on the surface, unwrapped to lie near `near` along periodic directions.
-pub(crate) fn parameters(s: &EvalSurface, dom: &Domain, p: Vec3, near: Option<[f64; 2]>, accept: f64) -> Result<[f64; 2]> {
- let mut q = uv::project(s, dom, p, near, accept).ok_or_else(|| KernelError::Failed("the face's boundary does not lie on its surface".into()))?;
- if let Some(n) = near {
- for d in 0..2 {
- q[d] = uv::unwrap(q[d], n[d], dom.period[d]);
- }
- }
- Ok(q)
-}
-
-/// The parameter box the outer boundary is restored to: along each direction the surface's own
-/// range where it has one of its own (a free-form surface's; not a periodic or unbounded
-/// direction, and not an analytic surface's), else the face's own span.
-pub(crate) fn natural_span(s: &EvalSurface, dom: &Domain, outer: &LoopSamples, analytic: bool, accept: f64) -> Result<[(f64, f64); 2]> {
- let mut span = [(0.0, 0.0); 2];
- for (d, out) in span.iter_mut().enumerate() {
- *out = match (dom.range.get(d).copied().flatten(), dom.period.get(d).copied().flatten()) {
- (Some(range), None) if !analytic => range,
- (_, period) => {
- let lo = extreme(s, dom, outer, d, false, accept);
- let hi = extreme(s, dom, outer, d, true, accept);
- if let Some(p) = period
- && hi - lo >= p * (1.0 - 1e-9)
- {
- return Err(KernelError::TooLarge("a face that goes all the way round its surface".into()));
- }
- (lo, hi)
- }
- };
- if !(out.1 - out.0 > 1e-12 * (1.0 + out.0.abs() + out.1.abs())) || !out.0.is_finite() || !out.1.is_finite() {
- return Err(KernelError::Invalid("the face has no extent along its surface".into()));
- }
- }
- Ok(span)
-}
-
-/// The least (`max == false`) or greatest parameter along direction `d` the loop reaches: the
-/// extreme sample, then placed on its edge between the neighbouring samples. Samples where the
-/// surface does not move along `d` (a pole) say nothing about `d` and are passed over.
-pub(crate) fn extreme(s: &EvalSurface, dom: &Domain, lp: &LoopSamples, d: usize, max: bool, accept: f64) -> f64 {
- let sign = if max { 1.0 } else { -1.0 };
- let mut best: Option<(f64, usize, usize)> = None;
- for (ei, (_, samples)) in lp.edges.iter().enumerate() {
- for (k, (_, _, q)) in samples.iter().enumerate() {
- if uv::degenerate(s, *q, d) {
- continue;
- }
- let x = sign * q[d];
- if best.is_none_or(|(b, _, _)| x > b) {
- best = Some((x, ei, k));
- }
- }
- }
- let Some((x, ei, k)) = best else { return f64::NAN };
- let Some((curve, samples)) = lp.edges.get(ei) else { return sign * x };
- let (Some(at), Some(lo), Some(hi)) = (samples.get(k), samples.get(k.saturating_sub(1)), samples.get(k + 1).or(samples.get(k))) else {
- return sign * x;
- };
- // Golden-section search for the extreme between the neighbouring samples.
- let value = |t: f64| -> Option<f64> {
- let p = from_p3(curve.subs(t));
- let q = uv::project(s, dom, p, Some(at.2), accept)?;
- Some(sign * uv::unwrap(q[d], at.2[d], dom.period[d]))
- };
- let g = (5f64.sqrt() - 1.0) / 2.0;
- let (mut a, mut b) = (lo.0, hi.0);
- let mut best = x;
- for _ in 0..EXTREME_STEPS {
- let (c, e) = (b - g * (b - a), a + g * (b - a));
- let (Some(fc), Some(fe)) = (value(c), value(e)) else { break };
- best = best.max(fc).max(fe);
- if fc > fe {
- b = e;
- } else {
- a = c;
- }
- }
- sign * best
-}
-
-/// Whether the curve passes within `tol` of `p`.
-pub(crate) fn passes(curve: &mt::Curve, p: mt::Point3, tol: f64) -> bool {
- let (t0, t1) = curve.range_tuple();
- let start = (0..=64)
- .map(|k| t0 + (t1 - t0) * k as f64 / 64.0)
- .min_by(|a, b| curve.subs(*a).distance(p).total_cmp(&curve.subs(*b).distance(p)))
- .unwrap_or(t0);
- let t = curve.search_nearest_parameter(p, Some(start), 100).unwrap_or(start).clamp(t0.min(t1), t0.max(t1));
- curve.subs(t).distance(p) <= tol
-}
-
-/// The parameter line of `surface` at `w` (v = w when `along_u`, else u = w) from parameter
-/// `from` to `to` along it, exact: a line on a plane, a B-spline surface's iso-curve, and on a
-/// revolved surface the profile turned to its angle or an arc about the axis.
-pub(crate) fn iso_curve(surface: &mt::Surface, along_u: bool, w: f64, from: f64, to: f64) -> Result<mt::Curve> {
- let at = |t: f64| if along_u { surface.subs(t, w) } else { surface.subs(w, t) };
- match surface {
- mt::Surface::Plane(_) => Ok(mt::Curve::Line(mt::Line(at(from), at(to)))),
- mt::Surface::BSplineSurface(_) | mt::Surface::NurbsSurface(_) => {
- let hom: mt::BSplineSurface<mt::Vector4> = match surface {
- mt::Surface::BSplineSurface(b) => mt::BSplineSurface::new(
- b.knot_vecs().clone(),
- b.control_points().iter().map(|row| row.iter().map(|p| p.to_homogeneous()).collect()).collect(),
- ),
- mt::Surface::NurbsSurface(n) => n.non_rationalized().clone(),
- _ => return Err(KernelError::Failed("not a B-spline surface".into())),
- };
- let iso = crate::step_in::split::iso_bsp(&hom, w, along_u).map_err(KernelError::Failed)?;
- Ok(piece(mt::Curve::NurbsCurve(iso), from, to))
- }
- mt::Surface::RevolutedCurve(proc) => {
- let rev = proc.entity();
- // Truck's revolved surface is (profile parameter, angle), swapped when the processor
- // is turned over; the processor's matrix places it.
- let along_profile = along_u == proc.orientation();
- let transform = *proc.transform();
- let (origin, axis) = (rev.origin(), rev.axis().normalize());
- if along_profile {
- let profile = rev.entity_curve();
- if let mt::Curve::Line(_) = profile {
- return Ok(mt::Curve::Line(mt::Line(at(from), at(to))));
- }
- if let mt::Curve::IntersectionCurve(_) = profile {
- return Err(KernelError::TooLarge("untrimming a surface revolved from an intersection curve".into()));
- }
- let turn = mt::Matrix4::from_translation(origin - mt::Point3::new(0.0, 0.0, 0.0))
- * mt::Matrix4::from_axis_angle(axis, mt::Rad(w))
- * mt::Matrix4::from_translation(mt::Point3::new(0.0, 0.0, 0.0) - origin);
- Ok(piece(profile.transformed(transform * turn), from, to))
- } else {
- // The profile point at `w` turns about the axis: an arc from angle `from` to `to`.
- let p = rev.entity_curve().subs(w);
- let centre = origin + axis * (p - origin).dot(axis);
- let r = (p - centre).magnitude();
- if !(r > 1e-12) {
- return Err(KernelError::Failed("an arc on the axis of a revolved surface".into()));
- }
- let x = (p - centre) / r;
- let frame = crate::step_in::geom::Frame { o: centre, x, y: axis.cross(x), z: axis };
- let arc = if to > from {
- crate::step_in::geom::conic_arc(&frame, r, r, from, to - from)
- } else {
- crate::step_in::geom::conic_arc(&frame, r, r, to, from - to).inverse()
- };
- Ok(mt::Curve::NurbsCurve(arc).transformed(transform))
- }
- }
- }
-}
-
-/// The piece of `curve` between its parameters `from` and `to`, running from `from`.
-pub(crate) fn piece(mut curve: mt::Curve, from: f64, to: f64) -> mt::Curve {
- let (lo, hi) = if from < to { (from, to) } else { (to, from) };
- let (t0, t1) = curve.range_tuple();
- let eps = (t1 - t0).abs() * 1e-12;
- if lo > t0 + eps {
- curve = curve.cut(lo);
- }
- if hi < t1 - eps {
- let _ = curve.cut(hi);
- }
- if from > to {
- curve.invert();
- }
- curve
-}
diff --git a/crates/kernel/src/plane_fit.rs b/crates/kernel/src/plane_fit.rs
index f44b7f316b..1b6d68a731 100644
--- a/crates/kernel/src/plane_fit.rs
+++ b/crates/kernel/src/plane_fit.rs
@@ -1,40 +1,26 @@
//! Planes fitted to points around a loop (Newell's method), for planar faces of polygons read
-//! from files and for patches filling a planar loop of edges, and points sampled along edges
-//! (shared with the fill of a loop that is not planar).
+//! from files and for patches filling a planar loop of edges, and points sampled along record
+//! edges (shared with the fill of a loop that is not planar).
-use mt::{BoundedCurve, EuclideanSpace, InnerSpace, MetricSpace, ParametricCurve};
use solidcraft_geom::Vec3;
-use truck_modeling as mt;
+use solidcraft_geom::brep::eval::CurveEval;
+use solidcraft_geom::brep::{Brep, Curve, Edge, Surface};
-use crate::body::{from_p3, p3};
-use crate::{KernelError, Result};
+use crate::Result;
/// The plane through points round a loop: its normal by Newell's method (turning with the
-/// loop), through their centroid; `None` for fewer than three points or no area.
-pub(crate) fn plane_through(pts: &[mt::Point3]) -> Option<mt::Plane> {
- let n = pts.len();
- if n < 3 {
+/// loop, the plane's natural normal), through their centroid; `None` for fewer than three points
+/// or no area.
+pub(crate) fn plane_through(pts: &[Vec3]) -> Option<Surface> {
+ if pts.len() < 3 {
return None;
}
- let mut nrm = mt::Vector3::new(0.0, 0.0, 0.0);
- let mut c = mt::Vector3::new(0.0, 0.0, 0.0);
- for i in 0..n {
- let (a, b) = (pts.get(i)?, pts.get((i + 1) % n)?);
- nrm.x += (a.y - b.y) * (a.z + b.z);
- nrm.y += (a.z - b.z) * (a.x + b.x);
- nrm.z += (a.x - b.x) * (a.y + b.y);
- c += a.to_vec();
- }
- let len = nrm.magnitude();
- if !(len > 1e-12) {
- return None;
- }
- let z = nrm / len;
- let o = mt::Point3::from_vec(c / n as f64);
- let a = if z.x.abs() < 0.9 { mt::Vector3::unit_x() } else { mt::Vector3::unit_y() };
- let x = (a - z * a.dot(z)).normalize();
+ let z = loop_area(pts).normalized()?;
+ let o = pts.iter().fold(Vec3::ZERO, |a, p| a + *p) / pts.len() as f64;
+ let a = if z.x.abs() < 0.9 { Vec3::X } else { Vec3::Y };
+ let x = (a - z * a.dot(z)).normalized()?;
let y = z.cross(x);
- Some(mt::Plane::new(o, o + x, o + y))
+ Some(Surface::Plane { origin: [o.x, o.y, o.z], u_axis: [x.x, x.y, x.z], v_axis: [y.x, y.y, y.z] })
}
/// The area vector of a closed polygon (Newell's method): normal to the loop, as long as the area
@@ -48,97 +34,88 @@ pub(crate) fn loop_area(points: &[Vec3]) -> Vec3 {
n * 0.5
}
-/// The point of `c` at `t` (`None` where an intersection curve cannot find it).
-fn curve_point(c: &mt::Curve, t: f64) -> Option<Vec3> {
- let p = match c {
- mt::Curve::IntersectionCurve(ic) => ic.search_triple(t)?.0,
- other => other.subs(t),
- };
- let p = from_p3(p);
- p.is_finite().then_some(p)
-}
-
-/// Points along an edge, in its own direction, at `s ∈ [0, 1]` of its parameter range. An
-/// intersection curve's point is searched from the surface parameters of the point found before
-/// when that one is near (an eighth of the range), and kept only when it lies near the curve's
-/// leader (a seeded search can slide to another branch of the surfaces' intersection); else the
-/// unseeded search decides. `None` where no point is found.
+/// Points along a record edge, in the direction a loop runs along it, at `s ∈ [0, 1]` of its
+/// interval: the record curve's own points (an intersection curve traced as the record holds it).
pub(crate) struct EdgeSampler {
- curve: mt::Curve,
+ curve: CurveEval,
range: (f64, f64),
- hint: Option<(f64, mt::Point2, mt::Point2)>,
}
impl EdgeSampler {
- pub(crate) fn new(edge: &mt::Edge) -> Option<EdgeSampler> {
- let curve = edge.oriented_curve();
- let range = curve.range_tuple();
- (range.0.is_finite() && range.1.is_finite() && range.0 < range.1).then_some(EdgeSampler { curve, range, hint: None })
+ /// The sampler of `edge` run from its start (`forward`) or from its end.
+ pub(crate) fn new(edge: &Edge, forward: bool) -> Option<EdgeSampler> {
+ let [t0, t1] = edge.interval;
+ let curve = CurveEval::new(&edge.curve).ok()?;
+ (t0.is_finite() && t1.is_finite() && t0 < t1).then_some(EdgeSampler { curve, range: if forward { (t0, t1) } else { (t1, t0) } })
}
pub(crate) fn at(&mut self, s: f64) -> Option<Vec3> {
let (t0, t1) = self.range;
let t = if s >= 1.0 { t1 } else { t0 + (t1 - t0) * s };
- let mt::Curve::IntersectionCurve(ic) = &self.curve else { return curve_point(&self.curve, t) };
- let leader = ic.leader();
- let (p, d) = (leader.subs(t), leader.der(t));
- let near = |q: mt::Point3| q.distance(p) <= 4.0 * ic.tolerance() + 1e-6;
- let seeded = self
- .hint
- .filter(|(tp, _, _)| (t - tp).abs() <= (t1 - t0) / 8.0)
- .and_then(|(_, a, b)| mt::double_projection(ic.surface0(), Some((a.x, a.y)), ic.surface1(), Some((b.x, b.y)), p, d, 100))
- .filter(|f| near(f.0));
- let found = seeded.or_else(|| mt::double_projection(ic.surface0(), None, ic.surface1(), None, p, d, 100))?;
- self.hint = Some((t, found.1, found.2));
- let q = from_p3(found.0);
- q.is_finite().then_some(q)
+ self.curve.point(t).filter(|p| p.is_finite())
}
}
-/// The planar face bounded by the closed loop `chain` (each edge oriented along it) when its
-/// edges are certainly in one plane, `None` otherwise (also when an edge cannot be sampled).
-/// The plane is fitted to points along the edges ([`plane_through`], the normal turning with the
-/// loop); the edges are certified within `tol` of it conservatively: a line by its ends, a
-/// B-spline or NURBS curve with positive weights by its control points (the curve lies in their
-/// convex hull), an intersection curve only when one of its two surfaces is a plane that the
-/// loop's points lie on and the fitted plane agrees with over the loop (the curve lies in that
-/// plane). Samples alone are never trusted: a spline can bulge out of the plane between them.
-pub(crate) fn planar_face(chain: &[mt::Edge], tol: f64) -> Result<Option<mt::Face>> {
+/// The plane of the closed loop `chain` of edges of `b` (each with the way the loop runs along
+/// it) when its edges are certainly in one plane, `None` otherwise (also when an edge cannot be
+/// sampled). The plane is fitted to points along the edges ([`plane_through`], its natural normal
+/// turning with the loop); the edges are certified within `tol` of it from their records: a line
+/// by its ends, a circle or ellipse by its frame, a polyline, B-spline or NURBS curve with
+/// positive weights by its points (the curve lies in their convex hull), an intersection curve
+/// only when one of its two surfaces is a plane that the loop's points lie on (the curve lies in
+/// that plane). Samples alone are never trusted: a spline can bulge out of the plane between them.
+pub(crate) fn planar_face(b: &Brep, chain: &[(u32, bool)], tol: f64) -> Result<Option<Surface>> {
const SAMPLES: usize = 16;
+ let edges: Vec<&Edge> = match chain.iter().map(|(e, _)| b.edges.get(*e as usize)).collect::<Option<_>>() {
+ Some(e) => e,
+ None => return Ok(None),
+ };
let mut pts = Vec::with_capacity(chain.len() * SAMPLES);
- for e in chain {
- let Some(mut sampler) = EdgeSampler::new(e) else { return Ok(None) };
+ for (e, (_, forward)) in edges.iter().zip(chain) {
+ let Some(mut sampler) = EdgeSampler::new(e, *forward) else { return Ok(None) };
for k in 0..SAMPLES {
let Some(p) = sampler.at(k as f64 / SAMPLES as f64) else { return Ok(None) };
- pts.push(p3(p));
+ pts.push(p);
}
}
let Some(plane) = plane_through(&pts) else { return Ok(None) };
- let (o, n) = (plane.origin(), plane.normal());
- let off = |p: mt::Point3, o: mt::Point3, n: mt::Vector3| (p - o).dot(n).abs();
- let on_plane = |p: mt::Point3| off(p, o, n) <= tol;
+ let Some((o, n)) = plane_frame(&plane) else { return Ok(None) };
+ let on = |p: Vec3, o: Vec3, n: Vec3| (p - o).dot(n).abs() <= tol;
+ let on_plane = |p: Vec3| on(p, o, n);
if !pts.iter().all(|p| on_plane(*p)) {
return Ok(None);
}
- // A support plane `q` of an intersection curve holds the loop when the loop's points lie on
- // it and their feet on the fitted plane do too.
- let holds = |q: &mt::Plane| {
- let (qo, qn) = (q.origin(), q.normal());
- pts.iter().all(|p| off(*p, qo, qn) <= tol && off(*p - n * (*p - o).dot(n), qo, qn) <= tol)
- };
- for e in chain {
- let certified = match e.curve() {
- mt::Curve::Line(l) => on_plane(l.0) && on_plane(l.1),
- mt::Curve::BSplineCurve(b) => b.control_points().iter().all(|p| on_plane(*p)),
- mt::Curve::NurbsCurve(c) => {
- c.non_rationalized().control_points().iter().all(|h| h.w > 0.0 && on_plane(mt::Point3::new(h.x / h.w, h.y / h.w, h.z / h.w)))
+ for e in &edges {
+ let certified = match &e.curve {
+ Curve::Line { start, end } => on_plane(Vec3::from(*start)) && on_plane(Vec3::from(*end)),
+ Curve::Circle { frame, .. } | Curve::Ellipse { frame, .. } => {
+ let z = Vec3::from(frame.x_axis).cross(Vec3::from(frame.y_axis));
+ on_plane(Vec3::from(frame.origin)) && z.cross(n).len() <= 1e-9
+ }
+ Curve::Polyline { points } | Curve::Spline { points, .. } => points.iter().all(|p| on_plane(Vec3::from(*p))),
+ Curve::RationalSpline { homogeneous, .. } => {
+ homogeneous.iter().all(|h| h[3] > 0.0 && on_plane(Vec3::new(h[0] / h[3], h[1] / h[3], h[2] / h[3])))
+ }
+ // A support plane holds the loop when the loop's points lie on it.
+ Curve::SurfaceIntersection { surfaces, .. } => {
+ surfaces.iter().filter_map(|s| plane_frame(s)).any(|(qo, qn)| pts.iter().all(|p| on(*p, qo, qn)))
}
- mt::Curve::IntersectionCurve(ic) => [ic.surface0(), ic.surface1()].into_iter().any(|s| matches!(s, mt::Surface::Plane(q) if holds(q))),
};
if !certified {
return Ok(None);
}
}
- let wire: mt::Wire = chain.to_vec().into();
- Ok(Some(mt::Face::try_new(vec![wire], mt::Surface::Plane(plane)).map_err(|e| KernelError::Failed(format!("patch: {e}")))?))
+ Ok(Some(plane))
+}
+
+/// A plane record's origin and unit normal (`None` for any other surface).
+fn plane_frame(s: &Surface) -> Option<(Vec3, Vec3)> {
+ match s {
+ Surface::Plane { origin, u_axis, v_axis } => Some((Vec3::from(*origin), Vec3::from(*u_axis).cross(Vec3::from(*v_axis)).normalized()?)),
+ Surface::PlaneThrough { origin, u_point, v_point } => {
+ let o = Vec3::from(*origin);
+ Some((o, (Vec3::from(*u_point) - o).cross(Vec3::from(*v_point) - o).normalized()?))
+ }
+ _ => None,
+ }
}
diff --git a/crates/kernel/src/spline_conv.rs b/crates/kernel/src/spline_conv.rs
index 01b8703544..e034d9f269 100644
--- a/crates/kernel/src/spline_conv.rs
+++ b/crates/kernel/src/spline_conv.rs
@@ -1,64 +1,81 @@
-//! geom's B-spline curves and surfaces as truck's NURBS geometry, weights kept (homogeneous
-//! control points carried over as they are).
+//! geom's B-spline curves and surfaces as schema 4 records, weights kept (homogeneous control
+//! points carried over as they are), and a whole tensor surface as a one-face sheet.
+use solidcraft_geom::Vec3;
+use solidcraft_geom::brep::{Curve, Curve2, Surface};
use solidcraft_geom::bspline::{HPoint, NurbsSurface};
-use truck_modeling as mt;
-use crate::body::p3;
+use crate::assemble::{AFace, AUse, Assembly};
+use crate::body::Body;
use crate::{KernelError, Result};
fn fail(m: impl std::fmt::Display) -> KernelError {
KernelError::Failed(format!("spline geometry: {m}"))
}
-/// A homogeneous control point as truck's.
-pub(crate) fn h4(h: HPoint) -> mt::Vector4 {
- mt::Vector4::new(h.x, h.y, h.z, h.w)
+/// A homogeneous control point as the record's `[x*w, y*w, z*w, w]`.
+pub(crate) fn h4(h: HPoint) -> [f64; 4] {
+ [h.x, h.y, h.z, h.w]
}
/// A NURBS curve of knots and homogeneous control points.
-pub(crate) fn nurbs_curve(knots: mt::KnotVec, ctrl: &[HPoint]) -> Result<mt::Curve> {
- let c = mt::BSplineCurve::try_new(knots, ctrl.iter().copied().map(h4).collect()).map_err(fail)?;
- Ok(mt::Curve::NurbsCurve(mt::NurbsCurve::new(c)))
+pub(crate) fn nurbs_curve(knots: &[f64], ctrl: &[HPoint]) -> Curve {
+ Curve::RationalSpline { knots: knots.to_vec(), homogeneous: ctrl.iter().copied().map(h4).collect() }
}
/// A NURBS surface of knots and homogeneous control points (`rows[i][j]`: i along u).
-pub(crate) fn nurbs_surface(knots: (mt::KnotVec, mt::KnotVec), rows: Vec<Vec<mt::Vector4>>) -> Result<mt::Surface> {
- let s = mt::BSplineSurface::try_new(knots, rows).map_err(fail)?;
- Ok(mt::Surface::NurbsSurface(mt::NurbsSurface::new(s)))
+pub(crate) fn nurbs_surface(u_knots: &[f64], v_knots: &[f64], rows: Vec<Vec<[f64; 4]>>) -> Surface {
+ Surface::RationalSpline { u_knots: u_knots.to_vec(), v_knots: v_knots.to_vec(), homogeneous: rows }
}
-/// geom's tensor surface as truck's.
-pub(crate) fn surface(s: &NurbsSurface) -> Result<mt::Surface> {
+/// geom's tensor surface as a record surface.
+pub(crate) fn surface(s: &NurbsSurface) -> Surface {
let [nu, nv] = s.count();
let [ku, kv] = s.knots();
- let rows: Vec<Vec<mt::Vector4>> = (0..nu).map(|i| (0..nv).map(|j| h4(s.point(i, j))).collect()).collect();
- nurbs_surface((mt::KnotVec::from(ku.clone()), mt::KnotVec::from(kv.clone())), rows)
+ nurbs_surface(ku, kv, (0..nu).map(|i| (0..nv).map(|j| h4(s.point(i, j))).collect()).collect())
}
-/// One face of a whole tensor surface: its four boundary curves as edges, sharing the corners.
-/// This is what a patch built as a single control net (`bridge`, `boundary`, the T-spline sheet)
-/// hands to the B-rep.
-pub(crate) fn tensor_face(s: &NurbsSurface) -> Result<mt::Face> {
+/// The active interval `[knots[degree], knots[count]]` of a direction with `count` points.
+fn active(knots: &[f64], count: usize) -> Result<[f64; 2]> {
+ let degree = knots.len().checked_sub(count + 1).ok_or_else(|| fail("knots and points disagree"))?;
+ match (knots.get(degree), knots.get(count)) {
+ (Some(a), Some(b)) if a < b => Ok([*a, *b]),
+ _ => Err(fail("an empty knot interval")),
+ }
+}
+
+/// One face of a whole tensor surface as a sheet: its four boundary curves (the net's first and
+/// last rows and columns) as edges sharing the corners, each with its exact pcurve (an edge's
+/// parameter is the surface's along it). This is what a patch built as a single control net
+/// (`bridge`, `boundary`, the T-spline sheet) hands to the B-rep.
+pub(crate) fn tensor_face(s: &NurbsSurface) -> Result<Body> {
let [nu, nv] = s.count();
if nu < 2 || nv < 2 {
return Err(fail("a face needs at least 2 x 2 control points"));
}
let [ku, kv] = s.knots();
+ let ([u0, u1], [v0, v1]) = (active(ku, nu)?, active(kv, nv)?);
let corners = [s.point(0, 0), s.point(nu - 1, 0), s.point(nu - 1, nv - 1), s.point(0, nv - 1)];
- let mut v: Vec<mt::Vertex> = Vec::with_capacity(4);
- for c in corners {
- let p = c.project().ok_or_else(|| fail("a corner has no position"))?;
- v.push(mt::builder::vertex(p3(p)));
- }
+ let corners: Vec<Vec3> = corners.iter().map(|c| c.project().ok_or_else(|| fail("a corner has no position"))).collect::<Result<_>>()?;
+ let diag = corners.iter().flat_map(|a| corners.iter().map(move |b| a.dist(*b))).fold(0.0, f64::max);
+ let mut asm = Assembly::sheet((diag * 1e-7).max(1e-9));
+ let v: Vec<u32> = corners.iter().map(|p| asm.vertex(*p)).collect::<Result<_>>()?;
+ let (Some(&a), Some(&b), Some(&c), Some(&d)) = (v.first(), v.get(1), v.get(2), v.get(3)) else { return Err(fail("corners")) };
let row = |j: usize| -> Vec<HPoint> { (0..nu).map(|i| s.point(i, j)).collect() };
let column = |i: usize| -> Vec<HPoint> { (0..nv).map(|j| s.point(i, j)).collect() };
- let (Some(v0), Some(v1), Some(v2), Some(v3)) = (v.first(), v.get(1), v.get(2), v.get(3)) else { return Err(fail("corners")) };
- let edge = |a: &mt::Vertex, b: &mt::Vertex, c: mt::Curve| mt::Edge::try_new(a, b, c).map_err(fail);
- let bottom = edge(v0, v1, nurbs_curve(mt::KnotVec::from(ku.clone()), &row(0))?)?;
- let right = edge(v1, v2, nurbs_curve(mt::KnotVec::from(kv.clone()), &column(nu - 1))?)?;
- let top = edge(v3, v2, nurbs_curve(mt::KnotVec::from(ku.clone()), &row(nv - 1))?)?;
- let left = edge(v0, v3, nurbs_curve(mt::KnotVec::from(kv.clone()), &column(0))?)?;
- let wire: mt::Wire = vec![bottom, right, top.inverse(), left.inverse()].into();
- mt::Face::try_new(vec![wire], surface(s)?).map_err(fail)
+ let line = |t: [f64; 2], p: [f64; 2], q: [f64; 2]| Curve2::Spline { knots: vec![t[0], t[0], t[1], t[1]], points: vec![p, q] };
+ // Bottom (v0) and top (v1) run along u, right (u1) and left (u0) along v, each from its
+ // lower corner; the loop runs counter-clockwise in (u, v).
+ let bottom = asm.edge(nurbs_curve(ku, &row(0)), [u0, u1], a, b)?;
+ let right = asm.edge(nurbs_curve(kv, &column(nu - 1)), [v0, v1], b, c)?;
+ let top = asm.edge(nurbs_curve(ku, &row(nv - 1)), [u0, u1], d, c)?;
+ let left = asm.edge(nurbs_curve(kv, &column(0)), [v0, v1], a, d)?;
+ let loop_ = vec![
+ AUse { edge: bottom, forward: true, given: Some(line([u0, u1], [u0, v0], [u1, v0])) },
+ AUse { edge: right, forward: true, given: Some(line([v0, v1], [u1, v0], [u1, v1])) },
+ AUse { edge: top, forward: false, given: Some(line([u0, u1], [u0, v1], [u1, v1])) },
+ AUse { edge: left, forward: false, given: Some(line([v0, v1], [u0, v0], [u0, v1])) },
+ ];
+ asm.face(AFace { surface: surface(s), natural_out: true, loops: vec![loop_], shell: 0, domain: Some([[u0, u1], [v0, v1]]) });
+ Body::from_record(asm.finish()?.record)
}