Wave 174/509: kernel: surface sweeps mitre at corners, as the solid sweep does (and 1 more)

2 commits, squashed; the originals stay reachable from tag archive/merge-main-develop.

- 30b02cdfa jyviko: kernel: the solid loft's rails anchored by loft_rails::railed; path curves shared
- 0d611ed84 jyviko: kernel: surface sweeps mitre at corners, as the solid sweep does

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ
This commit is contained in:
jyviko
2026-10-22 07:26:30 -04:00
parent 6d9703c97c
commit 2e39a45145
2 changed files with 256 additions and 360 deletions
+27 -267
View File
@@ -71,7 +71,9 @@ pub(crate) struct Draft {
}
#[cfg(feature = "smlib")]
pub(crate) use imp::{body_from_record, curve, extrude, loft, loft_rails, loft_to_point, revolve, screw, sphere, sweep, sweep_controlled};
pub(crate) use imp::{
body_from_record, curve, extrude, loft, loft_rails, loft_to_point, path_curve, revolve, screw, sphere, sweep, sweep_controlled,
};
/// The error of an SMLib operation in a build without SMLib.
#[cfg(not(feature = "smlib"))]
@@ -478,7 +480,8 @@ mod imp {
with_history(body, &roles, &walls)
}
fn path_curve(s: &crate::PathSeg) -> Result<Curve> {
/// A path segment as SMLib's curve, exactly.
pub(crate) fn path_curve(s: &crate::PathSeg) -> Result<Curve> {
Ok(match *s {
crate::PathSeg::Line { a, b } => Curve::Line { start: p(a), end: p(b) },
crate::PathSeg::Arc { a, center, axis, angle } => {
@@ -894,278 +897,35 @@ mod imp {
with_history(body, &roles, &columns)
}
/// A curve as a NURBS net: degree, control points (x, y, z) and weights, clamped knots. A line
/// is of degree 1; an arc is rational quadratic, one span per quarter turn or less.
struct Net {
degree: usize,
points: Vec<Vec3>,
weights: Vec<f64>,
knots: Vec<f64>,
}
impl Net {
fn of(c: &Curve) -> Option<Net> {
let v = |q: [f64; 3]| Vec3::new(q[0], q[1], q[2]);
Some(match c {
Curve::Line { start, end } => {
Net { degree: 1, points: vec![v(*start), v(*end)], weights: vec![1.0; 2], knots: vec![0.0, 0.0, 1.0, 1.0] }
}
Curve::Arc { center, axis, reference, radius, start, end } => {
let (c, k, x) = (v(*center), v(*axis), v(*reference));
let y = k.cross(x);
let sweep = end - start;
let m = (sweep / (std::f64::consts::PI / 2.0) - 1e-9).ceil().max(1.0) as usize;
let d = sweep / m as f64;
let at = |a: f64, r: f64| c + (x * a.cos() + y * a.sin()) * r;
let (mut points, 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;
points.push(at(a0 + d / 2.0, radius / (d / 2.0).cos()));
weights.push((d / 2.0).cos());
points.push(at(a0 + d, *radius));
weights.push(1.0);
let u = (j + 1) as f64 / m as f64;
knots.extend(if j + 1 < m { vec![u, u] } else { vec![1.0; 3] });
}
Net { degree: 2, points, weights, knots }
}
Curve::Nurbs { degree, points, knots } => Net {
degree: *degree,
points: points.iter().map(|q| Vec3::new(q[0], q[1], q[2])).collect(),
weights: points.iter().map(|q| q[3]).collect(),
knots: knots.clone(),
},
})
}
/// The same curve with other control points.
fn with(&self, points: Vec<Vec3>) -> Net {
Net { degree: self.degree, points, weights: self.weights.clone(), knots: self.knots.clone() }
}
/// Whether `o` has the same degree, knots and weights (its control points pair up).
fn pairs_with(&self, o: &Net) -> bool {
let near = |a: &[f64], b: &[f64]| a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() <= 1e-9 * (1.0 + x.abs()));
self.degree == o.degree && self.points.len() == o.points.len() && near(&self.knots, &o.knots) && near(&self.weights, &o.weights)
}
fn curve(&self) -> Curve {
let points = self.points.iter().zip(&self.weights).map(|(q, w)| [q.x, q.y, q.z, *w]).collect();
Curve::Nurbs { degree: self.degree, points, knots: self.knots.clone() }
}
/// The point `f` (0…1) of the way along the parameter range.
fn at(&self, f: f64) -> Option<Vec3> {
let ctrl = self.points.iter().zip(&self.weights).map(|(q, w)| [q.x * w, q.y * w, q.z * w, *w]).collect();
let c = solidcraft_geom::bspline::CurveN::<4> { degree: self.degree, knots: self.knots.clone(), ctrl };
let (t0, t1) = (*self.knots.first()?, *self.knots.last()?);
let ([x, y, z, w], _) = c.eval(t0 + (t1 - t0) * f.clamp(0.0, 1.0))?;
(w.abs() > 1e-300).then(|| Vec3::new(x / w, y / w, z / w))
}
}
/// The point of a section (its curves' nets) nearest `p`: as a wire parameter (the curve's
/// index plus how far along its parameter range), the point, and how far it is.
fn nearest_on(section: &[Net], p: Vec3) -> Option<(f64, Vec3, f64)> {
const SAMPLES: usize = 256;
let mut best: Option<(f64, Vec3, f64)> = None;
for (k, c) in section.iter().enumerate() {
let d = |f: f64| c.at(f).map_or(f64::INFINITY, |q| q.dist(p));
let Some(i) = (0..=SAMPLES).min_by(|a, b| d(*a as f64 / SAMPLES as f64).total_cmp(&d(*b as f64 / SAMPLES as f64))) else { continue };
// Golden-section search about the nearest sample.
let (mut lo, mut hi) = ((i as f64 - 1.0).max(0.0) / SAMPLES as f64, (i as f64 + 1.0).min(SAMPLES as f64) / SAMPLES as f64);
let g = 0.5 * (5f64.sqrt() - 1.0);
for _ in 0..80 {
let (a, b) = (hi - g * (hi - lo), lo + g * (hi - lo));
if d(a) < d(b) {
hi = b;
} else {
lo = a;
}
}
let f = 0.5 * (lo + hi);
let q = c.at(f)?;
if best.as_ref().is_none_or(|b| q.dist(p) < b.2) {
best = Some((k as f64 + f, q, q.dist(p)));
}
}
best
}
/// The point at wire parameter `g` of a section.
fn wire_point(section: &[Net], g: f64) -> Result<Vec3> {
let k = (g.floor().max(0.0) as usize).min(section.len().saturating_sub(1));
section.get(k).and_then(|c| c.at(g - k as f64)).ok_or_else(|| KernelError::Failed("loft rails: section".into()))
}
fn centroid(section: &[Net]) -> Vec3 {
let (sum, n) = section.iter().flat_map(|c| &c.points).fold((Vec3::ZERO, 0usize), |(s, n), q| (s + *q, n + 1));
sum * (1.0 / n.max(1) as f64)
}
/// A loft through `sections` (as [`loft`] takes them) guided by one or two `rails` (polylines
/// from the first section to the last, through every section's curve), by the law
/// [`crate::loft_rails`] gives a loft's rails: between each two sections stations are the
/// plain loft there (the sections' control points straight between two, the cubic through
/// them across more) moved so that the points the rails guide land on the rails. Each section
/// curve has to pair with the others' (the same kind, so their control points pair up).
/// [`crate::loft_rails::railed`] gives a loft's rails: between each two sections stations are
/// the plain loft there moved so that the points the rails guide land on the rails. Each
/// section curve has to pair with the others' (the same kind, so their control points pair
/// up).
pub(crate) fn loft_rails(sections: &[(Plane, Vec<Piece>)], first: usize, rails: &[Vec<Vec3>], fit: crate::RailFit) -> Result<Body> {
if rails.is_empty() || rails.len() > 2 {
return Err(KernelError::Invalid("a loft takes one or two guide rails".into()));
}
let fail = |m: &str| KernelError::Failed(format!("loft rails: {m}"));
let count = sections.len();
if count < 2 {
return Err(fail("sections"));
}
let curves: Vec<Vec<Curve>> = sections.iter().map(|(pl, ps)| curves(pl, ps)).collect::<Result<_>>()?;
let nets: Vec<Vec<Net>> = curves
let matched = sections
.iter()
.map(|cs| cs.iter().map(Net::of).collect::<Option<Vec<_>>>())
.collect::<Option<_>>()
.ok_or_else(|| fail("section curves"))?;
let lead = nets.first().ok_or_else(|| fail("sections"))?;
let n = lead.len();
if n == 0 || nets.iter().any(|s| s.len() != n || s.iter().zip(lead).any(|(a, b)| !a.pairs_with(b))) {
return Err(refuse("loft along guide rails between sections whose curves differ in kind (a line against an arc)"));
}
let mut bounds = solidcraft_geom::Aabb3::EMPTY;
for q in nets.iter().flatten().flat_map(|c| &c.points) {
bounds.add(*q);
}
let size = bounds.diagonal();
let tol = (size * 1e-4).max(1e-6);
// The sections' parameters along the loft: in proportion to the mean distance between
// their curves' starts.
let mut along = vec![0.0];
for w in nets.windows(2) {
let step = w[0].iter().zip(&w[1]).filter_map(|(a, b)| Some(a.points.first()?.dist(*b.points.first()?))).sum::<f64>() / n as f64;
along.push(along.last().copied().unwrap_or(0.0) + step);
}
let total = along.last().copied().unwrap_or(0.0);
if !(total > 1e-9) || along.windows(2).any(|w| !(w[1] - w[0] > 1e-9 * total)) {
return Err(KernelError::Invalid("two loft sections sit on top of each other".into()));
}
along.iter_mut().for_each(|u| *u /= total);
// The plain loft at v: each control point straight between two sections, the cubic (or
// quadratic) through them across more.
let degree_across = (count - 1).min(3);
let across: Vec<Vec<solidcraft_geom::bspline::CurveN<3>>> = if count == 2 {
Vec::new()
} else {
(0..n)
.map(|k| {
(0..lead.get(k).map_or(0, |c| c.points.len()))
.map(|j| {
let pts: Vec<[f64; 3]> = nets.iter().filter_map(|s| s.get(k)?.points.get(j).map(|q| [q.x, q.y, q.z])).collect();
solidcraft_geom::bspline::CurveN::interpolate(&along, &pts, degree_across).map_err(|e| fail(&e.to_string()))
})
.collect::<Result<Vec<_>>>()
})
.collect::<Result<_>>()?
};
let plain = |v: f64| -> Result<Vec<Net>> {
let (Some(a), Some(b)) = (nets.first(), nets.last()) else { return Err(fail("sections")) };
if count == 2 {
return Ok(a.iter().zip(b).map(|(ca, cb)| ca.with(ca.points.iter().zip(&cb.points).map(|(p, q)| p.lerp(*q, v)).collect())).collect());
}
a.iter()
.zip(&across)
.map(|(c, cs)| {
let pts = cs.iter().map(|x| x.eval(v).map(|([px, py, pz], _)| Vec3::new(px, py, pz))).collect::<Option<Vec<_>>>();
pts.map(|p| c.with(p)).ok_or_else(|| fail("the plain loft"))
})
.collect()
};
// The plain loft's middle and its direction there.
let middle = |v: f64| -> Result<(Vec3, Vec3)> {
let h = 1e-4;
let (a, b) = ((v - h).max(0.0), (v + h).min(1.0));
let d = centroid(&plain(b)?) - centroid(&plain(a)?);
let d = d.normalized().ok_or_else(|| KernelError::Invalid("two loft sections sit on top of each other".into()))?;
Ok((centroid(&plain(v)?), d))
};
// Each rail from its end nearer the first section's middle, and where it meets each
// section: the guided point (wire parameter), that point, the nudge onto it from the
// crossing, and how far along the rail the crossing is.
let start = centroid(lead);
type Anchor = (f64, Vec3, Vec3, (usize, f64));
let mut guided: Vec<(Vec<Vec3>, Vec<Anchor>)> = Vec::with_capacity(rails.len());
for r in rails {
let mut pts =
crate::sweep_path::clean(r).map_err(|_| KernelError::Invalid("a guide rail needs 2…100000 finite points along its length".into()))?;
if let (Some(a), Some(b)) = (pts.first(), pts.last())
&& b.dist(start) < a.dist(start)
{
pts.reverse();
}
let mut cursor = (0usize, 0.0f64);
let mut anchors = Vec::with_capacity(count);
for (i, ((plane, _), section)) in sections.iter().zip(&nets).enumerate() {
let Some((hit, at)) = crate::sweep_path::rail_crossing(&pts, plane.origin, plane.normal(), cursor, tol) else {
return Err(KernelError::Invalid(format!(
"a guide rail does not reach section {}: a rail has to run from the first section to the last, through every one",
i + 1
)));
};
cursor = at;
let (g, on, d) = nearest_on(section, hit).ok_or_else(|| fail("section"))?;
if d > tol {
return Err(KernelError::Invalid(format!(
"a guide rail crosses section {}'s plane {d:.3} mm from its curves: a rail has to pass through every section",
i + 1
)));
}
anchors.push((g, on, on - hit, at));
}
guided.push((pts, anchors));
}
if let [a, b] = &guided[..]
&& a.1.iter().zip(&b.1).any(|(p, q)| p.1.dist(q.1) <= tol)
{
return Err(KernelError::Invalid("the two guide rails meet a section at the same point".into()));
}
// The sections' normals, turned to agree with the first's.
let mut normals: Vec<Vec3> = Vec::with_capacity(count);
for (p, _) in sections {
let nn = p.normal();
let prev = normals.last().copied().unwrap_or(nn);
normals.push(if nn.dot(prev) < 0.0 { nn * -1.0 } else { nn });
}
let spans = count - 1;
let per = (crate::loft_rails::MAX_WIRES.saturating_sub(count) / spans).clamp(1, crate::loft_rails::MAX_PER_SPAN);
let mut all: Vec<Vec<Curve>> = Vec::with_capacity(count + spans * per);
for i in 0..spans {
all.push(nets.get(i).ok_or_else(|| fail("sections"))?.iter().map(Net::curve).collect());
let (Some(&v0), Some(&v1), Some(&n0), Some(&n1)) = (along.get(i), along.get(i + 1), normals.get(i), normals.get(i + 1)) else {
return Err(fail("sections"));
};
let mut cursors: Vec<(usize, f64)> = guided.iter().map(|(_, a)| a.get(i).map_or((0, 0.0), |x| x.3)).collect();
for q in 1..=per {
let f = q as f64 / (per + 1) as f64;
let v = v0 + f * (v1 - v0);
let station = plain(v)?;
let (mid, dir) = middle(v)?;
let normal = n0.lerp(n1, f).normalized().ok_or_else(|| fail("section planes"))?;
let mut pairs = Vec::with_capacity(guided.len());
for ((pts, anchors), cursor) in guided.iter().zip(cursors.iter_mut()) {
let (Some(a0), Some(a1)) = (anchors.get(i), anchors.get(i + 1)) else { return Err(fail("rail")) };
let anchor = wire_point(&station, crate::loft_rails::interpolate_g(a0.0, a1.0, f, n, true))?;
let Some((hit, at)) = crate::sweep_path::rail_crossing(pts, anchor, normal, *cursor, tol) else {
return Err(KernelError::Invalid(format!(
"a guide rail turns back between sections {} and {}: it has to run on from one section to the next",
i + 1,
i + 2
)));
};
*cursor = at;
pairs.push((anchor, hit + a0.2 * (1.0 - f) + a1.2 * f));
}
let map = crate::loft_rails::station_map(&pairs, mid, dir, fit, size)?;
all.push(station.iter().map(|c| c.with(c.points.iter().map(|q| map.apply(*q)).collect()).curve()).collect());
}
}
all.push(nets.last().ok_or_else(|| fail("sections"))?.iter().map(Net::curve).collect());
.map(|(pl, ps)| {
let segs: Vec<Seg2> = ps.iter().map(|x| x.seg).collect();
crate::loft_rails::Section::of(pl, &segs, ps.iter().map(|x| x.numbers.clone()).collect())
})
.collect::<Result<Vec<_>>>()?;
let all: Vec<Vec<Curve>> = crate::loft_rails::railed(&matched, true, rails, fit)?
.iter()
.map(|section| {
section
.iter()
.map(|c| {
let points = c.ctrl.iter().map(|h| [h[0] / h[3], h[1] / h[3], h[2] / h[3], h[3]]).collect();
Curve::Nurbs { degree: c.degree, points, knots: c.knots.clone() }
})
.collect()
})
.collect();
loft_through(sections, first, &all, 3)
}
+229 -93
View File
@@ -1023,8 +1023,8 @@ pub fn revolve_sheet(plane: &Plane, chains: &[Vec<Seg2>], axis_origin: Vec2, axi
/// A surface swept from chains of sketch segments on `plane` along a path that starts near them,
/// turning with it (SMLib's curve sweep: along lines an extrusion, round arcs about one axis a
/// revolution, exactly). A path whose direction jumps at a joint (a corner) is not supported yet.
/// The walls form one surface body with no caps; its history has no operands: every face is new.
/// revolution, exactly); at a corner the walls meet in a mitre, as the solid sweep's do. The
/// walls form one surface body with no caps; its history has no operands: every face is new.
pub fn sweep_sheet(plane: &Plane, chains: &[Vec<Seg2>], path: &[crate::PathSeg]) -> Result<Body> {
sweep_sheet_with(plane, chains, path, &crate::SweepControl::default())
}
@@ -1041,20 +1041,40 @@ pub fn sweep_sheet_with(plane: &Plane, chains: &[Vec<Seg2>], path: &[crate::Path
if path.is_empty() || path.len() > 1000 {
return Err(invalid("the path needs 1…1000 segments"));
}
let runs = smooth_runs(path)?;
let controlled = ctl.varies() || matches!(ctl.orientation, crate::SweepOrientation::Direction(_));
if controlled && runs.len() > 1 {
return Err(imp::refuse("sweep with a twist, an end scale, guide rails or an orientation direction along a path with corners"));
}
let translate = ctl.orientation == crate::SweepOrientation::Parallel;
let mut pieces = Vec::with_capacity(chains.len());
for chain in numbered(chains) {
if runs.len() > 1 {
pieces.extend(imp::cornered(plane, &chain, path, &runs, translate)?);
continue;
}
let r = if controlled { imp::swept_stations(plane, &chain, path, ctl)? } else { imp::swept(plane, &chain, path, translate)? };
let h = swept_from(&r, plane, &chain);
pieces.push((r, h));
}
sheet_of(pieces, runs.len() > 1)
}
/// The path's segments in runs along which its direction carries on (within a thousandth of a
/// radian across each joint): a new run starts at each corner.
fn smooth_runs(path: &[crate::PathSeg]) -> Result<Vec<std::ops::Range<usize>>> {
let ends: Vec<(Vec3, Vec3)> =
path.iter().map(crate::PathSeg::tangents).collect::<Option<_>>().ok_or_else(|| invalid("a path segment has no direction"))?;
if ends.windows(2).any(|w| w[0].1.dot(w[1].0) < (1e-3f64).cos()) {
return Err(imp::refuse("surface sweep along a path with corners"));
let mut runs = Vec::new();
let mut from = 0;
for (i, w) in ends.windows(2).enumerate() {
if w[0].1.dot(w[1].0) < (1e-3f64).cos() {
runs.push(from..i + 1);
from = i + 1;
}
}
let pieces = numbered(chains)
.into_iter()
.map(|chain| {
let r = if ctl.is_default() { imp::swept(plane, &chain, path)? } else { imp::swept_stations(plane, &chain, path, ctl)? };
let h = swept_from(&r, plane, &chain);
Ok((r, h))
})
.collect::<Result<Vec<_>>>()?;
sheet_of(pieces, false)
runs.push(from..path.len());
Ok(runs)
}
/// A surface swept from chains of sketch segments on `plane` along a 3D polyline path: along the
@@ -1232,40 +1252,8 @@ mod imp {
checked(&sheet.offset_sheet(d).map_err(sm("offset"))?, "offset")
}
/// A sketch segment on `plane` as SMLib's curve: an arc as SMLib's own circle, anything else
/// as its exact record curve.
fn curve(plane: &Plane, s: &Seg2) -> Result<Curve> {
if let Seg2::Arc { center, radius, start, sweep } = *s {
let n = plane.normal().normalized().ok_or_else(|| invalid("profile plane"))?;
// Clockwise in the plane is counter-clockwise about the other normal.
let (axis, a0) = if sweep >= 0.0 { (n, start) } else { (n * -1.0, -start) };
let turn = sweep.abs().min(std::f64::consts::TAU);
return Ok(Curve::Arc { center: a3(plane.to_world(center)), axis: a3(axis), reference: a3(plane.x), radius, start: a0, end: a0 + turn });
}
record_curve(&crate::freeform::segment(plane, s)?.0)
}
/// A record line or (rational) B-spline as SMLib's curve.
fn record_curve(c: &b::Curve) -> Result<Curve> {
let degree = |knots: &[f64], n: usize| knots.len().checked_sub(n + 1).ok_or_else(|| invalid("spline degree"));
Ok(match c {
b::Curve::Line { start, end } => Curve::Line { start: *start, end: *end },
b::Curve::Spline { knots, points } => Curve::Nurbs {
degree: degree(knots, points.len())?,
points: points.iter().map(|p| [p[0], p[1], p[2], 1.0]).collect(),
knots: knots.clone(),
},
b::Curve::RationalSpline { knots, homogeneous } => Curve::Nurbs {
degree: degree(knots, homogeneous.len())?,
points: homogeneous.iter().map(|h| [h[0] / h[3], h[1] / h[3], h[2] / h[3], h[3]]).collect(),
knots: knots.clone(),
},
_ => return Err(invalid("a profile curve SMLib's sweeps do not take")),
})
}
fn curves(plane: &Plane, chain: &[Numbered]) -> Result<Vec<Curve>> {
chain.iter().map(|(s, _)| curve(plane, s)).collect()
chain.iter().map(|(s, _)| crate::smlib_sweeps::curve(plane, s)).collect()
}
pub(super) fn extruded(base: &Plane, chain: &[Numbered], n: Vec3, distance: f64) -> Result<Brep> {
@@ -1276,29 +1264,171 @@ mod imp {
checked(&SmBrep::revolve(&curves(plane, chain)?, a3(origin), a3(axis), angle, false).map_err(sm("surface revolve"))?, "surface revolve")
}
/// A path segment as SMLib's curve.
fn path_curve(s: &crate::PathSeg) -> Result<Curve> {
Ok(match *s {
crate::PathSeg::Line { a, b } => Curve::Line { start: a3(a), end: a3(b) },
crate::PathSeg::Arc { a, center, axis, angle } => {
let k = axis.normalized().ok_or_else(|| invalid("a path arc has no axis"))?;
let (k, turn) = if angle < 0.0 { (k * -1.0, -angle) } else { (k, angle) };
let r = a - center;
let reference = r.normalized().ok_or_else(|| invalid("a path arc has no radius"))?;
Curve::Arc { center: a3(center), axis: a3(k), reference: a3(reference), radius: r.len(), start: 0.0, end: turn }
}
crate::PathSeg::Curve { plane, seg } => curve(&plane, &seg)?,
crate::PathSeg::Cubic { p } => Curve::Nurbs {
degree: 3,
points: p.iter().map(|q| [q.x, q.y, q.z, 1.0]).collect(),
knots: vec![0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0],
},
})
fn route(path: &[crate::PathSeg]) -> Result<Vec<Curve>> {
path.iter().map(crate::smlib_sweeps::path_curve).collect()
}
pub(super) fn swept(plane: &Plane, chain: &[Numbered], path: &[crate::PathSeg]) -> Result<Brep> {
let route = path.iter().map(path_curve).collect::<Result<Vec<_>>>()?;
checked(&SmBrep::sweep(&curves(plane, chain)?, &route, SweepFrame::Follow, false).map_err(sm("surface sweep"))?, "surface sweep")
fn frame(translate: bool) -> SweepFrame {
if translate { SweepFrame::Translate } else { SweepFrame::Follow }
}
/// The chain swept along the smooth `path`, turning with it, or only moving along it when
/// `translate`.
pub(super) fn swept(plane: &Plane, chain: &[Numbered], path: &[crate::PathSeg], translate: bool) -> Result<Brep> {
checked(&SmBrep::sweep(&curves(plane, chain)?, &route(path)?, frame(translate), false).map_err(sm("surface sweep"))?, "surface sweep")
}
/// `q` moved by the motion `a`.
fn apply(a: &Affine, q: Vec3) -> Vec3 {
let col = |i: usize| a.m.get(i).map_or(Vec3::ZERO, |c| v3(*c));
col(0) * q.x + col(1) * q.y + col(2) * q.z + v3(a.t)
}
/// `pl` carried by the rigid motion `a`.
fn placed(pl: &Plane, a: &Affine) -> Plane {
let o = apply(a, Vec3::ZERO);
Plane { origin: apply(a, pl.origin), x: apply(a, pl.x) - o, y: apply(a, pl.y) - o }
}
/// The bisector of a corner from direction `t1` to `t2` (unit, the way the path runs) and the
/// turn there; a corner that turns the path back on itself is refused.
fn mitre(t1: Vec3, t2: Vec3) -> Result<(Vec3, f64)> {
let turn = t1.dot(t2).clamp(-1.0, 1.0).acos();
if turn > std::f64::consts::PI - 1e-3 {
return Err(invalid("the path turns back on itself at a corner"));
}
Ok(((t1 + t2).normalized().ok_or_else(|| invalid("path corner"))?, turn))
}
/// A tool of square planar faces, one in each plane `cuts` (a point and its normal), `size`
/// across: what a run is imprinted with at its corners.
fn cutting_planes(cuts: &[(Vec3, Vec3)], size: f64) -> Result<SmBrep> {
let mut parts = Parts { tolerance: (size * 1e-9).max(1e-6), ..Parts::default() };
let h = size * 0.5;
let square = [Vec2::new(-h, -h), Vec2::new(h, -h), Vec2::new(h, h), Vec2::new(-h, h)];
let segs: Vec<Seg2> = (0..4).map(|i| Seg2::Line { a: square[i], b: square[(i + 1) % 4] }).collect();
for &(at, n) in cuts {
let u = n.cross(if n.x.abs() < 0.9 { Vec3::X } else { Vec3::Y }).normalized().ok_or_else(|| invalid("mitre plane"))?;
let pl = Plane { origin: at, x: u, y: n.cross(u) };
let lp = sketch_loop(&mut parts, &pl, &segs)?;
let domain = uv_box(std::slice::from_ref(&lp)).ok_or_else(|| invalid("mitre plane"))?;
parts.faces.push((b::Face { surface: crate::freeform::plane_surface(&pl), domain, loops: vec![lp] }, true));
}
SmBrep::from_record(&parts.canonical()?.brep, true).map_err(sm("sweep mitre"))
}
/// The faces of `sheet` (a run's walls, each from what `prov` says, in its record's order)
/// imprinted with `cuts` and kept where every cut's `keep` holds of a point inside them: the
/// piece between a run's mitres, each face from what its uncut face came from.
fn cut_back(sheet: &SmBrep, prov: &[FaceProv], cuts: &[(Vec3, Vec3)], size: f64) -> Result<(Brep, Vec<FaceProv>)> {
let (_, order) = sheet.to_native_ordered().map_err(|e| failed(format!("SMLib sweep mitre: {e}")))?;
let tagged = sheet.tagged(0).map_err(sm("sweep mitre"))?;
let Some(cut) = tagged.imprint(&cutting_planes(cuts, size)?).map_err(sm("sweep mitre"))? else {
return Ok((checked(sheet, "sweep mitre")?, prov.to_vec()));
};
let (record, kept_order) = cut.to_native_ordered().map_err(|e| failed(format!("SMLib sweep mitre: {e}")))?;
let h = cut.history().map_err(sm("sweep mitre"))?.history(&[order], &kept_order).map_err(|e| failed(format!("SMLib sweep mitre: {e}")))?;
// A point inside each face, from SMLib's face order to the record's.
let points = cut.face_points().map_err(sm("sweep mitre"))?;
let mut inside = vec![Vec3::ZERO; record.faces.len()];
for (i, p) in points.iter().enumerate() {
let k = if kept_order.faces.is_empty() { i } else { kept_order.faces.get(i).copied().unwrap_or(i) };
if let Some(slot) = inside.get_mut(k) {
*slot = v3(*p);
}
}
let keep: Vec<(usize, bool)> = (0..record.faces.len())
.filter(|f| inside.get(*f).is_some_and(|p| cuts.iter().all(|(at, n)| (*p - *at).dot(*n) < 0.0)))
.map(|f| (f, false))
.collect();
let c = Parts::of(&record, &keep)?.canonical()?;
let faces = c
.faces
.iter()
.map(|p| {
let f = keep.get(*p).map_or(0, |(f, _)| *f);
match h.faces.get(f).map(|x| x.origins.as_slice()) {
Some([FaceOrigin::Face { face, .. }]) => prov.get(*face).cloned().unwrap_or_else(|| record::generated(Vec::new())),
_ => record::generated(Vec::new()),
}
})
.collect();
Ok((c.brep, faces))
}
/// A sheet swept along a path with corners, by the solid sweep's corner model with open ends:
/// each smooth run swept on its own, turning with the path, carried on straight past each
/// corner (by the profile's reach times the tangent of half the turn, and a little more) and
/// cut back to the plane halving the corner, where the next run, cut back the same way, meets
/// it; the profile turns at a corner about the line square to both directions. Each run's
/// walls come from the segments they are swept from, found where the run starts; the runs are
/// stitched by the caller. Only moving along the path (`translate`), the profile is the same at
/// a corner in both runs, which meet there as they are.
pub(super) fn cornered(
plane: &Plane,
chain: &[Numbered],
path: &[crate::PathSeg],
runs: &[std::ops::Range<usize>],
translate: bool,
) -> Result<Vec<(Brep, Vec<FaceProv>)>> {
let bad = || invalid("a path segment has no direction");
let start = path.first().map(crate::PathSeg::start).ok_or_else(|| invalid("empty path"))?;
let end = path.last().map(crate::PathSeg::end).ok_or_else(|| invalid("empty path"))?;
let reach = chain
.iter()
.flat_map(|(s, _)| (0..=8).map(move |i| s.point_at(f64::from(i) / 8.0)))
.map(|q| plane.to_world(q).dist(start))
.fold(0.0f64, f64::max);
let size = 4.0 * (path.iter().map(length).sum::<f64>() + reach) + 1.0;
let (first_t, _) = path.first().and_then(crate::PathSeg::tangents).ok_or_else(bad)?;
let (_, last_t) = path.last().and_then(crate::PathSeg::tangents).ok_or_else(bad)?;
// A closed path ends where it starts; at a corner there the last run meets the first in a
// mitre too.
let closing = (end.dist(start) <= 1e-6 && last_t.dot(first_t) < (1e-3f64).cos()).then_some(first_t);
let over = |turn: f64| if translate { 0.0 } else { reach * (turn * 0.5).tan() * 1.1 + reach * 1e-3 + 1e-6 };
let mut pose = *plane;
// The mitre the next run starts from: its point, its normal (along the run) and the turn.
let mut entry = closing.filter(|_| !translate).map(|t| mitre(last_t, t).map(|(m, turn)| (start, m, turn))).transpose()?;
let mut pieces = Vec::with_capacity(runs.len());
for (ri, run) in runs.iter().enumerate() {
let segs = path.get(run.clone()).ok_or_else(|| invalid("path run"))?;
let (Some(first), Some(last)) = (segs.first(), segs.last()) else { return Err(invalid("path run")) };
let ((t0, _), (_, t1)) = (first.tangents().ok_or_else(bad)?, last.tangents().ok_or_else(bad)?);
let (a0, b1) = (first.start(), last.end());
let next = match runs.get(ri + 1).and_then(|r| path.get(r.start)) {
Some(s) => Some(s.tangents().ok_or_else(bad)?.0),
None => closing,
};
let exit = next.filter(|_| !translate).map(|t2| mitre(t1, t2)).transpose()?;
let pre = entry.map_or(0.0, |(_, _, turn)| over(turn));
let post = exit.map_or(0.0, |(_, turn)| over(turn));
let mut along = Vec::with_capacity(segs.len() + 2);
if pre > 0.0 {
along.push(crate::PathSeg::Line { a: a0 - t0 * pre, b: a0 });
}
along.extend_from_slice(segs);
if post > 0.0 {
along.push(crate::PathSeg::Line { a: b1, b: b1 + t1 * post });
}
let from = Plane { origin: pose.origin - t0 * pre, ..pose };
let (sheet, [_, _, at_last]) =
SmBrep::sweep_placed(&curves(&from, chain)?, &route(&along)?, frame(translate), false).map_err(sm("surface sweep"))?;
let prov = swept_from(&sheet.to_native().map_err(|e| failed(format!("SMLib surface sweep: {e}")))?, &from, chain);
// Kept: after the entry mitre, before the exit one.
let cuts: Vec<(Vec3, Vec3)> = entry.map(|(at, m, _)| (at, m * -1.0)).into_iter().chain(exit.map(|(m, _)| (b1, m))).collect();
pieces.push(cut_back(&sheet, &prov, &cuts, size)?);
// The profile at the run's end, turned through the corner onto the next run.
let at_end = placed(&from, &at_last);
pose = Plane { origin: at_end.origin - t1 * post, ..at_end };
entry = None;
if let (Some(t2), Some((m, turn))) = (next, exit) {
let k = t1.cross(t2).normalized().ok_or_else(|| invalid("path corner"))?;
let turn_v = |v: Vec3| crate::build::rotate_about(v, Vec3::ZERO, k, turn);
pose = Plane { origin: crate::build::rotate_about(pose.origin, b1, k, turn), x: turn_v(pose.x), y: turn_v(pose.y) };
entry = Some((b1, m, turn));
}
}
Ok(pieces)
}
/// Fewest and most stations of a sweep that twists, scales or follows rails.
@@ -1325,18 +1455,21 @@ mod imp {
checked(&SmBrep::sweep_stations(&curves(plane, chain)?, &maps, Ends::Open).map_err(sm("surface sweep"))?, "surface sweep")
}
/// How far a path segment turns (radians).
/// Samples of a segment's parameter its turn and length are read from.
const TURN_SAMPLES: usize = 64;
/// How far a path segment turns (radians): its tangent's turn through even steps of its
/// parameter.
fn turn_of(s: &crate::PathSeg) -> f64 {
match *s {
crate::PathSeg::Line { .. } => 0.0,
crate::PathSeg::Arc { angle, .. } => angle.abs(),
_ => {
let pts: Vec<Vec3> = std::iter::once(s.start()).chain(s.points_after_start(1e-3)).collect();
pts.windows(3)
.filter_map(|w| Some(((w[1] - w[0]).normalized()?, (w[2] - w[1]).normalized()?)))
.map(|(u, v)| u.cross(v).len().atan2(u.dot(v)))
.sum()
}
_ => (0..=TURN_SAMPLES)
.filter_map(|i| at(s, i as f64 / TURN_SAMPLES as f64).map(|(_, t)| t))
.collect::<Vec<_>>()
.windows(2)
.map(|w| w[0].cross(w[1]).len().atan2(w[0].dot(w[1])))
.sum(),
}
}
@@ -1365,33 +1498,27 @@ mod imp {
Ok((pts, tangents))
}
/// A path segment's length (an arc's exactly; a free-form one's by its spans' own lengths).
fn length(s: &crate::PathSeg) -> f64 {
match *s {
crate::PathSeg::Line { a, b } => a.dist(b),
crate::PathSeg::Arc { a, center, angle, .. } => a.dist(center) * angle.abs(),
_ => {
let pts: Vec<Vec3> = std::iter::once(s.start()).chain(s.points_after_start(1e-4)).collect();
pts.windows(2).map(|w| w[0].dist(w[1])).sum()
}
match s {
crate::PathSeg::Line { a, b } => a.dist(*b),
crate::PathSeg::Arc { a, center, angle, .. } => a.dist(*center) * angle.abs(),
crate::PathSeg::Curve { seg, .. } => seg.length(),
crate::PathSeg::Bezier(b) => b.length().unwrap_or(0.0),
}
}
/// The point `f` (0…1) of the way along a segment's parameter and its unit tangent there.
fn at(s: &crate::PathSeg, f: f64) -> Option<(Vec3, Vec3)> {
match *s {
crate::PathSeg::Line { a, b } => Some((a.lerp(b, f), (b - a).normalized()?)),
match s {
crate::PathSeg::Line { a, b } => Some((a.lerp(*b, f), (*b - *a).normalized()?)),
crate::PathSeg::Arc { a, center, axis, angle } => {
let k = axis.normalized()?;
let p = crate::build::rotate_about(a, center, k, angle * f);
Some((p, (k.cross(p - center) * angle.signum()).normalized()?))
let p = crate::build::rotate_about(*a, *center, k, angle * f);
Some((p, (k.cross(p - *center) * angle.signum()).normalized()?))
}
crate::PathSeg::Curve { plane, seg } => Some((plane.to_world(seg.point_at(f)), plane.dir_to_world(seg.derivative(f)).normalized()?)),
crate::PathSeg::Cubic { p: [p0, p1, p2, p3] } => {
let g = 1.0 - f;
let p = p0 * (g * g * g) + p1 * (3.0 * g * g * f) + p2 * (3.0 * g * f * f) + p3 * (f * f * f);
let d = (p1 - p0) * (3.0 * g * g) + (p2 - p1) * (6.0 * g * f) + (p3 - p2) * (3.0 * f * f);
Some((p, d.normalized()?))
}
crate::PathSeg::Bezier(b) => Some((b.point(f)?, b.derivative(f)?.normalized()?)),
}
}
@@ -1435,7 +1562,16 @@ mod imp {
pub(super) fn revolved(_: &Plane, _: &[Numbered], _: Vec3, _: Vec3, _: f64) -> Result<Brep> {
Err(not_built())
}
pub(super) fn swept(_: &Plane, _: &[Numbered], _: &[crate::PathSeg]) -> Result<Brep> {
pub(super) fn swept(_: &Plane, _: &[Numbered], _: &[crate::PathSeg], _: bool) -> Result<Brep> {
Err(not_built())
}
pub(super) fn cornered(
_: &Plane,
_: &[Numbered],
_: &[crate::PathSeg],
_: &[std::ops::Range<usize>],
_: bool,
) -> Result<Vec<(Brep, Vec<FaceProv>)>> {
Err(not_built())
}
pub(super) fn swept_stations(_: &Plane, _: &[Numbered], _: &[crate::PathSeg], _: &crate::SweepControl) -> Result<Brep> {