Wave 424/509: Tessellation: two curves that touch within the chord tolerance share nodes, so the face pinches there (and 3 more)
4 commits, squashed; the originals stay reachable from tag archive/merge-main-develop. - 368b34e3b jyviko: Tessellation: a curved face's grid reads the quarter turn from its surface, not its parameter - 9da160892 jyviko: Tessellation: two corners of a face a hair apart, within their tolerance, are one point of it - 7cbbe2bc2 jyviko: Tessellation: two curves that touch within the chord tolerance share nodes, so the face pinches there - 95f1258b7 jyviko: Motion interference: a collision is deepest where the parts share the most volume Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ
This commit is contained in:
@@ -4,7 +4,6 @@
|
||||
//! answers the pairs of parts that pass through each other along the way.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use solidcraft_doc::joints;
|
||||
@@ -31,8 +30,10 @@ pub const INTERFERENCE_DOC: &str = "study: id|name; occurrences?: [ids or names]
|
||||
default every occurrence), with against?: [ids or names] (then each of `occurrences` is checked only against these, such \
|
||||
as an arm against the parts it must miss), or contact_sets?: true (the pairs of the design's contact sets); samples? \
|
||||
(2…1000, default the study's steps + 1) → collisions: [{a, b, first_step, last_step, steps: [[from, to]…] (the step ranges where they overlap), \
|
||||
depth_mm (how far into each other, the most at deepest_step), volume_mm3 (their overlap there; null when it was not \
|
||||
cheap to work out)}], clear, \
|
||||
volume_mm3 (the most volume they share at a sample, worked out exactly from the bodies; null when it was not cheap to \
|
||||
work out at every sample they overlap), deepest_step (the first sample sharing that volume; with volume_mm3 null, the \
|
||||
one of the greatest depth_mm), depth_mm (how far into each other at most: an estimate from points of the bodies' \
|
||||
contact meshes, not exact)}], clear, \
|
||||
pairs (checked), samples (taken), truncated (the work budget ran out; checked_to: the last step checked), stopped_at, \
|
||||
stopped_by_loop. The study plays as motion.play plays it but contact sets do not stop it, on a copy (the design is not \
|
||||
changed). Parts are tested at the samples only: one that passes wholly through another between two samples is missed";
|
||||
@@ -43,9 +44,10 @@ const MAX_SAMPLES: usize = 1000;
|
||||
const MAX_SERIES: usize = 256;
|
||||
/// Most collision work over a whole study (see `ContactGeometry::hits`).
|
||||
const MAX_WORK: usize = 500_000_000;
|
||||
/// Most colliding pairs whose overlap volume is worked out, and most body booleans that takes.
|
||||
/// Most colliding pairs whose overlap volume is worked out, and most body booleans that takes
|
||||
/// over the whole study (one per pair of overlapping bodies at each sample a pair collides).
|
||||
const MAX_VOLUMES: usize = 16;
|
||||
const MAX_BOOLEANS: usize = 64;
|
||||
const MAX_BOOLEANS: usize = 256;
|
||||
|
||||
/// How many samples `p` asks for (`min`…`MAX_SAMPLES`, default the study's steps + 1).
|
||||
fn samples(p: &Value, m: &MotionStudy, min: usize, cmd: &str) -> Result<usize> {
|
||||
@@ -250,10 +252,29 @@ struct Collision {
|
||||
names: (String, String),
|
||||
/// The samples where they overlap, in order.
|
||||
samples: Vec<usize>,
|
||||
/// The most sampled mesh depth, and the first sample reaching it.
|
||||
depth: f64,
|
||||
deepest: usize,
|
||||
/// The design at the deepest sample (its placements).
|
||||
at_deepest: Arc<Document>,
|
||||
/// The most exact shared volume and the first sample sharing it; `None` once a sample's
|
||||
/// volume was not worked out (the pair got no volume slot, or the booleans ran out).
|
||||
most_volume: Option<(f64, usize)>,
|
||||
}
|
||||
|
||||
impl Collision {
|
||||
/// Takes the exact shared volume at sample `k` (`None`: not worked out). A volume larger by
|
||||
/// no more than the booleans' rounding is a tie, which keeps the earlier sample.
|
||||
fn take_volume(&mut self, k: usize, volume: Option<f64>) {
|
||||
self.most_volume = match (self.most_volume, volume) {
|
||||
(Some((best, at)), Some(v)) => Some(if v > best + 1e-9 * best.max(1.0) { (v, k) } else { (best, at) }),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
|
||||
/// The sample the collision is deepest at: where they share the most volume, else (no
|
||||
/// volume) where the sampled depth is greatest.
|
||||
fn deepest_sample(&self) -> usize {
|
||||
self.most_volume.map_or(self.deepest, |(_, at)| at)
|
||||
}
|
||||
}
|
||||
|
||||
/// The volume the parts under occurrences `a` and `b` share, placed as in `doc` (`None`: not
|
||||
@@ -358,12 +379,14 @@ pub(super) fn checked_pairs(s: &Session, p: &Value, cmd: &str) -> Result<Contact
|
||||
}
|
||||
|
||||
pub(super) fn interference(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let s: &Session = s;
|
||||
let cmd = "motion.interference";
|
||||
let m = s.doc.assembly.studies.get(study_index(s, p, cmd)?).cloned().ok_or_else(|| bad(cmd, "study"))?;
|
||||
let n = samples(p, &m, 2, cmd)?;
|
||||
let geometry = checked_pairs(s, p, cmd)?;
|
||||
let mut found: BTreeMap<(u64, u64), Collision> = BTreeMap::new();
|
||||
let (mut work, mut checked, mut truncated) = (0usize, 0usize, false);
|
||||
let mut booleans = MAX_BOOLEANS;
|
||||
let stop = play(s, &m, n, false, |t, k| {
|
||||
// Placing the meshes is work too, also where nothing comes near.
|
||||
work = work.saturating_add(geometry.vertex_count());
|
||||
@@ -383,18 +406,24 @@ pub(super) fn interference(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for ((a, an), (b, bn), depth) in hits {
|
||||
// Each pair once, the older occurrence (the lower id) first.
|
||||
let ((a, an), (b, bn)) = if a <= b { ((a, an), (b, bn)) } else { ((b, bn), (a, an)) };
|
||||
// The first MAX_VOLUMES pairs found have their shared volume worked out.
|
||||
let slots = found.len() < MAX_VOLUMES;
|
||||
let c = found.entry((a, b)).or_insert_with(|| Collision {
|
||||
names: (an, bn),
|
||||
samples: Vec::new(),
|
||||
depth: 0.0,
|
||||
deepest: k,
|
||||
at_deepest: t.doc.clone(),
|
||||
most_volume: slots.then_some((0.0, k)),
|
||||
});
|
||||
if c.samples.last() != Some(&k) {
|
||||
c.samples.push(k);
|
||||
if c.samples.last() == Some(&k) {
|
||||
continue;
|
||||
}
|
||||
c.samples.push(k);
|
||||
if depth > c.depth {
|
||||
(c.depth, c.deepest, c.at_deepest) = (depth, k, t.doc.clone());
|
||||
(c.depth, c.deepest) = (depth, k);
|
||||
}
|
||||
if c.most_volume.is_some() {
|
||||
c.take_volume(k, shared_volume(s, &t.doc, a, b, &mut booleans));
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
@@ -405,16 +434,14 @@ pub(super) fn interference(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let mut list: Vec<(&(u64, u64), &Collision)> = found.iter().collect();
|
||||
list.sort_by_key(|(_, c)| c.samples.first().copied().unwrap_or(usize::MAX));
|
||||
let mut booleans = MAX_BOOLEANS;
|
||||
let collisions: Vec<Value> = list
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, ((a, b), c))| {
|
||||
let volume = if i < MAX_VOLUMES { shared_volume(s, &c.at_deepest, *a, *b, &mut booleans) } else { None };
|
||||
.map(|(_, c)| {
|
||||
let volume = c.most_volume.map(|(v, _)| v);
|
||||
let first = c.samples.first().map(|k| step_of(&m, *k, n));
|
||||
let last = c.samples.last().map(|k| step_of(&m, *k, n));
|
||||
json!({"a": c.names.0, "b": c.names.1, "first_step": first, "last_step": last, "steps": ranges(&m, &c.samples, n),
|
||||
"depth_mm": c.depth, "deepest_step": step_of(&m, c.deepest, n), "volume_mm3": volume})
|
||||
"depth_mm": c.depth, "deepest_step": step_of(&m, c.deepest_sample(), n), "volume_mm3": volume})
|
||||
})
|
||||
.collect();
|
||||
let mut out = json!({"study": m.name, "steps": m.steps, "clear": collisions.is_empty(), "collisions": collisions,
|
||||
|
||||
@@ -147,10 +147,9 @@ fn interference_names_the_step_two_parts_start_to_collide() {
|
||||
assert_eq!((c["a"].as_str(), c["b"].as_str()), (Some("A:1"), Some("B:1")), "{r}");
|
||||
assert_eq!((c["first_step"].as_f64(), c["last_step"].as_f64()), (Some(11.0), Some(15.0)), "{r}");
|
||||
assert_eq!(c["steps"], json!([[11.0, 15.0]]), "{r}");
|
||||
let deepest = c["deepest_step"].as_f64().unwrap_or(f64::NAN);
|
||||
assert!(c["depth_mm"].as_f64().unwrap_or(0.0) > 1.0 && (11.0..=15.0).contains(&deepest), "{r}");
|
||||
let volume = c["volume_mm3"].as_f64().unwrap_or(f64::NAN);
|
||||
assert!((volume - 100.0 * (deepest - 10.0)).abs() < 1e-6, "{r}");
|
||||
// Deepest where they share the most: 5 mm of the 10 x 10 face at the end.
|
||||
assert!(c["depth_mm"].as_f64().unwrap_or(0.0) > 1.0 && c["deepest_step"] == 15.0, "{r}");
|
||||
assert!((c["volume_mm3"].as_f64().unwrap_or(f64::NAN) - 500.0).abs() < 1e-6, "{r}");
|
||||
}
|
||||
// B against a far block C only: B's pass through A is not asked about.
|
||||
run(&mut s, "component.create", json!({"name": "C"}));
|
||||
@@ -167,6 +166,39 @@ fn interference_names_the_step_two_parts_start_to_collide() {
|
||||
assert!(r["clear"] == true && r["collisions"] == json!([]), "{r}");
|
||||
}
|
||||
|
||||
/// An arm (40 x 10 x 10 from (0, -5, 0)) turns on a hinge at the origin from 0 to 90 degrees in
|
||||
/// 9 steps into a grounded block (50 x 10 x 10 from (-10, 30, 0)). Its corner (40, 5) reaches
|
||||
/// y = 40 sin θ + 5 cos θ, past 30 from 40.97 degrees, so it overlaps from step 5. Every point of
|
||||
/// the slab is within 5 mm of z = 0 or z = 10, so from 60 degrees on (where the arm's side
|
||||
/// crosses y = 35) the depth is 5 mm at every step: only the shared volume, which grows to the
|
||||
/// arm's 10 x 10 x 10 end inside the block at 90 degrees, tells the deepest step. Sampled twice
|
||||
/// as densely (5 degrees a sample), the overlap is seen from step 4.5 (45 degrees) and is still
|
||||
/// deepest at the end.
|
||||
#[test]
|
||||
fn interference_is_deepest_where_the_parts_share_the_most_volume() {
|
||||
let mut s = Session::default();
|
||||
for (name, size, corner) in [("Base", [20, 20, 10], [-10, -10, -10]), ("Arm", [40, 10, 10], [0, -5, 0]), ("Stop", [50, 10, 10], [-10, 30, 0])] {
|
||||
run(&mut s, "component.activate", json!({"component": "root"}));
|
||||
run(&mut s, "component.create", json!({"name": name}));
|
||||
run(&mut s, "solid.box", json!({"length": size[0], "width": size[1], "height": size[2], "corner": corner}));
|
||||
}
|
||||
run(&mut s, "component.activate", json!({"component": "root"}));
|
||||
for name in ["Base", "Stop"] {
|
||||
let o = occ(&s, name);
|
||||
run(&mut s, "occurrence.ground", json!({"occurrence": o, "grounded": true}));
|
||||
}
|
||||
let end = |o: &str| json!({"occurrence": o, "point": [0, 0, 0], "z": [0, 0, 1]});
|
||||
run(&mut s, "joint.create", json!({"type": "revolute", "name": "Hinge", "flip": true, "a": end("Base"), "b": end("Arm"), "quiet": true}));
|
||||
run(&mut s, "motion.study", json!({"name": "Open", "steps": 9, "keys": [{"joint": "Hinge", "points": [[0, 0], [9, 90]]}]}));
|
||||
for (samples, first) in [(10, 5.0), (19, 4.5)] {
|
||||
let r = run(&mut s, "motion.interference", json!({"study": "Open", "samples": samples, "occurrences": ["Arm"], "against": ["Stop"]}));
|
||||
let c = &r["collisions"][0];
|
||||
assert!(r["clear"] == false && c["first_step"] == first && c["last_step"] == 9.0 && c["deepest_step"] == 9.0, "{samples}: {r}");
|
||||
assert!((c["volume_mm3"].as_f64().unwrap_or(f64::NAN) - 1000.0).abs() < 1e-6, "{samples}: {r}");
|
||||
assert!(c["depth_mm"].as_f64().is_some_and(|d| d > 0.0 && d <= 5.0 + 1e-9), "{samples}: {r}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A number names a study by its id first, text by its name first: a study may be named like
|
||||
/// another's id.
|
||||
#[test]
|
||||
|
||||
@@ -15,7 +15,7 @@ const MAX_DEPTH: u32 = 24;
|
||||
/// The most of its curve's turn one segment may span (a quarter turn, with rounding room): the
|
||||
/// boundary of every face stays a polygon with the face's area, as a closed curve's first four
|
||||
/// segments keep it.
|
||||
const QUARTER_TURN: f64 = std::f64::consts::FRAC_PI_2 * (1.0 + 1e-9);
|
||||
pub(crate) const QUARTER_TURN: f64 = std::f64::consts::FRAC_PI_2 * (1.0 + 1e-9);
|
||||
|
||||
/// An edge's nodes, from its start vertex (interval min) to its end vertex (interval max).
|
||||
pub(crate) struct Nodes {
|
||||
@@ -23,6 +23,10 @@ pub(crate) struct Nodes {
|
||||
/// The curve's parameter at each node (the edge's interval, ends included): where each
|
||||
/// face's pcurve of the edge gives the node's (u, v).
|
||||
pub params: Vec<f64>,
|
||||
/// The parameters of the nodes that are another edge's node, where the two edges touch
|
||||
/// within the chord tolerance (see [`snap`]): in a face that runs both edges such a node is
|
||||
/// the other's point of the face, a pinch, not a crossing.
|
||||
pub snapped: Vec<f64>,
|
||||
}
|
||||
|
||||
/// Nodes of edge `ei` of `b` from its start to its end: every chord within the tolerance of
|
||||
@@ -56,7 +60,7 @@ pub(crate) fn sample_edge(b: &brep::Brep, ei: usize, rules: &Rules, h: f64) -> R
|
||||
*p = back;
|
||||
*t = t1;
|
||||
}
|
||||
return Ok(Nodes { points: pts, params });
|
||||
return Ok(Nodes { points: pts, params, snapped: Vec::new() });
|
||||
}
|
||||
let curve = CurveEval::new(edge.parameters()).map_err(|e| fail(e.to_string()))?;
|
||||
let at =
|
||||
@@ -115,7 +119,7 @@ pub(crate) fn sample_edge(b: &brep::Brep, ei: usize, rules: &Rules, h: f64) -> R
|
||||
if let Some(p) = out.last_mut() {
|
||||
*p = (t1, back);
|
||||
}
|
||||
Ok(Nodes { points: out.iter().map(|p| p.1).collect(), params: out.iter().map(|p| p.0).collect() })
|
||||
Ok(Nodes { points: out.iter().map(|p| p.1).collect(), params: out.iter().map(|p| p.0).collect(), snapped: Vec::new() })
|
||||
}
|
||||
|
||||
/// Edge `ei`'s nodes with each of its segments `segs` (counted from its start) halved at the
|
||||
@@ -158,12 +162,50 @@ pub(crate) fn split_segments(b: &brep::Brep, ei: usize, nodes: &mut Nodes, segs:
|
||||
points.push(pm);
|
||||
params.push(m);
|
||||
}
|
||||
*nodes = Nodes { points, params };
|
||||
nodes.points = points;
|
||||
nodes.params = params;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Edge `ei`'s nodes with `add` (each a parameter strictly inside a segment and the point there)
|
||||
/// put in, in order, each marked as snapped: the point is another edge's node within the chord
|
||||
/// tolerance of this edge's chord there (the edges touch), so the two edges share it. A parameter
|
||||
/// that is not strictly between its segment's two (a node already there) is left out. More than
|
||||
/// [`MAX_EDGE_NODES`] nodes is an error naming the edge.
|
||||
pub(crate) fn snap(ei: usize, nodes: &mut Nodes, add: &[(f64, Vec3)]) -> Result<()> {
|
||||
let mut add: Vec<(f64, Vec3)> = add.iter().copied().filter(|(t, p)| t.is_finite() && p.is_finite()).collect();
|
||||
add.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
add.dedup_by(|a, b| a.0 == b.0);
|
||||
if nodes.points.len() + add.len() > MAX_EDGE_NODES {
|
||||
return Err(KernelError::Failed(format!("tessellation: edge {ei}: more than {MAX_EDGE_NODES} nodes")));
|
||||
}
|
||||
let n = nodes.points.len().min(nodes.params.len());
|
||||
let (mut points, mut params) = (Vec::with_capacity(n + add.len()), Vec::with_capacity(n + add.len()));
|
||||
let mut next = add.iter().peekable();
|
||||
for k in 0..n {
|
||||
let (Some(&p), Some(&t)) = (nodes.points.get(k), nodes.params.get(k)) else { continue };
|
||||
points.push(p);
|
||||
params.push(t);
|
||||
let Some(&u) = nodes.params.get(k + 1) else { continue };
|
||||
while let Some(&&(m, q)) = next.peek() {
|
||||
if m >= u {
|
||||
break;
|
||||
}
|
||||
next.next();
|
||||
if m > t {
|
||||
points.push(q);
|
||||
params.push(m);
|
||||
nodes.snapped.push(m);
|
||||
}
|
||||
}
|
||||
}
|
||||
nodes.points = points;
|
||||
nodes.params = params;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Angle (radians) between two directions; zero when either is empty.
|
||||
fn turn(a: Vec3, b: Vec3) -> f64 {
|
||||
pub(crate) fn turn(a: Vec3, b: Vec3) -> f64 {
|
||||
let (la, lb) = (a.len(), b.len());
|
||||
if !(la > 0.0 && lb > 0.0) {
|
||||
return 0.0;
|
||||
|
||||
@@ -196,7 +196,7 @@ pub(crate) fn plan(b: &brep::Brep, tol: f64, turn: Option<size::Turn>) -> Result
|
||||
};
|
||||
let mut boundaries: Vec<Boundary> =
|
||||
crate::par::map("face boundaries", &indexed, curved >= PARALLEL_FACES, |&fi| face_boundary(fi, &nodes)).into_iter().collect::<Result<_>>()?;
|
||||
let tangled = untangle(b, &evals, &edge_faces, &mut nodes, &mut boundaries, &face_boundary)?;
|
||||
let tangled = untangle(b, &evals, &edge_faces, rules.tol, &mut nodes, &mut boundaries, &face_boundary)?;
|
||||
let planned = crate::par::map("face tessellation", &indexed, curved >= PARALLEL_FACES, |&fi| {
|
||||
let (Some(face), Some(eval), Some(size), Some(fb)) = (faces.get(fi), evals.get(fi), sizes.get(fi), boundaries.get(fi)) else {
|
||||
return Err(unsupported(format!("face {fi}: missing")));
|
||||
@@ -288,10 +288,19 @@ fn boundary(
|
||||
let mut out = Boundary { loops: Vec::with_capacity(face.loops.len()), segments: Vec::with_capacity(face.loops.len()), reach };
|
||||
// Each vertex's parameters, from the first edge use of the face to start there.
|
||||
let mut at_vertex: std::collections::HashMap<u32, [f64; 2]> = std::collections::HashMap::new();
|
||||
// The vertex pairs an edge of the face joins.
|
||||
let joined: std::collections::HashSet<(u32, u32)> = face_edges(face)
|
||||
.filter_map(|oe| b.edges.get(oe.edge as usize))
|
||||
.map(|e| (e.vertices[0].min(e.vertices[1]), e.vertices[0].max(e.vertices[1])))
|
||||
.collect();
|
||||
let vertex_point = |v: u32| b.vertices.get(v as usize).map(|x| (Vec3::new(x.point[0], x.point[1], x.point[2]), x.tolerance.max(0.0)));
|
||||
// Each loop's nodes that are another edge's node (see [`edges::snap`]).
|
||||
let mut snapped: Vec<Vec<bool>> = Vec::with_capacity(face.loops.len());
|
||||
for l in &face.loops {
|
||||
let Loop::Edges { edges } = l else { continue };
|
||||
let (mut pts, mut uvs): (Vec<Vec3>, Vec<[f64; 2]>) = (Vec::new(), Vec::new());
|
||||
let mut segs: Vec<(u32, u32)> = Vec::new();
|
||||
let mut shared: Vec<bool> = Vec::new();
|
||||
// Where the previous edge ended, and the periods its pcurve was moved by.
|
||||
let (mut end, mut shift): (Option<[f64; 2]>, [f64; 2]) = (None, [0.0; 2]);
|
||||
for oe in edges {
|
||||
@@ -306,6 +315,7 @@ fn boundary(
|
||||
// The edge's own tolerance: how far its curve may stand off the face.
|
||||
let accept = (rules.tol * 10.0).max(1e-6) + edge.tolerance.max(0.0);
|
||||
let mut ep: Vec<Vec3> = n.points.clone();
|
||||
let mut es: Vec<bool> = n.params.iter().map(|t| n.snapped.contains(t)).collect();
|
||||
let mut eq: Vec<[f64; 2]> = Vec::with_capacity(ep.len());
|
||||
for (k, (t, p)) in n.params.iter().zip(&n.points).enumerate() {
|
||||
let q = oe.pcurve.eval(t.clamp(p0, p1)).ok_or_else(|| fail(oe.edge, format!("its pcurve does not evaluate at t = {t}")))?;
|
||||
@@ -320,6 +330,7 @@ fn boundary(
|
||||
if !oe.forward {
|
||||
ep.reverse();
|
||||
eq.reverse();
|
||||
es.reverse();
|
||||
}
|
||||
if let (Some(e), Some(&start)) = (end, eq.first()) {
|
||||
for d in 0..2 {
|
||||
@@ -341,6 +352,24 @@ fn boundary(
|
||||
}
|
||||
}
|
||||
None => {
|
||||
// Another vertex of the face within the tolerance of both (and of the
|
||||
// chord tolerance), and not joined to this one by an edge (which makes
|
||||
// them two points however near: a step that small), is the same point:
|
||||
// the record's corners a hair apart (a planar boolean's, where a cut-out's
|
||||
// corner touches another loop's corner) are one point of the face, so its
|
||||
// loops touch there instead of crossing.
|
||||
let same = vertex_point(v).and_then(|(p, tv)| {
|
||||
at_vertex.iter().filter(|(w, _)| **w != v && !joined.contains(&(v.min(**w), v.max(**w)))).find_map(|(w, wq)| {
|
||||
let (pw, tw) = vertex_point(*w)?;
|
||||
(p.dist(pw) <= tv.max(tw).min(rules.tol)).then_some(*wq)
|
||||
})
|
||||
});
|
||||
if let Some(mut w) = same.filter(|w| !(0..2).any(|d| pole_along(*w, d) || pole_along(*q, d))) {
|
||||
for d in 0..2 {
|
||||
w[d] = uv::unwrap(w[d], q[d], dom.period[d]);
|
||||
}
|
||||
*q = w;
|
||||
}
|
||||
at_vertex.insert(v, *q);
|
||||
}
|
||||
}
|
||||
@@ -348,11 +377,13 @@ fn boundary(
|
||||
end = eq.last().copied();
|
||||
ep.pop();
|
||||
eq.pop();
|
||||
es.pop();
|
||||
// The segment from each node on: the edge's own, counted from its start.
|
||||
let m = ep.len() as u32;
|
||||
segs.extend((0..m).map(|j| (oe.edge, if oe.forward { j } else { m - 1 - j })));
|
||||
pts.extend(ep);
|
||||
uvs.extend(eq);
|
||||
shared.extend(es);
|
||||
}
|
||||
let n = uvs.len();
|
||||
let pole = |q: &[f64; 2]| (0..2).any(|d| pole_along(*q, d));
|
||||
@@ -367,10 +398,37 @@ fn boundary(
|
||||
uvs.rotate_left(k);
|
||||
pts.rotate_left(k);
|
||||
segs.rotate_left(k);
|
||||
shared.rotate_left(k);
|
||||
}
|
||||
if pts.len() >= 2 {
|
||||
out.loops.push(seam::Loop { uv: uvs, pts });
|
||||
out.segments.push(segs);
|
||||
snapped.push(shared);
|
||||
}
|
||||
}
|
||||
// A node snapped from another edge is that edge's node, the same point: where the face runs
|
||||
// that edge too, the node takes the other's parameters, so the face's boundary passes one
|
||||
// point of its (u, v) twice (a pinch) and does not cross itself there. Its own pcurve puts it
|
||||
// within the chord tolerance of that point, not on it.
|
||||
for (l, flags) in snapped.iter().enumerate() {
|
||||
for (k, _) in flags.iter().enumerate().filter(|(_, f)| **f) {
|
||||
let Some((&p, &q)) = out.loops.get(l).and_then(|lp| lp.pts.get(k).zip(lp.uv.get(k))) else { continue };
|
||||
let partner = out
|
||||
.loops
|
||||
.iter()
|
||||
.zip(&snapped)
|
||||
.flat_map(|(lp, fs)| lp.pts.iter().zip(&lp.uv).zip(fs))
|
||||
.filter(|((r, _), f)| !**f && **r == p)
|
||||
.map(|((_, w), _)| *w)
|
||||
.min_by(|a, b| (a[0] - q[0]).hypot(a[1] - q[1]).total_cmp(&(b[0] - q[0]).hypot(b[1] - q[1])));
|
||||
if let (Some(mut w), Some(slot)) = (partner, out.loops.get_mut(l).and_then(|lp| lp.uv.get_mut(k))) {
|
||||
for d in 0..2 {
|
||||
if dom.period[d].is_some() {
|
||||
w[d] = uv::unwrap(w[d], q[d], dom.period[d]);
|
||||
}
|
||||
}
|
||||
*slot = w;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
@@ -394,10 +452,12 @@ struct Boundary {
|
||||
/// so every face of the edge gets the new nodes; the faces of every edge split are checked again,
|
||||
/// until no chords cross. Boundaries that still cross after [`MAX_UNTANGLE`] rounds, or would
|
||||
/// put more than [`edges::MAX_EDGE_NODES`] on an edge, are an error naming the face and edges.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn untangle(
|
||||
b: &brep::Brep,
|
||||
evals: &[EvalSurface],
|
||||
edge_faces: &[Vec<usize>],
|
||||
tol: f64,
|
||||
nodes: &mut [edges::Nodes],
|
||||
boundaries: &mut [Boundary],
|
||||
face_boundary: &(dyn Fn(usize, &[edges::Nodes]) -> Result<Boundary> + Sync),
|
||||
@@ -419,6 +479,10 @@ fn untangle(
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
if round == MAX_UNTANGLE {
|
||||
// Halving cannot part two curves that touch or cross: where they come within the chord
|
||||
// tolerance of each other, they share nodes.
|
||||
let faces: Vec<usize> = tangled.iter().map(|(fi, _)| *fi).collect();
|
||||
tangled = snap_touches(evals, edge_faces, tol, nodes, boundaries, face_boundary, &faces)?;
|
||||
// Each face still crossing, with why: planned leniently, and named (`plan_or_fill`).
|
||||
return Ok(tangled
|
||||
.iter()
|
||||
@@ -459,6 +523,161 @@ fn untangle(
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
/// Rounds of [`snap_touches`] before a face that still crosses itself is refused.
|
||||
const MAX_SNAP: u32 = 8;
|
||||
|
||||
/// The faces `faces` whose boundaries cross themselves where two curves touch or cross (halving
|
||||
/// their chords does not part them, see [`untangle`]), with every node that lies within the chord
|
||||
/// tolerance `tol` of a crossing chord of another edge put onto that edge as well (see
|
||||
/// [`edges::snap`]): the two edges share the point, the face's boundary passes it twice (a pinch,
|
||||
/// as at a vertex two loops share), and the chords meet there instead of crossing. Where the
|
||||
/// curves run within the tolerance of each other for a stretch (a sliver between two touches),
|
||||
/// the nodes on either side are shared in turn, so the boundary runs out and back along one
|
||||
/// polyline there: a slit, which bounds the face on neither side. A node is not snapped where the
|
||||
/// pinch would turn part of its loop inside out by more than the tolerance (two curves crossing
|
||||
/// at an angle: the boundary is wrong there, not within the tolerance). Every face of a changed
|
||||
/// edge has its boundary built again. Returns the faces whose boundaries still cross, with the
|
||||
/// crossing segments.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn snap_touches(
|
||||
evals: &[EvalSurface],
|
||||
edge_faces: &[Vec<usize>],
|
||||
tol: f64,
|
||||
nodes: &mut [edges::Nodes],
|
||||
boundaries: &mut [Boundary],
|
||||
face_boundary: &(dyn Fn(usize, &[edges::Nodes]) -> Result<Boundary> + Sync),
|
||||
faces: &[usize],
|
||||
) -> Result<Vec<(usize, Vec<(u32, u32)>)>> {
|
||||
let crossing = |fi: usize, fb: &Boundary| -> Vec<(usize, usize)> {
|
||||
let Some(s) = evals.get(fi) else { return Vec::new() };
|
||||
tangle::crossing(s, fb.reach, &fb.loops)
|
||||
};
|
||||
let mut tangled: Vec<usize> = faces.to_vec();
|
||||
for _ in 0..MAX_SNAP {
|
||||
let mut add: HashMap<u32, Vec<(f64, Vec3)>> = HashMap::new();
|
||||
for &fi in &tangled {
|
||||
let Some(fb) = boundaries.get(fi) else { continue };
|
||||
for (l, k) in crossing(fi, fb) {
|
||||
let Some(&(e, j)) = fb.segments.get(l).and_then(|s| s.get(k)) else { continue };
|
||||
if let Some((t, p)) = touch(fb, nodes, (l, k), (e, j), tol) {
|
||||
add.entry(e).or_default().push((t, p));
|
||||
}
|
||||
}
|
||||
}
|
||||
if add.is_empty() {
|
||||
break;
|
||||
}
|
||||
let mut redo: Vec<usize> = Vec::new();
|
||||
for (e, points) in &add {
|
||||
let Some(slot) = nodes.get_mut(*e as usize) else { continue };
|
||||
edges::snap(*e as usize, slot, points)?;
|
||||
redo.extend(edge_faces.get(*e as usize).into_iter().flatten().copied());
|
||||
}
|
||||
redo.extend(tangled.iter().copied());
|
||||
redo.sort_unstable();
|
||||
redo.dedup();
|
||||
tangled.clear();
|
||||
for fi in redo {
|
||||
let fb = face_boundary(fi, nodes)?;
|
||||
let crosses = !crossing(fi, &fb).is_empty();
|
||||
if let Some(slot) = boundaries.get_mut(fi) {
|
||||
*slot = fb;
|
||||
}
|
||||
if crosses {
|
||||
tangled.push(fi);
|
||||
}
|
||||
}
|
||||
if tangled.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
}
|
||||
Ok(tangled
|
||||
.into_iter()
|
||||
.filter_map(|fi| {
|
||||
let fb = boundaries.get(fi)?;
|
||||
let c: Vec<(u32, u32)> = crossing(fi, fb).into_iter().filter_map(|(l, k)| fb.segments.get(l)?.get(k).copied()).collect();
|
||||
(!c.is_empty()).then_some((fi, c))
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// The node of face boundary `fb` nearest the crossing chord `at` (loop, node) of its boundary,
|
||||
/// segment `seg` (edge, segment from its start) of that edge, within `tol` of the chord strictly
|
||||
/// between its ends, on another edge, and not yet on this one; with the parameter on the edge
|
||||
/// where it projects onto the chord. `None` when there is none, or snapping it would turn part
|
||||
/// of its loop inside out by more than the tolerance (see [`snap_touches`]).
|
||||
fn touch(fb: &Boundary, nodes: &[edges::Nodes], at: (usize, usize), seg: (u32, u32), tol: f64) -> Option<(f64, Vec3)> {
|
||||
let (e, j) = seg;
|
||||
let n = nodes.get(e as usize)?;
|
||||
let j = j as usize;
|
||||
let (a, c) = (*n.points.get(j)?, *n.points.get(j + 1)?);
|
||||
let (ta, tc) = (*n.params.get(j)?, *n.params.get(j + 1)?);
|
||||
let ac = c - a;
|
||||
let len2 = ac.dot(ac);
|
||||
if !(len2 > 0.0) {
|
||||
return None;
|
||||
}
|
||||
let mut best: Option<(f64, f64, Vec3)> = None;
|
||||
for (l, lp) in fb.loops.iter().enumerate() {
|
||||
let segs = fb.segments.get(l)?;
|
||||
let m = lp.pts.len();
|
||||
for (k, &p) in lp.pts.iter().enumerate() {
|
||||
// The node's edges: the segment starting at it and the one ending there.
|
||||
let edges_at = [segs.get(k).map(|s| s.0), segs.get((k + m - 1) % m).map(|s| s.0)];
|
||||
if edges_at.contains(&Some(e)) || n.points.contains(&p) {
|
||||
continue;
|
||||
}
|
||||
let f = (p - a).dot(ac) / len2;
|
||||
let d = p.dist_to_segment(a, c);
|
||||
if !(f > 1e-6 && f < 1.0 - 1e-6 && d <= tol) || best.is_some_and(|(bd, _, _)| bd <= d) {
|
||||
continue;
|
||||
}
|
||||
if l == at.0 && inside_out(lp, at.1, k, tol) {
|
||||
continue;
|
||||
}
|
||||
best = Some((d, ta + f * (tc - ta), p));
|
||||
}
|
||||
}
|
||||
best.map(|(_, t, p)| (t, p))
|
||||
}
|
||||
|
||||
/// Whether pinching loop `lp` at node `k` and a new node (the same point) on its chord from node
|
||||
/// `at` would turn either part inside out by more than `tol`: a part whose winding in (u, v) is
|
||||
/// against the loop's, and whose area is more than `tol` across (twice its area in 3D over its
|
||||
/// length).
|
||||
fn inside_out(lp: &seam::Loop, at: usize, k: usize, tol: f64) -> bool {
|
||||
let m = lp.uv.len();
|
||||
if m < 3 {
|
||||
return false;
|
||||
}
|
||||
// The two parts: from the node after the chord's start round to `k`, and from `k` round to the
|
||||
// chord's start.
|
||||
let part = |from: usize, to: usize| -> Vec<usize> {
|
||||
let mut out = Vec::new();
|
||||
let mut i = from % m;
|
||||
loop {
|
||||
out.push(i);
|
||||
if i == to % m || out.len() > m {
|
||||
break;
|
||||
}
|
||||
i = (i + 1) % m;
|
||||
}
|
||||
out
|
||||
};
|
||||
let whole = area2(&lp.uv);
|
||||
[part(at + 1, k), part(k, at)].iter().any(|ids| {
|
||||
let uv: Vec<[f64; 2]> = ids.iter().filter_map(|&i| lp.uv.get(i).copied()).collect();
|
||||
let pts: Vec<Vec3> = ids.iter().filter_map(|&i| lp.pts.get(i).copied()).collect();
|
||||
if uv.len() < 3 || area2(&uv) * whole >= 0.0 {
|
||||
return false;
|
||||
}
|
||||
// Newell's vector: twice the area of the polygon in 3D.
|
||||
let twice = pts.iter().zip(pts.iter().cycle().skip(1)).fold(Vec3::ZERO, |acc, (p, q)| acc + p.cross(*q)).len();
|
||||
let length: f64 = pts.iter().zip(pts.iter().cycle().skip(1)).map(|(p, q)| p.dist(*q)).sum();
|
||||
twice > tol * length
|
||||
})
|
||||
}
|
||||
|
||||
/// Bounded work for the facet angle: a face whose boundary would get more than
|
||||
/// [`size::MAX_ANGLE_BOUNDARY`] segments has its curved edges sampled again at twice the angle,
|
||||
/// as often as it takes, down to the tolerance alone (a plate with a thousand small holes is
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
use solidcraft_geom::tess::EvalSurface;
|
||||
pub(crate) use solidcraft_geom::tess::uv::{Domain, degenerate_within, domain, unwrap};
|
||||
|
||||
use super::edges::{QUARTER_TURN, turn};
|
||||
use super::size::Rules;
|
||||
|
||||
/// Division of `range` along direction `d` so that between neighbouring lines the surface sags
|
||||
@@ -16,19 +17,10 @@ pub(crate) fn divide(s: &EvalSurface, d: usize, range: (f64, f64), across: (f64,
|
||||
if !(a1 > a0) {
|
||||
return vec![a0, a1];
|
||||
}
|
||||
let flat = limits(s, d, across, rules, h);
|
||||
// Start from quarter turns at most, so a closed iso-line is not taken for a flat one (a
|
||||
// plane's parameters are lengths and its lines are never closed).
|
||||
let initial = if matches!(s, EvalSurface::Plane { .. }) { 1 } else { ((a1 - a0) / std::f64::consts::FRAC_PI_2).ceil().clamp(1.0, 64.0) as u32 };
|
||||
// Both ends exactly (a0 + (a1 − a0) · 1 may round away from a1): the end lines are the
|
||||
// face's own parameter box, which the boundary nodes sit on.
|
||||
let starts: Vec<f64> = (0..=initial)
|
||||
.map(|i| {
|
||||
let t = f64::from(i) / f64::from(initial);
|
||||
a0 * (1.0 - t) + a1 * t
|
||||
})
|
||||
.collect();
|
||||
split(&starts, &flat, max_lines)
|
||||
// The whole range first: the limits split it, and no interval spans more than a quarter
|
||||
// turn of its iso-lines, so a closed iso-line is never taken for a flat one. Both ends
|
||||
// exactly: the end lines are the face's own parameter box, which the boundary nodes sit on.
|
||||
split(&[a0, a1], &limits(s, d, across, rules, h), max_lines)
|
||||
}
|
||||
|
||||
/// `lines` (increasing, ends included) with every interval that fails the same limits as
|
||||
@@ -80,8 +72,14 @@ pub(crate) fn fine_between(s: &EvalSurface, rules: &Rules, h: f64, a: [f64; 2],
|
||||
}
|
||||
}
|
||||
|
||||
/// An iso-line's extent below which it is a point, as a fraction of the chord tolerance (which
|
||||
/// is never finer than a millionth of the body, so this is far above rounding).
|
||||
const POINT: f64 = 1e-6;
|
||||
|
||||
/// Whether the surface between the iso-lines at `a` and `b` (direction `d`, sampled along
|
||||
/// iso-lines across `across`) is within the tolerance, the side length `h` and the facet angle.
|
||||
/// iso-lines across `across`) is within the tolerance, the side length `h` and the facet angle,
|
||||
/// and spans at most a quarter turn of each iso-line (as an edge segment does, see
|
||||
/// [`QUARTER_TURN`]): a turn read from the points, since a spline's parameter is no angle.
|
||||
fn limits<'a>(s: &'a EvalSurface, d: usize, across: (f64, f64), rules: &'a Rules, h: f64) -> impl Fn(f64, f64) -> bool + 'a {
|
||||
let tol = rules.tol;
|
||||
let uv = move |x: f64, y: f64| if d == 0 { (x, y) } else { (y, x) };
|
||||
@@ -105,6 +103,15 @@ fn limits<'a>(s: &'a EvalSurface, d: usize, across: (f64, f64), rules: &'a Rules
|
||||
if sag > tol {
|
||||
return false;
|
||||
}
|
||||
// The two half chords of an arc turning θ differ by θ/2; a closed iso-line's by π.
|
||||
// An iso-line within a millionth of the tolerance of one point (a pole) turns no
|
||||
// amount: its directions are rounding.
|
||||
if let Some(pm) = at(0.5 * (a + b), y)
|
||||
&& pa.dist(pm).max(pm.dist(pb)) > POINT * tol
|
||||
&& 2.0 * turn(pm - pa, pb - pm) > QUARTER_TURN
|
||||
{
|
||||
return false;
|
||||
}
|
||||
// At a pole the normal is undefined: take it from just inside the segment.
|
||||
let na = normal(a, y).or_else(|| normal(a + 1e-4 * (b - a), y));
|
||||
let nb = normal(b, y).or_else(|| normal(b - 1e-4 * (b - a), y));
|
||||
@@ -147,6 +154,26 @@ mod tests {
|
||||
assert_eq!(along.len(), 9);
|
||||
}
|
||||
|
||||
/// A quarter of a cylinder as a rational quadratic spline (as SMLib holds a bend), its range a
|
||||
/// rounding over π/2 as a boundary's pcurves give it: the quarter turn is read from the
|
||||
/// surface, not the parameter, so at a tolerance above its sag it is one interval; and a whole
|
||||
/// turn is still divided into quarters however coarse the tolerance.
|
||||
#[test]
|
||||
fn a_quarter_turn_is_read_from_the_surface_not_the_parameter() {
|
||||
let w = std::f64::consts::FRAC_1_SQRT_2;
|
||||
let q = std::f64::consts::FRAC_PI_2;
|
||||
let s = EvalSurface::nurbs(
|
||||
[1, 2],
|
||||
[vec![0.0, 0.0, 40.0, 40.0], vec![0.0, 0.0, 0.0, q, q, q]],
|
||||
[2, 3],
|
||||
vec![[1.0, 0.0, 0.0, 1.0], [1.0, 0.0, 40.0, 1.0], [w, w, 0.0, w], [w, w, 40.0 * w, w], [0.0, 1.0, 0.0, 1.0], [0.0, 1.0, 40.0, 1.0]],
|
||||
);
|
||||
let coarse = Rules { tol: 3.0, max_len: f64::INFINITY, turn: None };
|
||||
assert_eq!(divide(&s, 1, (-6.7e-13, q), (0.0, 40.0), &coarse, f64::INFINITY, 10_000), vec![-6.7e-13, q]);
|
||||
let whole = divide(&cylinder(), 1, (0.0, std::f64::consts::TAU), (0.0, 1.0), &Rules { tol: 100.0, ..coarse }, f64::INFINITY, 10_000);
|
||||
assert_eq!(whole.len(), 5, "{whole:?}");
|
||||
}
|
||||
|
||||
/// The first and last lines are the range's ends to the last bit: the boundary nodes sit on
|
||||
/// them, and a line a rounding inside would be taken for an interior one (a drill point's
|
||||
/// cone, where a0 + (a1 − a0) is not a1).
|
||||
|
||||
@@ -144,12 +144,14 @@ fn thread_display_mesh_stays_on_its_surfaces() {
|
||||
let [a, b2, c] = t.map(|i| mesh.positions[i as usize]);
|
||||
let (ra, rb, rcn) = (r(a), r(b2), r(c));
|
||||
let centre = r((a + b2 + c) * (1.0 / 3.0));
|
||||
// An end disc is flat: its triangles are its boundary's, and one with its three
|
||||
// corners on the rim (at r = rc) lies on the disc, not on a cylinder.
|
||||
let end_disc = [a, b2, c].iter().all(|v| v.z.abs() < 1e-9) || [a, b2, c].iter().all(|v| (v.z - (turns + 2.0) * p).abs() < 1e-9);
|
||||
for want in [rc, rm] {
|
||||
if [ra, rb, rcn].iter().all(|x| (x - want).abs() < 1e-4) {
|
||||
if !end_disc && [ra, rb, rcn].iter().all(|x| (x - want).abs() < 1e-4) {
|
||||
assert!(centre > want - 2.0 * tol, "{name}: triangle {ti} on the r = {want} cylinder cuts in to {centre}");
|
||||
}
|
||||
}
|
||||
let end_disc = [a, b2, c].iter().all(|v| v.z.abs() < 1e-9) || [a, b2, c].iter().all(|v| (v.z - (turns + 2.0) * p).abs() < 1e-9);
|
||||
assert!(end_disc || (centre > rc - 2.0 * tol && centre < rm + 1e-6), "{name}: triangle {ti} at radius {centre}, outside {rc}…{rm}");
|
||||
}
|
||||
// A mesh within the tolerance of the surfaces is within area × tolerance of the volume.
|
||||
|
||||
@@ -322,9 +322,11 @@ accelerations are finite differences between samples, central inside and one-sid
|
||||
so they are as smooth as the samples are dense (up to 1000, one per step by default). Angles are
|
||||
unwrapped, so a joint that turns on past half a turn keeps counting.
|
||||
`motion.interference {study, occurrences?, against?, contact_sets?, samples?}` answers each
|
||||
colliding pair with its `first_step`, `last_step`, the `steps` ranges where they overlap, how
|
||||
far into each other (`depth_mm`, the most at `deepest_step`) and their shared `volume_mm3`
|
||||
there (null when it is not cheap to work out). It plays the study as `motion.play` does, but
|
||||
colliding pair with its `first_step`, `last_step`, the `steps` ranges where they overlap, the
|
||||
most volume they share at a sample (`volume_mm3`, worked out exactly from the bodies; null when
|
||||
it is not cheap to work out at every sample they overlap), the first sample sharing that much
|
||||
(`deepest_step`) and how far into each other they reach (`depth_mm`, an estimate from points of
|
||||
the bodies' contact meshes). It plays the study as `motion.play` does, but
|
||||
contact sets don't stop it, and parts are tested at the samples only: a part that passes right
|
||||
through another between two samples is missed. Parts are told apart by occurrence, as contact
|
||||
sets tell them apart: an occurrence inside a sub-assembly placed twice is one part, so its two
|
||||
|
||||
Reference in New Issue
Block a user