Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Tessellation: trimmed faces of display meshes stay on their surfaces (#1653)

Irakli Kourtis932d8d6b4f7b
diff --git a/crates/engine/src/boolean_regression_tests.rs b/crates/engine/src/boolean_regression_tests.rs
index 8cf79c6f1a..2ed8cf4d5d 100644
--- a/crates/engine/src/boolean_regression_tests.rs
+++ b/crates/engine/src/boolean_regression_tests.rs
@@ -1119,3 +1119,34 @@ fn cut_beside_a_sealed_void_keeps_the_body() {
println!("rotated box beside a void: {got:.6} mm³, expected {want:.6}");
assert!((got - want).abs() < 1e-5 * want, "{got} vs {want}");
}
+
+/// The reference mesh of loft bodies joined into a bike frame covers each face once: within 1%
+/// of the area of a mesh at a tenth of the tolerance. The trimmed loft sides were meshed with a
+/// flat sheet through the down tube (Delaunay in raw parameters on a strip stretched twentyfold:
+/// two and a half times the area), and the seat tube's side with slivers across it (a boundary
+/// polyline hooking back past its vertex dropped a trimming curve's constraints).
+#[test]
+fn joined_loft_frames_reference_mesh_covers_each_face_once() {
+ for (script, name) in [
+ (include_str!("../../../examples/regressions/loft_join_bracket_hull_triangle.json"), "DT2"),
+ (include_str!("../../../examples/regressions/front_triangle_hull_triangle.json"), "FrontTriangle"),
+ ] {
+ let s = replay(script);
+ let state = s.model.state();
+ let body = &state.body(name).unwrap().body;
+ let per_face = |m: &solidcraft_geom::Mesh| {
+ let mut a = vec![0.0; body.face_count()];
+ for (t, f) in m.triangles.iter().zip(&m.tri_face) {
+ let [p0, p1, p2] = t.map(|i| m.positions[i as usize]);
+ a[*f as usize] += (p1 - p0).cross(p2 - p0).len() / 2.0;
+ }
+ a
+ };
+ let size = body.size();
+ let mesh = per_face(&body.reference_display_mesh_angular(size * 3e-4, 12f64.to_radians()).unwrap());
+ let fine = per_face(&body.reference_display_mesh_angular(size * 3e-5, 3f64.to_radians()).unwrap());
+ for (fi, (m, f)) in mesh.iter().zip(&fine).enumerate() {
+ assert!((m - f).abs() <= 0.01 * f.max(1.0), "{name} face {fi}: mesh {m:.0} mm², finer mesh {f:.0} mm²");
+ }
+ }
+}
diff --git a/crates/kernel/src/body.rs b/crates/kernel/src/body.rs
index 5b082e649a..b70d4ed6b8 100644
--- a/crates/kernel/src/body.rs
+++ b/crates/kernel/src/body.rs
@@ -256,7 +256,7 @@ const MIN_DISPLAY_ANGLE: f64 = std::f64::consts::PI / 180.0;
/// non-manifold shells an import can produce). Boundaries that lie on their surface only within
/// tolerance (imports, boolean results) are projected onto it.
fn mesh_shells(solid: &Solid, tol: f64) -> Vec<MeshedShell> {
- mesh_shells_within(solid, Deflection { rulings: true, ..Deflection::chord(tol) })
+ mesh_shells_within(solid, Deflection { display: true, ..Deflection::chord(tol) })
}
/// [`mesh_shells`] divided by a chord tolerance and, when it has one, a bound on the angle a
@@ -1242,9 +1242,9 @@ impl Body {
}
}
let deflection = if angle.is_finite() && angle > 0.0 {
- Deflection { chord: tol, angle: angle.max(MIN_DISPLAY_ANGLE), floor: tol * DISPLAY_ANGLE_FLOOR, rulings: true }
+ Deflection { chord: tol, angle: angle.max(MIN_DISPLAY_ANGLE), floor: tol * DISPLAY_ANGLE_FLOOR, display: true }
} else {
- Deflection { rulings: true, ..Deflection::chord(tol) }
+ Deflection { display: true, ..Deflection::chord(tol) }
};
guard("tessellate", || {
let meshed = mesh_shells_within(&self.solid, deflection);
diff --git a/crates/kernel/src/edge_polyline_tests.rs b/crates/kernel/src/edge_polyline_tests.rs
index 88d068e9df..a3d558573a 100644
--- a/crates/kernel/src/edge_polyline_tests.rs
+++ b/crates/kernel/src/edge_polyline_tests.rs
@@ -121,7 +121,7 @@ fn same_division(curve: &Curve, d: Deflection) -> Vec<Point3> {
/// The chord tolerance alone (booleans), then with the display's facet angle.
fn deflections(tol: f64) -> [Deflection; 2] {
- [Deflection::chord(tol), Deflection { chord: tol, angle: DISPLAY_ANGLE, floor: tol * 0.05, rulings: true }]
+ [Deflection::chord(tol), Deflection { chord: tol, angle: DISPLAY_ANGLE, floor: tol * 0.05, display: true }]
}
#[test]
diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs
index 4d01043c19..239e719c17 100644
--- a/crates/kernel/src/lib.rs
+++ b/crates/kernel/src/lib.rs
@@ -272,3 +272,6 @@ pub fn guard<T>(what: &str, f: impl FnOnce() -> Result<T>) -> Result<T> {
#[cfg(test)]
mod tests;
+
+#[cfg(test)]
+mod trimmed_face_mesh_tests;
diff --git a/crates/kernel/src/thin_face_tests.rs b/crates/kernel/src/thin_face_tests.rs
index faef716b94..6107619a97 100644
--- a/crates/kernel/src/thin_face_tests.rs
+++ b/crates/kernel/src/thin_face_tests.rs
@@ -69,7 +69,7 @@ fn a_face_touching_its_own_edge_meshes() {
let face = mt::Face::new(vec![wire], mt::Surface::Plane(plane));
let shell: mt::Shell = vec![face].into();
for tol in [0.3, 0.08, 0.02, 0.005] {
- let meshed = shell.robust_triangulation_within(Deflection { rulings: true, ..Deflection::chord(tol) });
+ let meshed = shell.robust_triangulation_within(Deflection { display: true, ..Deflection::chord(tol) });
let face = meshed.face_iter().next().unwrap();
let boundary: Vec<mt::Point3> = face.boundaries()[0].edge_iter().flat_map(|e| e.oriented_curve().0.into_iter().skip(1)).collect();
let mesh = face.surface().unwrap();
diff --git a/crates/kernel/src/trimmed_face_mesh_tests.rs b/crates/kernel/src/trimmed_face_mesh_tests.rs
new file mode 100644
index 0000000000..f1423f05c4
--- /dev/null
+++ b/crates/kernel/src/trimmed_face_mesh_tests.rs
@@ -0,0 +1,78 @@
+//! Tessellation of trimmed loft faces after a boolean: no triangle may leave the face.
+
+use std::f64::consts::FRAC_PI_2;
+
+use solidcraft_geom::{Loop2, Plane, Seg2, Vec2, Vec3};
+use truck_modeling::{self as mt, SearchNearestParameter};
+
+use crate::*;
+
+/// Counter-clockwise rounded rectangle centred on the origin.
+fn rounded(w: f64, h: f64, r: f64) -> Loop2 {
+ let (x, y) = (w / 2.0, h / 2.0);
+ let arc = |cx: f64, cy: f64, start: f64| Seg2::Arc { center: Vec2::new(cx, cy), radius: r, start, sweep: FRAC_PI_2 };
+ Loop2 {
+ segs: vec![
+ arc(x - r, -y + r, -FRAC_PI_2),
+ Seg2::Line { a: Vec2::new(x, -y + r), b: Vec2::new(x, y - r) },
+ arc(x - r, y - r, 0.0),
+ Seg2::Line { a: Vec2::new(x - r, y), b: Vec2::new(-x + r, y) },
+ arc(-x + r, y - r, FRAC_PI_2),
+ Seg2::Line { a: Vec2::new(-x, y - r), b: Vec2::new(-x, -y + r) },
+ arc(-x + r, -y + r, 2.0 * FRAC_PI_2),
+ Seg2::Line { a: Vec2::new(-x + r, -y), b: Vec2::new(x - r, -y) },
+ ],
+ }
+}
+
+/// The down tube of a bicycle frame: rounded-rectangle sections lofted along a bend.
+fn tube() -> Body {
+ let s = |o: [f64; 3], y: [f64; 3], w: f64, h: f64, r: f64| {
+ (Plane::new(Vec3::new(o[0], o[1], o[2]), Vec3::Y, Vec3::new(y[0], y[1], y[2])).unwrap(), rounded(w, h, r))
+ };
+ loft(&[
+ s([8.0, 0.0, 3.0], [-0.178, 0.0, 0.984], 38.0, 36.0, 10.8),
+ s([80.0, 0.0, 16.0], [-0.211, 0.0, 0.977], 60.0, 52.0, 15.6),
+ s([175.0, 0.0, 40.0], [-0.596, 0.0, 0.803], 76.0, 66.0, 19.8),
+ s([314.248, 0.0, 271.657], [-0.857, 0.0, 0.515], 74.0, 66.0, 19.8),
+ s([422.553, 0.0, 451.835], [-0.857, 0.0, 0.515], 66.0, 60.0, 18.0),
+ s([484.441, 0.0, 554.793], [-0.857, 0.0, 0.515], 46.0, 44.0, 13.2),
+ ])
+ .unwrap()
+}
+
+/// Each face's mesh area, and how far its triangles' centroids lie off its surface at most.
+fn per_face(body: &Body, mesh: &solidcraft_geom::Mesh) -> Vec<(f64, f64)> {
+ use mt::ParametricSurface;
+ let faces: Vec<&mt::Face> = body.solid.face_iter().collect();
+ let mut out = vec![(0.0, 0.0f64); faces.len()];
+ for (t, &f) in mesh.triangles.iter().zip(&mesh.tri_face) {
+ let ([a, b, c], Some(face), Some(slot)) = (mesh.tri(t).unwrap(), faces.get(f as usize), out.get_mut(f as usize)) else { continue };
+ slot.0 += (b - a).cross(c - a).len() / 2.0;
+ let g = (a + b + c) / 3.0;
+ let surface = face.oriented_surface();
+ let (u, v) = surface.search_nearest_parameter(mt::Point3::new(g.x, g.y, g.z), None, 50).unwrap();
+ slot.1 = slot.1.max(crate::body::from_p3(surface.subs(u, v)).dist(g));
+ }
+ out
+}
+
+/// A lofted tube whose side faces are ruled across (straight section edges) and long along
+/// the loft, joined to a cylinder that trims their ends: the display mesh of a trimmed side
+/// fanned one trimming node to boundary nodes hundreds of millimetres away (Delaunay in raw
+/// parameters on a strip stretched twentyfold), a flat sheet off the surface.
+#[test]
+fn trimmed_ruled_loft_faces_mesh_on_their_surfaces() {
+ let tube = tube();
+ let shell = cylinder(Vec3::new(0.0, -36.5, 0.0), Vec3::Y, 23.0, 73.0).unwrap();
+ let joined = boolean(&tube, &shell, BoolOp::Union).unwrap().unwrap();
+ let tol = (joined.size() * 1e-3).max(1e-3);
+ let display = per_face(&joined, &joined.reference_display_mesh_angular(tol, DISPLAY_ANGLE).unwrap());
+ let fine = per_face(&joined, &joined.tessellate(tol / 8.0).unwrap());
+ for (fi, ((area, off), (fine_area, _))) in display.iter().zip(&fine).enumerate() {
+ // A centroid sags at most about the chord tolerance (the bad sheet was 7 mm off at 0.6).
+ assert!(*off < 2.0 * tol, "face {fi}: a triangle lies {off:.2} mm off the surface (tolerance {tol:.2})");
+ // Covered once: the area of a much finer mesh (the bad face had two and a half times it).
+ assert!((area - fine_area).abs() < 0.02 * fine_area, "face {fi}: mesh area {area:.0} mm², finer mesh {fine_area:.0} mm²");
+ }
+}
diff --git a/crates/ui-egui/src/preselect_tests.rs b/crates/ui-egui/src/preselect_tests.rs
index 9afc5cf45e..1ae3c38120 100644
--- a/crates/ui-egui/src/preselect_tests.rs
+++ b/crates/ui-egui/src/preselect_tests.rs
@@ -1362,6 +1362,14 @@ fn modelled_thread_preview_updates_reports_errors_and_cancels_without_changes()
}
assert!(h.app.preview.error.as_deref().is_some_and(|e| e.contains("does not fit")), "{:?}", h.app.preview.error);
designation(&mut h, "M8x1.3");
+ // The M6 error stays until the new preview starts; wait for it to go, or
+ // `wait_feature_preview` would stop at the stale error on a host that schedules the
+ // preview a few frames later.
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120);
+ while h.app.preview.error.is_some() && std::time::Instant::now() < deadline {
+ h.frames(2);
+ std::thread::sleep(std::time::Duration::from_millis(10));
+ }
wait_feature_preview(&mut h);
assert!(h.app.preview.error.is_none());
assert_eq!(h.app.session.doc.to_json(), saved);
diff --git a/tests/robustness/goldens.json b/tests/robustness/goldens.json
index 1c882fbd02..bb62b4d58e 100644
--- a/tests/robustness/goldens.json
+++ b/tests/robustness/goldens.json
@@ -2,7 +2,7 @@
"about": "What each robustness seed builds (crates/engine/src/tests/robustness_goldens.rs, docs/robustness.md). Record changes with ROBUSTNESS_GOLDENS_BLESS=\"why\".",
"seeds": {
"0": {"area":4807.582879,"bodies":1,"edges":72,"error":null,"faces":27,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","hole","circular pattern","circular pattern","cut sphere","join cylinder","cut cylinder","cut sphere"],"unsupported":0,"volume":13472.328916},
- "1": {"area":2642.476583,"bodies":1,"edges":37,"error":null,"faces":15,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","cut cylinder","join cylinder"],"unsupported":0,"volume":6991.559261},
+ "1": {"area":2642.450646,"bodies":1,"edges":37,"error":null,"faces":15,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","cut cylinder","join cylinder"],"unsupported":0,"volume":6991.573271},
"2": {"area":2522.922626,"bodies":1,"edges":36,"error":"boolean Cut: the operation failed: no result","faces":14,"outcome":"failed","rejected":1,"shells":1,"steps":["box","cut cylinder","fillet","cut sphere","rectangular pattern"],"unsupported":2,"volume":5580.088497},
"3": {"area":6336.456143,"bodies":1,"edges":33,"error":null,"faces":13,"outcome":"ok","rejected":0,"shells":1,"steps":["box","cut box","hole","fillet","hole"],"unsupported":0,"volume":28037.146888},
"4": {"area":5810.088602,"bodies":1,"edges":27,"error":null,"faces":11,"outcome":"ok","rejected":0,"shells":1,"steps":["box","cut cylinder","fillet"],"unsupported":0,"volume":28461.628006},
@@ -15,16 +15,16 @@
"11": {"area":7858.300481,"bodies":1,"edges":33,"error":null,"faces":13,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","hole","rectangular pattern","fillet"],"unsupported":0,"volume":34605.048259},
"12": {"area":4668.773162,"bodies":1,"edges":59,"error":null,"faces":25,"outcome":"ok","rejected":0,"shells":2,"steps":["extruded profile","chamfer","join cylinder","join box","cut cylinder","circular pattern"],"unsupported":3,"volume":11874.973223},
"13": {"area":2112.846954,"bodies":1,"edges":99,"error":null,"faces":39,"outcome":"ok","rejected":1,"shells":1,"steps":["revolved section","cut cylinder","join box","rectangular pattern","cut cylinder","cut box","fillet","hole"],"unsupported":0,"volume":2410.783741},
- "14": {"area":10553.267409,"bodies":1,"edges":43,"error":null,"faces":20,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","cut cylinder","shell","fillet"],"unsupported":0,"volume":10369.008764},
+ "14": {"area":10554.182993,"bodies":1,"edges":43,"error":null,"faces":20,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","cut cylinder","shell","fillet"],"unsupported":0,"volume":10371.646072},
"15": {"area":2312.730168,"bodies":1,"edges":39,"error":null,"faces":15,"outcome":"ok","rejected":2,"shells":1,"steps":["revolved section","cut box","rectangular pattern","cut sphere","cut cylinder","cut sphere","join cylinder"],"unsupported":0,"volume":5728.661237},
"16": {"area":8872.878228,"bodies":1,"edges":49,"error":null,"faces":23,"outcome":"ok","rejected":0,"shells":3,"steps":["box","join cylinder","circular pattern","hole"],"unsupported":0,"volume":44953.407975},
"17": {"area":6022.921702,"bodies":1,"edges":48,"error":null,"faces":19,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","cut box","shell","cut cylinder"],"unsupported":0,"volume":2981.269959},
"18": {"area":5969.14407,"bodies":1,"edges":131,"error":null,"faces":53,"outcome":"ok","rejected":0,"shells":4,"steps":["extruded profile","join cylinder","circular pattern","cut cylinder","hole","cut cylinder","hole","circular pattern"],"unsupported":0,"volume":20696.295391},
"19": {"area":3440.869757,"bodies":1,"edges":42,"error":null,"faces":16,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","chamfer","cut sphere"],"unsupported":0,"volume":5909.174021},
- "20": {"area":5727.102692,"bodies":1,"edges":116,"error":null,"faces":45,"outcome":"ok","rejected":1,"shells":1,"steps":["extruded profile","fillet","cut box","cut cylinder","hole","circular pattern","cut box"],"unsupported":0,"volume":17142.747554},
+ "20": {"area":5729.705185,"bodies":1,"edges":116,"error":null,"faces":45,"outcome":"ok","rejected":1,"shells":1,"steps":["extruded profile","fillet","cut box","cut cylinder","hole","circular pattern","cut box"],"unsupported":0,"volume":17157.584515},
"21": {"area":5814.791707,"bodies":1,"edges":56,"error":null,"faces":22,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","join box","hole","fillet","hole","cut box"],"unsupported":1,"volume":19153.734422},
"22": {"area":4634.445571,"bodies":1,"edges":138,"error":null,"faces":54,"outcome":"ok","rejected":0,"shells":2,"steps":["revolved section","join box","join box","join box","rectangular pattern","cut cylinder"],"unsupported":0,"volume":7855.557174},
- "23": {"area":1795.696192,"bodies":1,"edges":16,"error":null,"faces":7,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","cut sphere"],"unsupported":0,"volume":3198.694598},
+ "23": {"area":1795.692727,"bodies":1,"edges":16,"error":null,"faces":7,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","cut sphere"],"unsupported":0,"volume":3198.694598},
"24": {"area":8910.288004,"bodies":1,"edges":64,"error":null,"faces":20,"outcome":"ok","rejected":1,"shells":1,"steps":["revolved section","chamfer","hole","cut box","cut sphere","cut sphere","hole"],"unsupported":1,"volume":32456.126515},
"25": {"area":7142.717684,"bodies":1,"edges":48,"error":null,"faces":19,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","shell"],"unsupported":0,"volume":7012.754625},
"26": {"area":6461.702601,"bodies":1,"edges":56,"error":null,"faces":22,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","join box","cut cylinder","rectangular pattern","cut sphere"],"unsupported":0,"volume":21188.159601},
@@ -41,7 +41,7 @@
"37": {"area":11714.822253,"bodies":1,"edges":44,"error":null,"faces":18,"outcome":"ok","rejected":1,"shells":1,"steps":["box","cut cylinder","join cylinder","cut sphere","circular pattern","fillet","circular pattern","rectangular pattern"],"unsupported":2,"volume":75556.602064},
"38": {"area":11769.375811,"bodies":1,"edges":30,"error":"offset: a corner whose faces don't meet the same way after t","faces":12,"outcome":"failed","rejected":1,"shells":1,"steps":["box","hole","cut cylinder","shell"],"unsupported":0,"volume":78261.020975},
"39": {"area":1892.051593,"bodies":1,"edges":27,"error":null,"faces":11,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","chamfer","cut sphere","rectangular pattern"],"unsupported":1,"volume":4040.619835},
- "40": {"area":15548.516294,"bodies":1,"edges":49,"error":"offset: a corner whose faces don't meet the same way after t","faces":22,"outcome":"failed","rejected":0,"shells":1,"steps":["extruded profile","cut cylinder","shell","cut cylinder","join cylinder","shell"],"unsupported":0,"volume":16543.777532},
+ "40": {"area":15549.121775,"bodies":1,"edges":49,"error":"offset: a corner whose faces don't meet the same way after t","faces":22,"outcome":"failed","rejected":0,"shells":1,"steps":["extruded profile","cut cylinder","shell","cut cylinder","join cylinder","shell"],"unsupported":0,"volume":16541.530092},
"41": {"area":7295.282884,"bodies":1,"edges":93,"error":null,"faces":32,"outcome":"ok","rejected":1,"shells":1,"steps":["box","cut sphere","shell","fillet","cut cylinder","rectangular pattern","fillet","cut sphere"],"unsupported":0,"volume":5185.221068},
"42": {"area":5486.877622,"bodies":1,"edges":51,"error":null,"faces":20,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","cut box","cut cylinder","rectangular pattern"],"unsupported":0,"volume":19095.106157},
"43": {"area":3492.988343,"bodies":1,"edges":72,"error":null,"faces":26,"outcome":"ok","rejected":2,"shells":1,"steps":["extruded profile","cut cylinder","rectangular pattern","fillet","hole","rectangular pattern","join cylinder"],"unsupported":1,"volume":7528.548742},
@@ -56,7 +56,7 @@
"52": {"area":8628.608654,"bodies":1,"edges":45,"error":null,"faces":18,"outcome":"ok","rejected":0,"shells":1,"steps":["box","shell","cut cylinder","chamfer","join cylinder"],"unsupported":1,"volume":9001.505742},
"53": {"area":17463.451761,"bodies":1,"edges":116,"error":null,"faces":48,"outcome":"ok","rejected":0,"shells":4,"steps":["extruded profile","cut cylinder","shell","fillet","join cylinder","circular pattern"],"unsupported":0,"volume":16954.551768},
"54": {"area":7075.531663,"bodies":1,"edges":81,"error":"offset: a corner whose faces don't meet the same way after t","faces":35,"outcome":"failed","rejected":0,"shells":4,"steps":["extruded profile","join box","circular pattern","cut cylinder","cut box","join cylinder","shell"],"unsupported":2,"volume":16028.147251},
- "55": {"area":6796.504547,"bodies":1,"edges":60,"error":null,"faces":23,"outcome":"ok","rejected":0,"shells":1,"steps":["box","fillet","cut sphere","circular pattern","rectangular pattern","cut sphere"],"unsupported":0,"volume":24744.182468},
+ "55": {"area":6795.599353,"bodies":1,"edges":60,"error":null,"faces":23,"outcome":"ok","rejected":0,"shells":1,"steps":["box","fillet","cut sphere","circular pattern","rectangular pattern","cut sphere"],"unsupported":0,"volume":24743.737783},
"56": {"area":4453.31728,"bodies":1,"edges":33,"error":null,"faces":13,"outcome":"ok","rejected":0,"shells":1,"steps":["box","cut box","chamfer"],"unsupported":0,"volume":11829.375},
"57": {"area":4671.095724,"bodies":1,"edges":66,"error":null,"faces":24,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","cut sphere","circular pattern","chamfer","cut sphere","cut sphere","cut cylinder"],"unsupported":2,"volume":16017.21038},
"58": {"area":4197.049258,"bodies":1,"edges":42,"error":null,"faces":16,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","fillet","cut sphere"],"unsupported":0,"volume":12543.173591},
@@ -65,7 +65,7 @@
"61": {"area":5020.413153,"bodies":1,"edges":36,"error":"boolean Cut: the operation failed: no result","faces":15,"outcome":"failed","rejected":0,"shells":1,"steps":["extruded profile","cut cylinder","shell","rectangular pattern"],"unsupported":0,"volume":4906.628538},
"62": {"area":8771.003732,"bodies":1,"edges":60,"error":null,"faces":23,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","cut cylinder","circular pattern","cut box","cut box","join cylinder"],"unsupported":2,"volume":40107.001728},
"63": {"area":4316.842909,"bodies":1,"edges":100,"error":null,"faces":38,"outcome":"ok","rejected":0,"shells":3,"steps":["revolved section","join box","cut cylinder","hole","cut cylinder","join box","rectangular pattern"],"unsupported":3,"volume":8229.233195},
- "64": {"area":4088.335645,"bodies":1,"edges":36,"error":null,"faces":14,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","fillet","join cylinder"],"unsupported":0,"volume":8495.220295},
+ "64": {"area":4088.335645,"bodies":1,"edges":36,"error":null,"faces":14,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","fillet","join cylinder"],"unsupported":0,"volume":8495.235267},
"65": {"area":8436.255548,"bodies":1,"edges":37,"error":null,"faces":15,"outcome":"ok","rejected":0,"shells":1,"steps":["box","cut cylinder","fillet","rectangular pattern","circular pattern","circular pattern","fillet","cut box"],"unsupported":0,"volume":45143.475817},
"66": {"area":9222.76638,"bodies":1,"edges":99,"error":null,"faces":37,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","join box","join box","join box","cut sphere","cut box"],"unsupported":1,"volume":35217.203139},
"67": {"area":7940.064,"bodies":1,"edges":84,"error":null,"faces":35,"outcome":"ok","rejected":1,"shells":2,"steps":["extruded profile","cut cylinder","hole","join cylinder","join box","hole","chamfer","rectangular pattern"],"unsupported":1,"volume":27606.450855},
@@ -87,7 +87,7 @@
"83": {"area":8632.834978,"bodies":1,"edges":95,"error":null,"faces":35,"outcome":"ok","rejected":0,"shells":2,"steps":["box","join box","rectangular pattern","shell","cut sphere","join box","fillet"],"unsupported":2,"volume":6339.218896},
"84": {"area":4906.192237,"bodies":1,"edges":67,"error":null,"faces":25,"outcome":"ok","rejected":2,"shells":1,"steps":["extruded profile","fillet","hole","hole","cut cylinder","cut box","fillet"],"unsupported":0,"volume":14219.865875},
"85": {"area":3309.210936,"bodies":1,"edges":57,"error":null,"faces":24,"outcome":"ok","rejected":1,"shells":2,"steps":["revolved section","fillet","cut sphere","circular pattern","join cylinder","hole","join box"],"unsupported":0,"volume":6904.455565},
- "86": {"area":7570.844423,"bodies":1,"edges":66,"error":"offset: a corner whose faces don't meet the same way after t","faces":30,"outcome":"failed","rejected":0,"shells":3,"steps":["extruded profile","join cylinder","join cylinder","circular pattern","hole","rectangular pattern","shell"],"unsupported":1,"volume":20478.868768},
+ "86": {"area":7580.468361,"bodies":1,"edges":66,"error":"offset: a corner whose faces don't meet the same way after t","faces":30,"outcome":"failed","rejected":0,"shells":3,"steps":["extruded profile","join cylinder","join cylinder","circular pattern","hole","rectangular pattern","shell"],"unsupported":1,"volume":20437.482684},
"87": {"area":4853.708989,"bodies":1,"edges":24,"error":null,"faces":10,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","cut box","rectangular pattern"],"unsupported":0,"volume":18568.611108},
"88": {"area":3947.799648,"bodies":1,"edges":18,"error":null,"faces":8,"outcome":"ok","rejected":0,"shells":1,"steps":["box","hole"],"unsupported":0,"volume":12788.04706},
"89": {"area":2512.5,"bodies":1,"edges":12,"error":null,"faces":6,"outcome":"ok","rejected":0,"shells":1,"steps":["box","cut box"],"unsupported":0,"volume":5906.25},
@@ -145,6 +145,7 @@
{"reason":"Rebase #2387 onto #2247: patterned pieces stay in one body. Seed 86 drills its hole, then reaches the same offset-corner shell refusal as main instead of shelling separate bodies. Completed steps still pass validity and volume-direction checks.","seeds":[86]},
{"reason":"A join whose coincident faces were pushed apart now trims the slab beyond the plane by editing faces when the boolean cut of it fails (a prism whose edge in the plane lies in the end face of a slab with rounded corners). Seed 70: the shell of a body in two lumps, refused before, now builds; its volume matches an independent offset of the profile (4120.90 vs 4120.67 mm3, the gap is the unshelled profile's own tessellation).","seeds":[70]},
{"reason":"#1648: a face whose boundary touches itself within the tolerance is triangulated through the touching point instead of across the face, so faces that meshed with triangles missing or outside them now mesh whole. Seeds 20 and 55 build the same designs (same steps, faces, edges and shells); only the measured area, and for seed 55 the volume, of their final bodies move. Seed 55: replaying it with the old and the new triangulation gives the same final body; two curved faces measured 442.14 and 325.42 mm2 with the old triangulation at a fine tolerance, 436.29 and 305.83 mm2 with the new one, which agrees with their coarser meshes, and its volume moves from 24740.93 to 24744.18 mm3, against 24743.58 mm3 from a mesh at 1e-4 mm. Seed 20, as main now builds it, moves only in area, from 5726.92956 to 5727.102692 mm2 (3e-5 relative). Recorded from the fork CI output (Linux).","seeds":[20,55]},
- {"reason":"A cut no longer comes out empty where a shell of one body meets nothing of the other (a sealed void, a body clear of the tool): truck placed such faces by their surfaces alone, which a turned body's reversed faces and a void's inward shell got wrong. Seeds 0, 45 and 77 each had a cut refused as empty that now takes what it should, and the generator builds different steps after it: seed 0 a sphere clear of the body (removes nothing), seed 45 a hole on the axis of a shelled turned body (widens its bore from r 2.5 to r 4 over 17.5 mm: 536.0 mm3), seed 77 a hole inside a turned body's bore (removes nothing; a later pattern copy drills r 1.5 through 27.5 mm: 194.4 mm3). Every step passes the validity and volume-direction checks.","seeds":[0,45,77]}
+ {"reason":"A cut no longer comes out empty where a shell of one body meets nothing of the other (a sealed void, a body clear of the tool): truck placed such faces by their surfaces alone, which a turned body's reversed faces and a void's inward shell got wrong. Seeds 0, 45 and 77 each had a cut refused as empty that now takes what it should, and the generator builds different steps after it: seed 0 a sphere clear of the body (removes nothing), seed 45 a hole on the axis of a shelled turned body (widens its bore from r 2.5 to r 4 over 17.5 mm: 536.0 mm3), seed 77 a hole inside a turned body's bore (removes nothing; a later pattern copy drills r 1.5 through 27.5 mm: 194.4 mm3). Every step passes the validity and volume-direction checks.","seeds":[0,45,77]},
+ {"reason":"Trimmed faces of display meshes stay on their surfaces (#1653): seeds 1, 23, 55, 64 and 86 end with bodies whose trimmed faces were meshed off their surfaces; measured on the corrected meshes their area and volume move slightly (seed 86 most: area +9.6 mm2, volume -41.4 mm3, 0.2 %). Steps, outcome and counts are unchanged; recorded from Linux CI on main at the time of the rebase. The slow seeds 14, 20 and 40 (run only by the merge queue) move too: 14 area +0.92 mm2 / volume +2.64 mm3, 20 area +2.60 mm2 / volume +14.8 mm3, 40 area +0.61 mm2 / volume -2.25 mm3, from merge-group run 39450833424.","seeds":[1,14,20,23,40,55,64,86]}
]
}
diff --git a/vendor/README.md b/vendor/README.md
index 726783874c..1d974fa7ee 100644
--- a/vendor/README.md
+++ b/vendor/README.md
@@ -180,6 +180,22 @@ Changes:
old test is kept as `tessellation::include_test_hooks`, behind a `test-hooks` feature that
only `solidcraft-kernel`'s tests turn on, and `crates/kernel/tests/tess_include_equivalence.rs`
compares the two.
+- `tessellation/triangulation.rs`: the constrained Delaunay triangulation of a trimmed face
+ works in (u, v) scaled by the surface's mean speed along each (a power of two, so exact both
+ ways). In raw parameters, a loft side ruled across (about 30 mm) and long along the loft
+ (about 600 mm) is a strip stretched twentyfold, and a trimming node was fanned to boundary
+ nodes hundreds of millimetres away: a flat sheet through a joined tube.
+- `tessellation/triangulation.rs`: every segment of a face's boundary becomes a constraint; one
+ that crosses or overlaps a constraint already added (an intersection edge's polyline can hook
+ back a few micrometres past its vertex) is split where they meet. truck dropped such a
+ segment and joined its start to the first later node it could reach, which on a joined tube
+ left a trimming curve's 130 nodes behind one constraint across the face: slivers from it
+ sagged millimetres off the surface, and a face pinched to a point (#1648) got no triangles.
+ All meshes; faces whose segments all go in mesh as before.
+- `tessellation/mod.rs`: `Deflection::rulings` is now `Deflection::display`: a mesh to display
+ or export (the kernel's `tessellate` and display meshes), which gets the ruling grid lines,
+ and the speed-scaled triangulation above. The meshes a Boolean operation intersects
+ (`Deflection::chord`) keep truck's (u, v) and insertion order.
- `lib.rs`: compiler warnings no longer fail the build. Example, test and bench targets are
dropped (their sources are not vendored).
- `tessellation/triangulation.rs`: adaptive division also splits a cell that bows off its
@@ -191,21 +207,12 @@ Changes:
face's mesh puts each point at its parameters on the face's own surface, so a point of an edge
that lies off a surface within tolerance (an intersection-curve sample whose projection did not
converge, an imported edge) came out in a different place on each of the edge's faces, and the
- exported mesh had a crack there. In display and export meshes (`Deflection::rulings`), a
+ exported mesh had a crack there. In display and export meshes (`Deflection::display`), a
vertex at a point of a face's boundary loops that is farther than `TOLERANCE` from the nearest
point of the face's edges now goes to that point, when it is within the chord tolerance
(`onto_edges`). Points within `TOLERANCE` stay on the surface, so exact geometry meshes as
before. The meshes Boolean operations intersect keep truck's points.
-- `tessellation/triangulation.rs`: a face whose boundary touches itself or another of its loops
- within `TOLERANCE` (pinched to a point where a body touches its edge, #1648) can cross there by
- less than that. A segment that would cross one already added was left out of the triangulation,
- and the fallback that joins the next point instead cut across the face: such a face came out
- with no triangles, or without those at the pinch, depending on which segment went in first.
- When a segment is left out, every boundary point within `TOLERANCE` of a segment, away from its
- ends, is put into it (`pinched`: at most 8192 boundary points, and at most 8192 put in), and
- the face is triangulated again. Faces whose segments all go in are triangulated as before.
-
-- `tessellation/triangulation.rs`: in display and export meshes (`Deflection::rulings`), a
+- `tessellation/triangulation.rs`: in display and export meshes (`Deflection::display`), a
direction left undivided along the rulings of a face ruled one way also gets a grid line
through each point of the face's boundary that lies inside the face along it
(`with_boundary_lines`), when there are at most 16 such points: corners standing into the
diff --git a/vendor/truck-meshalgo/src/tessellation/mod.rs b/vendor/truck-meshalgo/src/tessellation/mod.rs
index b51c098b0f..0ec2f9011c 100644
--- a/vendor/truck-meshalgo/src/tessellation/mod.rs
+++ b/vendor/truck-meshalgo/src/tessellation/mod.rs
@@ -122,10 +122,13 @@ pub struct Deflection {
pub angle: f64,
/// Sag below which `angle` no longer splits a facet.
pub floor: f64,
- /// SolidCraft: grid lines through the vertices that split a face's ruling edges (see
- /// `with_ruling_vertices`). Meshes for display and export ask for them; the meshes Boolean
- /// operations intersect do not, so a Boolean's result does not depend on them.
- pub rulings: bool,
+ /// SolidCraft: a mesh to display or export, which must lie on its faces, rather than one a
+ /// Boolean operation intersects (whose results must not depend on what follows). Such a
+ /// mesh gets grid lines through the vertices that split a face's ruling edges (see
+ /// `with_ruling_vertices`), triangulates a trimmed face in speed-scaled parameters
+ /// (`UvScale`), keeps every boundary segment as a constraint (`PolyBoundary::insert_to`),
+ /// and puts its boundary points on the face's edges (`onto_edges`).
+ pub display: bool,
}
impl Deflection {
@@ -145,7 +148,7 @@ impl Deflection {
chord: tol,
angle: f64::INFINITY,
floor: 0.0,
- rulings: false,
+ display: false,
}
}
@@ -158,7 +161,7 @@ impl Deflection {
let angle = self.angle * f64::from(1u32 << level.min(Self::MAX_RELAX));
match level == 0 || (level < Self::MAX_RELAX && angle < std::f64::consts::PI) {
true => Self { angle, ..*self },
- false => Self { rulings: self.rulings, ..Self::chord(self.chord) },
+ false => Self { display: self.display, ..Self::chord(self.chord) },
}
}
diff --git a/vendor/truck-meshalgo/src/tessellation/triangulation.rs b/vendor/truck-meshalgo/src/tessellation/triangulation.rs
index 1428376c9c..b9c36de414 100644
--- a/vendor/truck-meshalgo/src/tessellation/triangulation.rs
+++ b/vendor/truck-meshalgo/src/tessellation/triangulation.rs
@@ -12,6 +12,7 @@ use rayon::prelude::*;
type SPoint2 = spade::Point2<f64>;
type Cdt = ConstrainedDelaunayTriangulation<SPoint2>;
+type VertexId = handles::FixedVertexHandle;
type MeshedShell = Shell<Point3, PolylineCurve, Option<PolygonMesh>>;
type MeshedCShell = CompressedShell<Point3, PolylineCurve, Option<PolygonMesh>>;
@@ -484,7 +485,7 @@ fn shell_create_polygon<S: PreMeshableSurface>(
let mut mesh = trimming_tessellation(surface, &boundary, tol, cap);
// Display and export meshes only, as the ruling grid lines: the meshes Boolean
// operations intersect keep truck's points.
- if tol.rulings {
+ if tol.display {
let points: Vec<Point3> = wires.iter().flat_map(Wire::edge_iter).flat_map(|e| e.curve().0).collect();
onto_edges(&mut mesh, &boundary, &points, tol.chord);
}
@@ -881,21 +882,17 @@ impl PolyBoundary {
.unwrap_or(false)
}
- /// Inserts points and adds constraint into triangulation. SolidCraft: whether every segment
- /// went in.
- fn insert_to(&self, triangulation: &mut Cdt) -> bool {
- let poly2tri: Vec<_> = self
- .0
- .iter()
- .flatten()
- .map(|pt| {
- let p = [spade_round(pt.x), spade_round(pt.y)];
- triangulation.insert(SPoint2::from(p)).ok()
- })
- .collect();
- let mut prev: Option<usize> = None;
+ /// Inserts the loops' points into the triangulation; [`Self::add_constraints`] then joins
+ /// them.
+ fn insert_points(&self, triangulation: &mut Cdt, scale: UvScale) -> Vec<Option<VertexId>> {
+ self.0.iter().flatten().map(|pt| triangulation.insert(scale.to_cdt(*pt)).ok()).collect()
+ }
+
+ /// Adds the loops' segments between the vertices [`Self::insert_points`] gave. SolidCraft: a
+ /// segment that crosses one already added is split where they meet (truck dropped it and
+ /// joined across the face; #1648).
+ fn add_constraints(&self, triangulation: &mut Cdt, poly2tri: &[Option<VertexId>]) {
let mut counter = 0;
- let mut complete = true;
self.0
.iter()
.map(Vec::len)
@@ -905,73 +902,68 @@ impl PolyBoundary {
range.circular_tuple_windows()
})
.for_each(|(i, j)| {
- let Some(vj) = poly2tri[j] else { return };
- if let Some(p) = prev {
- let Some(v) = poly2tri[p] else { return };
- if triangulation.can_add_constraint(v, vj) {
- triangulation.add_constraint(v, vj);
- prev = None;
- }
+ let (Some(vi), Some(vj)) = (poly2tri[i], poly2tri[j]) else { return };
+ if vi == vj {
+ return;
+ }
+ if triangulation.can_add_constraint(vi, vj) {
+ triangulation.add_constraint(vi, vj);
} else {
- let Some(vi) = poly2tri[i] else { return };
- if triangulation.can_add_constraint(vi, vj) {
- triangulation.add_constraint(vi, vj);
- } else {
- complete = false;
- prev = Some(i);
- }
+ triangulation.add_constraint_and_split(vi, vj, |p| p);
}
});
- complete
}
}
-/// SolidCraft: most boundary points [`pinched`] compares with every segment, and most points it
-/// puts into segments.
-const MAX_PINCH_POINTS: usize = 8192;
-
-/// SolidCraft: `loops` with every point that lies within `TOLERANCE` of a segment, away from its
-/// ends, put into that segment (in order along it): where a loop touches itself or another,
-/// both pass through the same point. `None` when no point does, or the loops have more than
-/// [`MAX_PINCH_POINTS`] points, or more than that would be put in.
-fn pinched(loops: &[Vec<Point2>]) -> Option<Vec<Vec<Point2>>> {
- if loops.iter().map(Vec::len).sum::<usize>() > MAX_PINCH_POINTS {
- return None;
- }
- let mut extra: Vec<Vec<Vec<(f64, Point2)>>> = loops.iter().map(|l| vec![Vec::new(); l.len()]).collect();
- let mut found = 0;
- for (l, extra) in loops.iter().zip(&mut extra) {
- let n = l.len();
- for (i, extra) in extra.iter_mut().enumerate() {
- let (q0, q1) = (l[i], l[(i + 1) % n]);
- let d = q1 - q0;
- let len2 = d.magnitude2();
- if len2 <= TOLERANCE2 {
- continue;
- }
- for &p in loops.iter().flatten() {
- if p.distance2(q0) <= TOLERANCE2 || p.distance2(q1) <= TOLERANCE2 {
- continue;
- }
- let t = (p - q0).dot(d) / len2;
- if t > 0.0 && t < 1.0 && p.distance2(q0 + d * t) <= TOLERANCE2 {
- if found == MAX_PINCH_POINTS {
- return None;
- }
- extra.push((t, p));
- found += 1;
+/// SolidCraft: the (u, v) scale the triangulation works in, each parameter by the surface's mean
+/// speed along it (a power of two, so exact both ways): Delaunay in raw parameters fans a
+/// stretched strip (a long loft side) across the surface.
+#[derive(Clone, Copy, Debug)]
+struct UvScale([f64; 2]);
+
+impl UvScale {
+ const IDENTITY: UvScale = UvScale([1.0, 1.0]);
+ /// Most binary orders of magnitude between the two scales.
+ const MAX_EXPONENT: f64 = 30.0;
+ /// Samples per direction over the boundary's box.
+ const SAMPLES: usize = 5;
+
+ fn of(surface: &impl PreMeshableSurface, polyline: &PolyBoundary) -> Self {
+ let bdb: BoundingBox<Point2> = polyline.0.iter().flatten().collect();
+ let (min, max) = (bdb.min(), bdb.max());
+ if !(min.x.is_finite() && min.y.is_finite() && max.x.is_finite() && max.y.is_finite()) {
+ return Self::IDENTITY;
+ }
+ let n = Self::SAMPLES;
+ let (mut su, mut sv, mut count) = (0.0, 0.0, 0usize);
+ for i in 0..n {
+ for j in 0..n {
+ let (s, t) = (i as f64 / (n - 1) as f64, j as f64 / (n - 1) as f64);
+ let (u, v) = (min.x + (max.x - min.x) * s, min.y + (max.y - min.y) * t);
+ let (du, dv) = (surface.uder(u, v).magnitude(), surface.vder(u, v).magnitude());
+ if du.is_finite() && dv.is_finite() {
+ su += du;
+ sv += dv;
+ count += 1;
}
}
- extra.sort_by(|a, b| a.0.total_cmp(&b.0));
+ }
+ // Speeds' ratio, as a power of two; none where either speed vanishes throughout.
+ let ratio = su / sv;
+ if count == 0 || !(ratio.is_finite() && ratio > 0.0) {
+ return Self::IDENTITY;
+ }
+ let e = ratio.log2().round().clamp(-Self::MAX_EXPONENT, Self::MAX_EXPONENT);
+ // The faster parameter keeps its values; the slower one is shrunk.
+ match e >= 0.0 {
+ true => UvScale([1.0, (-e).exp2()]),
+ false => UvScale([e.exp2(), 1.0]),
}
}
- (found > 0).then(|| {
- loops
- .iter()
- .zip(extra)
- .map(|(l, extra)| l.iter().zip(extra).flat_map(|(p, e)| std::iter::once(*p).chain(e.into_iter().map(|(_, q)| q))).collect())
- .collect()
- })
+
+ fn to_cdt(self, p: Point2) -> SPoint2 { SPoint2::new(spade_round(p.x * self.0[0]), spade_round(p.y * self.0[1])) }
+
+ fn from_cdt(self, p: SPoint2) -> Point2 { Point2::new(p.x / self.0[0], p.y / self.0[1]) }
}
fn spade_round(x: f64) -> f64 {
@@ -1015,23 +1007,25 @@ pub(super) fn preview_face<S: RobustMeshableSurface>(surface: &S, loops: &[Vec<P
// SolidCraft: the normal entry point supplies None, preserving adaptive meshing.
fn trimming_with_steps<S: PreMeshableSurface>(surface: &S, polyboundary: &PolyBoundary, tol: Deflection, cap: usize, steps: Option<usize>) -> PolygonMesh {
let mut triangulation = Cdt::new();
- // SolidCraft: a loop that touches itself or another loop within `TOLERANCE` (a face pinched
- // to a point where a body touches its edge, #1648) can cross there by less than that. A
- // segment that would cross one already added is left out, the fallback in `insert_to` then
- // joins the next point across the face, and the face came out with no triangles. Its
- // segments are then taken through the points they pass, and it is triangulated again.
- if !polyboundary.insert_to(&mut triangulation) {
- if let Some(loops) = pinched(&polyboundary.0) {
- triangulation = Cdt::new();
- PolyBoundary(loops, Vec::new(), Vec::new()).insert_to(&mut triangulation);
- }
+ // Display meshes only (see `Deflection::display`).
+ let scale = if tol.display { UvScale::of(surface, polyboundary) } else { UvScale::IDENTITY };
+ let poly2tri = polyboundary.insert_points(&mut triangulation, scale);
+ if tol.display {
+ // Every point before any constraint, so no grid point lands on a split's inexact crossing.
+ let grid = insert_surface(&mut triangulation, surface, polyboundary, tol, cap, steps, scale);
+ polyboundary.add_constraints(&mut triangulation, &poly2tri);
+ add_grid_constraints(&mut triangulation, &grid);
+ } else {
+ polyboundary.add_constraints(&mut triangulation, &poly2tri);
+ let grid = insert_surface(&mut triangulation, surface, polyboundary, tol, cap, steps, scale);
+ add_grid_constraints(&mut triangulation, &grid);
}
- insert_surface(&mut triangulation, surface, polyboundary, tol, cap, steps);
let mut mesh = triangulation_into_polymesh(
triangulation.vertices(),
triangulation.inner_faces(),
surface,
polyboundary,
+ scale,
);
// SolidCraft: a face that came out with no triangles at all, though its boundary encloses
// an area in space (a lens thinner than the tolerance: its two edges are different curves,
@@ -1157,7 +1151,7 @@ fn ear_clipping(points: &[[f64; 2]]) -> Option<Vec<[usize; 3]>> {
Some(triangles)
}
-/// Inserts parameter divisions into triangulation.
+/// Inserts parameter divisions into triangulation; SolidCraft: returns their vertices, row by row, for [`add_grid_constraints`].
fn insert_surface(
triangulation: &mut Cdt,
surface: impl PreMeshableSurface,
@@ -1165,11 +1159,12 @@ fn insert_surface(
tol: Deflection,
cap: usize,
steps: Option<usize>,
-) {
+ scale: UvScale,
+) -> Vec<Vec<Option<VertexId>>> {
let bdb: BoundingBox<Point2> = polyline.0.iter().flatten().collect();
let range = ((bdb.min()[0], bdb.max()[0]), (bdb.min()[1], bdb.max()[1]));
if !(range.0 .0.is_finite() && range.0 .1.is_finite() && range.1 .0.is_finite() && range.1 .1.is_finite()) {
- return;
+ return Vec::new();
}
// SolidCraft: fixed preview grids skip both adaptive division and balancing.
let (udiv, vdiv) = if let Some(n) = steps {
@@ -1179,23 +1174,27 @@ fn insert_surface(
let (u, v) = bounded_surface_division(&surface, range, tol, cap);
let (u_ruled, v_ruled) = (u.len() <= 3, v.len() <= 3);
let (u, v) = balanced_grid(&surface, u, v, cap);
- let v = with_ruling_vertices(v, polyline, 1, tol.rulings && v_ruled, u.len(), cap);
- let u = with_ruling_vertices(u, polyline, 0, tol.rulings && u_ruled, v.len(), cap);
- let v = with_boundary_lines(v, polyline, 1, tol.rulings && v_ruled && !u_ruled, u.len(), cap);
- let u = with_boundary_lines(u, polyline, 0, tol.rulings && u_ruled && !v_ruled, v.len(), cap);
+ let v = with_ruling_vertices(v, polyline, 1, tol.display && v_ruled, u.len(), cap);
+ let u = with_ruling_vertices(u, polyline, 0, tol.display && u_ruled, v.len(), cap);
+ let v = with_boundary_lines(v, polyline, 1, tol.display && v_ruled && !u_ruled, u.len(), cap);
+ let u = with_boundary_lines(u, polyline, 0, tol.display && u_ruled && !v_ruled, v.len(), cap);
(u, v)
};
- let insert_res: Vec<Vec<Option<_>>> = udiv
- .into_iter()
+ udiv.into_iter()
.map(|u| {
vdiv.iter()
.map(|v| match polyline.include(Point2::new(u, *v)) {
- true => triangulation.insert(SPoint2::new(u, *v)).ok(),
+ true => triangulation.insert(scale.to_cdt(Point2::new(u, *v))).ok(),
false => None,
})
.collect()
})
- .collect();
+ .collect()
+}
+
+/// SolidCraft: joins neighbouring grid points [`insert_surface`] inserted, where no constraint
+/// is in the way (truck did this at the end of `insert_surface`).
+fn add_grid_constraints(triangulation: &mut Cdt, insert_res: &[Vec<Option<VertexId>>]) {
insert_res.windows(2).for_each(|vec| {
vec[0].windows(2).zip(&vec[1]).for_each(|(a, z)| {
if let Some(x) = a[0] {
@@ -1509,6 +1508,7 @@ fn triangulation_into_polymesh<'a>(
triangles: InnerFaceIterator<'a, SPoint2, (), CdtEdge<()>, ()>,
surface: &impl ParametricSurface3D,
polyline: &PolyBoundary,
+ scale: UvScale,
) -> PolygonMesh {
let mut positions = Vec::<Point3>::new();
let mut uv_coords = Vec::<Vector2>::new();
@@ -1516,7 +1516,7 @@ fn triangulation_into_polymesh<'a>(
let vmap: HashMap<_, _> = vertices
.enumerate()
.map(|(i, v)| {
- let p = *v.as_ref();
+ let p = scale.from_cdt(*v.as_ref());
let uv = Vector2::new(p.x, p.y);
positions.push(surface.subs(uv[0], uv[1]));
uv_coords.push(uv);
@@ -1527,8 +1527,7 @@ fn triangulation_into_polymesh<'a>(
let tri_faces: Vec<[StandardVertex; 3]> = triangles
.map(|tri| tri.vertices())
.filter(|tri| {
- fn sp2cg(p: SPoint2) -> Point2 { Point2::new(p.x, p.y) }
- let tri = array![i => sp2cg(*tri[i].as_ref()); 3];
+ let tri = array![i => scale.from_cdt(*tri[i].as_ref()); 3];
let (a, b) = (tri[1] - tri[0], tri[2] - tri[0]);
let c = tri[0] + (a + b) / 3.0;
let area = a.x * b.y - a.y * b.x;