Wave 325/509: Fill: its tolerances follow a size that does not depend on where the body is (and 3 more)

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

- b389601b0 jyviko: Ruled surface: a strip on a cone is SMLib's revolve of its ruling, a cone face
- 1e7713d1e jyviko: Fill: a patch's edges and vertices hold its fit's gap in SMLib's tolerance model
- 4faee7dd8 jyviko: Fill: the general fill takes a loop of one or two edges in exact pieces of their curves
- c5b038548 jyviko: Fill: its tolerances follow a size that does not depend on where the body is

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-29 01:02:58 -04:00
parent 48498d477a
commit e71d2e2844
4 changed files with 439 additions and 44 deletions
+232
View File
@@ -0,0 +1,232 @@
//! The smallest ball holding a set of points (Welzl's algorithm): a measure of a point set's size
//! that does not move with the points, whatever rigid motion carries them.
use crate::Vec3;
/// A ball: every point within `radius` of `center`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Ball {
pub center: Vec3,
pub radius: f64,
}
/// How much more than `radius` a point may lie from the centre and still count as inside: the
/// rounding of the centre's and radius' arithmetic, so a point the ball was made through is never
/// taken for one outside it.
const ROUNDING: f64 = 1e-12;
impl Ball {
/// The smallest ball holding every finite point of `points` (points that are not finite are
/// skipped), or `None` when there are none. Welzl's algorithm in its incremental form, the
/// points taken in a fixed shuffled order: expected `O(n)`. The ball is unique, so the order
/// only changes the last bits of its centre and radius.
pub fn enclosing(points: &[Vec3]) -> Option<Ball> {
let mut p: Vec<Vec3> = points.iter().copied().filter(|q| q.is_finite()).collect();
shuffle(&mut p);
let mut ball = Ball { center: *p.first()?, radius: 0.0 };
// Each loop keeps the smallest ball holding the points before it with the points of the
// loops outside it on its boundary (Welzl 1991): at most four are, in three dimensions.
for i in 1..p.len() {
if ball.holds(p[i]) {
continue;
}
ball = Ball { center: p[i], radius: 0.0 };
for j in 0..i {
if ball.holds(p[j]) {
continue;
}
ball = through(&[p[i], p[j]]);
for k in 0..j {
if ball.holds(p[k]) {
continue;
}
ball = through(&[p[i], p[j], p[k]]);
for l in 0..k {
if !ball.holds(p[l]) {
ball = through(&[p[i], p[j], p[k], p[l]]);
}
}
}
}
}
Some(ball)
}
pub fn diameter(&self) -> f64 {
2.0 * self.radius
}
/// Whether `p` lies in the ball, to the rounding of its arithmetic.
pub fn holds(&self, p: Vec3) -> bool {
p.dist(self.center) <= self.radius + ROUNDING * (self.radius + self.center.len())
}
}
/// The smallest ball with every one of `r` (two to four points) on its boundary; where they are
/// degenerate (three in a line, four in a plane, which exact arithmetic never asks for but
/// rounding can), the smallest ball through some of them that holds them all.
fn through(r: &[Vec3]) -> Ball {
let exact = match r {
[a, b] => Some((*a + *b) * 0.5),
[o, b, c] => circumcentre3(*o, *b, *c),
[o, b, c, d] => circumcentre4(*o, *b, *c, *d),
_ => None,
};
match exact {
Some(center) => with_center(center, r),
None => smallest_holding(r),
}
}
/// The ball about `center` reaching the farthest of `r`.
fn with_center(center: Vec3, r: &[Vec3]) -> Ball {
Ball { center, radius: r.iter().map(|q| q.dist(center)).fold(0.0, f64::max) }
}
/// The centre of the circle through `o`, `b` and `c`, or `None` when they are (nearly) in a line.
fn circumcentre3(o: Vec3, b: Vec3, c: Vec3) -> Option<Vec3> {
let (a, b) = (b - o, c - o);
let n = a.cross(b);
let n2 = n.len2();
if !(n2 > 1e-14 * a.len2() * b.len2()) {
return None;
}
Some(o + (b.cross(n) * a.len2() + n.cross(a) * b.len2()) / (2.0 * n2))
}
/// The centre of the sphere through `o`, `b`, `c` and `d`, or `None` when they are (nearly) in a
/// plane.
fn circumcentre4(o: Vec3, b: Vec3, c: Vec3, d: Vec3) -> Option<Vec3> {
let (a, b, c) = (b - o, c - o, d - o);
let det = a.dot(b.cross(c));
if !(det.abs() > 1e-7 * a.len() * b.len() * c.len()) {
return None;
}
Some(o + (b.cross(c) * a.len2() + c.cross(a) * b.len2() + a.cross(b) * c.len2()) / (2.0 * det))
}
/// The smallest of the balls through two or three of `r` that holds all of them; a ball about
/// their mean where none does (never, for two to four points).
fn smallest_holding(r: &[Vec3]) -> Ball {
let mut best: Option<Ball> = None;
let mut consider = |ball: Ball| {
if r.iter().all(|q| ball.holds(*q)) && best.is_none_or(|b| ball.radius < b.radius) {
best = Some(ball);
}
};
for i in 0..r.len() {
for j in i + 1..r.len() {
consider(with_center((r[i] + r[j]) * 0.5, r));
for k in j + 1..r.len() {
if let Some(c) = circumcentre3(r[i], r[j], r[k]) {
consider(with_center(c, r));
}
}
}
}
best.unwrap_or_else(|| {
let mean = r.iter().fold(Vec3::ZERO, |s, q| s + *q) / (r.len().max(1) as f64);
with_center(mean, r)
})
}
/// A Fisher–Yates shuffle from a fixed seed (SplitMix64), so the same points give the same ball.
fn shuffle(p: &mut [Vec3]) {
let mut state: u64 = 0x9E37_79B9_7F4A_7C15;
for i in (1..p.len()).rev() {
state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = state;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^= z >> 31;
p.swap(i, (z % (i as u64 + 1)) as usize);
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Points from a fixed generator in the cube [-1, 1]³.
fn cloud(n: usize, seed: u64) -> Vec<Vec3> {
let mut s = seed;
let mut next = || {
s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
(s >> 11) as f64 / (1u64 << 53) as f64 * 2.0 - 1.0
};
(0..n).map(|_| Vec3::new(next(), next(), next())).collect()
}
/// The smallest ball by brute force: of the balls through two, three or four of the points,
/// the smallest that holds them all.
fn brute(p: &[Vec3]) -> f64 {
let mut best = f64::INFINITY;
let n = p.len();
let mut try_ball = |b: Ball| {
if p.iter().all(|q| q.dist(b.center) <= b.radius * (1.0 + 1e-9)) {
best = best.min(b.radius);
}
};
for i in 0..n {
for j in i + 1..n {
try_ball(through(&[p[i], p[j]]));
for k in j + 1..n {
try_ball(through(&[p[i], p[j], p[k]]));
for l in k + 1..n {
try_ball(through(&[p[i], p[j], p[k], p[l]]));
}
}
}
}
best
}
#[test]
fn the_smallest_ball_holds_every_point_and_matches_brute_force() {
for seed in 1..40 {
let p = cloud(3 + seed as usize % 9, seed);
let ball = Ball::enclosing(&p).unwrap();
assert!(p.iter().all(|q| ball.holds(*q)), "seed {seed}: a point outside");
let want = brute(&p);
assert!((ball.radius - want).abs() <= 1e-12 * want, "seed {seed}: {} against {want}", ball.radius);
}
}
#[test]
fn known_balls() {
let cube: Vec<Vec3> = (0..8).map(|i| Vec3::new((i & 1) as f64, (i >> 1 & 1) as f64, (i >> 2 & 1) as f64)).collect();
let b = Ball::enclosing(&cube).unwrap();
assert!(b.center.dist(Vec3::new(0.5, 0.5, 0.5)) < 1e-15 && (b.radius - 3f64.sqrt() / 2.0).abs() < 1e-15);
let s = 3f64.sqrt();
let triangle = [Vec3::new(1.0, 0.0, 0.0), Vec3::new(-0.5, s / 2.0, 0.0), Vec3::new(-0.5, -s / 2.0, 0.0)];
assert!((Ball::enclosing(&triangle).unwrap().radius - 1.0).abs() < 1e-15);
// An obtuse triangle's ball is its longest side's.
let obtuse = [Vec3::new(-1.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 0.1, 0.0)];
assert!((Ball::enclosing(&obtuse).unwrap().radius - 1.0).abs() < 1e-15);
let tetra = [Vec3::new(1.0, 1.0, 1.0), Vec3::new(1.0, -1.0, -1.0), Vec3::new(-1.0, 1.0, -1.0), Vec3::new(-1.0, -1.0, 1.0)];
assert!((Ball::enclosing(&tetra).unwrap().radius - s).abs() < 1e-15);
// Points in a line and in a plane, repeated points, one point, none.
let line: Vec<Vec3> = (0..10).map(|i| Vec3::new(i as f64, 2.0 * i as f64, 0.0)).collect();
assert!((Ball::enclosing(&line).unwrap().diameter() - 9.0 * 5f64.sqrt()).abs() < 1e-12);
let square: Vec<Vec3> = (0..4).flat_map(|i| [Vec3::new((i & 1) as f64, (i >> 1) as f64, 0.0); 3]).collect();
assert!((Ball::enclosing(&square).unwrap().diameter() - 2f64.sqrt()).abs() < 1e-15);
assert_eq!(Ball::enclosing(&[Vec3::X]), Some(Ball { center: Vec3::X, radius: 0.0 }));
assert_eq!(Ball::enclosing(&[]), None);
assert_eq!(Ball::enclosing(&[Vec3::new(f64::NAN, 0.0, 0.0)]), None);
}
/// The ball's size is the set's own: a rigid motion leaves it, and points crowding one end
/// do not stretch it (twice the farthest point's distance from the centroid would be nearly
/// twice the diameter here).
#[test]
fn the_size_does_not_move_with_the_points_or_their_crowding() {
let p = cloud(200, 7);
let d = Ball::enclosing(&p).unwrap().diameter();
let (c, s) = (0.7f64.cos(), 0.7f64.sin());
let moved: Vec<Vec3> = p.iter().map(|q| Vec3::new(c * q.x - s * q.y + 30.0, s * q.x + c * q.y - 12.0, q.z + 5.0)).collect();
assert!((Ball::enclosing(&moved).unwrap().diameter() - d).abs() <= 1e-12 * d);
let mut crowded = vec![Vec3::ZERO; 99];
crowded.push(Vec3::new(1.0, 0.0, 0.0));
assert!((Ball::enclosing(&crowded).unwrap().diameter() - 1.0).abs() < 1e-15);
}
}
+2
View File
@@ -11,6 +11,7 @@
mod aabb2;
mod arcfit;
mod ball;
pub mod blend;
pub mod brep;
pub mod bspline;
@@ -40,6 +41,7 @@ mod vec;
pub use aabb2::Aabb2;
pub use arcfit::MAX_FIT_PIECES;
pub use ball::Ball;
pub use blend::hermite_bezier;
pub use bvh::{Bvh, MeshIndex};
pub use chain::{Chain, Closed, Ends, Open, Path, Planar, Ring};
+151 -41
View File
@@ -144,18 +144,20 @@ fn general_fill(
points: &[Vec3],
crown: f64,
) -> Result<(Body, PatchReport)> {
if !(3..=solidcraft_geom::fill_iso::MAX_ISO_EDGES).contains(&chain.len()) {
if !(1..=solidcraft_geom::fill_iso::MAX_ISO_EDGES).contains(&chain.len()) {
return Err(KernelError::Invalid(format!(
"not supported yet: a general patch on a loop of {} edges (three to {})",
"not supported yet: a general patch on a loop of {} edges (one to {})",
chain.len(),
solidcraft_geom::fill_iso::MAX_ISO_EDGES
)));
}
let edges: Vec<IsoEdge> = chain.iter().map(|&(e, forward)| iso_edge(record, e, forward)).collect::<Result<_>>()?;
let pieces = loop_pieces(record, chain)?;
let edges: Vec<IsoEdge> = pieces.iter().map(|p| iso_edge(record, p)).collect::<Result<_>>()?;
let size = body.size().max(solidcraft_geom::LINEAR_TOL);
let mut beside: Vec<Option<Beside>> = Vec::with_capacity(chain.len());
for (&(e, forward), order) in chain.iter().zip(orders) {
beside.push(if *order == Continuity::G0 { None } else { Some(Beside::new(record, e, forward, *order, size)?) });
let mut beside: Vec<Option<Beside>> = Vec::with_capacity(pieces.len());
for p in &pieces {
let order = chain.iter().position(|&(e, _)| e == p.edge).and_then(|k| orders.get(k)).copied().unwrap_or(Continuity::G0);
beside.push(if order == Continuity::G0 { None } else { Some(Beside::new(record, p.edge, p.forward, order, size)?) });
}
let mut across = |k: usize, ts: &[f64]| -> std::result::Result<Vec<Option<Across>>, String> {
match beside.get(k) {
@@ -166,7 +168,7 @@ fn general_fill(
};
let spec = IsoSpec { tol: face_tolerance(body), angle_tol: PATCH_ANGLE_TOL_DEG.to_radians(), crown, points };
let fill = solidcraft_geom::fill_iso::iso_fill(&edges, &mut across, &spec).map_err(spline_error)?;
let made = quilt_body(body, record, chain, &fill, face_tolerance(body))?;
let made = quilt_body(body, record, &pieces, &fill, face_tolerance(body))?;
let a = fill.achieved;
let report = PatchReport {
general: true,
@@ -234,11 +236,71 @@ pub(crate) fn matched_patch(body: &Body, chain: &[(usize, bool)], curvature_tol:
Ok((made, fill))
}
/// A piece of a loop edge as the general fill takes it: record edge `edge` over `interval` (in
/// its own parameter, min < max), run the loop's way along it (`forward`) or back.
#[derive(Clone, Copy, Debug, PartialEq)]
struct Piece {
edge: usize,
forward: bool,
interval: [f64; 2],
}
/// The loop `chain` as the general fill's sides: each edge whole, but for a loop of one or two
/// edges (a tube's end: one closed circle) each edge in equal pieces of its parameter, four sides
/// in all, so the fill is one four-sided patch on pieces of the edges' own curves.
fn loop_pieces(record: &b::Brep, chain: &[(usize, bool)]) -> Result<Vec<Piece>> {
let split = match chain.len() {
1 => 4,
2 => 2,
_ => 1,
};
let mut out = Vec::with_capacity(chain.len() * split);
for &(e, forward) in chain {
let edge = record.edges.get(e).ok_or_else(|| KernelError::Failed("patch: edge reference".into()))?;
let [a, z] = edge.interval;
// A break that falls on one of the curve's own knots (a conic's quarter points) is that
// knot exactly: a piece must not start a rounding error off one.
let own: Vec<f64> = match edge.parameters() {
b::Curve::Spline { knots, .. } | b::Curve::RationalSpline { knots, .. } => knots.clone(),
_ => Vec::new(),
};
let at = |i: usize| {
if i == 0 {
a
} else if i == split {
z
} else {
let t = a + (z - a) * i as f64 / split as f64;
own.iter().copied().find(|k| (k - t).abs() <= 1e-9 * (z - a).abs()).unwrap_or(t)
}
};
let mut pieces: Vec<Piece> = (0..split).map(|i| Piece { edge: e, forward, interval: [at(i), at(i + 1)] }).collect();
if !forward {
pieces.reverse();
}
out.extend(pieces);
}
Ok(out)
}
/// `t` on an edge's interval `[a, z]` reflected about its middle: the loop's parameter along an
/// edge it runs against.
fn reflected(a: f64, z: f64, t: f64) -> f64 {
if t == a {
z
} else if t == z {
a
} else {
a + z - t
}
}
/// A loop edge as the patch takes it: a B-spline on the edge's interval, rational when the edge
/// is (a circle or ellipse on the NURBS form SMLib holds it as, whose parameter the edge's interval
/// and pcurves are in), running the loop's way, its ends on the edge's vertices. A traced curve
/// has no such form in its own parameter and is refused by name.
fn iso_edge(record: &b::Brep, e: usize, forward: bool) -> Result<IsoEdge> {
fn iso_edge(record: &b::Brep, piece: &Piece) -> Result<IsoEdge> {
let Piece { edge: e, forward, interval: [lo, hi] } = *piece;
let edge = record.edges.get(e).ok_or_else(|| KernelError::Failed("patch: edge reference".into()))?;
let v3 = |p: &[f64; 3]| Vec3::new(p[0], p[1], p[2]);
let [a, z] = edge.interval;
@@ -267,18 +329,20 @@ fn iso_edge(record: &b::Brep, e: usize, forward: bool) -> Result<IsoEdge> {
)));
}
};
// The piece on the edge's interval, then run the loop's way.
let (mut knots, mut h) = solidcraft_geom::bspline::segment(degree, &knots, &h, a, z).map_err(spline_error)?;
// The piece of the edge, then run the loop's way (the edge's parameter reflected about its
// interval's middle).
let (mut knots, mut h) = solidcraft_geom::bspline::segment(degree, &knots, &h, lo, hi).map_err(spline_error)?;
if !forward {
knots = knots.iter().rev().map(|k| a + z - k).collect();
h.reverse();
// The interval's ends exactly (the reflection's rounding), so a piece's ends name them.
// The ends exactly (the reflection's rounding), so a piece's ends name them.
let (rlo, rhi) = (reflected(a, z, hi), reflected(a, z, lo));
let n = knots.len();
for (i, k) in knots.iter_mut().enumerate() {
if i <= degree {
*k = a;
*k = rlo;
} else if i + degree + 1 >= n {
*k = z;
*k = rhi;
}
}
}
@@ -288,14 +352,18 @@ fn iso_edge(record: &b::Brep, e: usize, forward: bool) -> Result<IsoEdge> {
.map(|q| q.project().filter(|_| q.w > 0.0))
.collect::<Option<Vec<Vec3>>>()
.ok_or_else(|| KernelError::Invalid(format!("not supported yet: a general patch on edge {e}, whose weights are not all positive")))?;
// Its ends exactly on the loop's vertices.
let vertex = |end: usize| record.vertices.get(edge.vertices[end] as usize).map(|v| v3(&v.point));
let (first, last) = if forward { (vertex(0), vertex(1)) } else { (vertex(1), vertex(0)) };
if let (Some(p), Some(q), Some(f)) = (first, last, points.first_mut()) {
// Its ends exactly on the loop's vertices, where they are the edge's ends.
let vertex = |at: f64| match (at == a, at == z) {
(true, _) => record.vertices.get(edge.vertices[0] as usize).map(|v| v3(&v.point)),
(_, true) => record.vertices.get(edge.vertices[1] as usize).map(|v| v3(&v.point)),
_ => None,
};
let (first, last) = if forward { (vertex(lo), vertex(hi)) } else { (vertex(hi), vertex(lo)) };
if let (Some(p), Some(f)) = (first, points.first_mut()) {
*f = p;
if let Some(l) = points.last_mut() {
*l = q;
}
}
if let (Some(q), Some(l)) = (last, points.last_mut()) {
*l = q;
}
let weights = rational.then(|| h.iter().map(|q| q.w).collect());
Ok(IsoEdge { degree, knots, points, weights })
@@ -715,7 +783,8 @@ fn patch_body(body: &Body, record: &b::Brep, chain: &[(usize, bool)], surface: b
if !ccw {
uses = uses.into_iter().rev().map(|u| PartUse { forward: !u.forward, ..u }).collect();
}
let made = assemble(Parts { vertices, edges, faces: vec![PartFace { surface, forward: true, loops: vec![uses] }], tolerance: tol }, false)?;
let mut made = assemble(Parts { vertices, edges, faces: vec![PartFace { surface, forward: true, loops: vec![uses] }], tolerance: tol }, false)?;
hold_gap(&mut made.brep, tol);
let smlib = solidcraft_smlib::Brep::from_record(&made.brep, true).map_err(|e| KernelError::Failed(format!("patch: SMLib: {e}")))?;
let (patch, order) = crate::native::body_from_smlib_ordered(&smlib)?;
// The patch's edges in its own order, each from the loop edge it is.
@@ -740,13 +809,13 @@ fn patch_body(body: &Body, record: &b::Brep, chain: &[(usize, bool)], surface: b
/// exact curve record; the spokes from the halves' common vertex to the centre; every pcurve the
/// straight line in (u, v) the patch gives its side. Its history is over `[body]`: every face is
/// new, each loop edge (or half) a piece of the body's own, each spoke new.
fn quilt_body(body: &Body, record: &b::Brep, chain: &[(usize, bool)], fill: &IsoFill, tol: f64) -> Result<Body> {
fn quilt_body(body: &Body, record: &b::Brep, chain: &[Piece], fill: &IsoFill, tol: f64) -> Result<Body> {
use solidcraft_geom::fill_iso::IsoSide;
let fail = |m: &str| KernelError::Failed(format!("patch: {m}"));
let index = |n: usize| u32::try_from(n).map_err(|_| fail("budget"));
let mut vertices: Vec<[f64; 3]> = Vec::new();
let mut vertex_of: std::collections::HashMap<u32, u32> = std::collections::HashMap::new();
let mut middle_of: std::collections::HashMap<usize, u32> = std::collections::HashMap::new();
let mut middle_of: std::collections::HashMap<(usize, u64), u32> = std::collections::HashMap::new();
let mut edges: Vec<PartEdge> = Vec::new();
// Each part edge's origin: the record edge it is a piece of (`None` for a spoke).
let mut origin: Vec<Option<usize>> = Vec::new();
@@ -769,12 +838,14 @@ fn quilt_body(body: &Body, record: &b::Brep, chain: &[(usize, bool)], fill: &Iso
};
match *side {
IsoSide::Edge { edge: k, from, to, uv } => {
let &(e, forward) = chain.get(k).ok_or_else(|| fail("side"))?;
let &Piece { edge: e, forward, interval: [plo, phi] } = chain.get(k).ok_or_else(|| fail("side"))?;
let edge = record.edges.get(e).ok_or_else(|| fail("edge reference"))?;
let [a, z] = edge.interval;
// The patch's parameter runs the loop's way: the edge's own, reversed where the
// loop runs against it.
let tau = |t: f64| if forward { t } else { a + z - t };
// The patch's parameter runs the loop's way: the edge's own, reflected where the
// loop runs against it; a side's ends are its piece's ends or middle, exactly.
let near = 1e-9 * (1.0 + (z - a).abs() + a.abs().max(z.abs()));
let snap = |t: f64| [plo, phi, 0.5 * (plo + phi)].into_iter().find(|s| (s - t).abs() <= near).unwrap_or(t);
let tau = |t: f64| snap(if forward { t } else { reflected(a, z, t) });
let (tf, tt) = (tau(from), tau(to));
let (lo, hi, along) = if tf < tt { (tf, tt, true) } else { (tt, tf, false) };
let key = (e, lo.to_bits(), hi.to_bits());
@@ -793,7 +864,7 @@ fn quilt_body(body: &Body, record: &b::Brep, chain: &[(usize, bool)], fill: &Iso
}
id
} else {
middle(&mut vertices, &mut middle_of, k, edge, t)?
middle(&mut vertices, &mut middle_of, e, edge, t)?
};
}
let id = index(edges.len())?;
@@ -813,9 +884,9 @@ fn quilt_body(body: &Body, record: &b::Brep, chain: &[(usize, bool)], fill: &Iso
Some(id) => *id,
None => {
let curve = fill.spokes.get(spoke).ok_or_else(|| fail("spoke"))?;
let &(e, _) = chain.get(spoke).ok_or_else(|| fail("spoke"))?;
let &Piece { edge: e, interval: [plo, phi], .. } = chain.get(spoke).ok_or_else(|| fail("spoke"))?;
let edge = record.edges.get(e).ok_or_else(|| fail("edge reference"))?;
let start = middle(&mut vertices, &mut middle_of, spoke, edge, 0.5 * (edge.interval[0] + edge.interval[1]))?;
let start = middle(&mut vertices, &mut middle_of, e, edge, 0.5 * (plo + phi))?;
let end = centre.ok_or_else(|| fail("centre"))?;
let id = index(edges.len())?;
let spline = match &curve.weights {
@@ -840,7 +911,8 @@ fn quilt_body(body: &Body, record: &b::Brep, chain: &[(usize, bool)], fill: &Iso
}
faces.push(PartFace { surface: crate::surfaces::spline_surface(&patch.surface), forward: true, loops: vec![uses] });
}
let made = assemble(Parts { vertices, edges, faces, tolerance: tol }, false)?;
let mut made = assemble(Parts { vertices, edges, faces, tolerance: tol }, false)?;
hold_gap(&mut made.brep, tol);
let smlib = solidcraft_smlib::Brep::from_record(&made.brep, true).map_err(|e| KernelError::Failed(format!("patch: SMLib: {e}")))?;
let (sheet, order) = crate::native::body_from_smlib_ordered(&smlib)?;
let Some(order) = order else { return Ok(sheet) };
@@ -863,8 +935,23 @@ fn quilt_body(body: &Body, record: &b::Brep, chain: &[(usize, bool)], fill: &Iso
sheet.with_history(history, &[body])
}
/// The vertex at parameter `t` inside loop edge `k` (record edge `edge`), made once.
fn middle(vertices: &mut Vec<[f64; 3]>, made: &mut std::collections::HashMap<usize, u32>, k: usize, edge: &b::Edge, t: f64) -> Result<u32> {
/// A patch record's edges and vertices given the tolerances that hold a surface `gap` from them.
/// A record's tolerance is SMLib's intersection tolerance, twice the zone tolerance SMLib holds an
/// edge's gap to its faces to, and a vertex holds gaps up to half its zone tolerance (SMLib's
/// `SM_XSECT_TO_ZONETOL3D`, `SmBrep::ValidateAndUpdateTolerances`): an edge takes `2·gap`, a
/// vertex `4·gap`.
fn hold_gap(brep: &mut b::Brep, gap: f64) {
for e in &mut brep.edges {
e.tolerance = e.tolerance.max(2.0 * gap);
}
for v in &mut brep.vertices {
v.tolerance = v.tolerance.max(4.0 * gap);
}
}
/// The vertex at parameter `t` inside record edge `e` (`edge`), made once.
fn middle(vertices: &mut Vec<[f64; 3]>, made: &mut std::collections::HashMap<(usize, u64), u32>, e: usize, edge: &b::Edge, t: f64) -> Result<u32> {
let k = (e, t.to_bits());
if let Some(v) = made.get(&k) {
return Ok(*v);
}
@@ -881,18 +968,31 @@ fn middle(vertices: &mut Vec<[f64; 3]>, made: &mut std::collections::HashMap<usi
/// tolerance, since a planar face is exact and other operations treat it as containing its
/// edges to that tolerance. A fitted face gets [`face_tolerance`], ten times looser.
pub(crate) fn planarity_tolerance(body: &Body) -> f64 {
(body.size() * 1e-7).max(solidcraft_geom::LINEAR_TOL)
(placed_size(body) * 1e-7).max(solidcraft_geom::LINEAR_TOL)
}
/// How far the fill's surface may be from the loop's edges: `10⁻⁶` of the body's size, at least
/// The body's size as the fill tolerances take it, the same wherever the body is and however it
/// is turned (the bounding box's diagonal is not: a cup turned 0.7 rad about (1, 2, 3) grows from
/// 54.7 to 61.6, and its fill was sampled to another tolerance): the diameter of the smallest ball
/// holding its vertices. (Twice the farthest vertex's distance from their centroid is not the
/// body's size where the vertices crowd one end: up to twice its diameter, and a rounded box's G2
/// corner patch, its vertices crowding that corner, then fitted past the box.) A body with no
/// vertices takes its box's diagonal.
fn placed_size(body: &Body) -> f64 {
let vertices: Vec<Vec3> = body.record().vertices.iter().map(|v| Vec3::new(v.point[0], v.point[1], v.point[2])).collect();
solidcraft_geom::Ball::enclosing(&vertices).map_or_else(|| body.size(), |ball| ball.diameter())
}
/// How far the fill's surface may be from the loop's edges: `10⁻⁶` of the body's size
/// ([`placed_size`]), at least
/// `10⁻⁵` mm — ten times [`planarity_tolerance`]. Ten times the linear tolerance because a
/// fitted surface approaches curved edges like a cubic spline, so each further factor of ten
/// costs about twice the spans each way, and imported edges may already lie `10⁻⁵` mm or more off
/// their vertices. Later operations must take the face to contain its edges within this
/// tolerance, not the linear one: the face's edges are the body's exact edges, the surface
/// between them is the fit (the patch record gives its edges this tolerance).
/// between them is the fit (the patch record's edges and vertices hold this gap: [`hold_gap`]).
pub(crate) fn face_tolerance(body: &Body) -> f64 {
(body.size() * 1e-6).max(1e-5)
(placed_size(body) * 1e-6).max(1e-5)
}
#[cfg(test)]
@@ -977,13 +1077,23 @@ mod tests {
}
/// Whether every edge of `made` is one of `of`'s own: the same kind of curve, on the same
/// curve record it is parameterised on (its NURBS form where it has one), on the same
/// interval. (A circle's or ellipse's frame is SMLib's again after a round trip, its axes
/// renormalised to the last bit.)
/// interval, on the curve it is parameterised on (its NURBS form where it has one) to
/// rounding: the same knots and control points within 10⁻¹² of their size. (SMLib makes a
/// conic's frame and NURBS form again on a round trip, the last bit of a coordinate apart.)
fn own_edges(made: &Body, of: &Body) -> bool {
let own = record(of).edges;
let kind = |e: &b::Edge| std::mem::discriminant(&e.curve);
record(made).edges.iter().all(|e| own.iter().any(|o| kind(o) == kind(e) && o.parameters() == e.parameters() && o.interval == e.interval))
let close = |p: &[f64], q: &[f64]| p.len() == q.len() && p.iter().zip(q).all(|(x, y)| (x - y).abs() <= 1e-12 * (1.0 + x.abs().max(y.abs())));
let same = |c: &b::Curve, d: &b::Curve| match (c, d) {
(b::Curve::Spline { knots: k, points: p }, b::Curve::Spline { knots: l, points: q }) => {
k == l && p.len() == q.len() && p.iter().zip(q).all(|(x, y)| close(x, y))
}
(b::Curve::RationalSpline { knots: k, homogeneous: p }, b::Curve::RationalSpline { knots: l, homogeneous: q }) => {
k == l && p.len() == q.len() && p.iter().zip(q).all(|(x, y)| close(x, y))
}
_ => c == d,
};
record(made).edges.iter().all(|e| own.iter().any(|o| kind(o) == kind(e) && same(o.parameters(), e.parameters()) && o.interval == e.interval))
}
/// The fill's mesh: every normal finite, and no triangle folded over (all face the same way
+54 -3
View File
@@ -145,8 +145,9 @@ pub fn ruled_surface_with(body: &Body, at: &[Vec3], r: &Ruled, handles: &[Option
return Err(KernelError::Invalid("the corners cut a strip away entirely: try a shorter distance".into()));
}
let edge = chain.get(j).map_or(0, |(e, _)| *e);
pieces
.push((s.face(&up_start, &up_end, top_start, top_end, tolerance)?, vec![record::generated(vec![FaceOrigin::Edge { operand: 0, edge }])]));
let face = s.face(&up_start, &up_end, top_start, top_end, tolerance)?;
let h = vec![record::generated(vec![FaceOrigin::Edge { operand: 0, edge }]); face.faces.len()];
pieces.push((face, h));
}
// Corner faces are made in place of the two edges meeting at the corner.
for (j, jt) in joints.iter().enumerate() {
@@ -878,6 +879,9 @@ struct Strip {
line: bool,
/// The strip lies in a plane.
planar: bool,
/// The axis (a point on it, its direction) of a strip that is a piece of a cone: the edge an
/// arc, its rulings keeping their angle to the arc's axis, leaning in or out.
cone: Option<(Vec3, Vec3)>,
start: End,
end: End,
}
@@ -891,13 +895,25 @@ impl Strip {
let line = sampled.planar && base.degree == 1 && base.ctrl.len() == 2 && sampled.affine.is_some();
let tangent = |f: f64| point_tangent(&top, f).and_then(|(_, t)| t.normalized()).unwrap_or(first.1);
let end = |(p, _, n, r): (Vec3, Vec3, Vec3, Vec3), tan: Vec3| End { at: p, ruling: r, top: p + r * d, tangent: tan, normal: n };
Strip { start: end(first, tangent(0.0)), end: end(last, tangent(1.0)), base, top, kind, line, planar: sampled.planar }
let cone = match sampled.affine {
Some(Affine::Radial { c, a, scale, .. }) if !sampled.planar && (scale - 1.0).abs() > 1e-12 => Some((c, a)),
_ => None,
};
Strip { start: end(first, tangent(0.0)), end: end(last, tangent(1.0)), base, top, kind, line, planar: sampled.planar, cone }
}
/// The strip's face on its own: the base edge, up the end side (`up_end`, points from the
/// edge's end to `top_end`), back along the far edge, down the start side (`up_start`, from
/// the edge's start to `top_start`).
fn face(&self, up_start: &[Vec3], up_end: &[Vec3], top_start: Vec3, top_end: Vec3, tolerance: f64) -> Result<Brep> {
// A piece of a cone between straight rulings is the ruling at the start turned about the
// cone's axis through the arc's angle, by SMLib's revolve: a cone face, as a cone, where
// the ruled B-spline between the arc and its image is the same surface on no analytic.
if let (Some((c, axis)), [_, _], [_, _]) = (self.cone, up_start, up_end)
&& let Some(f) = self.revolved(c, axis, top_start)?
{
return Ok(f);
}
let fail = || KernelError::Failed("ruled surface: a strip".into());
let mut parts = Parts { tolerance, ..Parts::default() };
let vertex = |p: Vec3, parts: &mut Parts| -> Result<u32> {
@@ -955,6 +971,41 @@ impl Strip {
};
face_of(parts, surface, uses)
}
/// [`Strip::face`] of a strip on a cone (`c`, `axis` its axis) bounded by straight rulings:
/// the start's ruling (from the edge's start to `top_start`) turned through the arc's angle,
/// right-handed about `axis` the way the edge runs; `None` where the edge's turn can't be read.
fn revolved(&self, c: Vec3, axis: Vec3, top_start: Vec3) -> Result<Option<Brep>> {
let (Some(bs), Some(be), Some((pm, _))) = (point(&self.base, 0.0), point(&self.base, 1.0), point_tangent(&self.base, 0.5)) else {
return Ok(None);
};
let flat = |p: Vec3| {
let q = p - c;
q - axis * q.dot(axis)
};
let angle_to = |p: Vec3| {
let (a, b) = (flat(bs), flat(p));
a.cross(b).dot(axis).atan2(a.dot(b))
};
// The turn to the end, the way the edge runs (through its middle); a closed arc is a turn.
let half = angle_to(pm);
let mut turn = angle_to(be);
if bs.dist(be) <= 1e-9 * (1.0 + flat(bs).len()) {
turn = std::f64::consts::TAU.copysign(half);
} else if half > 0.0 && turn < 0.0 {
turn += std::f64::consts::TAU;
} else if half < 0.0 && turn > 0.0 {
turn -= std::f64::consts::TAU;
}
let side = top_start - bs;
let Some(x) = side.normalized() else { return Ok(None) };
let Some(y) = (flat(bs) - x * flat(bs).dot(x)).normalized().or_else(|| (axis - x * axis.dot(x)).normalized()) else { return Ok(None) };
let plane = solidcraft_geom::Plane { origin: bs, x, y };
let line = solidcraft_geom::Seg2::Line { a: solidcraft_geom::Vec2::ZERO, b: solidcraft_geom::Vec2::new(side.len(), 0.0) };
// SMLib turns right-handed about the axis it is given.
let (axis, turn) = if turn < 0.0 { (axis * -1.0, -turn) } else { (axis, turn) };
Ok(Some(crate::surfaces::revolved_record(&plane, &[line], c, axis, turn)?))
}
}
/// A pcurve given as a straight line between two (u, v) points over its edge's interval.