Merge origin/main into fix/flush-pad-over-hole (keeps both round_pads_crossing_a_shallow_fall from #119 and drain_pads_flush_under_a_floor_with_a_hole, which now also checks a boss ring standing on the 1° top around the hole)
This commit is contained in:
commit
49ca7ef878
28 files changed
+1333
-94
No files matched your search
@@ -785,7 +785,8 @@ fn resample(lp: &Loop2, n: usize, angles: &[f64]) -> Loop2 {
|
||||
Loop2 { segs }
|
||||
}
|
||||
|
||||
/// Ruled loft through two or more planar sections (outer loops only).
|
||||
/// Ruled loft through two or more planar sections (outer loops only). The sections and the
|
||||
/// same sections in reverse order give the same body.
|
||||
pub fn loft(sections: &[(Plane, Loop2)]) -> Result<Body> {
|
||||
if sections.len() < 2 || sections.len() > 50 {
|
||||
return Err(KernelError::Invalid("a loft needs 2…50 sections".into()));
|
||||
@@ -794,10 +795,21 @@ pub fn loft(sections: &[(Plane, Loop2)]) -> Result<Body> {
|
||||
if n == 0 || n > MAX_SEGS {
|
||||
return Err(KernelError::Invalid("empty section".into()));
|
||||
}
|
||||
// Orient every section counter-clockwise about the first section's normal, then match
|
||||
// segment counts and starting points to the section with the most segments.
|
||||
let n0 = sections[0].0.normal();
|
||||
let oriented: Vec<(Plane, Loop2)> = sections
|
||||
// A canonical order, so that reversing the sections changes nothing: the one whose
|
||||
// first-to-last step has a positive largest component. The side faces' parameterisation
|
||||
// follows the order, and the boolean worked on one and failed on the other (a cut whose
|
||||
// loft touches the body along an edge: an internal panic, or "shell not oriented and
|
||||
// closed").
|
||||
let centre = |(p, l): &(Plane, Loop2)| p.to_world(l.centroid());
|
||||
let (Some(first), Some(last)) = (sections.first(), sections.last()) else { return Err(KernelError::Invalid("no sections".into())) };
|
||||
let step = centre(last) - centre(first);
|
||||
let big = [step.x, step.y, step.z].into_iter().max_by(|a, b| a.abs().total_cmp(&b.abs())).unwrap_or(0.0);
|
||||
let ordered: Vec<&(Plane, Loop2)> = if big < 0.0 { sections.iter().rev().collect() } else { sections.iter().collect() };
|
||||
// Orient every section counter-clockwise about the first section's normal (`Body::new`
|
||||
// turns the solid outward), then match segment counts and starting points to the section
|
||||
// with the most segments.
|
||||
let n0 = ordered.first().map(|(p, _)| p.normal()).unwrap_or(Vec3::Z);
|
||||
let oriented: Vec<(Plane, Loop2)> = ordered
|
||||
.iter()
|
||||
.map(|(p, l)| {
|
||||
let l = if p.normal().dot(n0) >= 0.0 { l.ccw() } else { l.ccw().reversed() };
|
||||
|
||||
+222
-30
@@ -2,8 +2,10 @@
|
||||
//! faces). Each face moves along its outward normal by its own distance: a plane is translated,
|
||||
//! a cylinder changes radius about its axis. Every vertex and edge goes to where its faces'
|
||||
//! moved surfaces meet; edges are lines or circular arcs. This is exact when the moved
|
||||
//! surfaces meet the way the old ones did (prismatic parts, bosses, fillets between walls);
|
||||
//! anything else is refused, so callers can fall back.
|
||||
//! surfaces meet the way the old ones did (prismatic parts, bosses, fillets between walls).
|
||||
//! A corner where more than three planes meet, whose moved planes miss a common point (a
|
||||
//! floor falling to a drain, a pyramid's apex), becomes several corners joined by short edges.
|
||||
//! Anything else is refused, so callers can fall back.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
@@ -422,6 +424,143 @@ fn span_step(ns: &[Vec3], s: &[f64]) -> Option<Vec3> {
|
||||
Some(v)
|
||||
}
|
||||
|
||||
/// Most faces round one corner that [`split_corner`] takes on.
|
||||
const MAX_SPLIT_FACES: usize = 48;
|
||||
|
||||
/// The corners in place of a corner where more than three planar faces meet and whose moved
|
||||
/// planes miss a common point (a hip floor's corner, a pyramid's apex): each new corner with
|
||||
/// the faces through it. Corners sharing two faces are joined by a new edge on those faces.
|
||||
/// Only corners whose edges are all convex or all concave: the faces there bound a convex
|
||||
/// region (the body's side or the outside's), and after the move its corners are the points on
|
||||
/// three moved planes inside all the others.
|
||||
fn split_corner(
|
||||
v: &mt::Vertex,
|
||||
at: &[usize],
|
||||
faces: &[mt::Face],
|
||||
efaces: &HashMap<mt::EdgeID, Vec<usize>>,
|
||||
old: &[Surf],
|
||||
new: &[Surf],
|
||||
size: f64,
|
||||
) -> Option<Vec<(Vec3, Vec<usize>)>> {
|
||||
if at.len() < 4 || at.len() > MAX_SPLIT_FACES {
|
||||
return None;
|
||||
}
|
||||
let p = from_p3(v.point());
|
||||
// (face, outward normal, old offset, moved offset).
|
||||
let planes: Vec<(usize, Vec3, f64, f64)> = at
|
||||
.iter()
|
||||
.map(|i| match (old.get(*i)?, new.get(*i)?) {
|
||||
(Surf::Plane { n, d }, Surf::Plane { d: d2, .. }) => Some((*i, *n, *d, *d2)),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Option<_>>()?;
|
||||
let normal = |fi: usize| planes.iter().find(|x| x.0 == fi).map(|x| x.1);
|
||||
// Edge kinds round the corner: a face's loop runs counter-clockwise about its outward
|
||||
// normal, so its inside is to the left; the edge is convex when the face beyond it falls
|
||||
// away from there.
|
||||
let mut sign = 0.0f64;
|
||||
let mut pairs: Vec<(usize, usize)> = Vec::new();
|
||||
for &(fi, na, ..) in &planes {
|
||||
for w in faces.get(fi)?.boundaries() {
|
||||
for e in w.edge_iter() {
|
||||
if e.front().id() != v.id() && e.back().id() != v.id() {
|
||||
continue;
|
||||
}
|
||||
let fb = efaces.get(&e.id())?.iter().copied().find(|j| *j != fi)?;
|
||||
pairs.push((fi, fb));
|
||||
let dir = (from_p3(e.back().point()) - from_p3(e.front().point())).normalized()?;
|
||||
let s = normal(fb)?.dot(na.cross(dir));
|
||||
if s.abs() < 1e-9 {
|
||||
continue;
|
||||
}
|
||||
if sign * s < 0.0 {
|
||||
return None;
|
||||
}
|
||||
sign = s.signum();
|
||||
}
|
||||
}
|
||||
}
|
||||
if sign == 0.0 {
|
||||
return None;
|
||||
}
|
||||
// Convex: the body's side, n·x ≤ d; concave: the outside's, n·x ≥ d.
|
||||
let side = -sign;
|
||||
let merge = size * 1e-6;
|
||||
let mut nodes: Vec<(Vec3, Vec<usize>)> = Vec::new();
|
||||
for (ia, a) in planes.iter().enumerate() {
|
||||
for (ib, b) in planes.iter().enumerate().skip(ia + 1) {
|
||||
for c in planes.iter().skip(ib + 1) {
|
||||
let den = a.1.dot(b.1.cross(c.1));
|
||||
if den.abs() < 1e-9 {
|
||||
continue;
|
||||
}
|
||||
let x = (b.1.cross(c.1) * a.3 + c.1.cross(a.1) * b.3 + a.1.cross(b.1) * c.3) * (1.0 / den);
|
||||
if !x.is_finite() || x.dist(p) > size || planes.iter().any(|q| side * (q.1.dot(x) - q.3) > merge) {
|
||||
continue;
|
||||
}
|
||||
let fs = [a.0, b.0, c.0];
|
||||
match nodes.iter_mut().find(|(q, _)| q.dist(x) < merge) {
|
||||
Some((_, nf)) => {
|
||||
for f in fs {
|
||||
if !nf.contains(&f) {
|
||||
nf.push(f);
|
||||
}
|
||||
}
|
||||
}
|
||||
None => nodes.push((x, fs.to_vec())),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Every face keeps a corner here, and every edge an end.
|
||||
if planes.iter().any(|q| !nodes.iter().any(|(_, nf)| nf.contains(&q.0)))
|
||||
|| pairs.iter().any(|(x, y)| !nodes.iter().any(|(_, nf)| nf.contains(x) && nf.contains(y)))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
// Each corner where its planes meet best (least squares, for planes meeting at one point
|
||||
// to within the merge distance).
|
||||
for (q, nf) in nodes.iter_mut() {
|
||||
let (ns, ss): (Vec<Vec3>, Vec<f64>) = nf.iter().filter_map(|f| planes.iter().find(|x| x.0 == *f)).map(|x| (x.1, x.3 - x.2)).unzip();
|
||||
*q = p + span_step(&ns, &ss)?;
|
||||
}
|
||||
Some(nodes)
|
||||
}
|
||||
|
||||
/// The corners of a split corner (see [`split_corner`]) on face `face`, in order from corner
|
||||
/// `from` to corner `to`, along the new edges between them.
|
||||
fn split_path(nodes: &[(Vec3, Vec<usize>)], face: usize, from: usize, to: usize) -> Option<Vec<usize>> {
|
||||
let joined = |x: usize, y: usize| {
|
||||
let (Some((_, a)), Some((_, b))) = (nodes.get(x), nodes.get(y)) else { return false };
|
||||
a.contains(&face) && b.contains(&face) && a.iter().filter(|f| b.contains(f)).count() >= 2
|
||||
};
|
||||
// Breadth first; `prev` leads back to `from`.
|
||||
let mut prev: Vec<Option<usize>> = vec![None; nodes.len()];
|
||||
let mut queue = std::collections::VecDeque::from([from]);
|
||||
let mut seen = vec![false; nodes.len()];
|
||||
*seen.get_mut(from)? = true;
|
||||
while let Some(x) = queue.pop_front() {
|
||||
if x == to {
|
||||
let mut path = vec![to];
|
||||
let mut cur = to;
|
||||
while let Some(p) = prev.get(cur).copied().flatten() {
|
||||
path.push(p);
|
||||
cur = p;
|
||||
}
|
||||
path.reverse();
|
||||
return Some(path);
|
||||
}
|
||||
for y in 0..nodes.len() {
|
||||
if !seen.get(y).copied().unwrap_or(true) && joined(x, y) {
|
||||
*seen.get_mut(y)? = true;
|
||||
*prev.get_mut(y)? = Some(x);
|
||||
queue.push_back(y);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// A line or circular arc through an edge (by samples): `None` for other curves.
|
||||
/// Maximum straight edges per face checked pairwise for crossings.
|
||||
const MAX_CROSSING_EDGES: usize = 2000;
|
||||
@@ -431,7 +570,7 @@ const MAX_CROSSING_EDGES: usize = 2000;
|
||||
fn crossed_loops(
|
||||
faces: &[mt::Face],
|
||||
old: &[Surf],
|
||||
newpos: &HashMap<mt::VertexID, Vec3>,
|
||||
pos: &dyn Fn(&mt::Vertex, &mt::Edge) -> Option<Vec3>,
|
||||
edge_collapsed: &dyn Fn(&mt::Edge) -> bool,
|
||||
size: f64,
|
||||
) -> Option<Vec3> {
|
||||
@@ -443,32 +582,32 @@ fn crossed_loops(
|
||||
}
|
||||
let (u, w) = (n.any_perp(), n.cross(n.any_perp()));
|
||||
let flat = |p: Vec3| (p.dot(u), p.dot(w));
|
||||
// Straight edges as (vertex ids, old ends, new ends) in the plane.
|
||||
let mut segs: Vec<([mt::VertexID; 2], [(f64, f64); 2])> = Vec::new();
|
||||
// Straight edges as (vertex ids, new ends in the plane, the plane's new offset).
|
||||
let mut segs: Vec<([mt::VertexID; 2], [(f64, f64); 2], f64)> = Vec::new();
|
||||
for wire in f.absolute_boundaries() {
|
||||
let (mut area_old, mut area_new, mut straight) = (0.0, 0.0, true);
|
||||
for e in wire.edge_iter() {
|
||||
let (v0, v1) = (e.front(), e.back());
|
||||
let (Some(q0), Some(q1)) = (newpos.get(&v0.id()), newpos.get(&v1.id())) else { return None };
|
||||
let (o0, o1, n0, n1) = (flat(from_p3(v0.point())), flat(from_p3(v1.point())), flat(*q0), flat(*q1));
|
||||
let (Some(q0), Some(q1)) = (pos(v0, e), pos(v1, e)) else { return None };
|
||||
let (o0, o1, n0, n1) = (flat(from_p3(v0.point())), flat(from_p3(v1.point())), flat(q0), flat(q1));
|
||||
area_old += o0.0 * o1.1 - o1.0 * o0.1;
|
||||
area_new += n0.0 * n1.1 - n1.0 * n0.1;
|
||||
if arc_mid(e, size * 1e-6) == Some(None) {
|
||||
segs.push(([v0.id(), v1.id()], [n0, n1]));
|
||||
segs.push(([v0.id(), v1.id()], [n0, n1], n.dot(q0)));
|
||||
} else {
|
||||
straight = false;
|
||||
}
|
||||
}
|
||||
if straight && area_old.abs() > eps && area_old * area_new <= 0.0 {
|
||||
return wire.vertex_iter().next().and_then(|v| newpos.get(&v.id()).copied());
|
||||
return wire.edge_iter().next().and_then(|e| pos(e.front(), e));
|
||||
}
|
||||
}
|
||||
if segs.len() > MAX_CROSSING_EDGES {
|
||||
continue;
|
||||
}
|
||||
let side = |a: (f64, f64), c: (f64, f64), p: (f64, f64)| (c.0 - a.0) * (p.1 - a.1) - (c.1 - a.1) * (p.0 - a.0);
|
||||
for (i, (ia, [a0, a1])) in segs.iter().enumerate() {
|
||||
for (ib, [b0, b1]) in segs.iter().skip(i + 1) {
|
||||
for (i, (ia, [a0, a1], d)) in segs.iter().enumerate() {
|
||||
for (ib, [b0, b1], _) in segs.iter().skip(i + 1) {
|
||||
if ia.iter().any(|v| ib.contains(v)) {
|
||||
continue;
|
||||
}
|
||||
@@ -478,8 +617,7 @@ fn crossed_loops(
|
||||
if ((s0 > tol && s1 < -tol) || (s0 < -tol && s1 > tol)) && ((t0 > tol && t1 < -tol) || (t0 < -tol && t1 > tol)) {
|
||||
let k = t0 / (t0 - t1);
|
||||
let (x, y) = (a0.0 + (a1.0 - a0.0) * k, a0.1 + (a1.1 - a0.1) * k);
|
||||
let d = n.dot(newpos.get(&ia[0]).copied().unwrap_or_default());
|
||||
return Some(u * x + w * y + n * d);
|
||||
return Some(u * x + w * y + n * *d);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -618,6 +756,8 @@ pub(crate) fn offset_body(b: &Body, shift: impl Fn(usize, Vec3) -> f64) -> Resul
|
||||
})
|
||||
.collect();
|
||||
let mut newpos: HashMap<mt::VertexID, Vec3> = HashMap::new();
|
||||
// Corners whose moved faces meet at several points (see `split_corner`).
|
||||
let mut splits: HashMap<mt::VertexID, Vec<(Vec3, Vec<usize>)>> = HashMap::new();
|
||||
for v in b.solid.vertex_iter() {
|
||||
let at = vfaces.get(&v.id()).ok_or_else(|| fail("vertex"))?;
|
||||
let p = from_p3(v.point());
|
||||
@@ -672,10 +812,33 @@ pub(crate) fn offset_body(b: &Body, shift: impl Fn(usize, Vec3) -> f64) -> Resul
|
||||
});
|
||||
let q = match apex {
|
||||
Some(q) if n.iter().all(|sf| sf.dist(q).abs() < size * 1e-6) => q,
|
||||
_ => move_point(p, &o, &s, &n, size * 1e-6).ok_or_else(|| fail("a corner whose faces don't meet the same way after the move"))?,
|
||||
_ => match move_point(p, &o, &s, &n, size * 1e-6) {
|
||||
Some(q) => q,
|
||||
None => {
|
||||
let nodes = (fs == *at)
|
||||
.then(|| split_corner(&v, at, &faces, &efaces, &old, &new, size))
|
||||
.flatten()
|
||||
.ok_or_else(|| fail("a corner whose faces don't meet the same way after the move"))?;
|
||||
let q = nodes.first().map(|x| x.0).ok_or_else(|| fail("corner"))?;
|
||||
splits.insert(v.id(), nodes);
|
||||
q
|
||||
}
|
||||
},
|
||||
};
|
||||
newpos.insert(v.id(), q);
|
||||
}
|
||||
// Which of a split corner's new corners an edge ends at.
|
||||
let node_of = |v: mt::VertexID, e: mt::EdgeID| -> Option<usize> {
|
||||
let fs = efaces.get(&e)?;
|
||||
splits.get(&v)?.iter().position(|(_, nf)| fs.iter().all(|i| nf.contains(i)))
|
||||
};
|
||||
// Where an edge's end goes.
|
||||
let end_pos = |v: &mt::Vertex, e: &mt::Edge| -> Option<Vec3> {
|
||||
match splits.get(&v.id()) {
|
||||
Some(nodes) => nodes.get(node_of(v.id(), e.id())?).map(|x| x.0),
|
||||
None => newpos.get(&v.id()).copied(),
|
||||
}
|
||||
};
|
||||
// An edge turned round: faces crossed over (a wall thinner than the move), which would
|
||||
// leave the body inside out.
|
||||
let edge_collapsed = |e: &mt::Edge| efaces.get(&e.id()).is_some_and(|fs| fs.iter().any(|i| is_collapsed(*i)));
|
||||
@@ -684,8 +847,8 @@ pub(crate) fn offset_body(b: &Body, shift: impl Fn(usize, Vec3) -> f64) -> Resul
|
||||
continue;
|
||||
}
|
||||
let (f0, f1) = (e.absolute_front(), e.absolute_back());
|
||||
let (Some(q0), Some(q1)) = (newpos.get(&f0.id()), newpos.get(&f1.id())) else { continue };
|
||||
let (old_v, new_v) = (from_p3(f1.point()) - from_p3(f0.point()), *q1 - *q0);
|
||||
let (Some(q0), Some(q1)) = (end_pos(f0, &e), end_pos(f1, &e)) else { continue };
|
||||
let (old_v, new_v) = (from_p3(f1.point()) - from_p3(f0.point()), q1 - q0);
|
||||
if old_v.len() > size * 1e-6 && old_v.dot(new_v) < 0.0 {
|
||||
return Err(fail("not supported yet: the move is larger than a wall or step is thick (faces would cross)"));
|
||||
}
|
||||
@@ -693,7 +856,7 @@ pub(crate) fn offset_body(b: &Body, shift: impl Fn(usize, Vec3) -> f64) -> Resul
|
||||
// A plane's loops crossing after the move: a rim or ledge narrower than the move (the hole
|
||||
// in a top face sliding past its outer edge) turns part of the face inside out, though no
|
||||
// edge turns round.
|
||||
if let Some(at) = crossed_loops(&faces, &old, &newpos, &edge_collapsed, size) {
|
||||
if let Some(at) = crossed_loops(&faces, &old, &end_pos, &edge_collapsed, size) {
|
||||
return Err(fail(&format!(
|
||||
"not supported yet: the move is larger than a rim or ledge near [{:.1}, {:.1}, {:.1}] is wide (a face would turn inside out)",
|
||||
at.x, at.y, at.z
|
||||
@@ -725,6 +888,16 @@ pub(crate) fn offset_body(b: &Body, shift: impl Fn(usize, Vec3) -> f64) -> Resul
|
||||
};
|
||||
verts.insert(v.id(), nv);
|
||||
}
|
||||
let node_verts: HashMap<mt::VertexID, Vec<mt::Vertex>> =
|
||||
splits.iter().map(|(id, nodes)| (*id, nodes.iter().map(|(q, _)| builder::vertex(p3(*q))).collect())).collect();
|
||||
let vert_at = |v: &mt::Vertex, e: &mt::Edge| -> Option<&mt::Vertex> {
|
||||
match node_verts.get(&v.id()) {
|
||||
Some(nv) => nv.get(node_of(v.id(), e.id())?),
|
||||
None => verts.get(&v.id()),
|
||||
}
|
||||
};
|
||||
// New edges between a split corner's corners (stored from the lower index).
|
||||
let mut links: HashMap<(mt::VertexID, usize, usize), mt::Edge> = HashMap::new();
|
||||
// Old edge → new edge, and whether it runs the other way (merged with its twin).
|
||||
let mut edges: HashMap<mt::EdgeID, (mt::Edge, bool)> = HashMap::new();
|
||||
let mut merged: HashMap<(mt::VertexID, mt::VertexID), mt::Edge> = HashMap::new();
|
||||
@@ -732,7 +905,7 @@ pub(crate) fn offset_body(b: &Body, shift: impl Fn(usize, Vec3) -> f64) -> Resul
|
||||
if edges.contains_key(&e.id()) {
|
||||
continue;
|
||||
}
|
||||
let (Some(a), Some(c)) = (verts.get(&e.absolute_front().id()), verts.get(&e.absolute_back().id())) else { return Err(fail("edge")) };
|
||||
let (Some(a), Some(c)) = (vert_at(e.absolute_front(), &e), vert_at(e.absolute_back(), &e)) else { return Err(fail("edge")) };
|
||||
let touches = edge_collapsed(&e);
|
||||
if a == c || from_p3(a.point()).dist(from_p3(c.point())) < size * 1e-9 {
|
||||
if touches {
|
||||
@@ -796,18 +969,37 @@ pub(crate) fn offset_body(b: &Body, shift: impl Fn(usize, Vec3) -> f64) -> Resul
|
||||
if is_collapsed(i) {
|
||||
continue;
|
||||
}
|
||||
let wires: Vec<mt::Wire> = f
|
||||
.absolute_boundaries()
|
||||
.iter()
|
||||
.map(|w| {
|
||||
w.edge_iter()
|
||||
.filter_map(|e| {
|
||||
edges.get(&e.id()).map(|(ne, flip)| if (e.front() == e.absolute_front()) != *flip { ne.clone() } else { ne.inverse() })
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.into()
|
||||
})
|
||||
.collect();
|
||||
let mut wires: Vec<mt::Wire> = Vec::new();
|
||||
for w in f.absolute_boundaries() {
|
||||
let old_edges: Vec<mt::Edge> = w.edge_iter().cloned().collect();
|
||||
let mut wire: Vec<mt::Edge> = Vec::new();
|
||||
for (j, e) in old_edges.iter().enumerate() {
|
||||
if let Some((ne, flip)) = edges.get(&e.id()) {
|
||||
wire.push(if (e.front() == e.absolute_front()) != *flip { ne.clone() } else { ne.inverse() });
|
||||
}
|
||||
// At a split corner, along the new edges from this edge's end to the next's.
|
||||
let v = e.back();
|
||||
let (Some(nodes), Some(next)) = (splits.get(&v.id()), old_edges.get((j + 1) % old_edges.len())) else { continue };
|
||||
let (Some(from), Some(to)) = (node_of(v.id(), e.id()), node_of(v.id(), next.id())) else { return Err(fail("split corner")) };
|
||||
let path = split_path(nodes, i, from, to).ok_or_else(|| fail("split corner"))?;
|
||||
for pair in path.windows(2) {
|
||||
let (Some(&x), Some(&y)) = (pair.first(), pair.get(1)) else { continue };
|
||||
let key = (v.id(), x.min(y), x.max(y));
|
||||
let link = match links.get(&key) {
|
||||
Some(l) => l.clone(),
|
||||
None => {
|
||||
let nv = node_verts.get(&v.id()).ok_or_else(|| fail("split corner"))?;
|
||||
let (Some(va), Some(vb)) = (nv.get(key.1), nv.get(key.2)) else { return Err(fail("split corner")) };
|
||||
let l = builder::line(va, vb);
|
||||
links.insert(key, l.clone());
|
||||
l
|
||||
}
|
||||
};
|
||||
wire.push(if x < y { link } else { link.inverse() });
|
||||
}
|
||||
}
|
||||
wires.push(wire.into());
|
||||
}
|
||||
let (Some(o), Some(n)) = (old.get(i), new.get(i)) else { return Err(fail("face")) };
|
||||
let surface = match (o.map_to(n), *o, *n) {
|
||||
(Some(mat), _, _) => mt::Transformed::transformed(&f.surface(), mat),
|
||||
|
||||
@@ -266,9 +266,12 @@ fn boolean_whole(a: &Body, b: &Body, op: BoolOp) -> Result<Option<Body>> {
|
||||
let size = a.size().max(b.size());
|
||||
// The checks mesh both bodies; where they meet in a region much thinner than they are (a
|
||||
// thin part trimmed by a long one), a step from their size would facet the small faces
|
||||
// there coarsely enough to fail the membership test on a correct result.
|
||||
// there coarsely enough to fail the membership test on a correct result. The meshes are
|
||||
// refined: a round side trimmed to a thin band (a short boss crossing a gently sloping
|
||||
// floor) is otherwise spanned by triangles cutting through it, which reads as missing
|
||||
// material.
|
||||
let tol_m = (size * 5e-4).min(meeting_size(a, b) * 2e-3).max(size * 1e-5);
|
||||
let meshes = (a.tessellate(tol_m).ok(), b.tessellate(tol_m).ok());
|
||||
let meshes = (a.tessellate_with(tol_m, true).ok(), b.tessellate_with(tol_m, true).ok());
|
||||
let (va, vb) = match &meshes {
|
||||
(Some(ma), Some(mb)) => (ma.measure().volume, mb.measure().volume),
|
||||
_ => (volume(a), volume(b)),
|
||||
@@ -277,7 +280,7 @@ fn boolean_whole(a: &Body, b: &Body, op: BoolOp) -> Result<Option<Body>> {
|
||||
// Volume bounds, then membership against the operands (catches misclassified pieces), on
|
||||
// one mesh of the result. Returns (plausible, volume).
|
||||
let check = |r: &Body| -> (bool, f64) {
|
||||
let Ok(mr) = r.tessellate(tol_m) else { return (false, f64::NAN) };
|
||||
let Ok(mr) = r.tessellate_with(tol_m, true) else { return (false, f64::NAN) };
|
||||
let v = mr.measure().volume;
|
||||
let bounds = v > 0.0
|
||||
&& match op {
|
||||
|
||||
@@ -199,16 +199,72 @@ impl Node {
|
||||
}
|
||||
}
|
||||
|
||||
/// Polygons of a body whose faces are all planar (None otherwise).
|
||||
fn planar_polys(b: &Body) -> Option<Vec<Poly>> {
|
||||
/// Why a body's polygons can't be had: in words that finish "the {role} has …" or "the
|
||||
/// {role}'s …".
|
||||
#[derive(Debug, PartialEq)]
|
||||
enum NotPlanar {
|
||||
/// Faces on curved surfaces, counted by kind.
|
||||
Curved(std::collections::BTreeMap<&'static str, usize>),
|
||||
/// Something else (a face that could not be meshed, too many polygons).
|
||||
Other(String),
|
||||
}
|
||||
|
||||
impl NotPlanar {
|
||||
fn describe(&self, role: &str) -> String {
|
||||
match self {
|
||||
NotPlanar::Curved(kinds) => {
|
||||
let n: usize = kinds.values().sum();
|
||||
let list: Vec<&str> = kinds.keys().copied().collect();
|
||||
format!("the {role} has {n} curved face{} ({})", if n == 1 { "" } else { "s" }, list.join(", "))
|
||||
}
|
||||
NotPlanar::Other(m) => format!("the {role}'s {m}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The plane of each face (from its mesh, which must be flat), or what stands in the way: the
|
||||
/// curved faces by the kind of surface they lie on.
|
||||
fn face_planes(b: &Body, faces: &[crate::FaceInfo]) -> std::result::Result<Vec<PlaneEq>, NotPlanar> {
|
||||
use crate::FaceSurface;
|
||||
let mut curved: std::collections::BTreeMap<&'static str, usize> = std::collections::BTreeMap::new();
|
||||
let mut out = Vec::with_capacity(faces.len());
|
||||
for f in faces {
|
||||
if f.area <= 0.0 {
|
||||
return Err(NotPlanar::Other(format!("face {} could not be meshed", f.index)));
|
||||
}
|
||||
match f.plane_normal {
|
||||
Some(n) => out.push(PlaneEq { n, w: n.dot(f.centroid) }),
|
||||
None => {
|
||||
let kind = match crate::face_surface(b, f.index) {
|
||||
Some(FaceSurface::Cylinder { .. }) => "cylinder",
|
||||
Some(FaceSurface::Cone { .. }) => "cone",
|
||||
Some(FaceSurface::Sphere { .. }) => "sphere",
|
||||
Some(FaceSurface::Torus { .. }) => "torus",
|
||||
Some(FaceSurface::Plane { .. }) => return Err(NotPlanar::Other(format!("face {} is planar but its mesh is not flat", f.index))),
|
||||
None => "freeform",
|
||||
};
|
||||
*curved.entry(kind).or_insert(0) += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
if curved.is_empty() { Ok(out) } else { Err(NotPlanar::Curved(curved)) }
|
||||
}
|
||||
|
||||
/// Polygons of a body whose faces are all planar.
|
||||
fn planar_polys(b: &Body) -> std::result::Result<Vec<Poly>, NotPlanar> {
|
||||
let tol = (b.size() * 1e-3).max(1e-3);
|
||||
let faces = b.faces(tol).ok()?;
|
||||
let mesh = b.tessellate(tol).ok()?;
|
||||
let planes: Vec<PlaneEq> = faces.iter().map(|f| f.plane_normal.map(|n| PlaneEq { n, w: n.dot(f.centroid) })).collect::<Option<_>>()?;
|
||||
let unmeshed = |e: KernelError| NotPlanar::Other(format!("faces could not be meshed ({e})"));
|
||||
let faces = b.faces(tol).map_err(unmeshed)?;
|
||||
let mesh = b.tessellate(tol).map_err(unmeshed)?;
|
||||
let planes = face_planes(b, &faces)?;
|
||||
if mesh.triangles.len() > MAX_POLYS {
|
||||
return Err(NotPlanar::Other(format!("mesh is too detailed ({} triangles)", mesh.triangles.len())));
|
||||
}
|
||||
let bad_mesh = || NotPlanar::Other("mesh is inconsistent".into());
|
||||
let mut out = Vec::new();
|
||||
for (t, fi) in mesh.triangles.iter().zip(&mesh.tri_face) {
|
||||
let [a, bb, c] = mesh.tri(t)?;
|
||||
let plane = *planes.get(*fi as usize)?;
|
||||
let [a, bb, c] = mesh.tri(t).ok_or_else(bad_mesh)?;
|
||||
let plane = *planes.get(*fi as usize).ok_or_else(bad_mesh)?;
|
||||
// Snap the vertices onto the exact face plane.
|
||||
let snap = |p: Vec3| p - plane.n * (plane.n.dot(p) - plane.w);
|
||||
let mut v = vec![snap(a), snap(bb), snap(c)];
|
||||
@@ -217,7 +273,7 @@ fn planar_polys(b: &Body) -> Option<Vec<Poly>> {
|
||||
}
|
||||
out.push(Poly { v, plane });
|
||||
}
|
||||
(out.len() <= MAX_POLYS).then_some(out)
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Polygons of any body: planar faces exactly, curved ones as their triangles (within `tol`).
|
||||
@@ -305,11 +361,19 @@ pub fn faceted_boolean(a: &Body, b: &Mesh, op: BoolOp, tol: f64) -> Result<Optio
|
||||
pub fn planar_boolean(a: &Body, b: &Body, op: BoolOp) -> Result<Option<Body>> {
|
||||
a.require_brep("a boolean")?;
|
||||
b.require_brep("a boolean")?;
|
||||
let (Some(pa), Some(pb)) = (planar_polys(a), planar_polys(b)) else {
|
||||
if let Some(r) = sliced_planar_boolean(a, b, op) {
|
||||
return r;
|
||||
let (pa, pb) = match (planar_polys(a), planar_polys(b)) {
|
||||
(Ok(pa), Ok(pb)) => (pa, pb),
|
||||
(ra, rb) => {
|
||||
if let Some(r) = sliced_planar_boolean(a, b, op) {
|
||||
return r;
|
||||
}
|
||||
let why: Vec<String> =
|
||||
[(ra.err(), "target"), (rb.err(), "tool")].into_iter().filter_map(|(e, role)| e.map(|e| e.describe(role))).collect();
|
||||
return Err(KernelError::Failed(format!(
|
||||
"not supported yet: the exact fallback for where the bodies meet (faces that touch, or cross at a shallow angle) takes planar faces only, and {}",
|
||||
why.join(" and ")
|
||||
)));
|
||||
}
|
||||
return Err(KernelError::Failed("not supported yet: coincident faces on curved bodies".into()));
|
||||
};
|
||||
let size = a.size().max(b.size());
|
||||
polys_boolean(pa, pb, size, op, size * 1e-9)
|
||||
@@ -320,7 +384,7 @@ pub fn planar_boolean(a: &Body, b: &Body, op: BoolOp) -> Result<Option<Body>> {
|
||||
/// hole): `a` is split across the slab, the middle piece takes the exact boolean, and the
|
||||
/// pieces outside are joined back on. `None` when no such slab exists.
|
||||
fn sliced_planar_boolean(a: &Body, b: &Body, op: BoolOp) -> Option<Result<Option<Body>>> {
|
||||
let pb = planar_polys(b)?;
|
||||
let pb = planar_polys(b).ok()?;
|
||||
let size = a.size().max(b.size());
|
||||
let tol = (a.size() * 1e-3).max(1e-3);
|
||||
let infos = a.faces(tol).ok()?;
|
||||
@@ -391,7 +455,7 @@ fn sliced_planar_boolean(a: &Body, b: &Body, op: BoolOp) -> Option<Result<Option
|
||||
outside.extend(crate::ops::half_space(&middle, &plane, !keep_positive)?);
|
||||
middle = crate::ops::half_space(&middle, &plane, keep_positive)?.ok_or_else(|| fail("nothing beside the tool"))?;
|
||||
}
|
||||
let pm = planar_polys(&middle).ok_or_else(|| fail("the middle piece is not planar"))?;
|
||||
let pm = planar_polys(&middle).map_err(|e| fail(&e.describe("middle piece")))?;
|
||||
let r = polys_boolean(pm, pb, size, op, size * 1e-9)?;
|
||||
if op == BoolOp::Intersect {
|
||||
return Ok(r);
|
||||
|
||||
@@ -334,6 +334,73 @@ fn drain_pads_flush_under_a_floor_with_a_hole() {
|
||||
let v = measure(&u).unwrap().volume;
|
||||
let expect = v_floor + PI * 400.0 * 5.0;
|
||||
assert!(rel(v, expect) < 2e-5, "disc across the hole: {v} vs {expect}");
|
||||
// A boss ring standing on the sloping top around the hole, its foot just under the top
|
||||
// everywhere: it adds its annulus times its height above the top at the centre.
|
||||
let foot = 10.0 + t * 30.0 - 0.2;
|
||||
let u = boolean(&floor, &ring(foot, 14.0), BoolOp::Union).unwrap().unwrap();
|
||||
let v = measure(&u).unwrap().volume;
|
||||
let expect = v_floor + PI * 300.0 * (14.0 - (10.0 + t * 50.0));
|
||||
assert!(rel(v, expect) < 2e-5, "boss ring on the slope: {v} vs {expect}");
|
||||
assert!(u.validity().is_empty(), "{:?}", u.validity());
|
||||
}
|
||||
|
||||
/// A trough whose floor falls 1° (or 2° toward a drain, in four faces), and short round pads
|
||||
/// and bosses crossing the fall. The B-rep results were right, but the plausibility check meshed
|
||||
/// them without refinement: on a round side trimmed to a thin band by the shallow cut, the plain
|
||||
/// mesh spans the band with triangles cutting through the cylinder, so the check saw missing
|
||||
/// material, rejected the result, and the planar fallback refused the round pad.
|
||||
#[test]
|
||||
fn round_pads_crossing_a_shallow_fall() {
|
||||
let hs = |n: Vec3, p: Vec3| {
|
||||
let n = n.normalized().unwrap();
|
||||
HalfSpace { n, d: n.dot(p) }
|
||||
};
|
||||
let walls = |floor: &[HalfSpace]| {
|
||||
let mut h = vec![
|
||||
hs(Vec3::X, Vec3::new(290.0, 0.0, 0.0)),
|
||||
hs(-Vec3::X, Vec3::new(10.0, 0.0, 0.0)),
|
||||
hs(Vec3::Y, Vec3::new(0.0, 140.0, 0.0)),
|
||||
hs(-Vec3::Y, Vec3::new(0.0, 10.0, 0.0)),
|
||||
hs(Vec3::Z, Vec3::new(0.0, 0.0, 90.0)),
|
||||
];
|
||||
h.extend_from_slice(floor);
|
||||
convex_polyhedron(&h).unwrap()
|
||||
};
|
||||
let block = box_solid(Vec3::ZERO, Vec3::new(300.0, 150.0, 80.0)).unwrap();
|
||||
// One fall along x at 1°: floor z = 8 + t (x − 10).
|
||||
let t = 1f64.to_radians().tan();
|
||||
let fall = boolean(&block, &walls(&[hs(Vec3::new(t, 0.0, -1.0), Vec3::new(10.0, 0.0, 8.0))]), BoolOp::Cut).unwrap().unwrap();
|
||||
let v0 = measure(&fall).unwrap().volume;
|
||||
for x in [60.0, 100.0] {
|
||||
// A pad from z = 9 to 12 (its bottom just under the floor, its top 2–3 mm above).
|
||||
let pad = cylinder(Vec3::new(x, 75.0, 9.0), Vec3::Z, 15.0, 3.0).unwrap();
|
||||
let u = boolean(&fall, &pad, BoolOp::Union).unwrap().unwrap();
|
||||
// The part of the pad above the floor: the floor under the disc is planar, so its mean
|
||||
// height is the height at the centre (where the floor is below z = 9 everywhere).
|
||||
let floor = |x: f64| 8.0 + t * (x - 10.0);
|
||||
let above = if floor(x - 15.0) >= 9.0 { PI * 225.0 * (12.0 - floor(x)) } else { f64::NAN };
|
||||
let v = measure(&u).unwrap().volume;
|
||||
if above.is_finite() {
|
||||
assert!(rel(v, v0 + above) < 1e-5, "pad at x {x}: {v} vs {}", v0 + above);
|
||||
} else {
|
||||
assert!(v > v0 && v < v0 + PI * 225.0 * 3.0, "pad at x {x}: {v}");
|
||||
}
|
||||
}
|
||||
// Four faces falling 2° toward a drain point, and a pad over a valley edge and a wall.
|
||||
let t2 = 2f64.to_radians().tan();
|
||||
let d = Vec3::new(240.0, 110.0, 8.0);
|
||||
let hopper = walls(&[
|
||||
hs(Vec3::new(t2, 0.0, -1.0), d),
|
||||
hs(Vec3::new(-t2, 0.0, -1.0), d),
|
||||
hs(Vec3::new(0.0, t2, -1.0), d),
|
||||
hs(Vec3::new(0.0, -t2, -1.0), d),
|
||||
]);
|
||||
let trough = boolean(&block, &hopper, BoolOp::Cut).unwrap().unwrap();
|
||||
let pad = cylinder(Vec3::new(270.0, 70.0, 8.0), Vec3::Z, 25.0, 5.0).unwrap();
|
||||
let u = boolean(&trough, &pad, BoolOp::Union).unwrap().unwrap();
|
||||
// Integrated over the disc (outside the wall at x = 290): about 6517 mm³ above the floor.
|
||||
let gain = measure(&u).unwrap().volume - measure(&trough).unwrap().volume;
|
||||
assert!((gain - 6517.0).abs() < 10.0, "{gain}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -363,6 +430,38 @@ fn planar_booleans_with_coincident_faces() {
|
||||
assert!(rel(measure(&i).unwrap().volume, 250.0) < 1e-9);
|
||||
}
|
||||
|
||||
/// The planar fallback runs after any failed B-rep boolean, not only on coincident faces; when
|
||||
/// it can't run it says which body has which curved faces (it used to blame "coincident faces
|
||||
/// on curved bodies" whatever the cause).
|
||||
#[test]
|
||||
fn planar_fallback_names_the_curved_faces() {
|
||||
let slab = box_solid(Vec3::ZERO, Vec3::new(40.0, 30.0, 10.0)).unwrap();
|
||||
let pad = cylinder(Vec3::new(20.0, 15.0, 5.0), Vec3::Z, 8.0, 10.0).unwrap();
|
||||
let e = planar_boolean(&slab, &pad, BoolOp::Union).unwrap_err().to_string();
|
||||
assert!(e.contains("not supported yet"), "{e}");
|
||||
assert!(e.contains("the tool has 2 curved faces (cylinder)"), "{e}");
|
||||
assert!(!e.contains("target"), "{e}");
|
||||
assert!(!e.contains("coincident faces on curved bodies"), "{e}");
|
||||
let ball = sphere(Vec3::new(20.0, 15.0, 10.0), 5.0).unwrap();
|
||||
let e = planar_boolean(&ball, &pad, BoolOp::Cut).unwrap_err().to_string();
|
||||
assert!(e.contains("the target has 6 curved faces (sphere) and the tool has 2 curved faces (cylinder)"), "{e}");
|
||||
// All-planar bodies, a face of one at a shallow angle (1°): the fallback takes them.
|
||||
let slope = Vec3::new(-1f64.to_radians().tan(), 0.0, 1.0).normalized().unwrap();
|
||||
let wedge = convex_polyhedron(&[
|
||||
HalfSpace { n: Vec3::X, d: 30.0 },
|
||||
HalfSpace { n: -Vec3::X, d: -10.0 },
|
||||
HalfSpace { n: Vec3::Y, d: 20.0 },
|
||||
HalfSpace { n: -Vec3::Y, d: -10.0 },
|
||||
HalfSpace { n: -Vec3::Z, d: -5.0 },
|
||||
HalfSpace { n: slope, d: slope.dot(Vec3::new(10.0, 0.0, 11.0)) },
|
||||
])
|
||||
.unwrap();
|
||||
let u = planar_boolean(&slab, &wedge, BoolOp::Union).unwrap().unwrap();
|
||||
let above = box_solid(Vec3::new(0.0, 0.0, 10.0), Vec3::new(40.0, 30.0, 20.0)).unwrap();
|
||||
let expect = 40.0 * 30.0 * 10.0 + measure(&boolean(&wedge, &above, BoolOp::Intersect).unwrap().unwrap()).unwrap().volume;
|
||||
assert!(rel(measure(&u).unwrap().volume, expect) < 1e-6, "{} vs {expect}", measure(&u).unwrap().volume);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connected_logo_join_preserves_exact_faces_at_edge_contact() {
|
||||
let mut body = box_solid(Vec3::ZERO, Vec3::new(10.0, 20.0, 10.0)).unwrap();
|
||||
@@ -1510,6 +1609,49 @@ fn smooth_loft_through_three_sections() {
|
||||
assert!(v > PI * 64.0 * 30.0 && v < 576.0 * 30.0, "{v}");
|
||||
}
|
||||
|
||||
/// A loft from the basin's whole outline (10 up) down to a drain pad in a corner (1 up), cut
|
||||
/// from a 3 mm shell: its top edges lie on the outer walls. One order of the sections failed
|
||||
/// the cut ("shell not oriented and closed", or a panic inside the intersection), the other
|
||||
/// worked; both orders now build the same body, valid and outward.
|
||||
#[test]
|
||||
fn loft_section_order_gives_the_same_body() {
|
||||
let r = |x0: f64, y0: f64, x1: f64, y1: f64| Loop2::polygon(&[Vec2::new(x0, y0), Vec2::new(x1, y0), Vec2::new(x1, y1), Vec2::new(x0, y1)]);
|
||||
let at = |z: f64| Plane::new(Vec3::new(0.0, 0.0, z), Vec3::X, Vec3::Y).unwrap();
|
||||
let big = (at(10.0), r(0.0, 0.0, 100.0, 60.0));
|
||||
let small = (at(1.0), r(80.0, 40.0, 90.0, 50.0));
|
||||
let basin = shell(&box_solid(Vec3::ZERO, Vec3::new(100.0, 60.0, 30.0)).unwrap(), &[Vec3::new(50.0, 30.0, 30.0)], 3.0).unwrap();
|
||||
// The material inside the loft: the floor from 1 to 3 up, the walls from 3 to 10.
|
||||
let v0 = measure(&basin).unwrap().volume;
|
||||
let removed = v0 - 41582.028;
|
||||
let mut volumes = Vec::new();
|
||||
for secs in [vec![big.clone(), small.clone()], vec![small.clone(), big.clone()]] {
|
||||
let l = loft(&secs).unwrap();
|
||||
let m = measure(&l).unwrap();
|
||||
assert!(m.volume > 0.0, "{}", m.volume);
|
||||
volumes.push(m.volume);
|
||||
let cut = boolean(&basin, &l, BoolOp::Cut).unwrap().unwrap();
|
||||
let v = measure(&cut).unwrap().volume;
|
||||
assert!((v0 - v - removed).abs() < 0.01 * removed, "{v} vs {}", v0 - removed);
|
||||
let joined = boolean(&basin, &l, BoolOp::Union).unwrap().unwrap();
|
||||
assert!(measure(&joined).unwrap().volume > v0);
|
||||
}
|
||||
assert!(rel(volumes[0], volumes[1]) < 1e-12, "{volumes:?}");
|
||||
// Reversed in z too (large below, small above, and sketched on planes facing down).
|
||||
let down = |z: f64| Plane::new(Vec3::new(0.0, 0.0, z), Vec3::Y, Vec3::X).unwrap();
|
||||
for secs in [
|
||||
vec![(at(0.0), r(0.0, 0.0, 100.0, 60.0)), (at(20.0), r(40.0, 20.0, 60.0, 40.0))],
|
||||
vec![(down(20.0), r(20.0, 40.0, 40.0, 60.0)), (at(0.0), r(0.0, 0.0, 100.0, 60.0))],
|
||||
] {
|
||||
// Prismoid: h/6 · (A0 + 4 Amid + A1).
|
||||
let want = 20.0 / 6.0 * (6000.0 + 4.0 * 60.0 * 40.0 + 400.0);
|
||||
let back: Vec<(Plane, Loop2)> = secs.iter().rev().cloned().collect();
|
||||
for b in [loft(&secs).unwrap(), loft(&back).unwrap()] {
|
||||
let v = measure(&b).unwrap().volume;
|
||||
assert!(rel(v, want) < 1e-6, "{v} vs {want}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tangent_holes_pinch_alike() {
|
||||
// Holes at ±15 and ±25 touch along a line (x = ±20); ±30 overlaps ±25. The ±25 wall is cut
|
||||
@@ -1684,3 +1826,104 @@ fn orientation_mesh_reuses_missing_face_check_at_matching_tolerance() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A trough whose floor falls about 1° toward a central drain, the fall starting right at the
|
||||
/// trough edges: four faces meet at each bottom corner (two walls, two fall facets) and at the
|
||||
/// drain (four facets). A tab on one end makes the body non-convex. The moved planes of four
|
||||
/// faces don't meet at one point, so each such corner of the cavity becomes two corners joined
|
||||
/// by a short edge. Checked against the volume integrated by hand.
|
||||
#[test]
|
||||
fn shell_where_four_faces_meet_at_a_corner() {
|
||||
let (w, l, ht, t) = (100.0, 60.0, 40.0, 2.0);
|
||||
// Drain depth: the long facets fall 1°.
|
||||
let h = 30.0 * 1f64.to_radians().tan();
|
||||
let facet = |n: Vec3, p: Vec3| {
|
||||
let n = n.normalized().unwrap();
|
||||
HalfSpace { n, d: n.dot(p) }
|
||||
};
|
||||
let facets = [
|
||||
facet(Vec3::new(0.0, -h, -30.0), Vec3::ZERO),
|
||||
facet(Vec3::new(0.0, h, -30.0), Vec3::new(0.0, l, 0.0)),
|
||||
facet(Vec3::new(-h, 0.0, -50.0), Vec3::ZERO),
|
||||
facet(Vec3::new(h, 0.0, -50.0), Vec3::new(w, 0.0, 0.0)),
|
||||
];
|
||||
let mut hs = vec![
|
||||
HalfSpace { n: -Vec3::X, d: 0.0 },
|
||||
HalfSpace { n: Vec3::X, d: w },
|
||||
HalfSpace { n: -Vec3::Y, d: 0.0 },
|
||||
HalfSpace { n: Vec3::Y, d: l },
|
||||
HalfSpace { n: Vec3::Z, d: ht },
|
||||
];
|
||||
hs.extend(facets);
|
||||
let trough = convex_polyhedron(&hs).unwrap();
|
||||
let pyramid = w * l * h / 3.0;
|
||||
assert!(rel(measure(&trough).unwrap().volume, w * l * ht + pyramid) < 1e-9);
|
||||
let tab = box_solid(Vec3::new(w, 20.0, 20.0), Vec3::new(w + 20.0, 40.0, ht)).unwrap();
|
||||
let body = boolean(&trough, &tab, BoolOp::Union).unwrap().unwrap();
|
||||
let s = shell(&body, &[Vec3::new(50.0, 30.0, ht)], t).unwrap();
|
||||
// The cavity: the walls in by t, above the floor facets moved in by t (midpoint rule; the
|
||||
// floor is linear between its creases).
|
||||
let floor = |x: f64, y: f64| facets.iter().map(|f| (f.d - t - f.n.x * x - f.n.y * y) / f.n.z).fold(f64::NEG_INFINITY, f64::max);
|
||||
let (nx, ny) = (960, 560);
|
||||
let (dx, dy) = ((w - 2.0 * t) / nx as f64, (l - 2.0 * t) / ny as f64);
|
||||
let mut cavity = 0.0;
|
||||
for i in 0..nx {
|
||||
for j in 0..ny {
|
||||
cavity += (ht - floor(t + (i as f64 + 0.5) * dx, t + (j as f64 + 0.5) * dy)) * dx * dy;
|
||||
}
|
||||
}
|
||||
let tab_cavity = 20.0 * (20.0 - 2.0 * t) * (20.0 - t);
|
||||
let want = w * l * ht + pyramid + 8000.0 - cavity - tab_cavity;
|
||||
let m = measure(&s).unwrap();
|
||||
assert!(rel(m.volume, want) < 1e-5, "{} vs {want}", m.volume);
|
||||
}
|
||||
|
||||
/// The same trough cut as a pocket into a slab (four faces meet at each concave corner of the
|
||||
/// pocket floor), shelled with its top open.
|
||||
#[test]
|
||||
fn shell_of_a_pocket_whose_floor_falls_to_a_drain() {
|
||||
let (px, py, pw, pl, top, depth, t) = (20.0, 15.0, 100.0, 60.0, 50.0, 30.0, 3.0);
|
||||
let h = 30.0 * 1f64.to_radians().tan();
|
||||
let z0 = top - depth;
|
||||
let facet = |n: Vec3, p: Vec3| {
|
||||
let n = n.normalized().unwrap();
|
||||
HalfSpace { n, d: n.dot(p) }
|
||||
};
|
||||
let facets = [
|
||||
facet(Vec3::new(0.0, -h, -30.0), Vec3::new(px, py, z0)),
|
||||
facet(Vec3::new(0.0, h, -30.0), Vec3::new(px, py + pl, z0)),
|
||||
facet(Vec3::new(-h, 0.0, -50.0), Vec3::new(px, py, z0)),
|
||||
facet(Vec3::new(h, 0.0, -50.0), Vec3::new(px + pw, py, z0)),
|
||||
];
|
||||
let mut hs = vec![
|
||||
HalfSpace { n: -Vec3::X, d: -px },
|
||||
HalfSpace { n: Vec3::X, d: px + pw },
|
||||
HalfSpace { n: -Vec3::Y, d: -py },
|
||||
HalfSpace { n: Vec3::Y, d: py + pl },
|
||||
HalfSpace { n: Vec3::Z, d: top + 10.0 },
|
||||
];
|
||||
hs.extend(facets);
|
||||
let pocket = convex_polyhedron(&hs).unwrap();
|
||||
let slab = box_solid(Vec3::ZERO, Vec3::new(140.0, 90.0, top)).unwrap();
|
||||
let basin = boolean(&slab, &pocket, BoolOp::Cut).unwrap().unwrap();
|
||||
let pocket_vol = pw * pl * depth + pw * pl * h / 3.0;
|
||||
assert!(rel(measure(&basin).unwrap().volume, 140.0 * 90.0 * top - pocket_vol) < 1e-9);
|
||||
let s = shell(&basin, &[Vec3::new(5.0, 5.0, top)], t).unwrap();
|
||||
// The cavity's columns: from t up to the top, or up to the pocket floor moved down by t
|
||||
// inside the pocket's walls moved out by t.
|
||||
let floor = |x: f64, y: f64| facets.iter().map(|f| (f.d + t - f.n.x * x - f.n.y * y) / f.n.z).fold(f64::NEG_INFINITY, f64::max);
|
||||
let (nx, ny) = (1340, 840);
|
||||
let (dx, dy) = ((140.0 - 2.0 * t) / nx as f64, (90.0 - 2.0 * t) / ny as f64);
|
||||
let mut cavity = 0.0;
|
||||
for i in 0..nx {
|
||||
for j in 0..ny {
|
||||
let (x, y) = (t + (i as f64 + 0.5) * dx, t + (j as f64 + 0.5) * dy);
|
||||
let inside = x > px - t && x < px + pw + t && y > py - t && y < py + pl + t;
|
||||
let roof = if inside { floor(x, y) } else { top };
|
||||
cavity += (roof - t) * dx * dy;
|
||||
}
|
||||
}
|
||||
let want = 140.0 * 90.0 * top - pocket_vol - cavity;
|
||||
let m = measure(&s).unwrap();
|
||||
assert!(rel(m.volume, want) < 1e-4, "{} vs {want}", m.volume);
|
||||
}
|
||||
Reference in new issue
Block a user