SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Wave 335/509: Tessellation: the band beside a slit and the sag refinement keep the face on both sides of it (and 3 more)
jyvikobe583dbfd791
diff --git a/crates/kernel/src/emboss.rs b/crates/kernel/src/emboss.rsindex e4b200f360..be32fce8b5 100644--- a/crates/kernel/src/emboss.rs+++ b/crates/kernel/src/emboss.rs@@ -9,7 +9,7 @@ use crate::numbered::NumberedRegion;use crate::offset::{Surf, face_edges, surf_of};use crate::{KernelError, Result, guard};use solidcraft_geom::brep::eval::CurveEval;-use solidcraft_geom::brep::{Brep, Curve, Frame, Loop, Surface};+use solidcraft_geom::brep::{Brep, Curve, Frame, Loop, Surface, form};use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2, Vec3};fn fail(s: &str) -> KernelError {@@ -40,10 +40,11 @@ fn wall_angles(b: &Brep, face: usize, o: Vec3, axis: Vec3, radial: Vec3, tangentif z.dot(axis).abs() < 1.0 - 1e-9 {continue;}- // The circle's parameter is its angle: the wall spans the edge's interval about the- // angle of its middle (a whole turn, from the seam, for a wall in one piece).- let c = CurveEval::new(e.parameters()).ok()?;- let [t0, t1] = e.interval;+ // The circle's parameter is its angle: the wall spans the edge's angles on the circle+ // (`interval` is on its NURBS form where it has one) about the angle of its middle (a+ // whole turn, from the seam, for a wall in one piece).+ let c = CurveEval::new(&e.curve).ok()?;+ let [t0, t1] = e.curve_interval()?;let am = angle(c.point(0.5 * (t0 + t1))?, o, axis, radial, tangent);let half = 0.5 * (t1 - t0);return Some((am - half, am + half));@@ -327,9 +328,12 @@ fn emboss_impl(body: &Body, anchor: Option<Vec3>, plane: &Plane, regions: &[Regilet at = o + axis * p.y + (radial * (p.x / r).cos() + tangent * (p.x / r).sin()) * r;return Ok(EmbossOutcome::Anchor(fi, at));}- let wall = Wrap { o, axis, radial, tangent, r };let mut asm = Assembly::from_record(&rec)?;let selected = asm.faces.get_mut(fi).and_then(Option::take).ok_or_else(|| fail("face"))?;+ // The footprint's arcs lie on the wall face and are labelled on its frame, so their NURBS+ // forms run on the face's own quarter grid and their pcurves there are exact.+ let label = form::frame_of(&selected.surface);+ let wall = Wrap { o, axis, radial, tangent, r, label, tol };// The wall's pieces left around the footprints: the face itself, then one per profile// hole (the original radius inside it).let mut base_patches: Vec<Vec<Vec<AUse>>> = vec![selected.loops.clone()];@@ -416,6 +420,9 @@ struct Wrap {radial: Vec3,tangent: Vec3,r: f64,+ /// The wall face's own frame, which the arcs at its radius are labelled on.+ label: Option<Frame>,+ tol: f64,}impl Wrap {@@ -441,7 +448,12 @@ impl Wrap {let (ta, tb) = (p.x / self.r, q.x / self.r);let forward = ta < tb;let (interval, ends) = if forward { ([ta, tb], (a, b)) } else { ([tb, ta], (b, a)) };- Ok(AUse { edge: asm.edge(Curve::Circle { frame, radius }, interval, ends.0, ends.1)?, forward, given: None })+ let circle = Curve::Circle { frame, radius };+ let (circle, interval) = match &self.label {+ Some(label) if (radius - self.r).abs() <= self.tol => form::on_frame(&circle, interval, label, self.tol).unwrap_or((circle, interval)),+ _ => (circle, interval),+ };+ Ok(AUse { edge: asm.edge(circle, interval, ends.0, ends.1)?, forward, given: None })}/// A profile loop wrapped onto the wall: its footprint at the wall's radius and its cap'sdiff --git a/crates/kernel/src/tess/cdt.rs b/crates/kernel/src/tess/cdt.rsindex 60c3dca0d9..e7d80f9b46 100644--- a/crates/kernel/src/tess/cdt.rs+++ b/crates/kernel/src/tess/cdt.rs@@ -79,6 +79,16 @@ pub(crate) fn triangulate(boundary: &[[f64; 2]], loops: &[std::ops::Range<usize>index.entry(h).or_insert(u32::try_from(i).ok()?);handles.push(h);}+ // A side the loops run along both ways (a slit, where a face's boundary goes out along a+ // line its two sides share and back) bounds the face on neither.+ let mut sides: Vec<(FixedVertexHandle, FixedVertexHandle)> = Vec::new();+ for r in loops {+ let n = r.len();+ for k in 0..n {+ sides.push((*handles.get(r.start + k)?, *handles.get(r.start + (k + 1) % n)?));+ }+ }+ let slits = slits(&sides);for r in loops {let n = r.len();for k in 0..n {@@ -102,7 +112,7 @@ pub(crate) fn triangulate(boundary: &[[f64; 2]], loops: &[std::ops::Range<usize>}if let Some((sag, budget)) = &fill.refine {let constraints = cdt.num_constraints();- let added = refine_sag(&mut cdt, sag, *budget, &from);+ let added = refine_sag(&mut cdt, sag, *budget, &from, &slits);if fill.shape {let params = RefinementParameters::<f64>::new().keep_constraint_edges()@@ -115,7 +125,7 @@ pub(crate) fn triangulate(boundary: &[[f64; 2]], loops: &[std::ops::Range<usize>// Shaping flips sides and adds points of its own; the triangles it leaves may// sag again (a long strip round a cylinder), so the sag is checked once more.if shaped > 0 {- refine_sag(&mut cdt, sag, budget.saturating_sub(added + shaped), &from);+ refine_sag(&mut cdt, sag, budget.saturating_sub(added + shaped), &from, &slits);}}// A split constraint would put a point on the boundary the neighbour does not have.@@ -125,7 +135,7 @@ pub(crate) fn triangulate(boundary: &[[f64; 2]], loops: &[std::ops::Range<usize>}let mut uv: Vec<[f64; 2]> = boundary.to_vec();let mut tris = Vec::new();- let region = region(&cdt);+ let region = region(&cdt, &slits);for face in cdt.inner_faces() {if !region.get(face.index()).copied().unwrap_or(false) {continue;@@ -185,6 +195,8 @@ pub(crate) fn band(points: &[[f64; 2]], n: usize, loops: &[std::ops::Range<usizesides.push((add(&mut cdt, a)?, add(&mut cdt, b)?));}}+ // The band runs along both sides of a slit (see `triangulate`): its sides bound it on neither.+ let slits = slits(&sides);for &(a, b) in stairs {sides.push((add(&mut cdt, a)?, add(&mut cdt, b)?));}@@ -197,7 +209,7 @@ pub(crate) fn band(points: &[[f64; 2]], n: usize, loops: &[std::ops::Range<usize}cdt.add_constraint(a, b);}- let region = region(&cdt);+ let region = region(&cdt, &slits);let mut tris = Vec::new();for face in cdt.inner_faces() {if !region.get(face.index()).copied().unwrap_or(false) {@@ -216,7 +228,14 @@ pub(crate) fn band(points: &[[f64; 2]], n: usize, loops: &[std::ops::Range<usize/// the tolerance from the triangle or whose corner normals turn more than the facet angle, and/// under the middle of every non-constraint side that sags more than the tolerance or is/// longer than [`LONG`] times `h`, until none does or `budget` points were added. Returns the points added.-fn refine_sag(cdt: &mut Cdt, sag: &Sag, budget: usize, from: &dyn Fn(Point2<f64>) -> [f64; 2]) -> usize {+/// `slits`: constraint sides the loops run along both ways, inside the region on both sides.+fn refine_sag(+ cdt: &mut Cdt,+ sag: &Sag,+ budget: usize,+ from: &dyn Fn(Point2<f64>) -> [f64; 2],+ slits: &std::collections::HashSet<(FixedVertexHandle, FixedVertexHandle)>,+) -> usize {let mut added = 0;let mut cache: HashMap<FixedVertexHandle, Option<(Vec3, Option<Vec3>)>> = HashMap::new();// The widest turn between two corner normals.@@ -232,7 +251,7 @@ fn refine_sag(cdt: &mut Cdt, sag: &Sag, budget: usize, from: &dyn Fn(Point2<f64>(sag.eval)(q[0], q[1])})};- let region = region(cdt);+ let region = region(cdt, slits);for face in cdt.inner_faces() {if !region.get(face.index()).copied().unwrap_or(false) {continue;@@ -304,18 +323,35 @@ fn refine_sag(cdt: &mut Cdt, sag: &Sag, budget: usize, from: &dyn Fn(Point2<f64>added}+/// The sides a boundary runs along an even number of times (a slit: out along a line and back),+/// each as its vertices in index order: the region lies on both sides of them.+fn slits(sides: &[(FixedVertexHandle, FixedVertexHandle)]) -> std::collections::HashSet<(FixedVertexHandle, FixedVertexHandle)> {+ let mut runs: HashMap<(FixedVertexHandle, FixedVertexHandle), usize> = HashMap::new();+ for &(a, b) in sides {+ if a != b {+ *runs.entry(if a.index() < b.index() { (a, b) } else { (b, a) }).or_insert(0) += 1;+ }+ }+ runs.into_iter().filter(|(_, n)| n % 2 == 0).map(|(e, _)| e).collect()+}+/// Per face (by index): inside the region the constraint loops bound. A flood fill from the-/// outer face that flips parity each time it crosses a constraint edge (holes are out), linear-/// in the number of triangles.-fn region(cdt: &Cdt) -> Vec<bool> {+/// outer face that flips parity each time it crosses a constraint edge (holes are out), but for+/// the sides in `slits` (run along both ways, the region on both sides), linear in the number of+/// triangles.+fn region(cdt: &Cdt, slits: &std::collections::HashSet<(FixedVertexHandle, FixedVertexHandle)>) -> Vec<bool> {use spade::handles::{FixedFaceHandle, InnerTag};+ let counts = |e: spade::handles::DirectedEdgeHandle<'_, _, _, _, _>| {+ let [a, b] = e.vertices().map(|v| v.fix());+ e.is_constraint_edge() && !slits.contains(&if a.index() < b.index() { (a, b) } else { (b, a) })+ };let mut parity: Vec<Option<bool>> = vec![None; cdt.num_all_faces()];let mut todo: Vec<(FixedFaceHandle<InnerTag>, bool)> = Vec::new();for e in cdt.convex_hull() {// Hull edges have the outer face on one side; the other side is an inner face.for side in [e, e.rev()] {if let Some(inner) = side.face().as_inner() {- todo.push((inner.fix(), e.is_constraint_edge()));+ todo.push((inner.fix(), counts(e)));}}}@@ -326,7 +362,7 @@ fn region(cdt: &Cdt) -> Vec<bool> {}for e in cdt.face(h).adjacent_edges() {if let Some(next) = e.rev().face().as_inner() {- todo.push((next.fix(), odd ^ e.is_constraint_edge()));+ todo.push((next.fix(), odd ^ counts(e)));}}}diff --git a/crates/kernel/src/tess/mod.rs b/crates/kernel/src/tess/mod.rsindex 204a8b2984..a912b3097e 100644--- a/crates/kernel/src/tess/mod.rs+++ b/crates/kernel/src/tess/mod.rs@@ -1133,7 +1133,8 @@ fn graded(a: [f64; 2], b: [f64; 2], sa: f64, sb: f64, h: f64, speed: [f64; 2], fall.into_iter().filter(|t| *t > 0.0 && *t < 1.0).collect()}-/// Every boundary segment (consecutive nodes of a loop) is the side of exactly one triangle:+/// Every boundary segment (consecutive nodes of a loop) is the side of exactly one triangle (two+/// for a slit the loops run along both ways):/// the face covers its boundary with nothing missing or doubled, so it meets its neighbours/// exactly. Some boundary nodes are one vertex, a side ending on any of them the same side: pole/// copies of one node (consecutive in a loop, at one point, the segment between them of no@@ -1186,12 +1187,19 @@ fn closed_boundary(ranges: &[std::ops::Range<usize>], fixed: &[Vec3], uvs: &[[f6}}}- ranges.iter().all(|r| {- (0..r.len()).all(|k| {+ // Each boundary side has a triangle for every time the loops run along it: one, or two for+ // a slit (a side run out and back, where the face meets itself along a line: a hole's wall+ // touching the wall round it), one triangle either side.+ let mut runs: HashMap<(u32, u32), u32> = HashMap::new();+ for r in ranges {+ for k in 0..r.len() {let (a, b) = segment(r, k);- side(a, b).is_none_or(|k| sides.get(&k).copied() == Some(1))- })- })+ if let Some(k) = side(a, b) {+ *runs.entry(k).or_default() += 1;+ }+ }+ }+ runs.iter().all(|(k, n)| sides.get(k).copied() == Some(*n))}#[cfg(test)]diff --git a/crates/kernel/src/tess/tangle.rs b/crates/kernel/src/tess/tangle.rsindex c53a982cef..877b656277 100644--- a/crates/kernel/src/tess/tangle.rs+++ b/crates/kernel/src/tess/tangle.rs@@ -95,6 +95,19 @@ pub(crate) fn crossing(s: &EvalSurface, reach: f64, loops: &[seam::Loop]) -> Vecout.push(x.at);out.push(y.at);}+ // A node of one chord lying on the other (inside it, not at its ends) is no crossing,+ // but no triangulation can keep both as constraints either: where two curves leave a+ // vertex they touch at along one tangent (a circle touching another from inside), the+ // inner one's node can fall on the outer one's chord (with the outer chord twice the+ // inner, exactly so but for the next order). The chord the node lies on is halved.+ // (Not where the two chords run along one line: a seam's two uses, a period apart,+ // lie on each other as copies.)+ if !along(x.a, x.b, y.a, y.b) && [y.a, y.b].iter().any(|q| on(x.a, x.b, *q)) {+ out.push(x.at);+ }+ if !along(y.a, y.b, x.a, x.b) && [x.a, x.b].iter().any(|q| on(y.a, y.b, *q)) {+ out.push(y.at);+ }}}out.sort_unstable();@@ -102,6 +115,28 @@ pub(crate) fn crossing(s: &EvalSurface, reach: f64, loops: &[seam::Loop]) -> Vecout}+/// Whether `q` lies on the segment `ab` within [`STRADDLE`] (of the segment's squared length,+/// off its line) strictly between its ends (not at either, by the same measure along it).+fn on(a: [f64; 2], b: [f64; 2], q: [f64; 2]) -> bool {+ let (dx, dy) = (b[0] - a[0], b[1] - a[1]);+ let len2 = dx * dx + dy * dy;+ if !(len2 > 0.0) {+ return false;+ }+ let (qx, qy) = (q[0] - a[0], q[1] - a[1]);+ let off = (dx * qy - dy * qx).abs();+ let along = (dx * qx + dy * qy) / len2;+ off <= 1e3 * STRADDLE * len2 && along > 1e-6 && along < 1.0 - 1e-6+}++/// Whether `c` and `d` both lie on the line of `ab` (within [`on`]'s measure).+fn along(a: [f64; 2], b: [f64; 2], c: [f64; 2], d: [f64; 2]) -> bool {+ let (dx, dy) = (b[0] - a[0], b[1] - a[1]);+ let len2 = dx * dx + dy * dy;+ let off = |q: [f64; 2]| (dx * (q[1] - a[1]) - dy * (q[0] - a[0])).abs();+ len2 > 0.0 && off(c) <= 1e3 * STRADDLE * len2 && off(d) <= 1e3 * STRADDLE * len2+}+/// Whether the segments `ab` and `cd` cross: each one's ends strictly either side of the other.fn cross(a: [f64; 2], b: [f64; 2], c: [f64; 2], d: [f64; 2]) -> bool {let orient = |p: [f64; 2], q: [f64; 2], r: [f64; 2]| (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]);diff --git a/crates/kernel/src/tess/tests.rs b/crates/kernel/src/tess/tests.rsindex a98fe87e09..81730249d6 100644--- a/crates/kernel/src/tess/tests.rs+++ b/crates/kernel/src/tess/tests.rs@@ -669,6 +669,39 @@ fn loops_touching_at_a_shared_vertex_bound_the_face() {assert!(closed_boundary(&ranges, &fixed, &uvs, &triangles), "the triangles follow both holes through their shared vertex");}+/// A face meeting itself along a line (a hole's wall tangent inside the wall round it, cut from+/// the boss side's top rim down to the hole's bottom): its loop runs up the slit and back down+/// it, with the face on both sides. The iso-line grid's band beside the slit is the face on+/// either side of it, and the triangles follow the slit both ways and cover the whole square.+#[test]+fn a_slit_in_a_trimmed_face_has_the_face_on_both_sides() {+ // The square [0, 8] × [0, 4], its loop starting at the slit's tip (3, 1) up to the top, round+ // the square and back down the slit.+ let mut uvs: Vec<[f64; 2]> = (1..=4).map(|k| [3.0, k as f64]).collect();+ uvs.extend((0..3).rev().map(|k| [k as f64, 4.0]));+ uvs.extend((0..4).rev().map(|k| [0.0, k as f64]));+ uvs.extend((1..=8).map(|k| [k as f64, 0.0]));+ uvs.extend((1..=4).map(|k| [8.0, k as f64]));+ uvs.extend((3..8).rev().map(|k| [k as f64, 4.0]));+ uvs.extend((2..4).rev().map(|k| [3.0, k as f64]));+ let fixed: Vec<Vec3> = uvs.iter().map(|q| Vec3::new(q[0], q[1], 0.0)).collect();+ let ranges = [std::ops::Range { start: 0, end: uvs.len() }];+ let traces = motorcycle::traces(&uvs, &ranges, [1.0, 1.0], 0.0);+ let lines = |n: usize, top: f64| (0..=n).map(|k| top * k as f64 / n as f64).collect::<Vec<f64>>();+ let Some((extra, triangles)) = cutgrid::cut_grid(&uvs, &ranges, &lines(16, 8.0), &lines(8, 4.0), &traces, [1.0, 1.0]) else { panic!("meshes") };+ assert!(closed_boundary(&ranges, &fixed, &uvs, &triangles), "the triangles follow the slit both ways");+ let mut all = uvs.clone();+ all.extend(extra);+ let area: f64 = triangles+ .iter()+ .map(|t| {+ let [a, b, c] = t.map(|i| all[i as usize]);+ 0.5 * ((b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]))+ })+ .sum();+ assert!((area - 32.0).abs() < 1e-12, "area {area}");+}+/// A face whose loop is a thin lune meshes: a half disc of radius 2.5 less a circle through the/// same ends 0.03 mm inside it at the middle, its inner side split at 11.25°. Each edge is/// sampled to the 0.1 mm chord on its own: the outer arc's chords (every 22.5°) sag 0.048 mm,@@ -1001,3 +1034,22 @@ fn triangles_standing_across_a_curved_sheet_are_flipped_along_it() {assert!(sides.contains(&(2, 3)) && !sides.contains(&(0, 1)), "{tris:?}");assert!(after < 0.5 * before, "{before} -> {after}");}++/// A disc with a boss standing on it tangent inside its rim: the disc's top is a ring whose inner+/// circle touches the outer one, one loop through the touching vertex. There both circles leave+/// along one tangent, and with the outer chord twice the inner (as their samplings fall) the inner+/// circle's first node lies on the outer's last chord: no triangulation keeps both. That chord is+/// halved, and the ring meshes strictly, to its area (300 pi), not the inner disc's.+#[test]+fn a_ring_touching_itself_at_a_vertex_meshes_strictly() {+ use solidcraft_geom::{Loop2, Plane, Region2, Vec2};+ let prism = |c: Vec2, r: f64, z0: f64, z1: f64| {+ ok(crate::extrude(&Plane::XY, &[Region2 { outer: Loop2::circle(c, r), holes: vec![] }], z0, z1)).pop().unwrap()+ };+ let stepped =+ ok(crate::boolean(&prism(Vec2::ZERO, 20.0, 0.0, 5.0), &prism(Vec2::new(10.0, 0.0), 10.0, 5.0, 15.0), crate::BoolOp::Union)).unwrap();+ let (_, stats) = ok(plan(&record(&stepped), 1e-4, None));+ assert!(stats.lenient.is_empty(), "{:?}", stats.lenient.iter().map(|r| &r.reason).collect::<Vec<_>>());+ let ring = ok(stepped.faces(1e-4)).into_iter().find(|f| (f.centroid.z - 5.0).abs() < 1e-6).unwrap();+ assert!((ring.area - 300.0 * PI).abs() < 0.05, "ring area {}", ring.area);+}