SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Wave 340/509: Display meshes: tests count the planner's grids; a mesh's outline is one line per straight edge (and 3 more)
jyvikob8b8d6b6a287
diff --git a/crates/doc/src/placed_mesh.rs b/crates/doc/src/placed_mesh.rsindex af308f9040..c6d877c539 100644--- a/crates/doc/src/placed_mesh.rs+++ b/crates/doc/src/placed_mesh.rs@@ -156,11 +156,55 @@ fn mesh_outlines(positions: &[Vec3], triangles: &[[u32; 3]]) -> Vec<Vec<Vec3>> {[(_, _, i), (_, _, j)] => normal(*i as usize).zip(normal(*j as usize)).is_some_and(|(n, m)| n.dot(m) <= cos),_ => true,};- if visible && let (Some(&a), Some(&b)) = (positions.get(a as usize), positions.get(b as usize)) {- edges.push(vec![a, b]);+ if visible && positions.get(a as usize).is_some() && positions.get(b as usize).is_some() {+ edges.push((a, b));}}- edges+ straight_runs(positions, &edges)+}++/// The outline sides `sides` (vertex index pairs) as polylines: sides that run on straight+/// through a vertex no other outline side meets are one line. A mesh whose straight edges are+/// in pieces (a box exported at a grid's spacing) then has one outline per edge, as its CAD+/// model did, and a click on it measures the whole edge.+fn straight_runs(positions: &[Vec3], sides: &[(u32, u32)]) -> Vec<Vec<Vec3>> {+ let mut at: std::collections::BTreeMap<u32, Vec<usize>> = std::collections::BTreeMap::new();+ for (i, &(a, b)) in sides.iter().enumerate() {+ at.entry(a).or_default().push(i);+ at.entry(b).or_default().push(i);+ }+ let point = |v: u32| positions.get(v as usize).copied().unwrap_or(Vec3::ZERO);+ let other = |i: usize, v: u32| sides.get(i).map_or(v, |&(a, b)| if a == v { b } else { a });+ // The side that continues `i` straight on through `v`, when `v` joins exactly two.+ let next = |i: usize, v: u32| -> Option<usize> {+ let [p, q] = at.get(&v)?.as_slice() else { return None };+ let j = if *p == i { *q } else { *p };+ let (into, out) = ((point(v) - point(other(i, v))).normalized()?, (point(other(j, v)) - point(v)).normalized()?);+ (into.dot(out) > 1.0 - 1e-9).then_some(j)+ };+ let mut used = vec![false; sides.len()];+ // Marks side `i` used; false when it already was.+ let mut take = |i: usize| used.get_mut(i).is_some_and(|u| !std::mem::replace(u, true));+ let mut runs = Vec::new();+ for (i, &(a, b)) in sides.iter().enumerate() {+ if !take(i) {+ continue;+ }+ let mut run = std::collections::VecDeque::from([a, b]);+ for (mut side, mut end, front) in [(i, b, false), (i, a, true)] {+ while let Some(j) = next(side, end).filter(|j| take(*j)) {+ end = other(j, end);+ side = j;+ if front {+ run.push_front(end);+ } else {+ run.push_back(end);+ }+ }+ }+ runs.push(run.into_iter().map(point).collect());+ }+ runs}/// Only proper rotations and translations preserve triangle winding, normal lengths and the@@ -182,7 +226,8 @@ mod tests {#[test]fn mesh_outlines_keep_boundaries_and_creases_without_smooth_facet_lines() {- for (degrees, expected) in [(0.0f64, 4), (15.0, 4), (30.0, 5), (45.0, 5), (90.0, 5)] {+ // Flat (0 degrees), the sides from Y through the origin to -Y run straight on: one line.+ for (degrees, expected) in [(0.0f64, 3), (15.0, 4), (30.0, 5), (45.0, 5), (90.0, 5)] {let angle = degrees.to_radians();let p = [Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::new(0., -angle.cos(), angle.sin())];let triangles = [[0, 1, 2], [1, 0, 3]];@@ -215,6 +260,12 @@ mod tests {let edges = mesh_outlines(&p, &triangles);assert_eq!(edges.len(), 2 * n as usize);assert!(edges.iter().all(|e| e[0].z == e[1].z));+ // A straight edge in pieces (a node at its middle, where the facets of the face meet)+ // is one outline; its corners stay corners.+ let p = [Vec3::ZERO, Vec3::X * 2., Vec3::new(2., 1., 0.), Vec3::Y, Vec3::X];+ let edges = mesh_outlines(&p, &[[0, 4, 3], [4, 1, 2], [4, 2, 3]]);+ assert_eq!(edges.len(), 4, "{edges:?}");+ assert!(edges.iter().any(|e| e == &[Vec3::ZERO, Vec3::X, Vec3::X * 2.] || e == &[Vec3::X * 2., Vec3::X, Vec3::ZERO]), "{edges:?}");// Bad indices and zero-area facets do not invent outlines or panic.assert!(mesh_outlines(&[Vec3::ZERO, Vec3::X, Vec3::X * 2.], &[[0, 1, 99], [0, 1, 2]]).is_empty());}diff --git a/crates/doc/src/project.rs b/crates/doc/src/project.rsindex c9edbb1d25..37a5dff11d 100644--- a/crates/doc/src/project.rs+++ b/crates/doc/src/project.rs@@ -426,7 +426,10 @@ fn projected_edges(body: &crate::ModelBody, mesh: &Mesh, plane: &Plane, edges: &let mut out = Vec::new();for (e, exact) in edges.iter().zip(exact_edges(body, plane, edges)) {match exact {- Some(g) => out.extend(g),+ Some(mut g) => {+ at_vertices(body, mesh, plane, *e, &mut g);+ out.extend(g);+ }None => {if let Some(pts) = mesh.edges.get(*e) {out.extend(fit_world(plane, pts));@@ -437,6 +440,51 @@ fn projected_edges(body: &crate::ModelBody, mesh: &Mesh, plane: &Plane, edges: &out}+/// Edge `e`'s exact pieces `g` with their outer ends on the edge's vertices, where they lie+/// within the edge's and the reading's tolerance of them. An edge's curve need only pass within+/// its tolerance of its vertices, and an arc is read off a NURBS within the planar-edge+/// tolerance: one SMLib made (a shell's offset corner) ended 2e-6 mm from the line it meets, and+/// the two ends, not taken for one point, left the loop open, so an offset of one curve found+/// no chain to follow. The vertex is the point both edges share.+fn at_vertices(body: &crate::ModelBody, mesh: &Mesh, plane: &Plane, e: usize, g: &mut [LinkGeom]) {+ let record = body.body.record();+ let Some(edge) = record.edges.get(e) else { return };+ let Some((first, last)) = mesh.edges.get(e).and_then(|pts| pts.first().zip(pts.last())) else { return };+ // The pieces are read within the planar-edge tolerance of the edge's curve, which passes+ // within its own tolerance of the vertices.+ let tol = edge.vertices.iter().filter_map(|v| record.vertices.get(*v as usize)).map(|v| v.tolerance).fold(edge.tolerance, f64::max)+ + body.body.planar_edges_tolerance();+ // Each vertex moves the piece end nearest it (the pieces' order and direction need not be+ // the edge's).+ for v in [plane.to_local(*first), plane.to_local(*last)] {+ let mut best: Option<(f64, &mut Vec2)> = None;+ for piece in g.iter_mut() {+ if let LinkGeom::Line(a, b) | LinkGeom::Arc { a, b, .. } | LinkGeom::Conic { a, b, .. } = piece {+ for p in [a, b] {+ let d = p.dist(v);+ if d <= tol && best.as_ref().is_none_or(|(bd, _)| d < *bd) {+ best = Some((d, p));+ }+ }+ }+ }+ if let Some((_, p)) = best {+ *p = v;+ }+ }+ // An arc is its centre and two ends on one circle: with its ends moved, its centre moves to+ // the nearest point equally far from both (on their bisector), or the sketch would move an+ // end back off the vertex onto the circle through the other.+ for piece in g.iter_mut() {+ if let LinkGeom::Arc { c, a, b } = piece+ && let Some(across) = Vec2::new(a.y - b.y, b.x - a.x).normalized()+ {+ let mid = (*a + *b) * 0.5;+ *c = mid + across * (*c - mid).dot(across);+ }+ }+}+/// A boundary segment as the link geometry that is the same curve.fn link_geom(s: &Seg2) -> Option<LinkGeom> {Some(match *s {diff --git a/crates/geom/src/brep/form.rs b/crates/geom/src/brep/form.rsindex 9a3dbbce33..619f8a4ec6 100644--- a/crates/geom/src/brep/form.rs+++ b/crates/geom/src/brep/form.rs@@ -590,6 +590,11 @@ pub fn extent(label: &Surface, loops: &[Vec<(&Curve, [f64; 2], bool)>]) -> Optio// and a box over both is more than a turn wide.let (mut l_lo, mut l_hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]);let mut prev: Option<[f64; 2]> = None;+ // The loop's bounds in each direction, each with the number of poles the loop had passed+ // through when it got there; and the first and last points off a pole.+ let mut bounds: Vec<(usize, usize, f64)> = Vec::new();+ let (mut crossings, mut on_pole) = (0usize, false);+ let mut first: Option<[f64; 2]> = None;for (c, [t0, t1], forward) in l {let curve = super::eval::CurveEval::new(c).ok()?;// The point at `t` on the label, a periodic parameter unwrapped next to `near`.@@ -604,28 +609,34 @@ pub fn extent(label: &Surface, loops: &[Vec<(&Curve, [f64; 2], bool)>]) -> Optio}Some(q)};- let mut samples: Vec<(f64, [f64; 2], [bool; 2])> = Vec::with_capacity(EXTENT_POINTS + 1);+ let mut samples: Vec<(f64, [f64; 2], [bool; 2], usize)> = Vec::with_capacity(EXTENT_POINTS + 1);for k in 0..=EXTENT_POINTS {let f = k as f64 / EXTENT_POINTS as f64;let t = if *forward { t0 * (1.0 - f) + t1 * f } else { t1 * (1.0 - f) + t0 * f };let q = at(t, prev)?;// At a pole the collapsed parameter is anything: it bounds nothing.let pole = eval.pole(q);- for d in 0..2 {- if !pole.get(d).copied().unwrap_or(false) {- l_lo[d] = l_lo[d].min(q[d]);- l_hi[d] = l_hi[d].max(q[d]);+ if pole.iter().any(|p| *p) {+ on_pole = first.is_some();+ } else {+ if on_pole {+ crossings += 1;+ on_pole = false;}- }- if !pole.iter().any(|p| *p) {+ first = first.or(Some(q));prev = Some(q);}- samples.push((t, q, pole));+ for (d, x) in q.iter().enumerate() {+ if !pole.get(d).copied().unwrap_or(false) {+ bounds.push((crossings, d, *x));+ }+ }+ samples.push((t, q, pole, crossings));}// A sample is a point of the boundary, not its extreme: each sample higher (or lower)// than its neighbours brackets an extreme of the edge, which is found there.for k in 0..samples.len() {- let (_, q, pole) = samples[k];+ let (_, q, pole, passed) = samples[k];let (a, b) = (samples[k.saturating_sub(1)].0, samples[(k + 1).min(samples.len() - 1)].0);for d in 0..2 {// Next to a pole the parameter it collapses is no function of the point: a@@ -646,12 +657,30 @@ pub fn extent(label: &Surface, loops: &[Vec<(&Curve, [f64; 2], bool)>]) -> Optio}let f = |t: f64| at(t, Some(q)).map_or(f64::NEG_INFINITY, |p| sign * p[d]);let x = sign * golden_max(&f, a.min(b), a.max(b));- l_lo[d] = l_lo[d].min(x);- l_hi[d] = l_hi[d].max(x);+ bounds.push((passed, d, x));}}}}+ // Through a pole the loop goes on from anywhere round the periodic direction it+ // collapses, so continuing from the point before it is no measure of where: a loop+ // through a pole closes in (u, v), the pole taking up its turn (a hemisphere bounded by its+ // rim and its seam, down the seam to the pole and up it on the other side). Past the+ // first pole, the loop is moved the whole periods that close it.+ let last = prev;+ for d in 0..2 {+ let shift = match (period.get(d), first, last) {+ (Some(Some(per)), Some(f), Some(e)) if crossings > 0 => -((e[d] - f[d]) / per).round() * per,+ _ => 0.0,+ };+ for &(passed, dd, x) in &bounds {+ if dd == d {+ let x = if passed > 0 { x + shift } else { x };+ l_lo[d] = l_lo[d].min(x);+ l_hi[d] = l_hi[d].max(x);+ }+ }+ }for d in 0..2 {if !(l_lo[d] <= l_hi[d]) {continue;diff --git a/crates/geom/src/brep/tests.rs b/crates/geom/src/brep/tests.rsindex 9856dd8601..208d0b4418 100644--- a/crates/geom/src/brep/tests.rs+++ b/crates/geom/src/brep/tests.rs@@ -850,6 +850,27 @@ fn a_hole_beside_the_seam_lies_in_its_face_turn() {assert!(v[0].abs() < 1e-9 && (v[1] - h).abs() < 1e-9, "{v:?}");}+/// A hemisphere bounded by its rim and its seam, its loop starting a quarter turn along the rim+/// (the order a re-imported dimple's loop came in): along the rim to the seam, down the seam to+/// the pole, up it on the other side and round the rest of the rim. Through the pole the loop goes+/// on a turn away; continuing from the point before the pole put the seam's second use on the+/// first and the box a quarter turn off the seam (oracle 14: the re-imported face's form over+/// -270..90 degrees, its pcurves over 0..360, and its area a quarter short).+#[test]+fn a_loop_through_a_pole_closes_its_turn_from_the_seam() {+ let r = 15.0f64;+ let sphere = Surface::Sphere { frame: Frame { origin: [0.; 3], x_axis: [1., 0., 0.], y_axis: [0., 1., 0.] }, radius: r };+ let rim = Curve::Circle { frame: Frame { origin: [0.; 3], x_axis: [1., 0., 0.], y_axis: [0., 1., 0.] }, radius: r };+ let seam = Curve::Circle { frame: Frame { origin: [0.; 3], x_axis: [1., 0., 0.], y_axis: [0., 0., -1.] }, radius: r };+ let outer =+ vec![(&rim, [0., FRAC_PI_2], false), (&seam, [0., FRAC_PI_2], true), (&seam, [0., FRAC_PI_2], false), (&rim, [FRAC_PI_2, TAU], false)];+ let [u, v] = form::extent(&sphere, &[outer]).expect("an extent");+ assert!((u[1] - u[0] - TAU).abs() < 1e-9, "one turn: {u:?}");+ let from = u[0].rem_euclid(TAU);+ assert!(from.min(TAU - from) < 1e-9, "from the seam: {u:?}");+ assert!((v[0] + FRAC_PI_2).abs() < 1e-9 && v[1].abs() < 1e-9, "{v:?}");+}+/// A face's box reaches its boundary's extremes, not its samples' nearest ones: an ellipse cut/// from a cylinder of radius 20 by a plane at 45 degrees rises 20 above its centre, at an angle/// between the points the box is sampled at. Short of it, the face's NURBS form stopped below thediff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rsindex 245f197a5e..12c6e83d2b 100644--- a/crates/io/src/lib.rs+++ b/crates/io/src/lib.rs@@ -838,8 +838,12 @@ mod tests {assert!(o.contains("o Body1") && o.contains("\nf "));}- /// OBJ shares a face's vertices (a cube: 8 positions, 6 normals, not 36 of each) and keeps- /// the body name as written, spaces included.+ /// OBJ shares the vertices faces meet at and keeps the body name as written, spaces included.+ /// The 10 × 20 × 30 box meshes as the planner's grids, no side longer than a fifth of its+ /// extent (the 37.4 mm diagonal): its edges in 2, 3 and 5 pieces, so its faces are grids of+ /// 2 × 3, 2 × 5 and 3 × 5 cells, 2 · (6 + 10 + 15) · 2 = 124 triangles. Welded, their+ /// corners are the 3 · 4 · 6 = 72 nodes of the box's lattice less the 1 · 2 · 4 inside it: 64+ /// positions (unwelded, 372), and one normal per face.#[test]fn obj_export_is_welded_and_keeps_names() {let (_, m) = model();@@ -850,10 +854,10 @@ mod tests {let o = String::from_utf8(export(&st, &[], Format::Obj, "t").unwrap()).unwrap();let count = |p: &str| o.lines().filter(|l| l.starts_with(p)).count();assert!(o.contains("\no Red Block\n"), "{o}");- assert_eq!((count("v "), count("vn "), count("f ")), (8, 6, 12), "{o}");+ assert_eq!((count("v "), count("vn "), count("f ")), (64, 6, 124), "{o}");let ids: Vec<usize> =o.lines().filter(|l| l.starts_with("f ")).flat_map(|l| l.split([' ', '/']).skip(1)).filter_map(|x| x.parse().ok()).collect();- assert!(ids.iter().all(|i| (1..=8).contains(i) || (1..=6).contains(i)));+ assert!(ids.iter().all(|i| (1..=64).contains(i)));}/// The design properties land in each format's own metadata (#1015): STEP and IGES headers,diff --git a/crates/kernel/src/body.rs b/crates/kernel/src/body.rsindex 773e4fdb58..2c233bfe00 100644--- a/crates/kernel/src/body.rs+++ b/crates/kernel/src/body.rs@@ -1198,6 +1198,13 @@ impl Body {.collect())}+ /// How far [`Body::planar_edges`] lets a piece it reads as a line or an arc lie from the+ /// edge's curve (a NURBS within this of a circle is that arc), so how far a piece's ends may+ /// lie from the edge's vertices.+ pub fn planar_edges_tolerance(&self) -> f64 {+ (self.size() * 1e-7).max(1e-9) * 10.0+ }+/// Edges `indices` (record edge indices) in `plane`'s coordinates, exactly: lines, circular/// arcs, and free-form curves as the Bézier spans they are, for a sketch to project them./// `None` for an edge that doesn't lie in a plane parallel to `plane`, isn't read exactly or@@ -1206,7 +1213,7 @@ impl Body {if self.is_mesh() {return vec![None; indices.len()];}- let tol = (self.size() * 1e-7).max(1e-9) * 10.0;+ let tol = self.planar_edges_tolerance();indices.iter().map(|i| {diff --git a/crates/ui-egui/src/hole_place_ui_tests.rs b/crates/ui-egui/src/hole_place_ui_tests.rsindex edf780914a..58254ed2fb 100644--- a/crates/ui-egui/src/hole_place_ui_tests.rs+++ b/crates/ui-egui/src/hole_place_ui_tests.rs@@ -304,6 +304,9 @@ fn the_dialog_shows_the_sizes_beside_a_section_of_the_hole() {#[test]fn tapped_thread_depth_field_keeps_focus_and_typing_separate_from_acceptance() {let mut h = Harness::new();+ // Tall enough for the tapped hole's rows and its section, so the partial depth field shows+ // above the dialog's footer (at 1000 px it scrolls under OK, and has no handle).+ h.call("ui.resize", json!({"width": 1600, "height": 1400}));h.app.run("solid.box", json!({"length":40,"width":30,"height":20})).unwrap();let hole = h.app.run("solid.hole", json!({"position":[20,15,20],"thread":"M6","depth":12})).unwrap()["feature"].as_u64().unwrap();let original = h.app.session.doc.to_json();diff --git a/crates/ui-egui/src/hole_placement_ui_tests.rs b/crates/ui-egui/src/hole_placement_ui_tests.rsindex 954972419c..7baa15c37a 100644--- a/crates/ui-egui/src/hole_placement_ui_tests.rs+++ b/crates/ui-egui/src/hole_placement_ui_tests.rs@@ -796,7 +796,9 @@ fn select_other_over_a_dense_cluster_looks_the_face_up_once() {// not the face's or the body's; every point on the face is still counted.let mut c = cylinder_with_cluster(json!({"plane": {"face": [0, 0, 20]}}), [5.0, 4.0], "top");let (many, body, face, near) = (c.many, c.body_tris, c.face_tris, c.near_tris);- assert!(body >= 4 * face && 4 * near <= face, "{body} triangles in the body, {face} in the face, {near} of them near the points");+ // The top cap is one of the cylinder's three faces (the planner meshes both caps alike), under+ // a third of its triangles; the points lie on a small part of it.+ assert!(body >= 3 * face && 4 * near <= face, "{body} triangles in the body, {face} in the face, {near} of them near the points");let (list, (lookups, tested)) = c.select_other();assert_eq!((rows_named(&list, "Point"), rows_named(&list, "Face")), (crate::select_other::MAX_PER_KIND, 1), "{list}");assert_eq!(list["total"], json!(many + 1), "every point on the face is counted: {list}");diff --git a/crates/ui-egui/src/ui_kit/layout.rs b/crates/ui-egui/src/ui_kit/layout.rsindex 97152d656f..638137b73e 100644--- a/crates/ui-egui/src/ui_kit/layout.rs+++ b/crates/ui-egui/src/ui_kit/layout.rs@@ -351,7 +351,13 @@ pub(super) fn named_control<R>(ui: &mut Ui, label: &str, add: impl FnOnce(&mut U/// Publish geometry without replacing native accessibility. Tokens: `none`.pub(super) fn publish_geometry(ui: &Ui, response: &Response) {let label = label(ui);- scenario::publish_target_as(&format!("dialog:{label}"), &format!("dialog:widget:{label}"), response.rect);+ scenario::publish_rect(&format!("dialog:widget:{label}"), response.rect);+ // A click lands where the field shows: a field scrolled out of a dialog's field area, under+ // its footer, has no handle (a click at its centre would press the button over it).+ let shown = response.rect.intersect(ui.clip_rect());+ if shown.is_positive() {+ scenario::publish_handle(&format!("dialog:{label}"), shown.center());+ }}#[cfg(test)]diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rsindex a9292ccf77..29bce24f67 100644--- a/crates/ui-egui/src/viewport.rs+++ b/crates/ui-egui/src/viewport.rs@@ -6999,7 +6999,10 @@ mod tests {for style in 0..4 {app.ui.visual_style = style;let scene = build_scene(&app).merged();- let lines = if style == 1 { 0 } else { 24 * crate::gpu::LINE_SIZE };+ // Twelve edges per placed box, in the saved mesh's pieces: no side longer than a fifth+ // of the 30 mm diagonal, so the eight 20 mm edges in four and the four 10 mm ones in+ // two, 40 segments.+ let lines = if style == 1 { 0 } else { 2 * 40 * crate::gpu::LINE_SIZE };assert_eq!(scene.lines.len(), lines, "style {style}: twelve edges per placed box");assert_eq!(scene.hidden.len(), if style == 3 { lines } else { 0 });assert_eq!(scene.tris.is_empty(), style == 2, "wireframe draws only the edges");diff --git a/crates/ui-egui/src/viewport_appearance_tests.rs b/crates/ui-egui/src/viewport_appearance_tests.rsindex d7842aaebb..f3d75b41de 100644--- a/crates/ui-egui/src/viewport_appearance_tests.rs+++ b/crates/ui-egui/src/viewport_appearance_tests.rs@@ -219,7 +219,9 @@ fn an_opacity_class_change_keeps_vertices_and_rewrites_only_the_runs() {assert!(block.bytes.opaque.is_empty() && !block.bytes.glass.is_empty(), "the triangles moved to the glass runs");let triangles: u32 = block.bytes.glass.iter().map(|r| r.len() as u32).sum::<u32>() / 3;assert_eq!(block.bytes.glass.len(), 1, "one body of one class is one run, drawn with no index buffer");- assert_eq!(triangles, 12, "every triangle of the box");+ // The planner's grids, no side longer than a fifth of the box's 26.9 mm diagonal: edges in+ // 4, 3 and 2 pieces, faces of 4 × 3, 4 × 2 and 3 × 2 cells, 2 · (12 + 8 + 6) · 2 triangles.+ assert_eq!(triangles, 104, "every triangle of the box");let vertex = block.bytes.glass.first().map_or(0, |r| r.start) as usize;let at = vertex * crate::gpu::TRI_SIZE;let colour = first_vertex(&second, block.bytes.vertices.get(at..).unwrap_or_default()).1;